Black boxes and oracles
This post is part of a series on Sailor Moon S - FrenchName edition. It digs deeper on a topic from It’s 1994 and Sailor Uranus is broken.
On the first night of this project, before it read a single line of assembly, I made the agent press buttons.
My instructions were: don’t read a 30-year-old program from the top. Make the real program do one small thing, watch which bytes change and which instruction changed them, and then read the code at that address. This post is about the bench that makes that possible, why it mattered more than anything else I built, and the times it lied.
Quick refresher: frames. The console redraws the screen 60 times a second, and the game’s logic advances once per redraw. Fighting games count everything in these ticks: a move’s startup, how long it hurts, how long you are stuck afterwards. For testing, the important property is that the game is deterministic. The same inputs on the same frames from the same starting state produce the same result, every time. Speedrunners rely on this: TASVideos defines a tool-assisted run as “a pre-programmed series of inputs that is intended to be played back in the exact same way every time”. Our harness is the same idea pointed at testing instead of speedrunning.
Watching memory. The emulator, Mesen2, can run a Lua script alongside the game. A script can ask to be called whenever the CPU writes a given address, and from inside that callback it can read the CPU’s registers, including the program counter (PC): the address of the code that is running. “Who writes the player’s action byte?” becomes a three-line script.
That was the plan. Step 1 of the brief Claude wrote for itself that evening (docs/project/history/claude_code_spec.md) reads:
Dynamic first. Boot ROM in emulator, pick Uranus (P1). Lua: log writes to $7E:1040/1041/1042 and $7E:1001/1002/1006/1007 with PC of the writing instruction (memory write callbacks). Perform 5A (standing light) once. The writer PC lands inside the animation interpreter — this single trace likely answers everything.
The approach is derived from human practices, common to those who do maintenance on undocumented codebases: it matters little that you prefer breath or depth first, you need to start somewhere and you need somewhere that is relevant from what you can actually check outside that unknown codebase. I said this blog series is first about black-box agentic development, and here was the starting point.
In fairness, this is not the only possible approach and it’s not unlikely that there are some better ones specifically for agents. But I didn’t know better and, more importantly, I knew the method worked, was great at limiting the scope of all the upcoming tasks, hence limit context usage. I couldn’t be sure it would scale well but since the workload would be lightened, hopefully I could compensate any speed limit by the relentlessness of agents.
Size, not complexity
As I stated before, what became clear fast, and clearer still on a bigger project later, is that the obstacle was virtually never the intrinsic complexity of the assembly. It was the size of the codebase. There is a lot of it, and almost none of it is relevant to the question you are asking at a given moment.
On this project, size happened to be manageable. The clean cartridge is 2,621,440 bytes (2.5 MiB, forty 64 KiB banks), and its sequel, which we later borrowed a character from, is 3.0 MiB. Claude could probably hold the whole problem at once if it needed. On Vampire Saved, a CPS-II arcade romhack I worked on afterwards, the parent romset alone unpacks to 44.3 MiB across 21 files, and the work had to go bit by bit.
In the case of romhacks an accurate emulator is both a way to test end to end and a tool to help cut size down to scope. For instance, when we tried to backport Sailor Saturn and needed to know how much of the engine was specific to her, Claude did not read the bank. It recorded which instructions executed in three situations (idle, Saturn attacking, Uranus attacking and connecting) and diffed them. The result (676235c) “bounds Saturn-exclusive code at 299 addrs (~630 B)”. A whole bank became 630 bytes worth reading.
As long as you can isolate proper scopes, the sky is the limit. That “dynamic first” approach is one way to isolate them.
The bench
The bench used is small, and an agent can run every piece of it alone, as part of its harness, without a window and without human interaction.
tools/run.shlaunches Mesen in--testrunnermode: no window, no frame limiter, one Lua script, one ROM, a timeout. It also pins the two controller types and--snes.ramPowerOnState=AllZeros. That last flag is there because on the first night Claude noticed that Mesen’s default, random power-on RAM, “made runs nondeterministic” (3ab1680). A test bench that boots differently each time is not a bench.tools/sms_env.luaandtools/probelib.luagive every script the same view of the repo and the same helpers: read RAM, read ROM, build a clean controller state. Mesen’s working directory is not the shell’s, so until these existed, scripts hardcoded absolute paths that only worked on my machine.- Probes. There are 407 tracked Lua files under
tools/. Many are probes: one question, one script, one trace file intraces/named for what it compared (_before/_after,_cleanfor the unmodified game,_f672for a frame number). The agent greps those files; it does not need to look at a screen. - Savestates as anchors. By 00:27 on the first night, the agent had navigated from power-on to a live match of Uranus against Moon with no human input and saved the state (
a8d75a7). From then on, a test starts mid-fight rather than at the boot logo; today 179 Lua files load a savestate. (Mesen only creates or loads states from inside a CPU-execution callback, so fixtures are written from a hook on a known address.)
“The difference between theory and practice is in theory there’s no difference”
You would think a script pressing Start on a title screen is the easiest part. It took two commits and a bit of human ingenuity.
The first problem was the game. Claude mapped the title menu’s input path and found that it looks at the “newly pressed” flags only every few frames: “Menu misses 1-frame press edges; navigation needs closed-loop pulsing” (3ab1680, “4-frame poll cadence”). A human never notices this, because a human finger holds a button for several frames, at irregular times. A script that pulses every fourth frame can line up with the poller’s blind spot forever. The proposed was is a period the poller cannot lock onto: “Use period-7 (3 on / 4 off) pulses — verified every pulse registers at the title menu.”
The second problem was the emulator. Twelve minutes later came 183fd0b in which Claude read Mesen’s own C++ for the Lua binding and found a critical misunderstanding on its part. The note it wrote:
### Mesen 2.1.1 setInput port bug (critical harness note)
`LuaApi::SetInput` does `ForceParamCount(3)` then `lua_settop(lua, 4)`, so the
documented 2nd parameter (port) is DISCARDED and always reads as 0. The port is
effectively the **3rd** argument: `emu.setInput(buttons, 0, port)` with port 0=JOY1, 1=JOY2.
Verified: setInput({start},0,0)+setInput({down},0,1) → $4219=10, $421B=04.
Consequence: any second setInput call written as (tbl, 1) silently clobbers port 0.
This is also the series’ first retraction, and it reinforced by belief that Claude could correct itself but also was prone to go for the seemingly best cost/benefit explanation in most circumstances, often without actuallly checking if it were correct or just “happened to fit that one time”.
In that case, the commit just before it had recorded, in the same notes file: “emu.setInput port indices are 0-based (port 0 = P1) — confirmed by $4219 latching start+down set on port 0.” That “confirmation” pressed buttons on port 0 and saw them arrive on port 0… Except that with Claude’s buggy interpretation, everything arrives on port 0, so the test could not have failed. The fix came from a test that could: one button on each port, two different registers… the pattern broke and then came the analysis and the fix. Not exactly a detail since literally 296 of our 407 Lua files call emu.setInput, and thus depends on that third argument being properly used.
Just because the harness is code doesn’t mean it’s right
A harness is code, and while code can’t “lie”, it can mislead. This one lied in four memorable ways.
A flag that did nothing. The first run.sh passed --debug.scriptWindow.scriptTimeout=300. It rode along on every run for about four weeks, until a measurement on 6 August (issue #52) showed it has no effect under --testrunner: “every Lua entry (script load and each callback) is capped at a hard 1 second whatever value is passed, so the flag was dead cargo”. The comment in run.sh still says so, so nobody adds it back.
Errors that vanish. Inside a Mesen memory callback, an error kills the hook without a message. A celebrated fix that added an assert “never worked: the ‘fixed’ script hung to timeout exactly like the unfixed one, message swallowed”.
Trap 12. “Anything thrown inside a Mesen memory callback dies WITHOUT A MESSAGE — assert included. […] a fix whose effect was never OBSERVED (only reasoned about) is not fixed.”
Silence that looks like an answer. Trap 9 collects three cases from one session, including “the character never jumps”, which was the round’s entrance animation and the GO! banner, not an input fault, and a script that crashed on a nil and still printed “done”.
Trap 9. “A probe that reports nothing is usually broken, not evidence of nothing. […] Prove the harness sees the thing before concluding the game does not do it.”
The PC that pointed one instruction late. This one closes the loop on “Dynamic first”. A write watch named two addresses as the code that zeroes a counter at round load. Except in the meantime I had set up documentation so that it would only accept data actually supported by the cartridge. The project’s doc checker, which re-reads the cartridge, refused to accept the documentation row. The real stores were three bytes earlier: “The session watch reports a write callback’s PC as the NEXT instruction” (8d689d8). The brief’s whole method rests on “the PC of the writing instruction”, and the PC we get is the one after it. That is fine, once you know: the dynamic trace tells you where to look, and the bytes tell you what is there.
Trap 27. “A write callback’s PC is the NEXT instruction. […] A watch’s PC FINDS a writer; the ROM NAMES it.”
If you want to try this: the project used Mesen2 2.1.1, whose repository is now archived; the maintained fork is MesenCE. [Note: I’ve no idea whether run.sh and the setInput quirk behave the same on MesenCE since I’ve not tested it.]
Still a human in the loop
Alas, the bench could not replace human testing (although that’s less and less true as the projects went on). For instance, on 21 July I reported, from toying around with the Lua training mode:
…the life refill only accurs after a normal hit. Special move damage does not trigger refill afeter 2s which leads me to think the trigger is not HP<96 as claimed but something else.
Claude reproduced it headlessly, with a dummy that “sat at damaged HP for 10+ seconds”, and traced it three modules deep. A projectile special’s hitbox lives on the projectile, so the frame-data tracker never saw the attacker’s move go active and left it in “startup” forever, which kept the combo open, and refill waits for the combo to close. Its reply opened with “Your instinct was right — the trigger isn’t HP < max.” The fix shipped with a new self-test, T10, that pins the projectile case (29f1cfe).
That is the division of labour in one exchange. I noticed something felt wrong in play and had a hunch about why. The agent turned the hunch into a reproduction, the reproduction into a mechanism, and the mechanism into a test that runs without me.
It works the other way too. for instance, every build carries a “naked-eye tell”, a version string on the title screen (“FrenchName Rev. S-02”), so that when I report both the agents and I know which exact version I was handling. Sounds obvious but if you’re overly reliant on the agents, you tend to glaze over such details and it bites hard when you lose hours chasing a problem which exact reproduction is linked to a specific version.
The cartridge as oracle
Testing has a name for the hard part: the oracle problem knowing what the right answer is when there is no specification. Here, the original cartridge is the specification. Whatever the 1994 code does is, by definition, correct, except where we deliberately change it. The agents and I derived therefrom three kinds of check.
Byte-identical side effects. A patch must change what it targets and nothing else. The first patch’s proof included “whiff/on-hit traces byte-identical” and a control character for whom the new code never runs (b914e3d). Michael Feathers calls these characterization tests: pin down what the code does before you change it (yes, this is a quote form Working Effectively with Legacy Code which is a book I’d still recommend at least skimming through, even in 2026).
Two implementations, one answer. The in-ROM training mode (patch 11) is “oracle-validated” against the Lua one, feature by feature: “38/38 oracle checks” (8ca4966). The precise Lua version judges the assembly version that has to fit in the cartridge.
A chain of hashes. A builder writes a complete ROM; only then does a diff tool turn clean and built images into a .bps patch (how patches are built). Applying that patch to the clean ROM must reproduce the built SHA-1 exactly. A recorded hash is something a script checks, not something a person trusts.
None of this needs the agent to understand the game. It needs the agent to run it, alone, the same way every time. That is the multiplier: an agent that can ask the program a question and get an answer in seconds stops guessing, because guessing has become more expensive and thus less useful than measuring.
From one game to any black box
Hardened on Vampire Saved, the same idea became its own project, first extracted “by asking of every piece: would this still be true if the thing under test were not that ROM, not CPS-2, not even a game?”. But that’s a story from another time.