Skip to course

Original project course · offline candidate

Build a time-travel debugger

Read here. Build and check your own code with Node. No account or network required.

Try the Watch & Poke Studio · Open the offline project checker

Build a time-travel debugger: from JavaScript state to a WebAssembly game

Build a debugger for a small deterministic JavaScript machine, then keep deepening the same tool until it can investigate a compiled WebAssembly game. Across 13 lessons you own control, inspection, stopping rules, tracing, replay, reverse state search, compact snapshots, value provenance, names and call stacks. The supplied machines are original teaching infrastructure. They have no access to native processes.

For a five-minute investigation, open the Watch & Poke Studio. Make a prediction, rewind the crash, then compare two runs from the same save. To build the machine behind those controls with your coding agent, start the five-rung Node project.

Entry skills and boundaries

This course is for a programmer comfortable editing/running JavaScript ES modules, writing functions and classes, using objects/arrays/Map, reading exceptions and passing quoted arguments in a terminal. The debugger assumes you can follow nested object mutation; the supplied VM defines its own instruction set. This is not a first programming course. If these prerequisites are unfamiliar, use the reduced examples and completion cases, then decide whether to review JavaScript first. No extra runtime or paid account is required.

Start offline

Use Node.js. The local construction run uses v26.5.1 on macOS; other Node versions and operating systems are unqualified. No npm install, API key, paid service or internet connection is needed.

Navigation stays open. The chapters are one cumulative climb, not 13 unrelated projects. You may implement and check any milestone directly; tests run cumulatively within each machine to preserve earlier behavior. Lesson 08 adapts your own Act I debugger to the compiled game, while a labelled fallback supports a learner who begins at Act II. The assistance routes supply prior layers for an independent unit attempt; the cumulative route keeps your own code.

Act I · Make state reversible in JavaScript

01 inspector; 02 conditional loop runner; 03 memory-change investigator; 04 trace recorder; 05 replay viewer; 06 reverse state search; 07 diagnosis tool and report. Read capstone.md for the less-guided final investigation and learner-owned extension. Timings are estimates until tried by people.

Act II · Put the debugger inside WebAssembly

Lesson 08 starts with the existing project/. Its blank WebAssembly files were placed there by the original node lab.mjs start project; no second clone or course download is needed. The type-in and supplied routes can still create a separate practice folder when you want to compare without touching your cumulative work.

What was measured

Numbers from the worked solution on the authoring Mac, 2026-11-13. The author-only numbers check re-derives every count from the course files. Timings vary with the computer and its load, so the ranges below include both idle and busy runs.

What this course does not claim

The checks run your JavaScript with your normal permissions. They are not a sandbox, so run code you understand.

node lab.mjs question 01a shows a prediction. node lab.mjs predict project 01a ANSWER --help-used none commits it before feedback; 01b is a changed case. Each coding check saves source, report, question/version, assistance and actual results in project/attempts before execution. Editing code does not revise earlier attempts. Local receipts are editable records, not credentials.

node lab.mjs export project NEW_EXPORT_DIRECTORY copies your code, report and attempts without overwriting an existing destination. Your project is nested at NEW_EXPORT_DIRECTORY/project/. Keep this course package and invoke the exported solution by its full path. For example, from this course directory after completing your project:

node lab.mjs export project ./my-debugger-export
node lab.mjs check ./my-debugger-export/project 07 --help-used "export replay"
node debug.mjs ./my-debugger-export/project/solution.mjs programs/counter.json

Use the help description that matches your actual assistance. No restore/import path is provided and no old receipt is promoted to current.

Optional help and acceptance limits

own-llm.md contains a copyable critique prompt for your own account. Nothing sends your work automatically. Deterministic checks cover their named cases; diagnosis reasoning uses a rubric. Author controls are outside this package. The Node terminal course is publicly available. Independent AI learner runs are separate evidence, not a human mastery claim. Human difficulty/time trials, rendered desktop/mobile inspection and actual browser ZIP receipt remain unqualified. Node runs the full toolchain; checker.html supplies the bounded offline fallback described below, with actual browser acceptance pending.

The runner executes your trusted local JavaScript with your normal process permissions. It is not a security sandbox; run code you understand.

Earlier-layer assistance

For Lessons 01–07, run node lab.mjs start-for NEW_DIRECTORY NN --use-prior to attempt a unit with completed earlier layers. For Lessons 08–13, each lesson names its examples/start-*.mjs route and the fallback used when Act I code is unavailable. These routes refuse existing destinations and record what was supplied in PROJECT.json and each check receipt. Supplied source is assistance, not hidden assessment material or a submission you can claim to have implemented. Keep and repair your cumulative project if you want your own complete artifact. No staff or model reply is required.

Human effectiveness and difficulty have not been measured. The launch route uses learner-run checks and optional critique from the learner's own account; it introduces no staffed/human-trial requirement. Independent engineering, packaging/download and actual platform acceptance remain separate.

Browser fallback and its limits

Open checker.html for an offline code editor and on-demand worker checks using the same public criteria. It preserves all submitted code/help/results and can export source plus the complete local history. The earlier-layer button creates a separate assisted draft. It requires a browser supporting module workers, data-module imports, crypto.subtle and localStorage; actual browser route/download acceptance is still pending. This debugger fallback accepts the supplied ./vm.mjs import. Use Node for custom modules, Node-only APIs and CLI export/replay. Unsupported browser execution is an execution error, not evidence that a Node-valid debugger violates the course contract. No staffed reply or paid model is involved.

Run the browser checker offline

In this extracted course directory, run node serve.mjs, then open http://127.0.0.1:8128/checker.html. Keep the terminal open; Ctrl+C stops it. The helper uses the same tested Node runtime as the CLI. It binds only 127.0.0.1 and serves an explicit read-only reader/checker/SVG list, never projects, directory listings or author files. No package install or internet connection is needed. If the port is already used, run node serve.mjs --port 0 and open the exact URL it prints. The default port stays fixed so the same browser origin can retain local attempts across restarts.

Directly opening checker.html as a file displays the local-preview command and refuses check execution; editing and source/history downloads remain available. Export any existing file-page work before switching origin. Browser state is per origin: the loopback page does not automatically import or reinterpret file-page attempts. Keep the old JSON export, start a new draft at the local URL, paste your own downloaded source and declare help. All prior records retain their saved source, assessment and verdict. The Node CLI route needs no preview server.

01. Control and inspect

Build inspect and step so you can pause a program, advance one instruction, and read its registers (four named integer slots a, b, c, d) and memory (eight integer cells 0 through 7) without changing the running machine.

Start here. A debugger is a tool that runs another program in small steps so you can watch it work. Each step is one instruction, a single command such as add c=2. Here the program runs on a tiny pretend computer written in JavaScript, so a mistake cannot harm your own machine. By the end of the course your debugger saves copies of that computer as it runs, so you can jump back to any earlier moment and see what changed.

Before the worked result

Suppose a debugger stores a snapshot (a saved copy of the machine state) with history.push(this.state) or returns this.state directly from inspect(). Run this check on set c=5, add c=2, halt:

const d = new Debugger(program);
d.step();
const snap = d.inspect();
snap.regs.c = 99;
console.log(d.inspect().regs.c);

Predict whether the last line prints 99 or 5, then run node lab.mjs question 01a and commit your prediction before checking:

node lab.mjs question 01a
node lab.mjs predict project 01a YOUR_ANSWER --help-used none

With a shallow copy ({ ...this.state }), snap.regs.c = 99 overwrites the live machine and prints 99. Because regs (registers), mem (memory), and output are nested objects, shallow copying leaves aliasing (two references pointing to the same object). Returning a detached (deep-copied) object keeps the machine at 5.

step advances state; inspect returns a detached copy On set c=5, add c=2, halt: step() moves pc from 0 to 1 and sets c from 0 to 5. Setting copy.regs.c to 99 leaves VM register c at 5. step() pc 0 -> 1 c: 0 -> 5 inspect() copy.regs.c = 99 VM c stays 5

A virtual machine (VM) executes instructions one by one from a small instruction list. Here pc (the program counter) holds the index of the next instruction, tick counts instructions already run, and output holds emitted integers.

Calling step() executes one instruction at pc, updates state, and returns an event (a record { tick, pc, op, writes, emitted }). In that record op is the operation, the instruction's name; writes lists the changed slots; and emitted holds the output values. If state.halted is already true, step() executes nothing and returns null.

Implement inspect() and step() in project/solution.mjs using the supplied vm.mjs helpers (initial, execute, validateProgram, clone). Do not alter vm.mjs; the VM semantics stay fixed.

Worked procedure

Inspect the reduced sibling example (set c=5, add c=2, halt) with:

node examples.mjs 01

Follow one transition step by step:

After the sibling's first step (pc moves from 0 to 1, c changes from 0 to 5), decide which fields a second inspect() call can still change if a caller edits the first snapshot.

Complete a changed case

Apply the step boundary to a d-register program (set d=6, add d=3, halt) before running the code suite:

node lab.mjs question 01b
node lab.mjs predict project 01b YOUR_ANSWER --help-used none

Build, check, and transfer

Start project once, edit project/solution.mjs, and run stage 01:

node lab.mjs start project
node lab.mjs check project 01 --help-used none
node debug.mjs project/solution.mjs programs/counter.json programs/first-session.json

If an earlier layer blocks you later, start a separate directory with node lab.mjs start-for unit01 01 --use-prior and check with --help-used supplied-prior. That assisted route supplies prior layers without touching your cumulative project.

A store and a load look like this in a program file: {"op":"store","address":2,"value":"a"} writes register a into cell 2, and {"op":"load","reg":"b","address":2} copies cell 2 into register b.

For transfer, write a short program that stores register a into memory cell 2, overwrites a, and loads cell 2 into register b. Predict pc, tick, and regs after each instruction before stepping through it with debug.mjs.

02. Conditional breakpoints

Add addBreakpoint and run so the debugger stops right before a chosen instruction runs when a register or memory condition holds.

Before the worked result

Consider a countdown loop that stores d into cell 3 on every pass:

[
  { "op": "set", "reg": "d", "value": 2 },
  { "op": "store", "address": 3, "value": "d" },
  { "op": "add", "reg": "d", "value": -1 },
  { "op": "jnz", "value": "d", "target": 1 }
]

Suppose you place a breakpoint (a rule that pauses execution before an instruction) at pc: 1 with condition d === 1, then call run(100). Predict whether mem[3] equals 1 or 2 when run stops, then commit your answer to case 02a:

node lab.mjs question 02a
node lab.mjs predict project 02a YOUR_ANSWER --help-used none

Intuition often expects mem[3] to hold 1. Because run checks breakpoints *before* executing the instruction at pc, mem[3] still holds 2 from the previous loop pass.

Breakpoint pauses before the pending store executes With breakpoint pc=1 and d=1 on the decrementing store loop: tick 2 writes mem[3]=2, and tick 4 stops before the second store, so d is 1 and mem[3] is still 2. break pc=1 when d=1 tick 2 mem[3] = 2 tick 4: paused before store d=1, mem[3] still 2

A breakpoint's pc names the *pending* instruction, not the instruction that finished on the previous tick. A condition ({ kind: 'reg', name: 'd', equals: 1 } or { kind: 'mem', address: 3, equals: 2 }) filters which visit pauses. If the condition is false, run executes the instruction and keeps going.

Implement addBreakpoint(spec) and run(limit = 1000) in project/solution.mjs. At each loop iteration in run:

Calling run() again right at a breakpoint stops immediately with 0 steps executed because pc and state have not changed. Calling step() bypasses (skips checking) breakpoints for one instruction so the loop can move past pc: 1.

Worked procedure

Inspect the loop sibling with node examples.mjs 02. Run it once and verify the stop record { reason: 'breakpoint', tick: 4, pc: 1 } alongside mem[3] === 2.

node examples.mjs 02

Notice the order inside run(limit): validate limit (1 through 10000), test halted, test breakpoints before counting a step, execute step(), test halted again, and return limit only when the loop finishes its budget without halting.

Complete a changed case

Test what happens when you call run() again without stepping past a breakpoint, then verify on case 02b:

node lab.mjs question 02b
node lab.mjs predict project 02b YOUR_ANSWER --help-used none

Build, check, and transfer

Run stage 02 against your cumulative project, then pause programs/counter.json on a single loop pass:

node lab.mjs check project 02 --help-used none
node debug.mjs project/solution.mjs programs/counter.json

Inside debug.mjs, enter break 2, run, inspect, step, and run to observe the breakpoint bypass. If stage 01 blocks you, use a separate directory with node lab.mjs start-for unit02 02 --use-prior and --help-used supplied-prior.

For transfer, write a loop with two store instructions and use addBreakpoint with a { kind: 'mem', address, equals } condition to pause before the second store on its second pass. Record the stop tick and mem state before and after calling step().

03. Watchpoints

Add watch so run stops right after a store changes a watched memory cell, even when you do not know which pc wrote it.

Before the worked result

Memory cell 2 starts at 0. Suppose you call d.watch(2) and run these three stores:

[
  { "op": "store", "address": 2, "value": 0 },
  { "op": "store", "address": 2, "value": 5 },
  { "op": "store", "address": 2, "value": 5 },
  { "op": "halt" }
]

Predict which tick stops first (tick 1 or tick 2) and what pc the stop record reports (1 or 2). Save your prediction for case 03a:

node lab.mjs question 03a
node lab.mjs predict project 03a YOUR_ANSWER --help-used none

A watchpoint observes a memory address instead of a pc. Intuition expects any store to cell 2 to stop at tick 1. Because writing 0 over 0 is a same-value store (before === after), run skips tick 1 and stops at tick 2 (0 -> 5) with pc: 2 (the *next* instruction).

Watchpoint skips same-value write and stops after change Watching address 2 across three stores: tick 1 writes 0 to 0 and continues; tick 2 changes 0 to 5 and stops after the store at next pc 2. watch(2) on cell 2 tick 1: 0 -> 0 unchanged, continues tick 2: 0 -> 5 stops, next pc 2

Keep the two pause boundaries separate:

Implement watch(address) (rejecting integers outside 0 through 7) and update run(limit) in project/solution.mjs. After const event = this.step(), scan event.writes for { address, before, after } where this.watches.has(address) and before !== after. If found, return { reason: 'watchpoint', tick: this.state.tick, pc: this.state.pc, write: clone(changed) }.

Worked procedure

Inspect the three-store sibling trace with:

node examples.mjs 03

Check the two separate filters on each write event:

Compare event.pc (1, the store that executed) against stop.pc (2, the next instruction ready to run).

Complete a changed case

Predict the stop pc and memory value when a watched cell is written from a register, then commit case 03b:

node lab.mjs question 03b
node lab.mjs predict project 03b YOUR_ANSWER --help-used none

Build, check, and transfer

Run stage 03 and test watch against programs/dispatch.json without reading its instruction list first:

node lab.mjs check project 03 --help-used none
node debug.mjs project/solution.mjs programs/dispatch.json

Inside debug.mjs, run watch 1, run, inspect, and run again to watch cell 1 change across loop passes. If earlier stages block you, use node lab.mjs start-for unit03 03 --use-prior in a fresh directory with --help-used supplied-prior.

For transfer, write a program with an unwatched store to cell 0, a same-value store to watched cell 4, and a changed store to cell 4. Verify run skips both early stores and stops only on the changed write.

04. Instruction traces

Extend step and add trace so every executed instruction records a detached event with its tick, pc, writes, and emitted values.

Before the worked result

Suppose a loop executes store at pc: 2 twice (first writing 0, then writing 1), and a caller mutates the returned trace:

const t = d.trace();
t[2].writes[0].after = 99;
console.log(d.trace()[2].writes[0].after);

Predict whether the second d.trace() call prints 99 or 0, and predict how many events exist after three stores (including a same-value store):

node lab.mjs question 04a
node lab.mjs predict project 04a YOUR_ANSWER --help-used none

Intuition sometimes drops same-value writes or pushes references to mutable state into this.events. In this contract, every executed instruction produces one event, and t[2].writes[0].after = 99 must leave the stored trace at 0.

Repeated pc creates separate events and trace returns detached copies In counter.json, pc 2 runs at tick 3 (cell 0: 0 to 0) and tick 7 (cell 0: 0 to 1). Editing a returned trace write to 99 leaves the stored trace at 0. Same pc 2, distinct tick events tick 3, pc 2 cell 0: 0 -> 0 tick 7, pc 2 cell 0: 0 -> 1 edit trace copy = 99; stored after stays 0

An event is not a full state snapshot. It holds { tick, pc, op, writes, emitted } where tick is the post-instruction tick (1, 2, 3...) and pc is the pre-instruction pc that executed. Because loops revisit the same pc, multiple events share pc: 2 while each event carries a unique tick.

Both step() and trace() must copy nested writes and emitted arrays so neither internal execution nor caller edits can alias (share a mutable reference with) stored history. Calling inspect(), addBreakpoint(), or watch() executes no instruction and creates zero trace events.

Worked procedure

Inspect the three-store trace from node examples.mjs 04:

node examples.mjs 04

Verify both copy boundaries in project/solution.mjs:

Notice why two copies are needed: copying on push protects this.events from caller edits to step()'s return value, and copying in trace() protects this.events from caller edits to trace().

Complete a changed case

Separate total executed events from emitted values on a four-instruction program, then check case 04b:

node lab.mjs question 04b
node lab.mjs predict project 04b YOUR_ANSWER --help-used none

Build, check, and transfer

Run stage 04 and inspect the full trace of programs/counter.json:

node lab.mjs check project 04 --help-used none
node debug.mjs project/solution.mjs programs/counter.json

Inside debug.mjs, run run 100 followed by trace, then find every event where op === "store". Identify which store changed cell 0 and which left it unchanged. If an earlier layer blocks you, use node lab.mjs start-for unit04 04 --use-prior in a fresh directory with --help-used supplied-prior.

For transfer, compare trace() across two fresh Debugger instances running the same program, then change one operand in a new instance and find the earliest tick where the two traces diverge.

05. Checkpoints and replay

Implement checkpoint and seek so you can jump back to any earlier recorded tick by replaying from tick 0 or a saved snapshot.

Before the worked result

Suppose a debugger steps 7 instructions, saves a checkpoint (a deep saved VM state at a tick) at tick 4, and calls seek(2) to jump back to tick 2:

d.seek(2);
d.step();
console.log(d.trace().length);

Predict whether d.trace().length drops to 2, grows to 8, or stays 7. Commit your prediction for case 05a:

node lab.mjs question 05a
node lab.mjs predict project 05a YOUR_ANSWER --help-used none

Many readers expect seek(2) to drop later history or expect step() to append a duplicate event. Because the recorded frontier (this.events.length) tracks the last tick reached, seek(2) leaves trace().length at 7, and stepping through known tick 3 appends nothing.

Checkpoint replay seeks forward while preserving trace frontier Timeline 0 to 7: checkpoint saved at tick 4. Calling seek(6) replays ticks 4 to 6 forward while trace length remains 7. seek(6) replays from tick 4 0 4 saved 6 seek 7 end frontier stays 7

Deterministic replay (computing a state by running the same instructions forward from an earlier state) works here because the VM has no clock, random numbers, or external input. Rebuilding tick 6 needs no snapshot at every tick:

Store an internal clone inside checkpoint(label) and return a separate clone({ label, tick, state }). Reject empty labels and reject seek(tick) when tick < 0 or tick > this.events.length.

Worked procedure

Inspect the checkpoint and replay example with:

node examples.mjs 05

Trace seek(target) in project/solution.mjs:

In step(), keep the guard if (this.events.length < state.tick) this.events.push(clone(event)) so stepping forward through already recorded ticks never duplicates events.

Complete a changed case

Predict both current tick and trace().length after calling seek(3) and stepping twice through a 10-tick trace:

node lab.mjs question 05b
node lab.mjs predict project 05b YOUR_ANSWER --help-used none

Build, check, and transfer

Run stage 05, then run the stage-05 replay script against programs/counter.json:

node lab.mjs check project 05 --help-used none
node debug.mjs project/solution.mjs programs/counter.json programs/replay-session-stage05.json

Compare the checkpoint snapshot against seek 7. If earlier layers block you, run node lab.mjs start-for unit05 05 --use-prior in a fresh directory with --help-used supplied-prior.

For transfer, write a program that emits a value before and after a checkpoint. Jump to a tick before the first emit, inspect output, then jump past the second emit and explain why saving only pc and regs would fail to rebuild output.

06. Reverse state search

Implement reverseFind so you can jump backward to the nearest earlier tick whose state matches a register or memory value.

Before the worked result

Suppose register d holds 1 at ticks 3, 4, and 5, then drops to 0 at tick 6 and 7. From tick 7, run:

const hit = d.reverseFind({ kind: 'reg', name: 'd', equals: 1 });
const miss = d.reverseFind({ kind: 'reg', name: 'a', equals: 99 });

Predict which tick hit returns (3 or 5) and which tick the debugger sits at after miss returns null. Commit your answer for 06a:

node lab.mjs question 06a
node lab.mjs predict project 06a YOUR_ANSWER --help-used none

Intuition often expects reverseFind to jump to tick 3 (where d was written) or leave the debugger at tick 0 after a failed scan. In reality, reverseFind scans *states* downward from an exclusive upper bound (beforeTick - 1 down to 0), returning tick 5, and restores the caller's state when miss finds nothing.

reverseFind scans downward from bound minus one to nearest match Ticks 0 through 7 have d values 0, 2, 2, 1, 1, 1, 0, 0. Starting from tick 7, reverseFind(d=1) excludes tick 7, checks tick 6 (d=0), and stops at nearest match tick 5. reverseFind(d = 1) from tick 7 t0 d=0 t1 d=2 t2 d=2 t3 d=1 t4 d=1 t5 d=1 t6 d=0 t7 d=0 nearest below 7 is tick 5

Separate state search from write search:

Validate condition (via matches(this.state, condition)) and beforeTick (0 <= beforeTick <= this.events.length + 1) before mutating this.state.

Worked procedure

Inspect the reverse search example with:

node examples.mjs 06

Build reverseFind(condition, beforeTick = this.state.tick) cleanly on top of seek:

If beforeTick === 0, the loop executes zero times, this.state stays at original, and reverseFind returns null.

Complete a changed case

Predict what inspect().pc returns after a no-match search on a halted three-instruction program:

node lab.mjs question 06b
node lab.mjs predict project 06b YOUR_ANSWER --help-used none

Build, check, and transfer

Run stage 06, then execute the full replay session (programs/replay-session.json) ending with find reg b 0:

node lab.mjs check project 06 --help-used none
node debug.mjs project/solution.mjs programs/counter.json programs/replay-session.json

Verify that searching for find reg a 999 leaves inspect() unchanged. If an earlier layer blocks you, run node lab.mjs start-for unit06 06 --use-prior in a fresh directory with --help-used supplied-prior.

For transfer, run programs/dispatch.json to completion, use reverseFind to locate an earlier memory value, and confirm that a fresh Debugger instance reaches the same state by forward step() calls.

07. Diagnose an unfamiliar program

Use your debugger, reproducible commands, and a written counterexperiment (a check designed to refute an alternative cause) to diagnose a faulty output in an unfamiliar program.

Before the worked result

A reviewer reports that programs/dispatch.json drops the final shipment from quantities 12, 9, 6, 3 instead of emitting their sum (30). Run your debugger on dispatch.json before reading the program or proposing a patch:

node debug.mjs project/solution.mjs programs/dispatch.json

Inside debug.mjs, enter watch 1, run, trace, and inspect. Predict whether output holds 27 or 30, then evaluate the claim on case 07a:

node lab.mjs question 07a
node lab.mjs predict project 07a YOUR_ANSWER --help-used none

The trace records all four stores (12, 9, 6, 3) and output holds [30]. Because the trace refutes the reported symptom, the complaint itself is unsupported: changing dispatch.json without checking evidence first would break a working program.

Trace evidence refutes an unsupported bug claim in dispatch.json In dispatch.json, trace writes record all four values 12, 9, 6, 3 and output is 30, refuting the missing-shipment complaint. dispatch.json trace vs complaint Reported symptom final shipment missing stores: 12, 9, 6, 3 output: [30] (unsupported)

Use dispatch.json as rehearsal, then apply the same discipline to programs/transfer.json (your fresh diagnosis surface described in capstone.md). A valid diagnosis report must prove four parts:

Worked procedure

Inspect the four-step diagnosis procedure with:

node examples.mjs 07

Follow the investigation loop without guessing from output alone:

Stage 07 verifies your debugger (07.instance-isolation and 07.changed-program); the causal reasoning belongs in your written report.

Complete a changed case

Distinguish a double-emit program bug from a duplicated-report claim on case 07b:

node lab.mjs question 07b
node lab.mjs predict project 07b YOUR_ANSWER --help-used none

Build, check, and transfer

Run stage 07 and export your completed project into a fresh directory to confirm it runs independently:

node lab.mjs check project 07 --help-used none
node lab.mjs export project ./my-debugger-export
node lab.mjs check ./my-debugger-export/project 07 --help-used "export check"

If earlier layers block stage 07, use node lab.mjs start-for unit07 07 --use-prior in a fresh directory for practice tooling (--help-used supplied-prior), remembering that supplied code is practice assistance rather than your own submission.

For your final learner-owned extension, write a small VM program with one plausible data-flow bug, record its intended behavior, and produce a reproducible diagnosis report for someone who has not read the code.

Carry your debugger into WebAssembly

Keep project/solution.mjs. Lesson 08 runs that debugger against Lob through an adapter, so the cost of copying a tiny JavaScript state becomes visible when the same operation copies 131,072 bytes of game memory on every instruction. The WebAssembly starter files already sit beside solution.mjs in the project created at the start of this course.

08 · A machine worth debugging

Your Lesson 07 JavaScript debugger can rewind a small teaching machine. Lob is a compiled artillery game with 131,072 memory bytes and runs of about a million instructions in WebAssembly (portable machine code that runs in browsers and in Node). Predict what happens before game_init starts the game when r_px reads the shell's horizontal position through an uninitialized pointer (a stored byte address pointing to another place in memory, the program's byte array): intuition expects a crash or missing-field error, yet cold zeroed bytes make r_px dereference address zero and quietly return 0 after exactly four instructions. Build the WebAssembly interpreter your debugger must pause and restore: code that performs one numbered operation, an instruction, per step.

Start

Terminal command
node examples/step-getter.mjs
Select code to copy. Scroll horizontally if needed.

Node 22 runs this JavaScript probe. A value stack holds temporary numbers. i32.const pushes a 32-bit integer; i32.load reads one; f32.load reads a 32-bit decimal. begin requests one function run; tick counts finished instructions; running marks an active request; returned holds its result.

The command executes the real game's r_px getter one instruction at a time. The game has not been initialized: its pointer and the bytes read through that pointer are zero. This is a probe of the interpreter, not a moving shell yet.

Four instructions through cold memoryexamples/getter-output.txt
begin: tick=0, running=true
1 i32.const stack=[0]
2 i32.load stack=[0]
3 f32.load stack=[0]
4 end stack=[]
returned=0; this is cold memory, before game_init
Select code to copy. Scroll horizontally if needed.

begin leaves the instruction count, called a tick, at zero. The final end returns the value and empties the stack.

Continue in the same project/ from Lesson 07. It contains your own solution.mjs debugger and the blank machine.mjs created when you began the course. Run its baseline now:

Terminal command
node lab.mjs check project 08 --help-used "continuing Lesson 07 project; Machine regions unfinished"
Select code to copy. Scroll horizontally if needed.

The blank machine fails with not written yet. That red result is the baseline you will repair. Later attempts remain under project/attempts/.

Keep every // region: NAME marker. Replace only the text between a matching pair. The six regions appear in this order:

123456
initial-statecall-entrystep-startreturn-framebranchmemory

Recovery routes

Use these only if you do not have the cumulative Lesson 07 project or need a disposable comparison. Every setup command refuses an existing path, so none can overwrite your attempt.

NeedCommandWhat you receive
Type in six marked regionsnode examples/start-chapter.mjs project08-write writestarter/machine-build.mjs with supporting instruction cases
Inspect a working checkpointnode examples/start-chapter.mjs project08-supplied suppliedA working implementation saved at this lesson boundary
Begin the 13-lesson course herenode lab.mjs start projectBoth the JavaScript debugger and WebAssembly machine starters; using the fallback debugger is recorded assistance

If you use AI, begin with the write route. Share one marked region at a time, inspect its state changes, and record the help used. A supplied-route baseline passes; a write-route baseline fails with not written yet.

What you are given

Lob was written in C and compiled to WebAssembly, a machine code that runs in browsers and in Node. You get the compiled file, targets/lob.wasm, and the same file decoded into a JSON listing, programs/lob.json. Decoding is taught in the Sightline course. Here you start from the listing. API.md ends with a table of all 62 instructions Lob and Lob II use.

The game is played through calls from outside: game_init(seed, mode) starts it, where the seed is a starting number that reproduces the same round. game_key(code) presses a key, and each call to game_tick() is one game frame, 1/60 of a second. The mode is a sum of four defence switches, optional game rules worth 1, 2, 4 and 8 that API.md describes under "public/sessions.mjs"; mode 0 enables none. Between calls, exported functions called getters, such as r_px below, each return one value of the game.

A WebAssembly global is a module-wide mutable or constant variable. Global 0 holds the C stack pointer, the address marking the top of compiled C's working stack, starting at byte 65,536. The pointer g, stored at address 78,112, points to Lob's game-state record.

Lob's memory after game_init(5, 1), not to scale: the C stack below 65,536, the 281-byte data segment at 65,536, then the 12,288 bytes game_init clears, holding the state at g = 65,904 and the three texts, and at 78,112 the pointer that holds g.

The game-state record that g points to sits with three texts in a stretch game_init clears to zero. The C stack, below 65,536, is where compiled C keeps some variables of its own, and the data segment is text the listing gives the machine to copy in before anything runs. The addresses of g and the texts depend on the seed.

The game keeps three text buffers:

BufferExample or purpose
Status lineAngle, power, wind and score
Message lineROUND 1, HIT!, SHORT BY 10
Help textControl rules and scoring distance

Angle runs from 5 through 85, power from 10 through 100, and a shell within 12 paces scores. The N key starts a new round with a new flag and wind.

Lob II, the second game, was written separately and compiled the same way. Its file is targets/lob2.wasm, and its listing programs/lob2.json. It takes the same calls and keys and keeps the same three texts in memory, and its help text gives the same rules. Its eight getters, g0 to g7, are deliberately named so they don't say what they hold, because Sightline asks its learners to work that out, and none of them returns the help text's address. Your machine runs both games, and one build in lesson 13 is a build of Lob II.

The listing has one entry per function. Here is the whole of function 14, the getter r_px, which returns the shell's horizontal position:

WebAssembly instructions and stack trace
0  ["i32.const", 0]
1  ["i32.load", 2, 78112]
2  ["f32.load", 2, 40]
3  ["end"]
Select code to copy. Scroll horizontally if needed.

Each instruction is a name followed by its immediates, the numbers written into the code. A load's two immediates are an alignment hint, which you can ignore, and an offset.

WebAssembly is a stack machine. Instructions take their operands from the top of a value stack and push their results back on it. Trace r_px by hand, writing the stack after each instruction, top on the right:

WebAssembly instructions and stack trace
0  i32.const 0           [0]
1  i32.load offset 78112 [g]          reads 4 bytes at 0 + 78112
2  f32.load offset 40    [px]         reads 4 bytes at g + 40
3  end                   the function returns px
Select code to copy. Scroll horizontally if needed.

i32.load pops an address, adds its offset, and pushes the 32-bit integer stored there: the pointer g from the figure. f32.load pops that pointer, adds 40 and pushes the 32-bit float stored there, the shell's position. At end the function returns what is left on the stack.

Function 12, r_target_x, returns the flag's position. The game keeps that position combined by exclusive or (i32.xor, below) with a key at g + 92, and the key is 0 unless mode 4 is on. Then f32.reinterpret_i32 reinterprets a 32-bit integer's raw bits as a 32-bit float without numeric conversion. It has one local variable, local 0:

WebAssembly instructions and stack trace
0  ["i32.const", 0]
1  ["i32.load", 2, 78112]
2  ["local.tee", 0]
3  ["i32.load", 2, 92]
4  ["local.get", 0]
5  ["i32.load", 2, 16]
6  ["i32.xor"]
7  ["f32.reinterpret_i32"]
8  ["end"]
Select code to copy. Scroll horizontally if needed.

local.get 0 pushes local 0's value. local.tee 0 stores the top of the stack in local 0 and leaves it on the stack. i32.xor pops two integers and pushes their bitwise exclusive or.

Question 08a: how many values are on the stack after instruction 4 of r_target_x has run? Commit your answer before reading on:

Terminal command
node lab.mjs predict project 08a YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

One plain object

Your machine keeps all changing data in machine.state.

FieldMeaning
memoryThe guest's bytes; guest means the WebAssembly program running inside this JavaScript interpreter
globalsProgram-wide variables initialized from the listing
stackTemporary values
framesFunction calls in progress
tick, callsCompleted instructions and calls begun

A frame holds the running function in func, its next instruction in at, its local values and its return data.

Later lessons copy, hash and restore this object. structuredClone(machine.state) must capture the whole moment, and machine.state = copy must restore it. State kept in a closure (variables captured inside an outer function rather than stored on machine.state) or another field would be missed.

What isn't state stays outside: the program, and anything you compute once from it, such as where each structured control region ends.

A run starts with begin(name, args), which pushes the first frame and runs nothing. step() runs one instruction. Its event reports { tick, func, at, op, writes }: when it ran, where it ran, the instruction name and its memory writes. invoke(name, args) begins a call and steps until it returns. Checks 08.memory-starts and 08.one-step inspect a new machine and its first step.

Allocate the state you will later restore

In project/machine.mjs, replace the initial-state region inside the constructor. The supplied starter prefix defines PAGE as 65,536 bytes, one WebAssembly 64 KiB memory page:

Initialize mutable stateexamples/machine-checkpoint.mjs · initial-state

Replace initial-state inside the constructor.

    const memory = new Uint8Array(this.program.memory.min * PAGE);
    for (const d of this.program.data) memory.set(d.bytes, d.offset);
    this.state = {
      memory,
      globals: this.program.globals.map((g) => g.init),
      stack: [],
      frames: [],
      tick: 0,
      calls: 0,
      result: undefined,
    };
Select code to copy. Scroll horizontally if needed.

A new typed array starts filled with zero. The data segments then install the compiled program's text at exact byte addresses. Globals copy their initial values; the stacks and counters start empty. The constructor's supplied prefix loads the program, matches each structured control region with its end and binds imports. Those facts do not change while the WebAssembly program runs, so they sit outside state.

Separate starting a call from executing it

Replace the whole call-entry region. It contains the running getter and three methods, including begin. The constructor also builds this.prepared, a Map caching each decoded function entry fn by function index, with fn.locals listing extra local types. Two supplied helpers normalize values at the boundary: coerce(type, v) converts a JavaScript number to the target WebAssembly type (such as v | 0 for i32 or Math.fround(v) for f32), and zeroOf(type) returns 0 or 0n for a local's WebAssembly type. A block is a bounded instruction region, and a loop is a repeating one. Inside enter, labels starts as []; this branch-target stack records where a branch exits each enclosing block or repeats each enclosing loop:

Start, enter and finish a callexamples/machine-checkpoint.mjs · call-entry

Replace the complete call-entry region.

  get running() {
    return this.state.frames.length > 0;
  }

  // Start a call to an export. Nothing runs until step().
  begin(name, args = []) {
    if (this.running)
      throw Error(`Machine: ${name} called while another call is unfinished`);
    const e = this.program.exports.find(
      (x) => x.name === name && x.kind === 'func',
    );
    if (!e) throw Error(`Machine: no exported function named ${name}`);
    const type = this.program.typeOf(e.index);
    if (args.length !== type.params.length)
      throw Error(
        `Machine: ${name} takes ${type.params.length} arguments, got ${args.length}`,
      );
    this.state.calls++;
    this.state.result = undefined;
    this.enter(
      e.index,
      args.map((a, i) => coerce(type.params[i], a)),
    );
  }

  // Run a whole export call and return its result.
  invoke(name, args = []) {
    this.begin(name, args);
    while (this.running) this.step();
    return this.state.result;
  }

  enter(index, args) {
    const fn = this.prepared.get(index);
    const locals = [...args, ...fn.locals.map(zeroOf)];
    this.state.frames.push({
      func: index,
      at: 0,
      locals,
      base: this.state.stack.length,
      labels: [],
    });
  }
Select code to copy. Scroll horizontally if needed.

begin checks the export and argument count before entering the call. enter appends a frame whose base remembers the caller's stack height. Arguments lead the locals; declared locals follow, initialized to zero. No instruction has executed yet. invoke is only a convenience loop over the same step that the debugger will use.

Trace begin('r_px'): one frame is added, its next instruction is zero, calls increases once and tick stays unchanged. A nested guest call uses enter, not begin: it must not look like a new call from outside.

Execute exactly one instruction

Replace the step-start region at the opening of step. In fn, fn.ops is the flat array of decoded numeric instruction codes matching fn.code for dispatch. The supplied switch starts immediately after its closing region marker; leave it in place.

Capture an instruction boundaryexamples/machine-checkpoint.mjs · step-start

Replace step-start; retain the following switch.

  step() {
    const s = this.state;
    const frame = s.frames[s.frames.length - 1];
    if (!frame)
      throw Error('Machine: no call in progress; use begin(name, args) first');
    const fn = this.prepared.get(frame.func);
    const at = frame.at;
    const ins = fn.code[at];
    const op = fn.ops[at];
    const event = {
      tick: s.tick + 1,
      func: frame.func,
      at,
      op: ins[0],
      writes: [],
    };
    const st = s.stack;
    frame.at = at + 1;
Emphasized lines: 2, 3. Select code to copy. Scroll horizontally if needed.

The event identifies the instruction before it executes. Advance frame.at before dispatch: an ordinary instruction then falls through to its successor, and a branch can replace that next position. The supplied tail of step, after the switch, increments s.tick and returns this event. A trap stops execution because an instruction is invalid, such as division by zero. A trapped instruction throws before that tail and is not counted as completed.

Tour the supplied switch now: i32.const pushes its immediate, local.get reads the current frame and end either closes a label or calls leave. Every access uses the s or frame fetched during this step. Holding a frame from an earlier call to step would break restoration when a debugger replaces the whole state.

Replace return-frame, the leave method below branch:

Return to the callerexamples/machine-checkpoint.mjs · return-frame

Replace return-frame with this leave method.

  leave(frame) {
    const s = this.state;
    const type = this.program.typeOf(frame.func);
    const results = type.results.length
      ? s.stack.slice(s.stack.length - type.results.length)
      : [];
    s.stack.length = frame.base;
    s.frames.pop();
    if (s.frames.length) s.stack.push(...results);
    else s.result = results[0];
  }
Select code to copy. Scroll horizontally if needed.

Save the result before cutting the stack back to frame.base. A nested call puts its result on the caller's stack; the outermost call puts it in state.result. On r_px's last instruction the stack holds its one result. That value survives the cut, the last frame disappears and running becomes false.

At this point the type-in route still cannot run the getter: memory is unfinished, and full-game checks also reach the unfinished branch region. A check now should retain those expected failures rather than suggest you broke the call boundary:

Terminal command
node lab.mjs check project 08 --help-used "followed state and call listings"
Select code to copy. Scroll horizontally if needed.

Blocks, loops and branches

WebAssembly has no jump to an arbitrary position. Code is nested in blocks, and a branch names a block by its depth, where 0 is the innermost block around the branch and 1 the one around that.

InstructionEffect
blockOpens a block; a branch lands after its end
loopOpens a loop; a branch lands after loop so it repeats
br NBranches to depth N
br_if NPops an integer and branches when it is nonzero
endCloses the inner block; the function's last end returns

Your machine needs, for each frame, a stack of open blocks: for each one, where a branch to it goes and how tall the value stack was when it opened. A branch cuts the value stack back to that height. A block that leaves a value, written ["block", "i32"], keeps its top value across the cut. Lob's blocks never do, but the checks test it, so here is one traced, top of the stack on the right:

WebAssembly instructions and stack trace
0  i32.const 7           [7]
1  block i32             [7]        the block opens at height 1
2  i32.const 1           [7, 1]
3  i32.const 2           [7, 1, 2]
4  br 0                  [7, 2]     keep the top value, cut to height 1, push it back
5  i32.const 9                      skipped: the branch went past the block's end
6  end                              skipped too
7  ...                   [7, 2]     the block left 2
Select code to copy. Scroll horizontally if needed.

The branch kept one value because the block leaves one. A plain block keeps none, and a branch to a loop keeps none either.

Here is the loop that starts game_init, function 4, shortened. It clears 12,288 bytes of memory, 8 bytes each time round, using i32.store8 to write one byte to memory. local.get, local.set, and local.tee read a local, write a local, or write a local while keeping the value on the stack. In ['loop', null], null says this loop carries no result value when it ends:

WebAssembly instructions and stack trace
0   ["i32.const", -12288]
1   ["local.set", 2]
2   ["loop", null]
3   ["local.get", 2]
4   ["i32.const", 78112]
5   ["i32.add"]
6   ["i32.const", 0]
7   ["i32.store8", 0, 0]
    ... the same five instructions for the next 7 bytes ...
43  ["local.get", 2]
44  ["i32.const", 8]
45  ["i32.add"]
46  ["local.tee", 2]
47  ["br_if", 0]
48  ["end"]
Select code to copy. Scroll horizontally if needed.

Local 2 starts at -12,288 and goes up by 8 each time round. br_if 0 branches back to instruction 3 while local 2 isn't zero, so the loop ends when local 2 reaches 0.

Question 08b: how many times does br_if 0 branch back to instruction 3? Commit before reading on:

Terminal command
node lab.mjs predict project 08b YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

This loop is why game_init alone runs more than 70,000 instructions before the game draws anything. Check 08.control runs small programs with nested blocks, loops, branches out of several levels and blocks that leave a value.

Implement the branch destination

Replace branch in project/machine.mjs. Each runtime label records label.height (the value-stack length when the block or loop began), label.loop (true for a loop, false for a block), and label.arity (the count of values, 0 or 1, carried across the branch). For both block and loop, label.end stores the branch-target base index (fn.ends[at] for a block, or at for the loop instruction itself), so label.end + 1 lands just after the closing end of a block or back on the first instruction inside a loop:

Jump without losing the enclosing stateexamples/machine-checkpoint.mjs · branch

Replace the branch region.

  branch(frame, depth) {
    const st = this.state.stack;
    // A branch past every open block targets the function body itself: it returns.
    if (depth === frame.labels.length) {
      this.leave(frame);
      return;
    }
    const label = frame.labels[frame.labels.length - 1 - depth];
    const kept = label.arity ? st.slice(st.length - label.arity) : [];
    st.length = label.height;
    st.push(...kept);
    if (label.loop) {
      frame.labels.length -= depth; // keep the loop's own label
      frame.at = label.end + 1; // back to the first instruction inside the loop
    } else {
      frame.labels.length -= depth + 1;
      frame.at = label.end + 1; // just past the block's end
    }
  }
Select code to copy. Scroll horizontally if needed.

Each label records a destination and the stack height to restore. Save a result before shortening the stack.

TargetLabel after branching
LoopKept for the next iteration
BlockRemoved after execution leaves it
Beyond every open labelReturn from the function

Tour prepare near the bottom of the supplied file. It pairs each block or loop with an end, and dispatch sets label.end to that end for a block or to the loop itself. prepare handles code nesting; frame.labels tracks the nesting active now.

Memory: widths, order and writes

Memory is a Uint8Array of 131,072 bytes, because the listing's memory.min is 2 pages of 65,536. It starts as zeros, with each data segment copied in at its offset: Lob's one segment, 281 bytes, at 65,536.

A load or store adds its offset to an address popped from the stack. The address is unsigned. The 32 bits of -4 mean 4,294,967,292, far outside memory, and an access that reaches past the last byte is a trap. A trap stops the program. Throw an Error whose message starts with trap:.

Values are stored little-endian, lowest byte first. i32.store of 300 writes 2C 01 00 00, since 300 is 0x0000012C. Create a DataView (JavaScript's byte-level reader and writer over raw memory) from state.memory when you use it. A view made in the constructor keeps pointing at old memory after machine.state = copy.

OperationBytesValue
i32.load, i32.store432-bit integer
f32.load, f32.store432-bit float
i32.load8_u1Integer from 0 through 255
i32.store8, i32.store161 or 2Low bytes of an integer
i64.store8i64.const value supplied as a BigInt

Every store reports a write in its event, { address, size, before, after }, with before and after as arrays of byte values. Read before from memory before you store. Lesson 10 rebuilds your Lesson 03 watchpoints, and "who last wrote this address", on these writes, so a store that writes the same value it found still reports a write.

Question 08c: an i32.store with offset 0 pops the value 1,000 and then the address 70,000. What is the byte at address 70,001 afterwards? Commit:

Terminal command
node lab.mjs predict project 08c YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Check 08.memory runs loads and stores of every width, offsets, byte order and out-of-bounds traps. 08.writes checks that every store in a run of Lob reports the bytes it wrote, and that nothing else reports a write.

Read the current memory, then report the write

Replace memory, containing both view and store. If an access goes out of bounds, view throws the error returned by the supplied helper trap(message), which halts execution with a WebAssembly runtime error:

Address the restored memoryexamples/machine-checkpoint.mjs · memory

Replace the complete memory region.

  view(base, offset, size) {
    const address = (base >>> 0) + offset;
    const memory = this.state.memory;
    if (address + size > memory.length)
      throw trap(`out of bounds memory access at ${address}`);
    return new DataView(memory.buffer, memory.byteOffset + address, size);
  }

  store(event, base, offset, size, write) {
    const view = this.view(base, offset, size);
    const address = view.byteOffset - this.state.memory.byteOffset;
    const before = Array.from(
      this.state.memory.subarray(address, address + size),
    );
    write(view);
    event.writes.push({
      address,
      size,
      before,
      after: Array.from(this.state.memory.subarray(address, address + size)),
    });
  }
Emphasized lines: 3, 6. Select code to copy. Scroll horizontally if needed.

base >>> 0 changes the reading of its 32 bits, then ordinary addition includes the offset. Do not wrap that sum back to 32 bits: a huge address must trap, not wrap to the beginning of memory. memory.byteOffset matters if the byte array is a view into a larger host buffer, the JavaScript-owned storage behind the guest's memory view. The event's address stays relative to the guest's memory, so store subtracts the host buffer's starting offset again.

before and after are copied arrays, not live views. A later guest write must not rewrite an earlier event's evidence. write(view) is supplied by each opcode case: for example, i32.store pops the value, pops the address, and passes a function that calls setInt32 with the little-endian flag.

All six holes are now filled. Run your file through the same probe as the first win, then the unit's real checks:

Terminal command
node examples/step-getter.mjs project/machine.mjs
# After filling the type-in route's starter from the listings:
node lab.mjs check project 08 --help-used "filled six regions from chapter listings; supplied opcode cases"
# After following the supplied route:
node lab.mjs check project 08 --help-used "supplied Machine checkpoint; followed traces and code tour"
Select code to copy. Scroll horizontally if needed.

Choose the check command matching your route and revise its description to match what you actually did. For AI-assisted changes, identify that assistance rather than claiming you filled the regions from the listings yourself.

The probe should print the earlier four-step trace. All 11 unit checks should pass, including the actual games. If not, follow the named check's first mismatch back to its section; preserve the failure and your explanation before editing. The next sections explain the supplied number and import cases exercised here.

Each check compares one boundary:

CheckBoundary
08.memory-starts, 08.one-stepNew memory and the first game_init steps
08.framesFrames after each call instruction
08.control, 08.memory, 08.numbersSmall programs against Node's engine
08.writesEvery reported store against Node's memory
08.lob-agrees, 08.lob2-agreesResults, getters and memory after every call
08.plain-stateExecution after copied state is restored, including on a new machine
08.speedA long Lob run and its ending memory

Only 08.plain-state assigns machine.state. Every other check runs each machine on from its constructor without replacing its state.

Break a restoration boundary, then repair it

In your project only, make view reuse a memory reference captured during construction. Inside the initial-state region, after the this.state = { ... }; statement and before the // endregion: initial-state line, add this.cachedMemory = this.state.memory;. In view, change const memory = this.state.memory; to const memory = this.cachedMemory;. Leave store as it is.

Question 08f: with this change, how many of unit 08's 11 checks fail? Write in project/report.md which ones you expect to fail and why, then commit the number before you run the check with --help-used describing this prescribed change:

Terminal command
node lab.mjs predict project 08f YOUR_ANSWER
node lab.mjs check project 08 --help-used "prescribed change: view reads memory cached in the constructor"
Select code to copy. Scroll horizontally if needed.

Keep the resulting attempt, and compare the checks that failed with what the lab said after your prediction.

Compare the cached array and machine.state.memory after assigning a structuredClone of the state. They contain equal bytes initially, but are they the same object? Explain why an interpreter can agree with the native engine on an ordinary run yet fail after restoration. Remove the cache, restore the memory lookup and rerun. The repair must preserve the checks, not special-case them. This mutation is guided practice; the new application below asks you to design behavior the walkthrough has not implemented.

Integers and floats

JavaScript stores numbers as 64-bit floats, so the machine must preserve narrower rules.

Guest valueJavaScript rule
i32, a 32-bit integerWrap addition with `0; multiply with Math.imul; read unsigned with >>> 0`
Signed division and remainderBoth trap on zero; only div_s traps on -2,147,483,648 by -1, while rem_s of those gives 0
Shift countUse the low 5 bits, so 33 becomes 1
f32, a 32-bit floatRound every result with Math.fround
f64 used by sin and cosPromote unchanged; demote with Math.fround

For example, f32.add of 0.1 and 0.2 is Math.fround(Math.fround(0.1) + Math.fround(0.2)).

These conversions are easy to get wrong:

Question 08d: what number does f32.convert_i32_u push when it pops -1? Commit:

Terminal command
node lab.mjs predict project 08d YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Check 08.numbers runs these instructions on the cases most likely to go wrong.

Calls and the outside world

call N calls function N. Imports come first, so Lob's functions 0 through 3 are server_round, cos, sin and server_wind. Its own functions start at 4.

Call targetBefore the callAfter the call
Defined functionPop arguments into a new frame's localsPush its result on the caller's stack
Imported functionPop arguments into the matching JavaScript functionPush its result; round an f32 with Math.fround

The caller's at field points after call, where it resumes. Check 08.frames follows game_init calls. Lob asks cos and sin when a shot fires. In mode 1, it asks server_round for each round and server_wind for each airborne game frame. Lesson 09 records those outside answers.

The C stack in the memory figure is that stack of its own, beside your machine's frames. A C variable whose address is taken, such as a small array, can't live in a WebAssembly local, so the compiled code keeps it there. Global 0, which starts at 65,536, is the pointer to its top. Function 6, which writes the status line, keeps number digits there while printing, so every game frame writes a few bytes below 65,536. Lesson 10 counts on this.

The answer key

Node's WebAssembly engine is the answer key. It runs targets/lob.wasm beside your machine with the same calls and outside answers.

After every callCompared evidence
Return valueExact value
Every getterExact value
131,072 memory bytesOne hash

Each machine gets its own makeWorld(seed) from public/world.mjs. Its sin and cos use JavaScript; its server functions use a seed separate from the game's. Try the comparison:

Terminal command
node lab.mjs agree project
node lab.mjs agree project --game lob2 --mode 7
Select code to copy. Scroll horizontally if needed.

A difference names the first call after which the two disagree. Checks 08.lob-agrees and 08.lob2-agrees run several seeds and modes. 08.plain-state copies and restores your state in the middle of a call, and 08.speed times a run of about 900,000 instructions.

Keep the host responsive

Your debugger must eventually let a person pause a guest that takes too long or never returns. Add a budgeted runner in project/run-slice.mjs, which both chapter routes created as a stub. If you chose the original blank-start command, copy starter/run-slice.mjs to that new file first, preserving any file you already wrote. This is required new application: the Machine listings above do not contain the runner, and no finished runner is supplied.

Export synchronous runSlice(machine, budget). The caller has already used machine.begin. A positive safe integer is a whole JavaScript number from 1 through Number.MAX_SAFE_INTEGER, where integer arithmetic remains exact.

CaseRequired result
Budget is not a positive safe integerReject it before changing the machine
Machine is runningCall step() at most budget times; never call invoke or begin
Final instruction uses the last budget slotReturn { executed, stopped: 'returned' }
Machine is already idleReturn { executed: 0, stopped: 'returned' }
Budget ends firstReturn { executed, stopped: 'budget' }
Guest trapsPreserve the exception

Before coding, sketch the order of validation, the idle test, stepping and the final status decision in project/report.md. Work out the exact-boundary case: if the last permitted instruction is end, which status tells the truth? Keep that initial reasoning. Run the unfinished file once, then implement and run again; describe assistance honestly for each attempt:

Terminal command
node examples/check-slice.mjs project --help-used "initial attempt; no runner written"
node examples/check-slice.mjs project --help-used "describe what helped your implementation"
Select code to copy. Scroll horizontally if needed.

The checker snapshots machine.mjs, run-slice.mjs and your report before running.

It testsIt preserves
Invalid input, idle state, resumption, an endless loop and a trapThe exact code and slice-receipt.json under project/attempts/
game_init split into small slicesA comparison with one uninterrupted final state

node lab.mjs status project lists every runner attempt. A failed attempt never replaces an earlier one.

Inspect the endless-loop listing in examples/check-slice.mjs. Explain how the runner can return to its caller while the guest is still running. Then choose a different budget for your own Lob initialization experiment. Report how many slices ran and show that their completed instruction counts add up to the final tick. A pass alone is not your explanation.

The budget has a narrow boundary:

BoundedNot bounded
Guest instructionsTime spent inside an imported JavaScript function

A real interface schedules the next slice after its event loop handles input. As a stretch, build a Run/Pause control and measure several budgets during game_init. Keep scheduling outside Machine so instruction behavior stays unchanged.

The wall

Now measure the wall, the point where copying the whole state on every step stops working. node lab.mjs wall project runs your Lesson 01–07 debugger through public/part-one-vm.mjs. Its execute(program, state) copies all of machine.state with structuredClone, then runs one instruction. Your Lesson 01–07 small machine copied only 8 memory cells per step.

Question 08e: the lab's run is 1,043,331 instructions, and each step copies all 131,072 bytes of memory. How many gigabytes, 10^9 bytes, does one pass over the run copy? Round to a whole number, and commit before you run the lab:

Terminal command
node lab.mjs predict project 08e YOUR_ANSWER
node lab.mjs wall project --part-one project/solution.mjs
# If you began at Lesson 08, use the labelled fallback instead:
node lab.mjs wall project
Select code to copy. Scroll horizontally if needed.

The first command uses the debugger you built in Lessons 01–07. The fallback command is an assisted route for learners who began at Lesson 08. Both write measurements to project/wall.json.

MeasurementHow to read it
Machine timeCost without state copies
Debugger time per stepDivide by machine time to get the slowdown
reverseFind estimateReplays required to find the latest earlier matching byte

Machine timings vary with load, so trust your printed ratio. The README's measured slowdown spans 100 to 800 times. reverseFind compounds that cost: each candidate tick replays from the nearest checkpoint, a saved machine-state copy from which execution can resume. With no checkpoint after tick 0, an answer 1,000 ticks back can require a thousand near-million-step replays, which wall prints as a multi-hour estimate.

Record your numbers and that printed multi-hour reverseFind estimate in project/report.md. Lessons 09 and 10 record once, keep changed-page snapshots, and replay thousands of instructions instead of the whole run.

Optional: your own decoder

If you took Sightline and wrote its wasm.mjs, check it against the supplied listings. This needs that file at that path; without Sightline, skip this section:

Terminal command
# Optional: only if you have Sightline's wasm.mjs at this path
node lab.mjs decoder ../sightline/work/wasm.mjs
Select code to copy. Scroll horizontally if needed.

It compares every instruction of both games, name, immediates and file position, and prints the first difference. When they agree, your decoder produces exactly the listing this course gives you.

09 · Record and replay

Build a recorder that saves numbers a server returns to Lob, an artillery game, then reuses them to find the first changed instruction, one numbered machine operation.

game_init(5, 1) starts Lob with game seed 5 and mode 1, the defence switch that makes the game ask a server for wind. Run the same function calls, requests to run named functions, twice. You might expect identical memory, the game's stored bytes. Memory already differs after the first call: the server's own seed 42, a repeatable starting number, gives wind 1; seed 43 gives -2.

Start

lab.mjs is the course checker. Node runs it here to test lesson 08 code in your project folder:

Terminal command
node lab.mjs check project 08
Select code to copy. Scroll horizontally if needed.

If it fails, create a separate project with the supplied machine: node examples/start-chapter.mjs project9 supplied. Use project9 below.

Choose a recorder start. A route command refuses to replace edited code.

RouteCommandWhat you receive
Type in six marked regionsnode examples/start-recorder.mjs project writestarter/recorder-build.mjs plus supporting code
Inspect working regionsnode examples/start-recorder.mjs project suppliedexamples/recorder-checkpoint.mjs
Start from the APIKeep the stub from node lab.mjs startNo worked regions

Both route commands also create unfinished project/trim.mjs. If you use AI, share one marked region at a time, inspect the answer, and record the help used.

Run the matching recorder baseline:

Terminal command
# Type-in route (write), including AI users before requesting changes:
node lab.mjs check project 09 --help-used "chapter write starter; six regions unfinished"
# Supplied route:
node lab.mjs check project 09 --help-used "supplied recorder checkpoint; initial baseline"
Select code to copy. Scroll horizontally if needed.

The type-in route fails with not written yet; the supplied route passes. Both establish a baseline. Check receipts record your starting route and --help-used note.

Keep each // region: NAME marker. Replace only the text inside its matching pair. For recovery, create a separate supplied project and compare files instead of overwriting your attempt.

What makes a run repeat

Make two recordings of the same calls with two worlds, the outside functions that answer the game. makeWorld(seed) creates those functions from a server seed.

Kept equalChangedFirst result
Game seed 5, mode 1, and all 759 callsWorld seed 42 versus 43Memory differs after game_init

game_init asks server_round(1) for wind. The worlds answer differently. A recording therefore keeps the calls and every imported answer, the value an outside function returned, in order.

Record

record(program, imports, calls) runs the calls on a new machine. Give the machine imports that call the real ones and push each answer onto a list as it passes: { name, args, result }. Keep each call's result, and after each call the memory hash, hashMemory(machine.state.memory) from public/hash.mjs. The whole recording is plain JSON, so it can be saved and read back.

Note every answer as it passes

In project/recorder.mjs, replace the record region:

Record calls, answers, results and hashesexamples/recorder-checkpoint.mjs · record

Replace the record region.

export function record(program, imports, calls) {
  const answers = [];
  const noting = {};
  for (const { name } of program.imports) {
    noting[name] = (...args) => {
      const result = imports[name](...args);
      answers.push({ name, args, result });
      return result;
    };
  }
  const machine = new Machine(program, noting);
  const results = [];
  const hashes = [];
  for (const call of calls) {
    const result = machine.invoke(call.name, call.args);
    results.push(result === undefined ? null : result);
    hashes.push(hashMemory(machine.state.memory));
  }
  return {
    format: 'ttd2-recording-1',
    program: program.name,
    sha256: program.sha256,
    calls: calls.map((call) => ({ name: call.name, args: [...call.args] })),
    results,
    answers,
    hashes,
  };
}
Emphasized lines: 4, 5, 6, 7, 8, 9. Select code to copy. Scroll horizontally if needed.

The machine never sees the real imports. It gets noting, one function per import the listing names, and each of those passes the question to the real import, notes the answer and hands it back unchanged. The world is asked exactly once per question, which check 09.record counts: asking it a second time to note the answer would move the server on and record an answer the game never got. args is the rest parameter, a fresh plain array, so the recording can keep it.

The machine is new, so the run starts from the listing's memory, as every replay will. invoke returns undefined for a function with no result, and JSON has no undefined, so the recording stores null. Each hash is taken after its call returns. The calls are copied, so a caller who later edits its own list doesn't change the recording.

Lob's two-shot recording above holds 759 calls and 277 answers. Question 09a: which of the four imports gave most of those 277 answers? Commit before you make the recording:

Observed output
node lab.mjs predict project 09a YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

The memory hash after every call isn't needed to replay. It costs 64 hex characters per call. In return, a replay can check at every call that its memory still matches the recording, and the last section of this lesson can find a divergence without replaying the original. rr offers a similar check as an option, comparing checksums of a program's memory as it replays.

Check 09.record compares your recording with an independent run that counts every answer, and 09.recording-json round-trips it through JSON.stringify.

Once record works, make the two recordings of the first section, then look inside them:

Observed output
node lab.mjs record project --world 42 --out project/run42.json
node lab.mjs record project --world 43 --out project/run43.json
node examples/show-recording.mjs project/run42.json project/run43.json
Select code to copy. Scroll horizontally if needed.

examples/show-recording.mjs prints the size of each recording, its first call and first answer, and the first call after which the two memory hashes differ:

Two worlds, the same callsexamples/recording-output.txt
project/run42.json: ttd2-recording-1, program lob
  759 calls, 277 answers, 759 hashes
  call 0: game_init(5, 1) returned null; memory hash after it 674f60c95fd31eab...
  answer 0: server_round(1) returned 1
project/run43.json: ttd2-recording-1, program lob
  759 calls, 277 answers, 759 hashes
  call 0: game_init(5, 1) returned null; memory hash after it 405cce2ea030c094...
  answer 0: server_round(1) returned -2
First call whose memory hashes differ: call 0, game_init(5, 1)
Select code to copy. Scroll horizontally if needed.

The calls are the same and the first answer is not, so the hashes part after call 0. That is the claim of the first section, read from your own recordings.

Replay

replay(program, recording) runs the recording's calls on a new machine whose imports answer from the recording, in order, without any world. Keep a position in the answers list. When the game calls an import, the next recorded answer must be for the same import with the same arguments. Return its result and move on.

If the next answer does not match, replay has left its recording. Throw an error with this divergence value:

FieldMeaning
tickInstructions finished before the import's call instruction
callIndex in recording.calls
reasonPlain account of the mismatch

The call instruction's event would report tick + 1. With check: true, a changed call result or ending memory hash is also a divergence.

Answer from the recording, or refuse

Replace the recorded-imports region. It builds the imports a replay gives its machine:

Imports that answer from a recordingexamples/recorder-checkpoint.mjs · recorded-imports

Replace the recorded-imports region.

export function recordedImports(program, recording, machineOf, start = 0) {
  let next = start;
  const imports = {};
  for (const { name } of program.imports) {
    imports[name] = (...args) => {
      const answer = recording.answers[next];
      const state = machineOf().state;
      const where = { tick: state.tick, call: state.calls - 1 };
      const asked = `${name}(${args.join(', ')})`;
      if (!answer)
        throw new ReplayDivergence({
          ...where,
          reason: `the program asked ${asked} after the recording's last answer`,
        });
      if (
        answer.name !== name ||
        answer.args.length !== args.length ||
        answer.args.some((value, i) => !Object.is(value, args[i]))
      )
        throw new ReplayDivergence({
          ...where,
          reason: `the program asked ${asked}, the recording holds ${answer.name}(${answer.args.join(', ')})`,
        });
      next++;
      return answer.result;
    };
  }
  return { imports, position: () => next };
}
Select code to copy. Scroll horizontally if needed.

next is the position in the answer list. It belongs to this replay, not the game, so restoring game state must not move it.

NameRole
nextIndex of the next recorded answer
position()Reports that index
startBegins answering partway through the recording

The imports have to exist before the machine does, because the Machine's constructor takes them. So they receive machineOf, a function that returns the machine once it has been made, and read the machine's state only when the game asks. An import runs in the middle of the call instruction's step. Lesson 08's Machine adds one to state.tick only after an instruction's work is done, so at that moment state.tick is the number of instructions finished before the call instruction, the tick the contract asks for. A machine that counts the tick before running the instruction makes every such tick one too high, and check 09.replay-questions says so. begin has already counted the call into the game, so its index is state.calls - 1.

Object.is compares each argument exactly, so a sin asked of an angle one part in 2^40 away from the recorded one is still a different question. Check 09.replay-questions makes that edit, among others.

Run the calls and compare

Replace the replay region:

Replay without a worldexamples/recorder-checkpoint.mjs · replay

Replace the replay region.

export function replay(program, recording, { check = true } = {}) {
  let machine;
  const answered = recordedImports(program, recording, () => machine);
  machine = new Machine(program, answered.imports);
  const results = [];
  const hashes = [];
  recording.calls.forEach((call, k) => {
    const value = machine.invoke(call.name, call.args);
    const result = value === undefined ? null : value;
    const hash = hashMemory(machine.state.memory);
    results.push(result);
    hashes.push(hash);
    const where = { tick: machine.state.tick, call: k };
    if (check && !Object.is(result, recording.results[k]))
      throw new ReplayDivergence({
        ...where,
        reason: `call ${k} returned ${result}, the recording says ${recording.results[k]}`,
      });
    if (check && hash !== recording.hashes[k])
      throw new ReplayDivergence({
        ...where,
        reason: `memory after call ${k} differs from the recording`,
      });
  });
  return { machine, results, hashes };
}
Select code to copy. Scroll horizontally if needed.

machine is declared before the imports and assigned after, so the closure given to recordedImports can return it.

DivergenceReported tick
No recorded answer matchesThe import's call instruction
Result or ending hash differsThe tick when the outer call returned

With { check: false }, replay still refuses an unanswerable question but continues past a wrong result or hash. It never changes recording, since lesson 10 reuses one recording many times.

Tour learnerRecorder in lab.mjs now. Before it imports your recorder.mjs, it wraps Machine.prototype.step from your machine.mjs with a counter, and the checks do the same. That counter is how every instruction count in this lesson is measured, so your recorder must make its machines from the Machine it imports from ./machine.mjs and run every instruction through step. invoke does, because it is a loop over step.

Try it on a recording with one answer's argument changed. Answers and calls are numbered from 0. In the recording above, the first cos answer is answer 1. Change its argument from 0.8028514385223389 to 0.8128514385223389 and replay the copy:

Observed output
node lab.mjs tamper project/run42.json --answer 1 --arg 0.01 --out project/edited.json
node lab.mjs replay project project/edited.json
Select code to copy. Scroll horizontally if needed.
A replay refuses a question it can't answerexamples/replay-output.txt
Answer 1 (cos) now says it was asked cos(0.8128514385223389), not cos(0.8028514385223389).
Wrote project/edited.json. Its hashes are still the original's.
The replay left its recording at tick 88494, call 19: the program asked cos(0.8028514385223389), the recording holds cos(0.8128514385223389)
Select code to copy. Scroll horizontally if needed.

The replay stops at call 19, the key press that fires the first shot, at tick 88,494. The game asks for the cosine of the barrel's angle, and the recording holds the cosine of another angle. node lab.mjs replay project project/run42.json replays the untouched recording to its end.

Tour tamperCmd in lab.mjs too. It changes one answer or one call in a copy and writes it out with the original's hashes untouched, which is why the replay above could compare every call with what the untampered run did.

Check 09.replay replays recordings of Lob and Lob II with no world at all. 09.replay-questions edits recordings and expects your error at the right tick and call, and 09.replay-check changes a recorded result or hash and expects a divergence only with check: true.

Finding where a tampered replay first differs

tampered is a copy of a recording with one answer changed, and its hashes are still the original's. After which tick does its replay first have different memory from the original's?

Observed output
node lab.mjs tamper project/run42.json --answer 12 --add 0.25 --out project/tampered.json
Select code to copy. Scroll horizontally if needed.

Answer 12 is the tenth server_wind answer, the wind during one game frame of the first shot's flight. Changing it changes that game frame's acceleration, and memory differs from the moment the shell's new position is stored.

The only test you have is whole-state equality, where two memories are the same if their hashes are the same. You can only compare hashes at moments you choose, not ask "which instruction made this hash different?" That is the setting for bisection. Keep two moments, one where the memories are known equal and one where they are known different, test the moment halfway between, and keep the half where they still change from equal to different.

Running both replays from tick 0 for every halfway test would cost two whole runs per test. Recorded hashes give the search a shorter route.

StageWorkEvidence kept
Find call kReplay the changed recording once and compare each ending hash with the originalA copied state from the start of the first changed call
Search call kStart two machines from that state, using each answer listThe first instruction whose memory differs

Inside call k, a bisection test runs each machine to a chosen halfway tick and compares hashes. Each result keeps the half that still crosses from equal to different. A side-by-side search instead steps both machines together and compares bytes after every write. It costs twice the changed instruction's offset, but still works if memory later becomes equal again.

Step 1 on the tampered recording: calls 0 to 28 end with the same memory hash as the original's, call 29 is the first that differs, and the scan stops there without replaying the rest of the 759 calls. Step 2 searches only call 29, 796 instructions from tick 96,469, where memory is still equal, to tick 97,265, where it differs.

For the tampered recording above, step 1 stops at call 29, a game frame of 796 instructions starting at tick 96,469, and keeps the state saved at that tick for step 2.

Inside one call, stepping side by side is the cheaper of the two, and either meets the checks. Bisection wins where only whole states can be compared at chosen moments. Step 1 compares whole states too, since one side exists only as recorded hashes, but every call's hash is already on hand, so it scans calls in order and stops at the first mismatch; so too is any test you can run only at chosen moments, such as comparing two debugging sessions that are too slow to step together. Bisection also assumes a difference, once made, lasts to the end of the call, and the checks' tampers do.

Question 09b: bisection over the 796 instructions of call 29 starts knowing memory is equal after 0 of them and different after all 796. Each test halves the interval. How many tests does it take, at most, until the two ends are one instruction apart? Commit:

Observed output
node lab.mjs predict project 09b YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Find the call from the recorded hashes

Step 1 goes in the find-call region:

Replay once, saving each call's starting stateexamples/recorder-checkpoint.mjs · find-call

Replace the find-call region.

export function firstDivergence(program, original, tampered) {
  let machine;
  const answered = recordedImports(program, tampered, () => machine);
  machine = new Machine(program, answered.imports);
  for (let k = 0; k < tampered.calls.length; k++) {
    const start = globalThis.structuredClone(machine.state);
    const answerAt = answered.position();
    let left = false;
    try {
      machine.invoke(tampered.calls[k].name, tampered.calls[k].args);
    } catch (error) {
      if (!(error instanceof ReplayDivergence)) throw error;
      left = true;
    }
    const same =
      !left && hashMemory(machine.state.memory) === original.hashes[k];
    if (same) continue;
    return bisectCall(program, original, tampered, k, start, answerAt);
  }
  return null;
}
Emphasized lines: 6, 7. Select code to copy. Scroll horizontally if needed.

Only the tampered recording is replayed. The original takes part through its hashes alone, which is why this loop costs one replay up to the call where the two part, not two. Copying the state before every call costs memory and time, but it runs no instructions, so the counter doesn't see it. answerAt is the answer position at the start of the call: the search inside the call has to answer the same questions from the same place in both recordings.

A tampered replay can also ask a question its recording doesn't hold, a cos of an angle the tamper changed, for example. That counts as a call that ends different. A key the game ignores leaves the hash equal, so the loop goes on, and a tamper that never changes memory reaches the end and returns null.

Run one call from a saved state

Replace the run-from region:

Restore, begin and stop after a limitexamples/recorder-checkpoint.mjs · run-from

Replace the run-from region.

function runFrom(program, recording, k, start, answerAt, limit) {
  let machine;
  const answered = recordedImports(program, recording, () => machine, answerAt);
  machine = new Machine(program, answered.imports);
  machine.state = globalThis.structuredClone(start);
  machine.begin(recording.calls[k].name, recording.calls[k].args);
  let ran = 0;
  try {
    while (machine.running && ran < limit) {
      machine.step();
      ran++;
    }
  } catch (error) {
    if (!(error instanceof ReplayDivergence)) throw error;
    return { machine, ran, left: true };
  }
  return { machine, ran, left: false };
}
Emphasized lines: 5. Select code to copy. Scroll horizontally if needed.

Because the machine keeps everything in machine.state, as lesson 08 required, assigning a copy puts a new machine at the exact start of call k. The copy matters again here, because each test runs from the same saved state and must not change it for the next one. begin starts the call and step runs at most limit instructions of it. ran counts instructions that finished, so a question the recording can't answer stops the run with left set and ran short of the limit.

Bisect inside the call

Replace the bisect region:

Keep one end equal and the other differentexamples/recorder-checkpoint.mjs · bisect

Replace the bisect region.

function bisectCall(program, original, tampered, k, start, answerAt) {
  const run = (recording, limit) =>
    runFrom(program, recording, k, start, answerAt, limit);
  const a = run(original, Infinity);
  const b = run(tampered, Infinity);
  const differs = (t) => {
    const x = run(original, t);
    const y = run(tampered, t);
    if (y.left && y.ran < t) return true;
    return (
      hashMemory(x.machine.state.memory) !== hashMemory(y.machine.state.memory)
    );
  };
  let lo = 0; // memory is equal after lo instructions of call k
  let hi = Math.max(a.ran, b.left ? b.ran + 1 : b.ran); // and differs after hi
  while (hi - lo > 1) {
    const mid = (lo + hi) >> 1;
    if (differs(mid)) hi = mid;
    else lo = mid;
  }
  return start.tick + hi;
}
Emphasized lines: 14, 15, 16, 17, 18, 19. Select code to copy. Scroll horizontally if needed.

The two first runs measure each version of the call. Memory is equal after 0 instructions, because both start from the same state, and different once both versions have finished, because that is how step 1 chose this call. A tampered run that left its recording counts as different from the instruction that asked, which is why hi is then one more than the instructions it finished. differs(t) runs both versions t instructions from the saved state, and each loop keeps the half whose ends are still equal and different. When the ends are one apart, hi instructions into the call is the first moment memory differs, and the instruction that made it so has the tick start.tick + hi, the tick its own event reports.

Run the search on the tamper above:

Observed output
node lab.mjs diverge project project/run42.json project/tampered.json
Select code to copy. Scroll horizontally if needed.
The search and what it ranexamples/diverge-output.txt
Memory first differs after tick 96568.
Your firstDivergence ran 101431 instructions.
Select code to copy. Scroll horizontally if needed.
Bisection inside call 29, one row per test: t = 398, 199 and 99 differ, then t = 49, 74, 86, 92, 95, 97 and 98 are equal, so the interval in question halves each time until its ends are 98 and 99. Memory first differs 99 instructions into the call, at tick 96,469 + 99 = 96,568.

Each test halves the interval still in question. Your firstDivergence returns 96,568, or null when the two replays never differ, for example when an answer is "changed" to the value it already had.

The lab prints how many instructions your search ran. The worked solution finds the call from the hashes and then bisects inside it, and runs 101,431 for this case: 97,265 to replay the tampered recording up to the end of call 29, and the rest to run both versions of call 29 and bisect inside it. Stepping side by side inside the call runs fewer, because it costs only twice the distance to the divergence. Bisecting from tick 0 instead, replaying both recordings from the start for every test, takes about 20 tests over the run's 652,927 instructions, and each test replays both recordings up to the tick it tests.

The checks separate search from recording:

CheckEvidence
09.divergenceKnown first changed ticks match
09.divergence-noneChanges that leave memory equal return null
09.divergence-budgetLate changes match first, then stay inside the instruction limit
09.record, 09.recording-json, 09.replay, 09.replay-questions, 09.replay-checkRecord and replay behavior without calling firstDivergence

All six regions are filled. Run the unit's checks, describing what you did:

Terminal command
# After filling the type-in route's starter from the listings:
node lab.mjs check project 09 --help-used "filled six regions from chapter listings"
# After following the supplied route:
node lab.mjs check project 09 --help-used "supplied recorder checkpoint; followed the explanations and tours"
Select code to copy. Scroll horizontally if needed.

All 8 checks should pass. If one fails, its first mismatch names the section to reread. Keep the failing attempt and your explanation before you edit.

Break the saved state, then repair it

In your project only, change the first line inside the loop of find-call so that it keeps the machine's own state instead of a copy:

JavaScript
const start = machine.state;
Select code to copy. Scroll horizontally if needed.

Question 09d: with this change, how many of the eight checks fail? Before you run anything, write in project/report.md which ones you expect to fail and why, then commit the number. Then run the check with --help-used describing this prescribed change, and run the search again:

Terminal command
node lab.mjs predict project 09d YOUR_ANSWER
node lab.mjs check project 09 --help-used "prescribed change: find-call keeps machine.state without a copy"
node lab.mjs diverge project project/run42.json project/tampered.json
Select code to copy. Scroll horizontally if needed.

Compare the checks that failed with what the lab said after your prediction. Compare the tick diverge prints with 96,568 and with the length of call 29. Explain the difference: what does start hold by the time bisectCall reads start.tick, and which state does runFrom restore? Which of the checks only record and replay, and what did they report? Restore the copy, rerun the check and keep both attempts. This change is guided practice; the new application below asks for behavior none of these listings implements.

A different tamper

Question 09c: in project/run42.json, call 12 is a key press, the last of eleven presses of up (key 3). Up and down (key 4) change the power, and N (key 6) starts a new round. API.md lists every key under "public/sessions.mjs". Change call 12 to down with node lab.mjs tamper project/run42.json --call 12 --key 4 --out project/key.json, then predict whether firstDivergence will find a tick inside call 12 or later. Answer inside or later, and commit before you run diverge:

Observed output
node lab.mjs predict project 09c YOUR_ANSWER
node lab.mjs diverge project project/run42.json project/key.json
Select code to copy. Scroll horizontally if needed.

Use it on a new case: trim a recording

A short recording that still shows a bug costs less to replay. Write trimRecording(program, recording, n) in project/trim.mjs. If needed, copy starter/trim.mjs there. No finished version is supplied.

Input or resultContract
nAccept an integer from 0 through the call count; reject anything else before stepping
Returned recordingKeep the first n calls, results and hashes, plus exactly their imported answers
WorkRun no more instructions than those calls take
OwnershipLeave the input unchanged and share no nested arrays or objects
ImportsUse only ./recorder.mjs and ./machine.mjs

The returned value must match a fresh record call on the same prefix. You may assume the input recording replays without a divergence.

Before you write code, answer two questions in project/report.md. Why can't the answers be cut by counting calls, or by looking at the recording alone? If call n - 1 is a game frame with a shell in the air, which side of the cut does its server_wind answer fall on, and how does your code know? Keep that first reasoning. Then run the checker on the unfinished file, implement, and run it again, describing assistance honestly each time:

Terminal command
node examples/check-trim.mjs project --help-used "initial attempt; nothing written"
node examples/check-trim.mjs project --help-used "describe what helped your implementation"
Select code to copy. Scroll horizontally if needed.

The checker preserves each attempt before running it.

Saved under project/attempts/Compared during the run
Machine, recorder, trim code, project data, report and trim-receipt.jsonYour trim against Node recordings of shorter Lob and Lob II call lists
Every earlier attempt, including failuresInstruction count and replay of the trimmed result

node lab.mjs status project lists these under "New-application attempts".

As a stretch, trim from the other end as well: a recording that starts at call m instead of call 0 needs the machine's state at the start of call m, not only the calls after it. Lesson 10 keeps those states.

Keep the working tool

project/recorder.mjs now records, replays and finds where two runs part, and the lab's record, replay and diverge commands run it. Its end-of-unit checkpoint is examples/recorder-checkpoint.mjs; recover from it with a new project, as in "Start", never by copying it over your file.

Write the tick your search found and the instructions it ran in project/report.md, beside the numbers from lesson 08's wall. Lesson 10 keeps snapshots during a replay so that any moment, not only the start of a call, can be reached by replaying a few thousand instructions.

10 · Run backwards

Build debugger commands, which pause or rewind the game, that move to an earlier position, the state after a counted instruction, while copying only changed memory pages, fixed-size blocks of stored bytes.

In Lob, an artillery game, stand at position 96,569 and step back to 96,568. You might expect one instruction of work. The debugger restores the nearest snapshot, a saved state at 96,000, then replays, runs again, 568 instructions. This happens inside game_tick, the function that advances one displayed game update.

Start

Run the checks for the machine and recorder you built in lessons 08 and 09:

Terminal command
node lab.mjs check project 08
node lab.mjs check project 09
Select code to copy. Scroll horizontally if needed.

If either fails, make a supplied project and record the same run:

Terminal command
node examples/start-chapter.mjs project10 supplied
node examples/start-recorder.mjs project10 supplied
node lab.mjs record project10 --world 42 --out project10/run42.json
Select code to copy. Scroll horizontally if needed.

Use project10 below if you took that recovery route.

Choose how to create project/debugger.mjs:

RouteCommandWhat you receive
Type innode examples/start-debugger.mjs project writeEight unfinished regions with support code
Inspect working codenode examples/start-debugger.mjs project suppliedThe working checkpoint to test and break
Build from the contractNo setup commandThe stub from lab.mjs start; use API.md

The setup command refuses to replace an edited file. Both setup routes also create unfinished project/reverse-find.mjs. The eight regions are constructor, first-pass, capture, restore, move, stops, search-back and last-write.

Run the first check with the description matching where you started:

Terminal command
# Type-in route (write), including AI users before requesting changes:
node lab.mjs check project 10 --help-used "chapter write starter; eight regions unfinished"
# Supplied route:
node lab.mjs check project 10 --help-used "supplied debugger checkpoint; initial baseline"
Select code to copy. Scroll horizontally if needed.

The route command records write or supplied in PROJECT.json, and every check receipt keeps it as unit10_start_route. That says where you began, not who wrote your current code; keep using --help-used to say what helped each attempt. The type-in route fails all nine checks with not written yet, and the supplied route passes them. Either result is a baseline, not evidence of understanding.

Keep the // region: NAME and // endregion: NAME markers. A listing replaces everything between its matching pair, including the unfinished methods there. The listings omit the marker lines. To recover later without losing edits, run the two supplied setup commands above from the course folder with project-recovery in place of project10, then run node examples/start-debugger.mjs project-recovery supplied and compare its debugger.mjs with yours. Don't copy the checkpoint over your attempt.

Positions

The debugger works on one recording. A position is a moment between instructions. Position t is the state after t instructions of the run, counted across all its calls, so position 0 is before game_init runs anything and position end is after the last call returns. Between two calls no function is running. The next instruction is the first one of the next call, and where() names it with that call's index.

The debugger answers each question at its current position:

MethodResult
seek(t)Move to position t
step(n) / stepBack(n)Move forward or backward by n instructions
continue(stops) / continueBack(stops)Find the nearest later or earlier stop
read(address, size)Return bytes from memory
state()Return a separate copy of the whole machine state

debug.mjs uses state() to call game getters. Check 10.state compares its memory and frames with a replay from tick 0.

Tour the supplied nextInstruction and where in your debugger.mjs now. During a call, the instruction that runs next is the innermost frame's at. Between calls the machine has no frames, so nextInstruction looks up the function the next call starts in, which the constructor keeps in this.callFunc, and answers its instruction 0. Breakpoints use the same method, which is how a breakpoint on a call's first instruction fires at the position between calls.

Every check this lesson names is one of unit 10's checks, and one command runs them all. Describe what helped each attempt, as in lessons 08 and 09:

Terminal command
node lab.mjs check project 10 --help-used "describe what helped"
Select code to copy. Scroll horizontally if needed.

Until you write your Debugger, its checks fail with "not written yet". Run the command again whenever you finish a region.

The obvious way, and its cost

The simplest debugger replays the recording from tick 0 every time it moves. seek(t) then costs t instructions, and so does every stepBack. On lesson 09's recording, 652,927 instructions long, stepping back once from near the end replays more than 650,000 instructions to move one.

Your Lesson 05 debugger replayed from the nearest checkpoint instead of from 0. Each checkpoint copied all 131,072 memory bytes.

Backward designWork to move one instruction near the end
Replay from tick 0More than 650,000 instructions
Restore a full checkpointShort replay, large saved state
Share unchanged pagesShort replay, small saved state

Snapshots that share pages

Cut memory into 4,096-byte pages. Lob's 131,072 bytes become 32 pages. These are debugger pages, not WebAssembly's 64 KiB pages. A snapshot keeps one page object for each part of memory.

State partSnapshot rule
Page written since the prior snapshotCopy its bytes
Page not writtenReuse the prior page object
Frames, stack, globals and countersCopy with structuredClone
Used-answer countSave it so imports resume at the right answer

Take a snapshot every K instructions. Each write event gives an address and size. Mark every page from Math.floor(address / 4096) through the page holding the last written byte.

One machine, answered from the recording

In project/debugger.mjs, replace the constructor region. It holds the constructor and the tick getter:

Open a recordingexamples/debugger-checkpoint.mjs · constructor

Replace the constructor region.

  constructor(
    program,
    recording,
    { every = 1000, pageSize = 4096, check = true } = {},
  ) {
    whole(every, 'every', 1);
    whole(pageSize, 'pageSize', 1);
    this.program = program;
    this.recording = recording;
    this.every = every;
    this.pageSize = pageSize;
    // The function each call starts in: what runs next between calls.
    this.callFunc = recording.calls.map(
      (call) =>
        program.exports.find((e) => e.kind === 'func' && e.name === call.name)
          .index,
    );
    // One machine for the whole session. Its imports ask this.answers, which
    // restore() replaces, so a replay answers from the right place.
    const imports = {};
    for (const { name } of program.imports)
      imports[name] = (...args) => this.answers.imports[name](...args);
    this.machine = new Machine(program, imports);
    this.answers = recordedImports(program, recording, () => this.machine);
    this.snapshots = [];
    this.end = this.firstPass(check);
    this.restore(this.snapshots[0]);
  }

  get tick() {
    return this.machine.state.tick;
  }
Select code to copy. Scroll horizontally if needed.

The Debugger keeps one machine for the whole session. Its imports don't answer from a fixed place in the recording: each one asks this.answers, which restore replaces whenever the machine jumps to a snapshot. That is lesson 09's recordedImports, started at the answer position the snapshot saved. The constructor replays the whole recording once, in firstPass, and then puts the machine back at the first snapshot, position 0. Opening a recording therefore costs one replay of the run, inside the checks' limit of about two.

this.callFunc turns each call's export name into its function index once, for nextInstruction. The options default to a snapshot every 1,000 instructions and pages of 4,096 bytes.

Mark written pages during the first pass

Replace the first-pass region:

Replay once, keeping a snapshot every `every` instructionsexamples/debugger-checkpoint.mjs · first-pass

Replace the first-pass region.

  firstPass(check) {
    const m = this.machine;
    const written = new Uint8Array(
      Math.ceil(m.state.memory.length / this.pageSize),
    );
    this.snapshots.push(this.capture());
    for (let k = 0; k < this.recording.calls.length; k++) {
      do {
        const event = this.forward();
        for (const w of event.writes) {
          const first = Math.floor(w.address / this.pageSize);
          const last = Math.floor((w.address + w.size - 1) / this.pageSize);
          for (let p = first; p <= last; p++) written[p] = 1;
        }
        if (m.state.tick % this.every === 0) {
          this.snapshots.push(this.capture(this.snapshots.at(-1), written));
          written.fill(0);
        }
      } while (m.running);
      if (check) this.checkCall(k);
    }
    return m.state.tick;
  }
Select code to copy. Scroll horizontally if needed.

written has one entry per page, set to 1 when any instruction writes that page and cleared after each snapshot. A write's first and last byte can sit on two pages, so the loop marks every page from the first to the last. A snapshot is taken whenever the tick reaches a multiple of every, which puts snapshot i at tick i * every; moveTo and the backward search rely on that. After each call, checkCall compares memory with the recording's hash, as replay did in lesson 09, so a debugger never answers questions about a run that isn't the recorded one.

Question 10a: in Lob, seed 3, mode 0 (no defences), the first game frame after game_init runs 827 instructions. How many of the 32 pages of 4,096 bytes does it write to? Commit before reading on:

Observed output
node lab.mjs predict project 10a YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Share what wasn't written

Replace the capture region:

Copy only the written pagesexamples/debugger-checkpoint.mjs · capture

Replace the capture region.

  capture(previous = null, written = null) {
    const { memory, ...rest } = this.machine.state;
    const pages = [];
    for (let p = 0; p * this.pageSize < memory.length; p++) {
      const start = p * this.pageSize;
      pages.push(
        previous && !written[p]
          ? previous.pages[p]
          : memory.slice(start, start + this.pageSize),
      );
    }
    return {
      tick: rest.tick,
      pages,
      state: globalThis.structuredClone(rest),
      answered: this.answers.position(),
    };
  }
Select code to copy. Scroll horizontally if needed.

Each page is either the previous snapshot's page object, when nothing wrote it, or a fresh slice, which copies those bytes. The rest of the state goes through structuredClone without its memory, and answered saves the position in the recording's answers. Called with no previous snapshot, capture copies every page; the first snapshot and lastWrite call it that way.

Restoring a snapshot means building a Uint8Array of 131,072 bytes from its pages, copying the small state back, and pointing the machine at both. Never let the machine write into a snapshot's pages. Copy them into a fresh memory first, or the next replay would write into the snapshot's pages, and a later restore of it would give different memory.

Restore without sharing

Replace the restore region:

Rebuild memory and answers from a snapshotexamples/debugger-checkpoint.mjs · restore

Replace the restore region.

  restore(snapshot) {
    const bytes = snapshot.pages.reduce((n, page) => n + page.length, 0);
    const memory = new Uint8Array(bytes);
    snapshot.pages.forEach((page, p) => memory.set(page, p * this.pageSize));
    this.machine.state = {
      ...globalThis.structuredClone(snapshot.state),
      memory,
    };
    this.answers = recordedImports(
      this.program,
      this.recording,
      () => this.machine,
      snapshot.answered,
    );
  }
Select code to copy. Scroll horizontally if needed.

memory.set copies pages, so replay cannot mutate the snapshot. structuredClone protects its smaller state. Restoring this.answers resumes at the saved answer.

Check 10.page-sharing takes your snapshots after a first pass and counts the bytes they hold, counting a page shared by several snapshots once. It also checks that each snapshot's pages, laid end to end, are exactly the memory at its tick.

Going back

continue(stops) and continueBack(stops) take stops = { breakpoints: [{ func, at }], watches: [{ address, size }] } and return { reason, tick }. A breakpoint { func, at } fires at a position whose next instruction is that one, so the debugger stops before it runs. A watch fires right after an instruction that changed one of its bytes, and the debugger stops after the write. Both continue and continueBack move at least one instruction, so from a position where a breakpoint fires, continue finds the next time it fires, not this one.

With snapshots, every backward move restores saved state and replays forward:

MoveRestore and replay rule
stepBack(n) from tRestore at or before t - n; replay to t - n
seek(t)Restore at or before t; replay to t
continueBack(stops)Replay earlier stretches, the instructions between snapshots; keep the latest stop in the first matching stretch
lastWrite(address)Search stretches for the latest instruction that wrote the byte, changed or not

Question 10b: your snapshots are every 1,000 instructions, at ticks 0, 1,000, 2,000 and so on. You stand at position 96,568 and call stepBack(1). How many instructions does the debugger replay? Commit:

Observed output
node lab.mjs predict project 10b YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Shared pages buy one more saving. If the page holding a watched byte is the very same object in two neighbouring snapshots, no instruction wrote that page between them, so the stretch between them can't hold a match and doesn't need to be replayed. For a byte on a page nothing has written for a long time, lastWrite then skips most of the run. How often that happens depends on the page size. A page is skipped only if none of its bytes was written, so smaller pages are skipped more often, and each snapshot then holds more page objects.

Check 10.lob2 asks the same kinds of question about a Lob II recording, so nothing may depend on Lob's own addresses.

Move by restoring and replaying

Replace the move region:

seek, step and stepBackexamples/debugger-checkpoint.mjs · move

Replace the move region.

  forward() {
    const m = this.machine;
    if (!m.running) {
      const call = this.recording.calls[m.state.calls];
      m.begin(call.name, call.args);
    }
    return m.step();
  }

  moveTo(t) {
    const snapshot = this.snapshots[Math.floor(t / this.every)];
    if (this.tick > t || this.tick < snapshot.tick) this.restore(snapshot);
    while (this.tick < t) this.forward();
  }

  seek(tick) {
    if (!Number.isInteger(tick) || tick < 0 || tick > this.end)
      throw RangeError(`seek: ${tick} is not a position from 0 to ${this.end}`);
    this.moveTo(tick);
    return this.tick;
  }

  step(n = 1) {
    this.moveTo(Math.min(this.end, this.tick + whole(n, 'step')));
    return this.tick;
  }

  stepBack(n = 1) {
    this.moveTo(Math.max(0, this.tick - whole(n, 'stepBack')));
    return this.tick;
  }
Select code to copy. Scroll horizontally if needed.

forward runs the run's next instruction. Between calls it first begins the next call, which is why a position between calls has no frames: the call starts only when its first instruction runs. moveTo picks the last snapshot at or before the target and restores it only when it has to: when the machine has passed the target, or hasn't reached that snapshot yet. Moving forward a little from where the machine stands replays only the distance. seek refuses a position outside 0 to end, step and stepBack clamp at end and 0, and all three go through moveTo.

With forward written, the constructor's first pass can run, so you can now look at the snapshots your debugger keeps for lesson 09's recording:

Observed output
node examples/show-snapshots.mjs project project/run42.json
Select code to copy. Scroll horizontally if needed.
What the snapshots holdexamples/snapshots-output.txt
project/run42.json: 652927 instructions, 653 snapshots
each snapshot: 32 pages of 4096 bytes, 131072 bytes in all
full copies would hold 85590016 bytes; these hold 7557120 (8.83%)
pages copied by a snapshot after the first: at most 3, on average 2.78
the last snapshot, page by page, holds the copy made by snapshot:
  pages 0-7: 0 0 0 0 0 0 0 0
  pages 8-15: 0 0 0 0 0 0 0 652
  pages 16-23: 652 652 68 70 0 0 0 0
  pages 24-31: 0 0 0 0 0 0 0 0
Select code to copy. Scroll horizontally if needed.
A grid of snapshots, one row per snapshot labelled by its tick, one column per page, 0 to 31. Snapshot 0 copies every page. Up to tick 70,000 the snapshots copy only pages among 16 to 19, which game_init's loop clears; from tick 75,000 every snapshot copies pages 15, 16 and 17 and shares the rest. The last snapshot, at 652,000, shares 27 pages with snapshot 0.

The rows are snapshot 0, each snapshot that copies a set of pages no earlier one copied, and the last. A filled page is a copy this snapshot made; a pale one is an earlier snapshot's object, shared. Pages 15 to 17, copied on every game frame, hold the C stack, the game's state and the status line from lesson 08's memory figure.

Stop before or after

Replace the stops region:

Test the position the machine has reachedexamples/debugger-checkpoint.mjs · stops

Replace the stops region.

  stopHere({ breakpoints = [], watches = [] }, event) {
    if (event && event.writes.some((w) => changesWatched(w, watches)))
      return 'watchpoint';
    const next = this.nextInstruction();
    if (
      next &&
      breakpoints.some((b) => b.func === next.func && b.at === next.at)
    )
      return 'breakpoint';
    return null;
  }

  continue(stops = {}) {
    while (this.tick < this.end) {
      const event = this.forward();
      const reason = this.stopHere(stops, event);
      if (reason) return { reason, tick: this.tick };
    }
    return { reason: 'end', tick: this.tick };
  }
Select code to copy. Scroll horizontally if needed.

stopHere looks at a position from two sides. A watch looks backward, at the event of the instruction that led here, because it fires after a write. A breakpoint looks forward, at the instruction that runs next. Tour the supplied changesWatched at the bottom of the file: a store that rewrites a byte with the value it already held doesn't fire a watch. continue steps first and tests after, so it never reports the position it started from. Lesson 12 adds function stops to stopHere.

Search backward one stretch at a time

Replace the search-back region:

continueBack, searchBack and the shared-page testexamples/debugger-checkpoint.mjs · search-back

Replace the search-back region.

  continueBack(stops = {}) {
    const here = this.tick;
    if (here === 0) return { reason: 'start', tick: 0 };
    const pages = (stops.watches ?? []).flatMap((w) =>
      pagesOf(w.address, w.size ?? 1, this.pageSize),
    );
    const watchesOnly = !stops.breakpoints?.length;
    const found = this.searchBack(
      here - 1,
      (event) => {
        const reason = this.stopHere(stops, event);
        return reason ? { reason, tick: this.tick } : null;
      },
      (i) => !watchesOnly || this.mayHaveWritten(i, pages),
    );
    if (found) {
      this.moveTo(found.tick);
      return found;
    }
    this.moveTo(0);
    return { reason: this.stopHere(stops, null) ?? 'start', tick: 0 };
  }

  searchBack(last, test, mayMatch = () => true) {
    for (let i = Math.ceil(last / this.every) - 1; i >= 0; i--) {
      if (!mayMatch(i)) continue;
      const snapshot = this.snapshots[i];
      const stop = Math.min(last, snapshot.tick + this.every);
      this.restore(snapshot);
      let found = null;
      while (this.tick < stop) {
        const finding = test(this.forward());
        if (finding) found = finding;
      }
      if (found) return found;
    }
    return null;
  }

  mayHaveWritten(i, pages) {
    const a = this.snapshots[i];
    const b = this.snapshots[i + 1];
    return !b || pages.some((p) => a.pages[p] !== b.pages[p]);
  }
Select code to copy. Scroll horizontally if needed.

searchBack(last, test, mayMatch) is the procedure the bullet list described, written once for both backward searches. Stretch i is the instructions after snapshot i, up to snapshot i + 1 or last. It restores the snapshot, replays the stretch once and keeps the latest finding, because the answer is the latest match, not the first. The first stretch, going back, that holds a finding has the answer, so the cost is about the distance to the match plus up to two stretches.

mayHaveWritten(i, pages) is the shared-page saving: it answers no when snapshot i + 1 holds the same page objects as snapshot i. continueBack uses it only when every stop is a watch, because a breakpoint can fire in a stretch that writes nothing. When nothing matches, continueBack goes to 0 and reports 'start', unless a breakpoint fires at position 0 itself.

Ask who last wrote a byte

Replace the last-write region:

lastWrite, and put the machine backexamples/debugger-checkpoint.mjs · last-write

Replace the last-write region.

  lastWrite(address) {
    const size = this.machine.state.memory.length;
    if (!Number.isInteger(address) || address < 0 || address >= size)
      throw RangeError(`lastWrite: ${address} is not an address inside memory`);
    const back = this.capture();
    const page = Math.floor(address / this.pageSize);
    const found = this.searchBack(
      back.tick,
      (event) => {
        const w = event.writes.findLast(
          (w) => address >= w.address && address < w.address + w.size,
        );
        if (!w) return null;
        const { tick, func, at } = event;
        return { tick, func, at, address: w.address, size: w.size };
      },
      (i) => this.mayHaveWritten(i, [page]),
    );
    this.restore(back);
    return found;
  }
Select code to copy. Scroll horizontally if needed.

lastWrite counts any write to the byte, changed or not, as the contract asks, and findLast picks the last write of an instruction that wrote the byte twice. It starts by capturing the current position, with every page copied, and restores it at the end: the method answers without moving the debugger. Only the page holding the byte matters, so every stretch in which that page stayed shared is skipped.

Try the moves on lesson 09's recording with examples/back-session.txt, a script of debug.mjs commands. In it, seek, back and rcontinue (continue backward) move your debugger, last-write goes to the last write of an address, break sets a breakpoint, where prints the position and cost the instructions your machine has run:

Observed output
node debug.mjs project project/run42.json examples/back-session.txt
Select code to copy. Scroll horizontally if needed.
Moving backward and what it costexamples/back-session-output.txt
project/run42.json: 759 calls, 652927 instructions. Type help for commands.
> seek 300000
tick 300000, call 295 (game_tick), next: function 6, instruction 768: i32.const 0
> where
tick 300000, call 295 (game_tick), next: function 6, instruction 768: i32.const 0
> cost
652927 instructions run by your machine so far, 652927 of them while your Debugger opened the recording
> back 1
tick 299999, call 295 (game_tick), next: function 6, instruction 767: i64.store 0 0
> cost
653926 instructions run by your machine so far, 652927 of them while your Debugger opened the recording
> break 8:0
stops: {"breakpoints":[{"func":8,"at":0}],"watches":[],"functions":[]}
> rcontinue
breakpoint at tick 299502, call 295 (game_tick), next: function 8, instruction 0: global.get 0
> cost
655426 instructions run by your machine so far, 652927 of them while your Debugger opened the recording
> last-write 78112
tick 69152: function 4, instruction 76: i32.store 2 78112 wrote 4 bytes at 78112
> cost
656578 instructions run by your machine so far, 652927 of them while your Debugger opened the recording
Select code to copy. Scroll horizontally if needed.

cost counts every instruction since debug.mjs started, the opening replay included, so take differences. seek 300000 cost nothing, because position 300,000 is a snapshot. The next two moves each restore the snapshot before them and replay forward:

Two moves on the stretch between the snapshots at 299,000 and 300,000. back 1 from 300,000 restores the snapshot at 299,000 and replays 999 instructions to 299,999. rcontinue from 299,999 with breakpoint 8:0 restores the same snapshot, replays up to 299,998, 998 instructions, finds the breakpoint fires only at 299,502, then restores again and replays 502 to stand there: 1,500 in all.

The last write of g, the 4 bytes at 78,112, was made in game_init, more than 200,000 instructions before the position rcontinue reached, and finding it replayed about a thousand, because page 19 stayed shared for the rest of the run.

Budgets

The checks count every instruction your machine runs, by counting calls to its step. They ask questions near the end of a long recording and give each kind a budget, a few times what a snapshot every few thousand instructions needs, and far less than a replay from tick 0.

Question 10e: snapshots are every 1,000 instructions. The debugger stands at position 300,000 and calls seek(300400), then seek(300200). How many instructions does the second seek replay? Commit:

Observed output
node lab.mjs predict project 10e YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Each check makes its own debugger, moves it, and compares what it finds with a replay from tick 0 or with a scan of the recording:

CheckMoves, and the snapshots they restoreCompares
10.seekSeeks to positions spread over the run, the start and the end among them. The targets are far apart, so no two seeks restore the same snapshot.The position, where() and all of memory, after each seek, with a replay from tick 0
10.step-backSeeks, then steps back one instruction or a few hundred, or forward a few. A step back restores the snapshot at or before the new position, often the one the seek just restored.The same as 10.seek
10.continueSeeks and calls continue, which only runs forward, so nothing is restored after the seek.Each stop, with a scan of every instruction
10.continue-backSeeks and calls continueBack, which restores the snapshot of the stretch it stands in, often the one the seek just restored, then earlier ones.Each stop, with a scan of every instruction
10.last-writeSeeks and calls lastWrite, which searches back the same way and then puts the debugger back.The write found, with a scan of every write; and that the debugger did not move
10.stateSeeks inside a call and then to the next position between calls.state()'s memory and frames at each, with a replay from tick 0; then it changes the copy and checks that the debugger's memory did not change
10.page-sharingSeeks to the end, which restores the snapshot before the end, then counts the bytes the snapshots' pages hold.A sample of those bytes, with a replay; no position
10.budgetOpens a debugger, seeks near the end and asks backward questions in a row, which restore some snapshots more than once.The instructions each question replays: it fails a debugger that replays from the start for any of them. It compares no position, memory or answer with a replay
10.lob2On a Lob II recording, at a few positions: seeks, steps back one instruction, seeks there again, asks lastWrite and calls continueBack.Each result, with a replay or a scan

All eight regions are filled. Run the unit's checks, describing what you did:

Terminal command
# After filling the type-in route's starter from the listings:
node lab.mjs check project 10 --help-used "filled eight regions from chapter listings"
# After following the supplied route:
node lab.mjs check project 10 --help-used "supplied debugger checkpoint; followed the explanations and tours"
Select code to copy. Scroll horizontally if needed.

All 9 checks should pass. If one fails, its first mismatch names the section to reread. Keep the failing attempt and your explanation before you edit.

Try your debugger on lesson 09's recording by hand too:

Observed output
node debug.mjs project project/run42.json
Select code to copy. Scroll horizontally if needed.

With no keyboard, in a container or from another program, put the commands in a file, one per line, and pass that file as the last argument: node debug.mjs project project/run42.json project/session.txt. A script stops at its first error.

help lists the commands and their arguments. seek TICK, back N, break FUNC:AT, watch ADDR SIZE, continue, rcontinue (continue backward), call N (go to the start of call N) and last-write ADDR call your debugger, read ADDR SIZE TYPE reads memory as u8, i32, f32 or text, and cost shows how many instructions your machine has run since debug.mjs started, including any replay your Debugger made when it opened the recording. For example, break 8:0 and then continue stop where the next call to game_tick begins.

Break a snapshot, then repair it

In your project only, change the line in restore that copies the snapshot's small state, so that the machine gets the snapshot's own objects instead of a copy:

JavaScript
...snapshot.state,
Select code to copy. Scroll horizontally if needed.

Question 10d: with this change, how many of the nine checks fail? Before you run anything, write in project/report.md which ones you expect to fail and why, then commit the number. Then run the check with --help-used describing this prescribed change:

Terminal command
node lab.mjs predict project 10d YOUR_ANSWER
node lab.mjs check project 10 --help-used "prescribed change: restore uses snapshot.state without a copy"
Select code to copy. Scroll horizontally if needed.

Compare the checks that failed with what the lab said after your prediction. Read the first failure's position and the one it expected. Explain what happened to the snapshot the first time a replay ran from it, and what a second restore of the same snapshot then gives. For each check that passed, say why this change doesn't reach it. Restore the copy and rerun the check, keeping both attempts:

Terminal command
node lab.mjs check project 10 --help-used "prescribed change removed"
Select code to copy. Scroll horizontally if needed.

This change is guided practice; the new application below asks for behavior none of these listings implements.

A question to ask backward

In project/run42.json, the first shot is fired by call 19. The getter r_px, a function that reads the shell's horizontal position, loads it from g + 40. The 4 bytes at address 78,112 hold g, the base address of the game's state.

Question 10c: use your debugger. Go to the start of call 301 (call 301 in debug.mjs), read g with read 78112 4 i32, and ask last-write for the address g + 40. In which call was that write made? Commit the call number your debugger reports:

Observed output
node lab.mjs predict project 10c YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Then work out what the backward search cost. Read cost just before last-write and again after it, and take the difference, because cost also counts any replay your Debugger made when it opened the recording, and the seeks call 301 made. Compare that with lesson 08's estimate for your Lesson 01–07 reverse search, and write both numbers in project/report.md.

Two last-write questions drawn as strips of the run from tick 0. For the pointer g, at 78,112 on page 19, asked at 299,502, only the stretch holding the write at tick 69,152 in call 0 is replayed and the other 230 are skipped: 1,000 instructions, then 152 to move there. For g + 40 at 65,944, on page 16, asked at the start of call 301, all 113 stretches back to the write at tick 191,487 in call 147 are replayed: 112,864, then 487 to move there, 113,351 in all.

What you should have seen: last-write costs 113,351 instructions here, far more than the earlier questions. g + 40 is on page 16, a page written so often that every snapshot copies it, so mayHaveWritten can't rule out any stretch and lastWrite replays every one between here and the write. g itself, on page 19, costs 1,152.

Use it on a new case: find a value backward

Lesson 08 timed reverseFind, a search for the latest earlier position where bytes held a chosen value. Rebuild it with snapshots in project/reverse-find.mjs. Both setup routes created that file. Otherwise, copy starter/reverse-find.mjs there first.

Contract partRequirement
InputreverseFind(debugger, { address, size, equals }); equals holds size bytes
MatchReturn the greatest earlier position, including 0, and stand there
No matchReturn null without moving
Invalid inputRefuse before moving; reject bad ranges, sizes and byte values
BudgetAt most 20,000 replayed instructions, or 80,000 for a missing value
Allowed dataPublic debugger methods plus each snapshot's tick and pages

Before you write code, answer two questions in project/report.md. A page holding your bytes is the same object in snapshots i and i + 1: what do you know about the value at every position between them, and how can you learn it without replaying? Inside a stretch you must replay, why is the first match you see not the answer? Keep that first reasoning. Then run the checker on the unfinished file, implement, and run it again, describing assistance honestly each time:

Terminal command
node examples/check-reverse-find.mjs project --help-used "initial attempt; nothing written"
node examples/check-reverse-find.mjs project --help-used "describe what helped your implementation"
Select code to copy. Scroll horizontally if needed.

The budget covers the checker's chosen bytes, not every address. It asks near the end about a recent change and about pages untouched since game_init, including the page holding g at 78,112.

Checked caseReplay limit
Value present20,000 instructions
Value never present80,000 instructions
Busy pages 15 to 17Not asked; a missing value could require the whole run

The checker keeps each run inspectable:

ArtifactLocation
Source, project record and reportA new folder under project/attempts/
Resultrfind-receipt.json in that folder
CasesOne-pass histories from Lob and Lob II

As a stretch, make continueBack skip stretches for a breakpoint too: a breakpoint can fire only in a stretch that runs its instruction, and a first pass can note which functions each stretch ran.

Keep the working tool

project/debugger.mjs now moves to any position, steps back, continues back to a breakpoint or watch, and names the last write of a byte, each from a snapshot within its budget. Its end-of-unit checkpoint is examples/debugger-checkpoint.mjs; recover from it with a new project, as in "Start", never by copying it over your file. Lesson 11 builds an index of the recording in one replay, so that a last write long ago on a busy page costs nothing to find, and lesson 12 adds the call stack and function stops to this file.

Earlier ideas, new cases

Questions from lessons 08 and 09, on cases you haven't seen. Commit each before checking.

Question 08a3: r_power, function 10, runs i32.const 0, i32.load offset 78112, local.tee 0, i32.load offset 92, local.get 0, i32.load offset 4, i32.xor, end. How many values are on the value stack after instruction 2, local.tee 0?

Observed output
node lab.mjs predict project 08a3 YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Question 08c3: an i32.store with offset 2 pops the value 287,454,020 (0x11223344) and then the address 5,000. What is the byte at address 5,004 afterwards, as a decimal number?

Observed output
node lab.mjs predict project 08c3 YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Question 09b3: a tampered recording first differs inside a call of 8,193 instructions. Bisecting inside it, at most how many tests until the two ends are one instruction apart?

Observed output
node lab.mjs predict project 09b3 YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

11 · Question a recording

Build an index, a saved lookup table, that explains values in a recording, a saved execution with game requests and server results, without running it again.

A tick counts finished instructions, numbered machine operations. At tick 89,345, instruction 89,345 changes the shell position bytes, stored numbers from 0 to 255, during game_tick, the function advancing one game frame. You might expect one earlier change. The real sources(89345) lookup lists 16 earlier stores, instructions that write bytes, plus results from cos, a math function, and server_wind, the server function supplying wind.

Start

First prove that the machine, recorder and reverse debugger still work:

Terminal command
node lab.mjs check project 08
node lab.mjs check project 09
node lab.mjs check project 10
Select code to copy. Scroll horizontally if needed.

If a prerequisite fails, create a supplied project and record a run:

Terminal command
node examples/start-chapter.mjs project11 supplied
node examples/start-recorder.mjs project11 supplied
node examples/start-debugger.mjs project11 supplied
node lab.mjs record project11 --world 42 --out project11/run42.json
Select code to copy. Scroll horizontally if needed.

Use project11 below if you took that route.

Choose how to create project/query.mjs:

RouteCommandWhat you receive
Type innode examples/start-query.mjs project writeTen unfinished regions with support code
Inspect working codenode examples/start-query.mjs project suppliedThe working checkpoint to test and break
Build from the contractNo setup commandThe stub from lab.mjs start; use API.md

The setup command refuses to replace an edited file. Both setup routes create unfinished project/value-sources.mjs. The ten regions are keep-writes, by-byte, last-writer, leaves, producers, frames, follow, memory, replay and sources.

Run the first check with the description matching where you started:

Terminal command
# Type-in route (write), including AI users before requesting changes:
node lab.mjs check project 11 --help-used "chapter write starter; ten regions unfinished"
# Supplied route:
node lab.mjs check project 11 --help-used "supplied query checkpoint; initial baseline"
Select code to copy. Scroll horizontally if needed.

The route command records write or supplied in PROJECT.json, and every check receipt keeps it as unit11_start_route. That says where you began, not who wrote your current code; keep using --help-used to say what helped each attempt. The type-in route fails every unit 11 check with not written yet, and the supplied route passes them all. Either result is a baseline, not evidence of understanding.

Keep the // region: NAME and // endregion: NAME markers. A listing replaces everything between its matching pair, including the line there that throws "not written yet". The listings omit the marker lines. To recover later without losing edits, run the supplied setup commands above from the course folder with project-recovery in place of project11, then run node examples/start-query.mjs project-recovery supplied and compare its query.mjs with yours. Don't copy the checkpoint over your attempt.

The index reads two machine fields that API.md does not name:

FieldMeaningRegions that read it
state.stackValues waiting for instructionsfollow, memory
state.resultValue returned by a finished callreplay

Lesson 08's machine uses those names. If yours differs, change those reads.

Last writers, indexed

Build the index during one replay:

Kept dataUse
Each byte's write ticks, in orderBinary search for the last tick below beforeTick
Function and instruction number atReport the writing instruction
Write start and sizeReport the whole write

A 4-byte store adds four byte entries. Lesson 09's recording makes 65,859 entries. Growing typed arrays hold them in a few megabytes. A byte written 1,000 times needs about ten comparisons.

Tour the supplied List near the top of your query.mjs now. It is that growing typed array: push doubles the array when it is full, and done() returns a copy of exactly what was pushed. Then tour the supplied lines at the start of buildIndex. They make one machine whose imports answer from the recording, as lesson 09's replay did, and prepared, which gives every instruction of every function a kind from the table KIND ('load', 'binary', 'call' and so on), so the replay looks up how an instruction moves values without reading its name again. An instruction outside the table stops the index before it runs anything.

Keep every write

In project/query.mjs, replace the keep-writes region:

Keep each write, and who last wrote each byte so farexamples/query-checkpoint.mjs · keep-writes

Replace the keep-writes region.

  // Every write, one entry in each list, in tick order.
  const wTick = new List(Int32Array);
  const wFunc = new List(Int32Array);
  const wAt = new List(Int32Array);
  const wAddress = new List(Int32Array);
  const wSize = new List(Int32Array);
  // Per byte: the tick of the store that last wrote it so far, 0 if none.
  const writer = new Int32Array(memorySize);
  const keepWrites = (event, t) => {
    for (const w of event.writes) {
      wTick.push(t);
      wFunc.push(event.func);
      wAt.push(event.at);
      wAddress.push(w.address);
      wSize.push(w.size);
      writer.fill(t, w.address, w.address + w.size);
    }
  };
Select code to copy. Scroll horizontally if needed.

The replay calls keepWrites after every instruction with the instruction's event and tick. Each write goes into five lists at the same position, so write number w is wTick[w], wFunc[w], wAt[w], wAddress[w] and wSize[w]. The replay runs in tick order, so the lists are in tick order without any sorting. writer is different: it holds, for every byte, only the latest store that wrote it. lastWriter doesn't use it. The chains later in this lesson do, because a load needs to know which store wrote each byte it reads at the moment it reads it.

Group the writes by byte

After the replay, makeIndex turns the writes into one list per byte. Replace the by-byte region:

One list of writes per byte, still in tick orderexamples/query-checkpoint.mjs · by-byte

Replace the by-byte region.

  // Per byte, the writes that touched it in tick order:
  // byteWrites[byteStart[a]] up to byteWrites[byteStart[a + 1]].
  const byteStart = new Int32Array(memorySize + 1);
  for (let w = 0; w < writes.tick.length; w++)
    for (let i = 0; i < writes.size[w]; i++)
      byteStart[writes.address[w] + i + 1]++;
  for (let a = 0; a < memorySize; a++) byteStart[a + 1] += byteStart[a];
  const byteWrites = new Int32Array(byteStart[memorySize]);
  const next = byteStart.slice(0, memorySize);
  for (let w = 0; w < writes.tick.length; w++)
    for (let i = 0; i < writes.size[w]; i++)
      byteWrites[next[writes.address[w] + i]++] = w;
Select code to copy. Scroll horizontally if needed.

All the per-byte lists live in one Int32Array, byteWrites, one after another, and byteStart[a] is where byte a's list begins. The first loop counts how many writes cover each byte, the second turns the counts into starting places, and the third puts each write's number at the next free place of every byte it covers. Writes are placed in tick order, so each byte's list is in tick order too, which is what the binary search needs.

Binary search one byte's list

Replace the last-writer region:

lastWriter: the greatest tick below beforeTickexamples/query-checkpoint.mjs · last-writer

Replace the last-writer region.

  const lastWriter = (address, beforeTick) => {
    if (!Number.isInteger(address) || address < 0 || address >= memorySize)
      throw Error(
        `lastWriter: ${address} is not an address in memory (0 to ${memorySize - 1})`,
      );
    if (typeof beforeTick !== 'number' || Number.isNaN(beforeTick))
      throw Error(`lastWriter: beforeTick must be a number, got ${beforeTick}`);
    // Binary search for the first write at or after beforeTick.
    let lo = byteStart[address];
    let hi = byteStart[address + 1];
    while (lo < hi) {
      const mid = (lo + hi) >> 1;
      if (writes.tick[byteWrites[mid]] < beforeTick) lo = mid + 1;
      else hi = mid;
    }
    if (lo === byteStart[address]) return null;
    const w = byteWrites[lo - 1];
    return {
      tick: writes.tick[w],
      func: writes.func[w],
      at: writes.at[w],
      address: writes.address[w],
      size: writes.size[w],
    };
  };
Select code to copy. Scroll horizontally if needed.

The loop narrows lo and hi to the first write at or after beforeTick, so the write just before it, at lo - 1, is the answer. If there is none, nothing wrote the byte before that tick. The answer is the whole write, its start and size, even when the byte is inside a wider store. The debugger's lastWrite at position p is lastWriter(address, p + 1), because the instruction at tick p has already run at position p.

Question 11a: in Lob, seed 3, mode 0 (no defences), how many times is the byte at the address g + 72 written during game_init and the first 10 game frames, where g is the 4 bytes at 78,112? g + 72 is the lowest byte of the game-frame counter. Commit:

Observed output
node lab.mjs predict project 11a YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Check 11.last-writer asks generated questions about recordings you haven't seen and compares with a scan of every write. It and the other checks this lesson names make up unit 11's checks, which one command runs:

Terminal command
node lab.mjs check project 11 --help-used "describe what helped"
Select code to copy. Scroll horizontally if needed.

On the type-in route they still fail with "not written yet" at this point, because buildIndex runs the regions that follow values before it returns. Run the command again once the sources region is filled.

Where a value came from

A store copies a value off the stack, and that value was computed by an earlier instruction from its operands. Those came from loads, constants, locals or calls, and each load read bytes that an earlier store wrote or that still held their initial value. Following those links backward from a store gives the chain of the stored value.

The chain of the shell position stored at g + 40 at tick 89,345, in call 20 of lesson 09's recording. It comes from the position and the horizontal speed stored in call 19 and from answer 3, server_wind. The position comes from the cannon position stored by game_init and from answer 1, cos; the speed comes from answer 1 and from 11 presses of up, each storing the power from the one before, back to the key and the angle and power stored by game_init.

A box is a store, named by the field of g it wrote, with its tick and call. An oval is an outside answer, named by its recording index. An arrow points to an input value.

sources(tick) takes a store tick and returns four sorted lists:

ListContents
storesEarlier stores on the chain, by tick
answersOutside answers, by recording.answers index
argsGame-call arguments as [call, index]
initialBytes loaded before any store wrote them

The chain follows values, not addresses. A load depends on bytes read, while a store passes on its value. Otherwise every chain would include the pointer g.

ProducerInputs followed
Arithmetic or selectEvery value operand
Load or storeData bytes or stored value, never the address
Local, global or defined callThe value passed through
Outside functionIts recorded answer
ConstantNone

API.md settles the cases that could go either way: select depends on its condition as well as both values, a one-byte store on the whole value it was given, and a load of bytes written by several stores on all of them.

Question 11f: a store at g + 8 writes the i32.add of two operands: a load of the 4 bytes at g + 4, which the store at tick 5,000 last wrote, and i32.const 3. The address g came from a load at 78,112, which the store at tick 1,000 wrote. Which of these stores are on the stored value's chain: (a) tick 5,000 only, (b) tick 1,000 only, or (c) both? Answer a, b or c, and commit:

Observed output
node lab.mjs predict project 11f YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

How to follow a value

Replay once and give every value a producer, the tick of the instruction that made it. Keep a producer beside stack values, locals, globals and memory bytes.

InstructionProducer movement
ArithmeticPop operand producers; push this tick
ConstantPush a value with no inputs
Local or globalMove the producer with the value
LoadRecord each read byte's producer; push this tick
StoreRecord the value producer; mark written bytes with this tick
Outside callPush the recorded answer's producer
Defined callMove argument producers into parameters; return the result producer
Game-call argumentCreate a producer reported as [call, index]

Branches cut the stack back, so cut the producers back with it, keeping a block's result.

Record, for each tick, the producers it took as inputs. sources(tick) then walks backward from the store's input. Visit a tick, add its inputs to the walk, note each store, answer and argument met, and never visit a tick twice. The walk only touches the chain, so most questions finish in a few thousand steps whatever the recording's length.

The seven listings below build that procedure. Three of their choices save memory without changing any answer: a constant gets the producer "nothing" instead of its own tick, since nothing can be on its chain; a value computed from a single producer takes that producer instead of a tick of its own, since its chain is the same; and an import call's value takes its answer's producer directly.

Number the leaves

A producer has to fit in one slot of an Int32Array. A chain ends at leaves: an answer, a call argument or an initial byte. Ticks are positive, so leaves get negative numbers. Replace the leaves region:

One whole number for every kind of producerexamples/query-checkpoint.mjs · leaves

Replace the leaves region.

  // A producer is one whole number: 0 is nothing (a constant), t > 0 is the
  // instruction at tick t, and the leaves are negative: the answers first, then
  // every argument of every call, then the initial bytes by address.
  const nAnswers = recording.answers.length;
  const argBase = [];
  let nArgs = 0;
  for (const c of calls) {
    argBase.push(nArgs);
    nArgs += c.args.length;
  }
  const argCall = new Int32Array(nArgs);
  const argPos = new Int32Array(nArgs);
  calls.forEach((c, k) =>
    c.args.forEach((_, i) => {
      argCall[argBase[k] + i] = k;
      argPos[argBase[k] + i] = i;
    }),
  );
  const answerId = (a) => -1 - a;
  const argId = (k, i) => -1 - nAnswers - argBase[k] - i;
  const initialId = (address) => -1 - nAnswers - nArgs - address;
Select code to copy. Scroll horizontally if needed.

The leaves are the producers a chain ends at: an answer, an argument of a call into the game, or an initial byte. Ticks are positive, so the leaves take the negative numbers, one range after another: answer a is -1 - a, then every argument of every call, in call order, then every byte of memory by address. argBase[k] is where call k's arguments start in that range, and argCall and argPos turn an argument's number back into [call, index] when sources reports it. The number 0 is left for nothing.

Producers beside the machine's values

Replace the producers region:

What the index records per tick, and the producers of what the machine holdsexamples/query-checkpoint.mjs · producers

Replace the producers region.

  // Per tick: where its inputs start in deps, and whether it was a store.
  const depStart = new List(Int32Array);
  const deps = new List(Int32Array);
  const isStore = new List(Uint8Array);
  depStart.push(0); // tick 0 is no instruction
  isStore.push(0);

  // The producers of what the machine holds right now: one per stack value,
  // one per global, and the frames with one per local.
  let P = new Int32Array(1024);
  let sp = 0;
  const G = new Int32Array(program.globals.length);
  const frames = []; // { func, locals, base, labels: [{ height, arity, loop }] }
  const push = (id) => {
    if (sp === P.length) {
      const bigger = new Int32Array(P.length * 2);
      bigger.set(P);
      P = bigger;
    }
    P[sp++] = id;
  };

  // A computed value. With no operand producer it is nothing; with one, it
  // carries that operand's chain, so it takes its producer; with more, it is
  // tick t, whose inputs are the operands' producers.
  const scratch = new Int32Array(8);
  let nScratch = 0;
  const add = (id) => {
    if (id === 0) return;
    for (let i = 0; i < nScratch; i++) if (scratch[i] === id) return;
    scratch[nScratch++] = id;
  };
  const made = (t) => {
    if (nScratch === 0) return 0;
    if (nScratch === 1) return scratch[0];
    for (let i = 0; i < nScratch; i++) deps.push(scratch[i]);
    return t;
  };
Select code to copy. Scroll horizontally if needed.

depStart, deps and isStore are what the index keeps for the questions. Tick t's inputs run from deps[depStart[t]] up to, but not including, deps[depStart[t + 1]], so every tick costs one number in depStart and one byte in isStore, however many inputs it has. P and sp mirror the machine's value stack, one producer per value, G mirrors the globals, and each frame will hold one producer per local. These last only as long as the replay.

add and made make a computed value's producer. add collects the operands' producers, skipping 0, which means no producer, and any producer already collected. made(t) returns 0 if none was collected, the one producer if only one was, and otherwise records them all as tick t's inputs and returns t. An i32.add of a loaded value and a constant therefore passes on the load's producer, and its chain is the load's chain, as the rules ask.

Branches, returns and calls

Replace the frames region:

Cut the producers back as the stack is cut backexamples/query-checkpoint.mjs · frames

Replace the frames region.

  // A branch keeps its target's results and cuts the producers back with the
  // stack; a loop's label stays, because the loop can be branched to again.
  const branch = (frame, depth) => {
    const label = frame.labels[frame.labels.length - 1 - depth];
    for (let i = 0; i < label.arity; i++)
      P[label.height + i] = P[sp - label.arity + i];
    sp = label.height + label.arity;
    frame.labels.length -= label.loop ? depth : depth + 1;
  };
  // A return hands the results' producers back to the caller; the outermost
  // call's result leaves the machine.
  const leave = () => {
    const frame = frames.pop();
    const n = prepared.get(frame.func).results;
    for (let i = 0; i < n; i++) P[frame.base + i] = P[sp - n + i];
    sp = frame.base + (frames.length ? n : 0);
  };
  // A call's arguments become the new frame's first locals; the other locals
  // start as nothing.
  const enter = (func, args) => {
    const locals = new Int32Array(args.length + prepared.get(func).locals);
    locals.set(args);
    frames.push({ func, locals, base: sp, labels: [] });
  };
Select code to copy. Scroll horizontally if needed.

branch, leave and enter follow lesson 08's branch, return and call. A label remembers the stack's height when its block began and how many results the block leaves. branch copies those results' producers down to that height and cuts sp there, so the values a branch drops take their producers with them. A branch to a loop keeps the loop's label, because the loop can be branched to again. leave does the same for a function's results, and enter starts a frame whose first locals are the producers of the call's arguments and whose other locals are nothing.

Move the producers instruction by instruction

Replace the follow region:

follow: one case per kind of instructionexamples/query-checkpoint.mjs · follow

Replace the follow region.

  // Move the producers as the instruction at tick t is about to move values.
  // stack is the machine's value stack before the instruction runs.
  const follow = (kind, ins, frame, t, stack) => {
    switch (kind) {
      case 'block':
        frame.labels.push({ height: sp, arity: ins[1] ? 1 : 0, loop: false });
        break;
      case 'loop':
        frame.labels.push({ height: sp, arity: 0, loop: true });
        break;
      case 'br':
        branch(frame, ins[1]);
        break;
      case 'br_if':
        sp--; // the condition is a decision: on no chain
        if (stack[stack.length - 1] !== 0) branch(frame, ins[1]);
        break;
      case 'end':
        if (frame.labels.length) frame.labels.pop();
        else leave();
        break;
      case 'return':
        leave();
        break;
      case 'call': {
        const n = program.typeOf(ins[1]).params.length;
        if (ins[1] < nImports) {
          sp -= n; // an import's arguments are not followed
          if (program.typeOf(ins[1]).results.length)
            push(answerId(answered.position()));
        } else {
          const args = P.slice(sp - n, sp);
          sp -= n;
          enter(ins[1], args);
        }
        break;
      }
      case 'local.get':
        push(frame.locals[ins[1]]);
        break;
      case 'local.set':
        frame.locals[ins[1]] = P[--sp];
        break;
      case 'local.tee':
        frame.locals[ins[1]] = P[sp - 1];
        break;
      case 'global.get':
        push(G[ins[1]]);
        break;
      case 'global.set':
        G[ins[1]] = P[--sp];
        break;
      case 'const':
        push(0);
        break;
      case 'unary':
        break; // the same operand, so the same chain
      case 'binary':
        nScratch = 0;
        add(P[sp - 2]);
        add(P[sp - 1]);
        sp -= 1;
        P[sp - 1] = made(t);
        break;
      case 'select':
        nScratch = 0;
        add(P[sp - 3]);
        add(P[sp - 2]);
        add(P[sp - 1]);
        sp -= 2;
        P[sp - 1] = made(t);
        break;
      case 'load':
        load(ins, t, stack);
        break;
      case 'store':
        store();
        break;
    }
  };
Select code to copy. Scroll horizontally if needed.

follow runs just before the machine runs the instruction, while the operands are still on the machine's stack, and does to P what the instruction is about to do to the stack. br_if drops its condition's producer without recording it anywhere, because a branch's condition is on no chain ("Decisions are not followed" below says why); it reads the condition's value from the machine's stack only to know whether the branch will be taken. An import call drops its arguments' producers and pushes the leaf of the answer the machine is about to use. A call to a defined function moves its arguments' producers into the new frame. Loads and stores go to the next region.

Loads and stores: bytes, not addresses

Replace the memory region:

A load depends on the bytes it reads; a store on its valueexamples/query-checkpoint.mjs · memory

Replace the memory region.

  // A load depends on the bytes it read, each on the store that last wrote
  // it, or on the byte itself if no store has. Its address is not followed.
  const load = (ins, t, stack) => {
    const address = (stack[stack.length - 1] >>> 0) + ins[2];
    nScratch = 0;
    for (let i = 0; i < LOAD_SIZE[ins[0]]; i++) {
      if (address + i >= memorySize) break;
      const w = writer[address + i];
      add(w !== 0 ? w : initialId(address + i));
    }
    P[sp - 1] = made(t);
  };
  // A store's only input is its value's producer; its address is not
  // followed. keepWrites then makes this tick the writer of every byte.
  const store = () => {
    const value = P[--sp];
    sp--;
    if (value !== 0) deps.push(value);
  };
Select code to copy. Scroll horizontally if needed.

A load reads its address from the machine's stack and looks up, in writer, the store that last wrote each byte it is about to read. A byte no store has written gives its initial leaf. The load's result replaces the address's producer on top of P, so the address is never an input. A store pops its value's producer and records it as its only input, then drops the address's producer. After the machine runs it, keepWrites makes this tick the writer of every byte it wrote, so the next load of those bytes depends on this store.

Replay once

Replace the replay region:

Replay every call, keeping the producers in step with the machineexamples/query-checkpoint.mjs · replay

Replace the replay region.

  for (let k = 0; k < calls.length; k++) {
    m.begin(calls[k].name, calls[k].args);
    enter(
      program.exportIndex(calls[k].name),
      calls[k].args.map((_, i) => argId(k, i)),
    );
    while (m.running) {
      const top = s.frames[s.frames.length - 1];
      const frame = frames[frames.length - 1];
      const fn = prepared.get(top.func);
      const ins = fn.code[top.at];
      const kind = fn.kinds[top.at];
      const t = s.tick + 1;
      depStart.push(deps.n);
      isStore.push(kind === 'store' ? 1 : 0);
      follow(kind, ins, frame, t, s.stack);
      const asked = answered.position();
      const event = m.step();
      keepWrites(event, t);
      // The producers must still match the machine: its stack, its frames and
      // the answers it has used.
      const used = kind === 'call' && ins[1] < nImports ? 1 : 0;
      if (
        frame.func !== top.func ||
        sp !== s.stack.length ||
        frames.length !== s.frames.length ||
        answered.position() !== asked + used ||
        (event.writes.length !== 0) !== (kind === 'store')
      )
        throw Error(
          `buildIndex: lost track of the machine at tick ${t} (${ins[0]} at (${event.func}, ${event.at}))`,
        );
    }
    const result = s.result === undefined ? null : s.result;
    if (!Object.is(result, recording.results[k]))
      throw Error(
        `buildIndex: call ${k} returned ${result}, the recording says ${recording.results[k]}`,
      );
  }
  depStart.push(deps.n);
Select code to copy. Scroll horizontally if needed.

Each call begins with a frame whose locals are the call's argument leaves. Then, for every instruction, the loop records where its inputs start, moves the producers with follow, lets your machine run it and keeps its writes. After each instruction it compares the producers with the machine: the same stack height, the same number of frames, one answer used by an import call and none otherwise, and writes exactly when the instruction was a store. A mistake in follow then stops the replay at the first tick where one of these disagrees, instead of giving wrong chains later. After each call, the result must be the recorded one, as in lesson 09.

Walk back from a store

Replace the sources region:

sources: visit each producer on the chain onceexamples/query-checkpoint.mjs · sources

Replace the sources region.

  // seenTick[t] === epoch: tick t was visited during the current question.
  const { nAnswers, nArgs, argCall, argPos } = leaves;
  const seenTick = new Int32Array(end + 1);
  const seenLeaf = new Int32Array(nAnswers + nArgs + memorySize);
  let epoch = 0;
  const sources = (tick) => {
    if (!Number.isInteger(tick) || tick < 1 || tick > end || !isStore[tick])
      throw Error(
        `sources: tick ${tick} is not the tick of a store instruction`,
      );
    epoch++;
    const stores = [];
    const answers = [];
    const args = [];
    const initial = [];
    const todo = [];
    for (let i = depStart[tick]; i < depStart[tick + 1]; i++)
      todo.push(deps[i]);
    while (todo.length) {
      const id = todo.pop();
      if (id > 0) {
        if (seenTick[id] === epoch) continue;
        seenTick[id] = epoch;
        if (isStore[id]) stores.push(id);
        for (let i = depStart[id]; i < depStart[id + 1]; i++)
          todo.push(deps[i]);
        continue;
      }
      const leaf = -1 - id;
      if (seenLeaf[leaf] === epoch) continue;
      seenLeaf[leaf] = epoch;
      if (leaf < nAnswers) answers.push(leaf);
      else if (leaf < nAnswers + nArgs) args.push(leaf - nAnswers);
      else initial.push(leaf - nAnswers - nArgs);
    }
    const up = (a, b) => a - b;
    return {
      stores: stores.sort(up),
      answers: answers.sort(up),
      args: args.sort(up).map((x) => [argCall[x], argPos[x]]),
      initial: initial.sort(up),
    };
  };
Select code to copy. Scroll horizontally if needed.

The walk starts from the store's value producer. It visits each tick once, adds that tick's inputs, and sorts each leaf into its output list. seenTick and seenLeaf hold an epoch number that changes for every question, so the arrays need no clearing. The requested store stays out of its own chain.

For sources(89345), the first flight gives this state trace:

ValueEarlier source
New shell positionPrior position, horizontal speed, answer 3 (server_wind)
Horizontal speedPower, a constant, answer 1 (cos)
Power11 key-press stores, then game_init
First positionCannon position at g + 20
Stored power keygame_init store at g + 92

The result holds 16 stores and 2 answers. game_init wrote the starting angle and power together in one 8-byte store. Mode 4 is off, so the XOR key at g + 92 is 0.

By rule, the angle isn't on the chain, because it reached the outside world only as the argument of cos, and an import's arguments aren't followed. Nor is the pointer g, because it was only ever an address.

Question 11b: in lesson 09's recording, made with the server defences on, the shell's position is stored at g + 40 on every game frame of a flight. How many server_wind answers are on the chain of the position stored on the tenth game frame of the first flight? Commit:

Observed output
node lab.mjs predict project 11b YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Checks 11.sources-lob and 11.sources-lob2 ask generated questions about Lob and Lob II recordings, and 11.sources-rules asks about a small program built to use the rules Lob never needs: a global that carries a value, a function that takes arguments and returns a result, a block that leaves a value, a branch that drops values. Every address that small program loads from or stores to is a constant, or computed only from constants, such as a loop counter that starts at a constant. Each check compares your four lists one by one. The lists it expects were worked out by a brute force that carries every value's full set of sources forward through the whole recording, a different method from the walk above, so the same mistake is unlikely in both.

All ten regions are filled. Run the unit's checks, describing what you did:

Terminal command
# After filling the type-in route's starter from the listings:
node lab.mjs check project 11 --help-used "filled ten regions from chapter listings"
# After following the supplied route:
node lab.mjs check project 11 --help-used "supplied query checkpoint; followed the explanations and tours"
Select code to copy. Scroll horizontally if needed.

Every unit 11 check should pass. If one fails, its first mismatch names the section to reread. Keep the failing attempt and your explanation before you edit.

Cost

buildIndex may replay the recording once or twice, and after that no question may replay it. Check 11.no-replay counts the instructions your machine runs while hundreds of questions are answered, and expects none.

See what your index kept for lesson 09's recording, and what asking it costs:

Observed output
node examples/show-index.mjs project project/run42.json
Select code to copy. Scroll horizontally if needed.
What the index holds, and the instructions run to ask itexamples/index-output.txt
project/run42.json: 652927 instructions in 759 calls
building the index ran 652927 instructions on your machine
per-byte lists: 65859 entries, for 12301 bytes written at least once
the most written byte is 65508, written 2944 times; a binary search in its list takes at most 12 comparisons
sources asked about all 36810 stores: the longest chain holds 739 stores
instructions run while answering those questions: 0
Select code to copy. Scroll horizontally if needed.

Building the index ran exactly one replay of the run. The per-byte lists hold the 65,859 entries counted earlier, for 12,301 bytes. The most written byte lies in the C stack just below 65,536, and a binary search finds any write in its list in at most 12 comparisons. The script then asked sources about every store of the run, and your machine ran no instruction while it did: everything a question needs was kept during the replay.

Observed output
node debug.mjs project project/run42.json
Select code to copy. Scroll horizontally if needed.

As in lesson 10, you can also put the commands in a file, one per line, and pass it as the last argument, for a session with no keyboard.

In debug.mjs, who ADDR asks your index for the last writer, and sources asks for the chain of the store at the current tick. Stand right after a store with who or last-write, then ask sources. It prints how many stores the chain holds and the newest 8 of them, newest first, each with its tick, its function and instruction, and the address it wrote. sources N shows the newest N, and sources all shows every one. Then come the chain's answers, call arguments and initial bytes.

examples/query-session.txt asks for the worked chain of tick 89,345 twice:

Observed output
node debug.mjs project project/run42.json examples/query-session.txt
Select code to copy. Scroll horizontally if needed.
The worked chain, asked twiceexamples/query-session-output.txt
project/run42.json: 759 calls, 652927 instructions. Type help for commands.
> seek 89345
tick 89345, call 20 (game_tick), next: function 8, instruction 539: local.get 1
> sources
stores: 16 on the chain; the newest 8, newest first (sources N shows N, sources all every one):
  tick 88553: function 7, instruction 181: f32.store 2 48 wrote 4 bytes at 65952
  tick 88529: function 7, instruction 157: f32.store 2 40 wrote 4 bytes at 65944
  tick 83439: function 7, instruction 91: i32.store 2 4 wrote 4 bytes at 65908
  tick 82713: function 7, instruction 91: i32.store 2 4 wrote 4 bytes at 65908
  tick 81987: function 7, instruction 91: i32.store 2 4 wrote 4 bytes at 65908
  tick 81261: function 7, instruction 91: i32.store 2 4 wrote 4 bytes at 65908
  tick 80535: function 7, instruction 91: i32.store 2 4 wrote 4 bytes at 65908
  tick 79809: function 7, instruction 91: i32.store 2 4 wrote 4 bytes at 65908
answers: 1 (cos) 3 (server_wind)
call arguments: none
initial bytes: none
> cost
1306199 instructions run by your machine so far, 652927 of them while your Debugger opened the recording
> sources 3
stores: 16 on the chain; the newest 3, newest first (sources N shows N, sources all every one):
  tick 88553: function 7, instruction 181: f32.store 2 48 wrote 4 bytes at 65952
  tick 88529: function 7, instruction 157: f32.store 2 40 wrote 4 bytes at 65944
  tick 83439: function 7, instruction 91: i32.store 2 4 wrote 4 bytes at 65908
answers: 1 (cos) 3 (server_wind)
call arguments: none
initial bytes: none
> cost
1306199 instructions run by your machine so far, 652927 of them while your Debugger opened the recording
Select code to copy. Scroll horizontally if needed.

The listed stores are the ones the worked chain named: the speed and the position stored by firing, then the presses of up storing the power at g + 4. The first cost counts the replay your Debugger made when it opened the recording, the short replay seek made from the snapshot at 89,000, and one more replay of the whole run, for the index, which debug.mjs builds the first time you ask who or sources. The second cost is the same number: the second question ran no instruction.

Question 11c: in project/run42.json the second shot is fired by call 396, and as it fires the game adds 1 to its shot counter and stores it. How many stores are on the chain of the value that store writes? Lesson 08's loop that clears memory is part of the answer. Commit before you check with who and sources:

Observed output
node lab.mjs predict project 11c YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Now follow a chain from the status line. The getter r_line_ptr returns its address, and read ADDR text shows the bytes as text. Character i lives at the returned address plus i.

CharacterWhat its chain reaches
Fixed letterA constant
Angle, power or score digitEarlier stores, back to game_init
Wind arrow > or <An outside answer in project/run42.json

Use who on one wind-arrow byte, then ask sources. In project/report.md, record each store's tick, function and address. Name the final answer and its outside function. Explain why a character chosen from constants still has a chain. listing FUNC:AT 30 shows the choosing instructions around the store.

Decisions are not followed

A br_if pops a condition and branches, and the branch decides which instructions run, but no value flows from the condition into what those instructions compute.

Question 11d: in project/run42.json the first shell lands in call 148, and the game stores 0 in its flying flag at g + 36 (tick 192,256). The store runs only because a br_if found the shell below the ground. How many entries does sources(192256) list, in all four lists together? Commit:

Observed output
node lab.mjs predict project 11d YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

A store of a constant has an empty chain even when it ran only because of a long computation before it. When a store's chain is empty or doesn't explain a wrong value, the cause may be a decision, so look at the branch that led to the store, with back and listing (listing FUNC:AT N prints the instructions from N before AT to N after it).

Follow an address, then repair it

In your project only, make a load depend on its address as well. In the load function of the memory region, add this line right after nScratch = 0;, so that the address's producer, the top of P, is collected with the bytes':

JavaScript
add(P[sp - 1]);
Select code to copy. Scroll horizontally if needed.

Question 11e: with this change, how many of unit 11's five checks fail? Before you run anything, write in project/report.md which ones you expect to fail and why, and what you expect sources at tick 89,345 to show, then commit the number. Then run the check with --help-used describing this prescribed change, and open debug.mjs and ask sources all at tick 89,345 (seek 89345, then sources all; as in lesson 10, those two commands can also go in a file passed as the last argument):

Terminal command
node lab.mjs predict project 11e YOUR_ANSWER
node lab.mjs check project 11 --help-used "prescribed change: a load also follows its address"
node debug.mjs project project/run42.json
Select code to copy. Scroll horizontally if needed.

Compare the checks that failed, and the chain at tick 89,345, with what the lab said after your prediction. Explain in project/report.md which entries the change added to that chain, and why one rule can add the same entries to many chains. Remove the line and rerun the check, keeping both attempts:

Terminal command
node lab.mjs check project 11 --help-used "prescribed change removed"
Select code to copy. Scroll horizontally if needed.

This guided change alters an existing rule. The next application combines the index's rules in a new way.

Use it on a new case: where a value in memory came from

sources starts from a store tick. Memory inspection starts from bytes at a position. Write valueSources(index, { address, size, position }) in project/value-sources.mjs. The setup routes created it. Otherwise, copy starter/value-sources.mjs there first.

Contract partRequirement
Result{ stores, answers, args, initial } for the bytes after position instructions
Written byteInclude its last store and that store's chain
Unwritten byteInclude its address in initial
OrderingIncreasing, without repeats; args by call then index
Invalid inputRefuse non-whole values, bad sizes, positions or memory ranges
Memory boundAddresses 0 through 131,071; two 64 KiB WebAssembly pages
BudgetRun no machine instruction
Allowed index dataend, lastWriter and sources only

Before you write code, answer two questions in project/report.md. Which beforeTick do you pass to lastWriter for a value at position p, and what goes wrong with the other choice? Two bytes of a 4-byte value were written by one store: how many times does that store appear in your answer, and why? Keep that first reasoning. Then run the checker on the unfinished file, implement, and run it again, describing assistance honestly each time:

Terminal command
node examples/check-value-sources.mjs project --help-used "initial attempt; nothing written"
node examples/check-value-sources.mjs project --help-used "describe what helped your implementation"
Select code to copy. Scroll horizontally if needed.

Every question, including a refused one, must run zero machine instructions. The checker counts step calls around each valueSources call. Building its indexes is outside that count, and the whole check has 120 seconds.

Evidence savedCases asked
Source, PROJECT.json, report and vsources-receipt.json in a new attempt folderInvalid inputs and g after game_init
Earlier attempts stay intactFour one-byte stores and unwritten bytes
Expected lists kept as length plus salted hashA store's own tick, the tick before, and a Lob II value

Your query.mjs must pass unit 11 first because every expected answer uses its index.

As a stretch, add a value ADDR SIZE command to your own copy of debug.mjs that asks valueSources about the bytes at the current position.

Keep the working tool

project/query.mjs now builds an index of a recording in one replay and answers, without replaying, who last wrote any byte before any tick and which stores, answers, arguments and initial bytes a stored value was computed from. debug.mjs uses it for who and sources. Its end-of-unit checkpoint is examples/query-checkpoint.mjs; recover from it with a new project, as in "Start", never by copying it over your file. Lesson 12 gives the debugger function names, the call stack and line numbers, and lesson 13's investigations use who and sources to find planted bugs.

Earlier ideas, new cases

Question 08b3: a loop starts with local 1 at 150, subtracts 5 from it each time round, and ends with br_if 0, which branches back while local 1 isn't zero. How many times does br_if 0 branch back?

Observed output
node lab.mjs predict project 08b3 YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Question 09a3: record lesson 09's game (Lob, seed 5) in mode 0, with no server defences, and with three shots instead of two. How many answers does the recording hold?

Observed output
node lab.mjs predict project 09a3 YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Question 10b3: snapshots are every 2,000 instructions, at ticks 0, 2,000, 4,000 and so on. You stand at position 96,568 and call stepBack(600). How many instructions does the debugger replay?

Observed output
node lab.mjs predict project 10b3 YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

12 · Stack and names

Build a debugger, a tool that pauses and inspects code, that connects each function, a named block of code, to its text name, internal number, and source line, its line in the original C programming language; shows which functions are running; stops by name; and runs until one finishes.

break update_hud means “stop when function update_hud starts.” Lob is an artillery game, and update_hud refreshes its status display. You might expect a stop. The code says no function named update_hud: the file kept internal function number 6 but removed its name entry (not a branch label from Lesson 08), the saved text connecting update_hud to 6.

Start

Use your project from lessons 08 to 11. Confirm its machine, recorder, and debugger first:

Terminal command
node lab.mjs check project 08
node lab.mjs check project 09
node lab.mjs check project 10
Select code to copy. Scroll horizontally if needed.

If those fail, create project12 from the supplied checkpoints and use that name below:

Terminal command
node examples/start-chapter.mjs project12 supplied
node examples/start-recorder.mjs project12 supplied
node examples/start-debugger.mjs project12 supplied
node lab.mjs record project12 --world 42 --out project12/run42.json
Select code to copy. Scroll horizontally if needed.

Choose one start. Both commands preserve an edited names.mjs and create the unfinished next-line.mjs when missing.

StartCommandWhat you receive
Write the marked regionsnode examples/start-names.mjs project writeSupplied reader shell; four name regions remain
Inspect working codenode examples/start-names.mjs project suppliedFinished names; stack checkpoint only when your debugger still matches lesson 10

The lesson changes four regions in names.mjs and four in debugger.mjs. Keep each // region: NAME pair. The checkpoints are examples/names-checkpoint.mjs and examples/stack-checkpoint.mjs; compare them in a recovery project, never copy them over your work.

Run the baseline that matches your start:

Terminal command
# Type-in route (write), including AI users before requesting changes:
node lab.mjs check project 12 --help-used "chapter write starter; four regions unfinished"
# Supplied route:
node lab.mjs check project 12 --help-used "supplied names and stack checkpoints; initial baseline"
Select code to copy. Scroll horizontally if needed.

The receipt records unit12_start_route. On the write route, four checks report not written yet; the function-stop check returns a wrong real answer. The supplied route passes when it can install both checkpoints. Keep using --help-used to name the help behind each attempt.

Where names live

targets/lob.wasm was linked with its names stripped, left out of the file, because Sightline asks its learners to work out what each unnamed function does. For this lesson the course built the same C file again, with the same compiler, and kept its names, in targets/lob-names.wasm. Its code is byte for byte the code of lob.wasm, so programs/lob.json describes it too. The extra bytes are custom sections at the end of the file.

The whole of lob-names.wasm to scale: 8 fixed bytes, 9 standard sections, most of it the code section of 5,957 bytes, then 3 custom sections of 589 bytes: name, 372 bytes, producers, 66, and target_features, 151. Below, not to scale, the custom section name: its id 0, its size 369, its own name, then subsections 0, 1, 7 and 9. Subsection 1, whose size field says 312 bytes, holds the 29 function names.

A WebAssembly file is 8 fixed bytes followed by sections, each an id byte, its size in bytes, then that many bytes. Custom sections have id 0, and their contents start with a name: a length, then that many bytes of text (UTF-8, which for these names is plain ASCII). The one named name holds the names.

Sizes and lengths are LEB128 numbers, in which each byte carries 7 bits of the number, lowest first, and its top bit says whether another byte follows. 1D is 29. B8 02 is two bytes. B8 has its top bit set and carries 56, and 02 carries 2, worth 2 × 128. Together, 312. (Sightline teaches LEB128 and the rest of the file format in depth.)

Inside the name section are subsections, each an id byte, a size and contents. Subsection 1 holds function names: a count, then for each function its index and its name. Skip any other subsection by its size. Here are the first bytes of the name section in lob-names.wasm, after its own name:

Observed output
00 0F              subsection 0, 15 bytes: the module's own name
0E 6C 6F 62 2D ... a name of 14 bytes: lob-names.wasm
01 B8 02           subsection 1, 312 bytes: function names
1D                 29 names follow
00                 function 0
0C 73 65 72 76 65 72 5F 72 6F 75 6E 64
                   a name of 12 bytes: server_round
01 06 6A 73 5F 63 6F 73
Select code to copy. Scroll horizontally if needed.

The 29 names are Lob's 4 imports and its 25 functions.

Question 12a: decode the last line. What name does the name section give function 1? Commit:

Observed output
node lab.mjs predict project 12a YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

functionNames(bytes) in names.mjs walks the sections from byte 8, skips every section that isn't the custom section name, and returns { index: name } for every entry of subsection 1, or {} when the file has no name section. Check 12.names reads both named and stripped files, and a small file of its own that puts other subsections before subsection 1. It and the other checks this lesson names make up unit 12's checks, which one command runs:

Terminal command
node lab.mjs check project 12 --help-used "describe what helped"
Select code to copy. Scroll horizontally if needed.

Read numbers and names

The supplied Reader at the top of names.mjs keeps a position in the file, pos, and byte() returns the byte there and moves past it, refusing to read past the end. In project/names.mjs, replace the leb128 region, which adds the two reads everything else is made of:

LEB128 numbers and namesexamples/names-checkpoint.mjs · leb128

Replace the leb128 region.

  // Unsigned LEB128: 7 bits per byte, lowest first. A byte with its top bit
  // set says another byte follows.
  u32() {
    let value = 0;
    let shift = 0;
    let b;
    do {
      b = this.byte();
      value += (b & 0x7f) * 2 ** shift;
      shift += 7;
    } while (b & 0x80);
    return value;
  }

  // A length, then that many bytes of UTF-8 text.
  name() {
    const length = this.u32();
    const end = this.pos + length;
    if (end > this.bytes.length)
      throw Error('functionNames: a name runs past the end of the file');
    const text = new globalThis.TextDecoder().decode(
      this.bytes.subarray(this.pos, end),
    );
    this.pos = end;
    return text;
  }
Select code to copy. Scroll horizontally if needed.

u32 adds each byte's low 7 bits at the place shift gives them, 0, then 7, then 14, and goes on while the byte's top bit, 0x80, is set. For the B8 02 decoded earlier, u32 adds B8 & 0x7f, 56, at shift 0, then 2 at shift 7, 256, and stops because 02's top bit is clear: 312. Multiplying by 2 ** shift keeps the arithmetic in ordinary numbers. JavaScript's << works on 32-bit signed integers, so in a fifth byte, at shift 28, it could turn a large number negative. name() reads a length with u32 and decodes that many bytes as text, so every name in the file costs one call.

Walk the sections

Replace the sections region:

functionNames: find the name sectionexamples/names-checkpoint.mjs · sections

Replace the sections region.

// { [index]: name } for every function the "name" section names; {} without one.
export function functionNames(bytes) {
  const magic = [0x00, 0x61, 0x73, 0x6d];
  if (!magic.every((b, i) => bytes[i] === b))
    throw Error('functionNames: not a WebAssembly file');
  const r = new Reader(bytes, 8);
  while (r.pos < bytes.length) {
    const id = r.byte();
    const size = r.u32();
    const end = r.pos + size;
    if (id === 0 && r.name() === 'name') return functionSubsection(r, end);
    r.pos = end;
  }
  return {};
}
Select code to copy. Scroll horizontally if needed.

After the 8 fixed bytes, each section starts with its id and size, so end is where the next section begins. A section that isn't custom, or a custom section with another name, is skipped by setting pos to end without reading its contents. Only custom sections have a name to read, which is why the test reads it only when id === 0. A file without a name section runs out of sections and gets {}.

Read subsection 1

Replace the subsections region:

Every function's index and nameexamples/names-checkpoint.mjs · subsections

Replace the subsections region.

// Inside the name section: subsections, each an id byte, a size and contents.
// Subsection 1 is a count, then each function's index and name; skip the rest.
function functionSubsection(r, end) {
  const names = {};
  while (r.pos < end) {
    const id = r.byte();
    const size = r.u32();
    const next = r.pos + size;
    if (id === 1) {
      for (let n = r.u32(); n > 0; n--) {
        const index = r.u32();
        names[index] = r.name();
      }
    }
    r.pos = next;
  }
  return names;
}
Select code to copy. Scroll horizontally if needed.

Each subsection is found the way sections were, by its id and size, and next is where the following one begins. Subsection 1 is read entry by entry: an index, then a name. Every other subsection, the module's name in subsection 0 among them, is skipped by jumping to next. Setting pos to next after subsection 1 too means the next subsection is read from where it really starts, even if subsection 1 held more than its entries. The order of subsections doesn't matter, which is what the check's small file tests.

Read Lob's names with your functionNames:

Observed output
node examples/show-names.mjs project
Select code to copy. Scroll horizontally if needed.

The output calls game_tick the function run once per game frame. It calls r_px the getter that returns the shell's horizontal position.

The names your functionNames readsexamples/names-output.txt
targets/lob-names.wasm: 7271 bytes, 29 names
  0 server_round    1 js_cos          2 js_sin          3 server_wind
  4 game_init       5 new_round       6 update_hud      7 game_key
  8 game_tick       9 r_angle         10 r_power        11 r_cannon_x
  12 r_target_x     13 r_flying       14 r_px           15 r_py
  16 r_impact_x     17 r_impact_age   18 r_result       19 r_wind_level
  20 r_cloud        21 r_trail_ptr    22 r_trail_n      23 r_trail_head
  24 r_line_ptr     25 r_msg_ptr      26 r_help_ptr     27 r_mode
  28 r_state
targets/lob.wasm: 6682 bytes, no name section, so {}
Select code to copy. Scroll horizontally if needed.

The named build is 589 bytes longer than the stripped one: the name section and the two other custom sections in the figure. The stripped build has no section called name, so the walk reaches the end of the file and returns {}. Most of these names were already in the listing. The game exports game_init, game_key, game_tick and every getter under these names, and it imports server_round and server_wind under theirs. Only the name section holds the names of the two functions the game doesn't export, new_round and update_hud, and the C names of the two imports the game asks for as cos and sin. In debug.mjs, break update_hud now finds function 6 by its name.

FileWhat function 6 is called
lob.wasmNo stored label
lob-names.wasmupdate_hud

The call stack

Your machine already keeps the call stack in state.frames, outermost first, each with the function it's running and the at of its next instruction. stack() returns [{ func, at }] for those frames at the debugger's current position, or [] between calls. A call to an import pushes no frame, because the import runs outside the machine and returns at once.

In debug.mjs, stack prints the frames with names, and where names the instruction that runs next.

Question 12b: you stop where update_hud, function 6, begins during a call to game_tick. How many entries does stack() return? Commit:

Observed output
node lab.mjs predict project 12b YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

A stop where update_hud begins comes after game_tick's call instruction has pushed update_hud's frame, so that frame counts. A call that comes from outside the game, from the recording rather than from another function, works differently. It begins between calls, so at a stop where it begins, its instruction 0 runs next but no function is running yet, and stack() is [].

List the frames

In project/debugger.mjs, find the stack region near the end of the class. It holds the stub of stack(), which throws "stack: not written yet (lesson 12)". Replace everything between // region: stack and // endregion: stack with the listing below. If your file has no such markers, because you wrote it without lesson 10's starter, replace your stack() stub with the listing and add the two marker lines around it:

stack(): the frames, outermost firstexamples/stack-checkpoint.mjs · stack

Replace the stack region, which holds the stack() stub.

  stack() {
    return this.machine.state.frames.map((f) => ({ func: f.func, at: f.at }));
  }
Select code to copy. Scroll horizontally if needed.

The frames are copied into new objects, so a caller that changes what stack() returned can't change the machine. Each frame's at is the instruction that frame runs next: the innermost frame's is the instruction that runs next in the whole run, and a caller's is the instruction after its call, where it carries on when the call returns. Between calls the machine has no frames, so the list is empty, which is what API.md asks.

Check 12.stack compares your stacks with a fresh machine at many positions.

Stopping at a function

A function stop fires at a position where a call to that function begins, meaning the next instruction is the function's instruction 0. Add functions: [index] to the stops continue and continueBack understand, with reason: 'function'. In debug.mjs, break update_hud adds a function stop by name, and break 6:120 a breakpoint at one instruction.

Stop kindMay fire without a write?Safe to skip an unchanged page stretch?
WatchNoYes
BreakpointYesNo
Function startYesNo

Two places in lesson 10's debugger.mjs need the change. stopHere, in the stops region, tests the stops at each position, so it needs the function test. And continueBack, in the search-back region, decides which stretches it may skip with const watchesOnly = !stops.breakpoints?.length;. A function stop, like a breakpoint, can fire in a stretch that writes nothing, so that line must count function stops too. Left as it is, a continueBack given only functions counts as "watches only" with no watched pages, skips every stretch and reports 'start'.

Your first node lab.mjs check project 12 doesn't say "not written yet" for 12.function-stops. Lesson 10's continue and continueBack already exist and run; they ignore a functions list they don't know, so the check gets a real answer from them, such as { reason: "end" } from continue, and prints it beside the stop it expected.

Baseline12.function-stops result
Lesson 10 debuggerRuns, but misses the requested function stop
Lesson 12 debuggerStops with reason: 'function'

Test for a function stop

Tour the supplied nextInstruction again, directly above where in your debugger.mjs. During a call it answers the innermost frame's next instruction, and between calls the first instruction of the next call, { func: this.callFunc[calls], at: 0 }. So the instruction a call begins with is visible at the position before it runs, whether the call comes from another function or from the recording.

Replace the stops region. Only the marked lines differ from lesson 10's:

stopHere with function stopsexamples/stack-checkpoint.mjs · stops

Replace the stops region; the marked lines are new.

  stopHere({ breakpoints = [], watches = [], functions = [] }, event) {
    if (event && event.writes.some((w) => changesWatched(w, watches)))
      return 'watchpoint';
    const next = this.nextInstruction();
    if (
      next &&
      breakpoints.some((b) => b.func === next.func && b.at === next.at)
    )
      return 'breakpoint';
    // A function's instruction 0 runs next only where a call to it begins.
    if (next && next.at === 0 && functions.includes(next.func))
      return 'function';
    return null;
  }

  continue(stops = {}) {
    while (this.tick < this.end) {
      const event = this.forward();
      const reason = this.stopHere(stops, event);
      if (reason) return { reason, tick: this.tick };
    }
    return { reason: 'end', tick: this.tick };
  }
Emphasized lines: 1, 10, 11, 12. Select code to copy. Scroll horizontally if needed.

stopHere now takes functions, defaulting to none, so every caller from lesson 10 still works. The function test looks forward, like the breakpoint test, at the instruction that runs next. Both halves of its condition matter: the function must be one of the stopped ones, and its instruction 0 must be next. Instruction 0 of a function runs next only where a call to it begins. A branch inside a function goes either forward to the end of a block or back to the first instruction inside a loop, after the loop instruction itself, and neither is instruction 0. continue is unchanged: it already asks stopHere after every instruction.

Then replace the search-back region. Only the marked line differs from lesson 10's:

continueBack skips stretches only when every stop is a watchexamples/stack-checkpoint.mjs · search-back

Replace the search-back region; the marked line is changed.

  continueBack(stops = {}) {
    const here = this.tick;
    if (here === 0) return { reason: 'start', tick: 0 };
    const pages = (stops.watches ?? []).flatMap((w) =>
      pagesOf(w.address, w.size ?? 1, this.pageSize),
    );
    const watchesOnly = !stops.breakpoints?.length && !stops.functions?.length;
    const found = this.searchBack(
      here - 1,
      (event) => {
        const reason = this.stopHere(stops, event);
        return reason ? { reason, tick: this.tick } : null;
      },
      (i) => !watchesOnly || this.mayHaveWritten(i, pages),
    );
    if (found) {
      this.moveTo(found.tick);
      return found;
    }
    this.moveTo(0);
    return { reason: this.stopHere(stops, null) ?? 'start', tick: 0 };
  }

  searchBack(last, test, mayMatch = () => true) {
    for (let i = Math.ceil(last / this.every) - 1; i >= 0; i--) {
      if (!mayMatch(i)) continue;
      const snapshot = this.snapshots[i];
      const stop = Math.min(last, snapshot.tick + this.every);
      this.restore(snapshot);
      let found = null;
      while (this.tick < stop) {
        const finding = test(this.forward());
        if (finding) found = finding;
      }
      if (found) return found;
    }
    return null;
  }

  mayHaveWritten(i, pages) {
    const a = this.snapshots[i];
    const b = this.snapshots[i + 1];
    return !b || pages.some((p) => a.pages[p] !== b.pages[p]);
  }
Emphasized lines: 7. Select code to copy. Scroll horizontally if needed.

watchesOnly decides whether continueBack may skip a stretch whose watched pages stayed shared. With a function stop present it is now false, so every stretch going back is replayed until one holds a stop, as with a breakpoint. The cost is about the distance to the stop plus up to two stretches, lesson 10's cost for a breakpoint.

Run to the end of the function

stepOut() runs forward until the function running now has returned to its caller, that is, until the call stack is shorter than it is now. In debug.mjs it's finish. Between calls there is no function running. Define what stepOut() does there and say so in a comment.

Find the step-out region, which holds the stub of stepOut() that throws "stepOut: not written yet (lesson 12)". Replace everything between // region: step-out and // endregion: step-out with the listing below, or, in a file without those markers, replace your stepOut() stub and add the two marker lines around it:

stepOut: forward until there are fewer framesexamples/stack-checkpoint.mjs · step-out

Replace the step-out region, which holds the stepOut() stub.

  // Forward to the first position with fewer frames than now. Between calls no
  // function is running, so stepOut runs the whole next call and stops where it
  // has returned, at the next position between calls. At the end it stays.
  stepOut() {
    const depth = this.machine.state.frames.length;
    if (depth === 0) {
      if (this.tick < this.end) {
        do {
          this.forward();
        } while (this.machine.running);
      }
    } else {
      while (this.machine.state.frames.length >= depth) this.forward();
    }
    return this.tick;
  }
Select code to copy. Scroll horizontally if needed.

Inside a call, stepOut counts the frames now and runs instructions until there are fewer. A call made on the way pushes a frame and pops that frame again, which doesn't stop stepOut; the stop comes when the starting function's own return or final end pops its frame. The first position with fewer frames is where the caller carries on, or, for the outermost function of a call, the position between calls after it. Between calls, this checkpoint runs the whole next call, the one where() names, and stops where it has returned. Another choice would do, such as refusing or not moving, as long as the comment says which. forward() is lesson 10's: between calls it begins the next call first. Moving forward replays only the distance moved, so stepOut costs the instructions it runs.

Starting positionStop condition
Inside a functionThe frame count first becomes smaller
Between callsThe next whole call returns
End of recordingStay at the end

Checks 12.function-stops and 12.step-out compare your stops with a scan of every instruction. 12.function-stops seeks to positions spread over a recording and from each asks both continue and continueBack for a function stop. 12.step-out seeks to positions inside calls and calls stepOut, which counts frames and passes no stops to the debugger. 12.stack seeks and compares stack() with a fresh machine, and 12.names and 12.lines call only names.mjs.

All four changes to debugger.mjs are in. examples/stack-session.txt is a script of debug.mjs commands that goes to the first game frame of lesson 09's recording, stops where update_hud begins, prints the stack, runs to the end of update_hud with finish, and then continues backward to the stop again:

Observed output
node debug.mjs project project/run42.json examples/stack-session.txt
Select code to copy. Scroll horizontally if needed.
A function stop, the stack and finishexamples/stack-session-output.txt
project/run42.json: 759 calls, 652927 instructions. Type help for commands.
> call 13
tick 84111, call 13 (game_tick), next: function 8 (game_tick), instruction 0: global.get 0
> break update_hud
stops: {"breakpoints":[],"watches":[],"functions":[6]}
> continue
function at tick 84157, call 13 (game_tick), next: function 6 (update_hud), instruction 0: global.get 0
> stack
0: function 8 (game_tick), instruction 570: local.get 0
1: function 6 (update_hud), instruction 0: global.get 0
> finish
tick 84827, call 13 (game_tick), next: function 8 (game_tick), instruction 570: local.get 0
> stack
0: function 8 (game_tick), instruction 570: local.get 0
> cost
659299 instructions run by your machine so far, 652927 of them while your Debugger opened the recording
> rcontinue
function at tick 84157, call 13 (game_tick), next: function 6 (update_hud), instruction 0: global.get 0
> cost
660282 instructions run by your machine so far, 652927 of them while your Debugger opened the recording
Select code to copy. Scroll horizontally if needed.
The call stack from the snapshot at 84,000 through call 13, as the number of frames at each position. The snapshot falls inside call 12, which holds two frames and has returned by 84,111, where call 13 begins. game_tick's frame is alone until update_hud begins at 84,157, where the function stop fires; two frames until finish stops at 84,827 with one frame again. Below, rcontinue from 84,827 restores the snapshot, replays 826 instructions noting each stop, then restores again and replays 157 to the stop: 983 in all.

The function stop fires with update_hud's instruction 0 next, and the stack shows game_tick waiting at its instruction 570, the one after its call. finish stops at the first position with fewer frames, where game_tick carries on at instruction 570, 670 instructions after the stop. The two cost lines differ by 983, the two replays under the figure: 826 instructions to replay the stretch from the snapshot at 84,000 to the position before the one rcontinue started from, and 157 to move back to the stop. The first cost also counts the replay your Debugger made when it opened the recording, and the seeks call 13 made.

MoveInstructions replayed from snapshot 84,000
Search back to the earlier stop826
Restore and stand on that stop157

Lines

The compiler can also write a line table, which gives, for each stretch of code, the line of the C source it came from. It lives in .debug_line, one of the sections of DWARF, the standard format for debugging information, which only a build with debugging information carries. No file this course ships carries DWARF, because DWARF also records the layout of every C struct, which is what Sightline asks its learners to work out. The course decoded the line table of a debugging build when it built the targets and saved its rows in lines/lob.json: { offset, line, column }, sorted by offset. DWARF counts a WebAssembly address from the start of the code section's contents, after its id byte and size. The code section holds the functions' instructions, and the listing records where its contents start as codeSectionStart. The course added that start, so offset is a file offset like the listing's offsets, where offsets[k] is the file offset of instruction k.

Row fieldPlain meaning
offsetByte position in the .wasm file
lineC source line assigned by the compiler
columnCharacter position on that source line

An instruction belongs to the last row at or before its offset. lineAt(lines, offset) finds that row with a binary search and returns { line, column }, or null before the first row.

Here are five rows of lines/lob.json, around the end of the loop of lesson 08 that clears memory in game_init:

Observed output
offset  line  column
   555   259      52
   561     0      52
   565   259      26
   566   259       3
   571   260       5
Select code to copy. Scroll horizontally if needed.

Some rows say line 0. That means the compiler assigned no source line. Lob has 561 such instructions among its 2,806. The stack operation local.get copies a function variable's value onto the working stack. i32.const pushes a fixed 32-bit integer. Both begin repeated copies in lesson 08's unrolled clearing loop, and some copies have line 0. debug.mjs prints "no line" for them.

DWARF also marks the end of each function with an end-of-sequence row. The course keeps that marker as line 0, so one function's last source line never covers the next function.

The C source isn't given, so a line number is a label rather than a place you can read. It still groups instructions into statements. An assignment compiled to eight instructions gives all eight one line, and comparing lines is how a debugger steps by line.

Question 12c: instruction 47 of game_init, the br_if 0 that closes that loop, is at file offset 568. What line does lineAt give it? Commit:

Observed output
node lab.mjs predict project 12c YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Find the row

Replace the line-at region of project/names.mjs:

lineAt: the last row at or before an offsetexamples/names-checkpoint.mjs · line-at

Replace the line-at region.

// { line, column } of the last row at or before `offset`, or null when every
// row comes after it. Rows are sorted by offset.
export function lineAt(lines, offset) {
  let lo = 0;
  let hi = lines.length;
  // Rows before lo are at or before offset; rows from hi on come after it.
  while (lo < hi) {
    const mid = (lo + hi) >> 1;
    if (lines[mid].offset <= offset) lo = mid + 1;
    else hi = mid;
  }
  if (lo === 0) return null;
  return { line: lines[lo - 1].line, column: lines[lo - 1].column };
}
Select code to copy. Scroll horizontally if needed.

The search keeps one rule true as lo and hi close in: every row before lo is at or before offset, and every row from hi on comes after it. When they meet, lo is the first row past offset, so the preceding row is the answer. When lo is still 0, every row comes after the offset and there is no line. Lob's table has 1,050 rows, so a question takes at most 11 comparisons. A row of line 0 is returned like any other; deciding what it means is left to the caller, as debug.mjs does.

Check 12.lines asks lineAt about every instruction of Lob and compares with the rows.

Search stateKnown fact
Before loRow offset is at or before the requested offset
From hi onwardRow offset comes after the requested offset

debug.mjs calls your lineAt from its supplied describe function, which every command uses to print an instruction. Tour it near the top of debug.mjs. It looks up the instruction's file offset in the listing, f.offsets[at], and passes it to lineOf, which calls your lineAt to find the row. Then it adds [line N] after the instruction, or [no line] for a row of line 0, beside the name your functionNames gave. Run the same script again:

Observed output
node debug.mjs project project/run42.json examples/stack-session.txt
Select code to copy. Scroll horizontally if needed.
The same session, with linesexamples/lines-session-output.txt
project/run42.json: 759 calls, 652927 instructions. Type help for commands.
> call 13
tick 84111, call 13 (game_tick), next: function 8 (game_tick), instruction 0: global.get 0  [line 306]
> break update_hud
stops: {"breakpoints":[],"watches":[],"functions":[6]}
> continue
function at tick 84157, call 13 (game_tick), next: function 6 (update_hud), instruction 0: global.get 0  [line 136]
> stack
0: function 8 (game_tick), instruction 570: local.get 0  [line 335]
1: function 6 (update_hud), instruction 0: global.get 0  [line 136]
> finish
tick 84827, call 13 (game_tick), next: function 8 (game_tick), instruction 570: local.get 0  [line 335]
> stack
0: function 8 (game_tick), instruction 570: local.get 0  [line 335]
> cost
659299 instructions run by your machine so far, 652927 of them while your Debugger opened the recording
> rcontinue
function at tick 84157, call 13 (game_tick), next: function 6 (update_hud), instruction 0: global.get 0  [line 136]
> cost
660282 instructions run by your machine so far, 652927 of them while your Debugger opened the recording
Select code to copy. Scroll horizontally if needed.

Every instruction now carries its line. game_tick's instruction 570, where it carries on after update_hud returns, is on line 335, a statement after the one that called update_hud. The run, the stops and the costs are the same as before: reading lines runs nothing.

Every region of both files is filled. Run the unit's checks, describing what you did:

Terminal command
# After filling the type-in route's starter and your debugger from the listings:
node lab.mjs check project 12 --help-used "filled four names regions and four debugger changes from chapter listings"
# After following the supplied route:
node lab.mjs check project 12 --help-used "supplied names and stack checkpoints; followed the explanations and tours"
Select code to copy. Scroll horizontally if needed.

All 5 checks should pass. If one fails, its first mismatch names the section to reread. Keep the failing attempt and your explanation before you edit.

Read a stack

Open lesson 09's recording in debug.mjs, break new_round, and at each stop print the stack with stack. continue takes you to the next round. At one stop, finish and print the stack again. As in lesson 10, you can type these commands, or put them in a file, one per line, and pass it as the last argument, for a session with no keyboard. Write in project/report.md which call started each round, by index, and which function called new_round each time.

Stop anywhere in a function, then repair it

In your project only, take the first half out of the function test in stopHere, so that it reads:

JavaScript
if (next && functions.includes(next.func))
Select code to copy. Scroll horizontally if needed.

Question 12d: with this change, how many of unit 12's five checks fail? Before you run anything, write in project/report.md which ones you expect to fail and why, and where the rcontinue in examples/stack-session.txt will stop now, then commit the number. Then run the check with --help-used describing this prescribed change, and run the session again:

Terminal command
node lab.mjs predict project 12d YOUR_ANSWER
node lab.mjs check project 12 --help-used "prescribed change: a function stop at any instruction of the function"
node debug.mjs project project/run42.json examples/stack-session.txt
Select code to copy. Scroll horizontally if needed.

Compare the checks that failed, and where rcontinue stopped, with what the lab said after your prediction. Read the first failure's position and the one it expected. Explain in project/report.md why a backward search and a forward search can differ under this change. Put back next.at === 0 && and rerun the check, keeping both attempts:

Terminal command
node lab.mjs check project 12 --help-used "prescribed change removed"
Select code to copy. Scroll horizontally if needed.

This change is guided practice; the new application below asks for behavior none of these listings implements.

Use it on a new case: step by line

step moves one instruction, and finish a whole function. A person reading C wants a step between the two: run to the next line of the function they're in, stepping over any function it calls, as gdb's next does. Write nextLine(debugger, program, lines) in project/next-line.mjs, which both route commands created. If you didn't use them, copy starter/next-line.mjs to project/next-line.mjs first. No finished version is supplied, and none of the listings above does this. Its contract:

InputRole
debuggerCurrent replay position and movement
programInstruction offsets
linesSource line rows
Frame count while steppingMeaning
Greater than the startInside a called function; keep moving
Equal to the start, new nonzero lineStop
Less than the startStarting function returned; stop
Starting positionAllowed action
Inside a functionSearch for the next line or return
Between calls or at endThrow before moving

Before you write code, answer two questions in project/report.md. A line calls update_hud, and update_hud's own instructions carry other lines: what tells you to keep going inside it, and what would go wrong if you compared only lines? A loop whose whole body is on one line jumps back to its start: where does your step stop? Keep that first reasoning. Then run the checker on the unfinished file, implement, and run it again, describing assistance honestly each time:

Terminal command
node examples/check-next-line.mjs project --help-used "initial attempt; nothing written"
node examples/check-next-line.mjs project --help-used "describe what helped your implementation"
Select code to copy. Scroll horizontally if needed.

The budget holds for every question the checker asks: a step may run at most the number of instructions it moves forward, plus 2,000. Moving forward one instruction at a time costs exactly the distance, and the 2,000 leave room for one restore from a snapshot and a short replay. A step that replays from position 0, or from far behind, for each instruction doesn't fit.

Checker groupBoundary it exercises
Between calls and endRefusal without movement
Called functionStep over deeper frames
Last function lineStop after return
Line 0 and one-line loopIgnore missing or unchanged lines

The checker copies machine.mjs, recorder.mjs, debugger.mjs, names.mjs, next-line.mjs, PROJECT.json and your report.md into a new folder under project/attempts/ before it runs anything, and saves its results beside them in nline-receipt.json. A failure never replaces an earlier attempt, and node lab.mjs status project lists every attempt under "New-application attempts". It replays one of unit 10's check recordings, a run of Lob, once on your machine, keeping the frames and the instruction at every position, and works out each answer from that pass and the line table. It then asks six groups of questions: refusals between calls and at the end; a line followed by another line of the same function; a line that calls a function; the last line of a function; line-0 instructions and a long loop on one line in game_init; and twenty steps in a row through a game frame.

Saved artifactPurpose
project/attempts/*/nline-receipt.jsonKeeps each result
Copied project filesMakes that attempt reproducible

As a stretch, add a next command to your own copy of debug.mjs that calls nextLine.

Keep the working tool

project/names.mjs now reads function names from a binary's name section and finds the source line of any instruction, and project/debugger.mjs lists the call stack, stops where a named function begins and runs to the end of the current function. debug.mjs uses them for every instruction it prints and for stack, break NAME and finish. The end-of-unit checkpoints are examples/names-checkpoint.mjs and examples/stack-checkpoint.mjs; recover from them with a new project, as in "Start", never by copying them over your files. Lesson 13 adds no new code to the debugger: you use it, with your index from lesson 11, to find the planted bug in each of six later builds of the game.

Earlier ideas, new cases

Question 08d3: f32.convert_i32_u pops the value 16,777,219, which is 2 to the power 24, plus 3. What number does it push?

Observed output
node lab.mjs predict project 08d3 YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Question 10a3: in Lob, seed 3, mode 0, the first game frame after game_init writes to 3 of the 32 pages of 4,096 bytes. With pages of 16,384 bytes instead, how many of the 8 pages would it write to?

Observed output
node lab.mjs predict project 10a3 YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Question 11c3: in project/run42.json, calls 2 to 12 are presses of the up key, and each adds 1 to the power at g + 4. The game keeps the power XORed with a key at g + 92: game_init stores the key once, 0 in this recording, and stores the starting power, 60, together with the angle in one 8-byte store. How many stores are on the chain of the value stored at g + 4 in call 4?

Observed output
node lab.mjs predict project 11c3 YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

13 · The ladder

Use six broken builds, game versions, to follow each visible failure to the first instruction, a numbered machine operation, that changes a correct byte, a number from 0 to 255, into a wrong one.

In build 1, the second shell lands 10 paces from its target flag. A shell within 12 scores, so predict HIT!; the game prints SHORT BY 10. A first bad write is that earliest wrong-byte instruction. Each investigation reruns a command script, a debugger-command file, under an instruction limit, its maximum number of machine operations.

lab.mjs is the course tool. Node, the JavaScript runner, uses ladder to list each build, its recording, a saved execution, and its limit:

Terminal command
node lab.mjs ladder
Select code to copy. Scroll horizontally if needed.

Start

Your project must pass units 08 to 12 because every investigation uses your machine, recorder, debugger, index, and names. The six recordings already exist.

If needed, build a supplied project13:

Terminal command
node examples/start-chapter.mjs project13 supplied
node examples/start-recorder.mjs project13 supplied
node examples/start-debugger.mjs project13 supplied
node examples/start-query.mjs project13 supplied
node examples/start-names.mjs project13 supplied
Select code to copy. Scroll horizontally if needed.

Use project13 in later commands. Otherwise, keep using project. Add each worked listing to project/investigations/1.txt in order. Builds 2 to 6 remain your investigations. Create the new byte-history application:

Terminal command
node examples/start-changes.mjs project
Select code to copy. Scroll horizontally if needed.

The command preserves an existing changes.mjs. Record a baseline:

Terminal command
node lab.mjs check project 13 --help-used "lesson 13 start; investigation stubs"
Select code to copy. Scroll horizontally if needed.

Each stub reports not written yet. A check passes when its script ends with answer, names the first bad write by function, instruction, address, and tick, and stays within budget.

What you have and what you don't

For each build you get its .wasm file (with function names), its listing in programs/ladder/, and its recording in recordings/ladder/. You don't get its C source, and its memory is laid out differently from lob.wasm. The game's state sits elsewhere and its fields are in another order. So you can't find the change by comparing memory with lob.wasm, and a listing compared line by line with lob.wasm's differs almost everywhere.

What you can compare is behaviour. lob.wasm is the last good build of Lob, and lob2.wasm is the good build for build 6. A getter is a function that reads one game value. r_px returns the shell's horizontal position; r_result returns its landing kind. Lob II exposes unnamed getters g0 to g7. debug.mjs runs each changed build and its good build on the same calls in Node's engine:

Changed buildGood build used by compare
1 to 5lob.wasm
6lob2.wasm

Neither command uses your machine or counts towards the budget. They tell you where to look, and your debugger finds the write.

The method

Work backward from the first visible difference to the first bad write.

The seven steps of the method as boxes from top to bottom, each with the debug.mjs commands it uses: find the first visible difference, find the address the getter reads, find who wrote it, judge that store, look before it, list every change to the byte, name it. An arrow goes back from step 4 to step 3 when an input was already wrong, and from step 5 to itself when the first store in the stretch is already wrong.

The two arrows that go back are steps 4 and 5 below, and each moves the candidate store earlier in the run.

  1. Find the first visible difference. Start from the build's symptom, or run diverge. Note the call and the getter.
First evidenceRecord before moving backward
diverge outputCall index and getter name
  1. Find the address. A getter reads memory, so run it in your head from the listing, or stand between calls and read the bytes it reads. In Lob, r_px reads the pointer at 78,112 and then the 4 bytes at an offset from it. In a ladder build the pointer's address and the offset can both differ (build 1's pointer is at 72,992), and the listing gives both. The address the pointer holds, where the state lives, also depends on the seed, game_init's first argument, even in the good build: lob.wasm keeps its state at 65,888 in a game started with seed 4 and at 66,304 with seed 30. Read the pointer at the call you are investigating, in the run you are investigating. In mode 2 the game moves its state to a new address at every new round (API.md, "public/sessions.mjs"), so an address read in round 2 may hold something else in round 1.
Address factWhere to get it
Pointer locationGetter listing
Field offsetGetter listing
State address for this roundread at the call being investigated
  1. Find who wrote it. Stand at the start of the call after the one where the getter first differs (call 238 after a difference in call 237). There last-write ADDR (your Debugger) or who ADDR (your index) takes you to the last store to that byte.
CommandPosition after it runs
last-write ADDRImmediately after the last store to that byte
who ADDRSame store, found through the index
  1. Judge that store. Read its value and ask sources which stores, answers and arguments it was computed from. In a ladder build a chain can hold hundreds of stores, so sources prints their count and the newest 8, each with its tick, function and address, and sources N shows the newest N. If one of its inputs was already wrong, that input's store is earlier on the chain, so go back to step 3 with it. If all its inputs hold the values a correct build would have, and its result is still wrong, the planted change acts here.

Question 13a: in some build, a store writes 0 over 0 at the first byte of the message line. Immediately before this store, at the same point of the run, the good build's message already reads HIT!, so its first byte holds H. Can that store be the first bad write? Answer yes or no, and commit:

Observed output
node lab.mjs predict project 13a YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.
  1. Look before it. The code that made one wrong store often made others a few instructions earlier, from the same wrong decision. Step back a little (back 30) and list what the next instructions write (writes 30, which also moves the debugger 30 instructions forward, back where you stood). The earliest store in that stretch with a wrong value is your new candidate, even if it isn't the one your symptom led you to. If the stretch's first store is already wrong, step back further.
Candidate stateNext move
Inputs already wrongFollow the earlier input store
Inputs right, stored result wrongInspect nearby earlier stores
Byte was wrong before this storeSearch farther back
  1. List every change. A wrong byte's last writer may not be the store that first made it wrong. Remove earlier stops with clear, then set watch ADDR on the byte, seek 0 and continue again and again. Each stop is right after a store that changed the byte, so the stops list every change to it from the start of the run.
  2. Name it. Stand right after the first bad write (last-write, who and a watch's stop leave you there, and after writes, seek the tick it printed for that store) and run answer.

To judge a store, take what is right from the help text (angle 5 to 85, power 10 to 100, land within 12 paces to score), from what the good build shows through its getters on the same calls, and from arithmetic you can redo from the listing. Lob II's getters don't say what they hold, so for build 6 your notion of right comes from compare against lob2.wasm and from the build's symptom in node lab.mjs ladder.

Source of truthUse it for
Help textGame rules and valid ranges
Good-build gettersExpected value on the same calls
Listing arithmeticWhether the store computed that value

The last writer of a wrong value isn't always the first bad write: the same wrong store may have run earlier, and its earlier result may since have been overwritten, which step 6 shows. A store can also write a right value to the wrong address. Then the inputs sources lists can all be right, because the chain doesn't follow addresses, so look at how the address was computed.

A worked investigation: build 1

Build 1's symptom: the second shell lands 10 paces short of the flag and the message reads SHORT BY 10, although the help says a shell within 12 paces scores. lob.wasm shows HIT! on the same calls. Here is the investigation, built up in project/investigations/1.txt one step of the method at a time. After each step, run the script so far:

Observed output
node debug.mjs project 1 project/investigations/1.txt
Select code to copy. Scroll horizontally if needed.

debug.mjs opens build 1's recording with your Debugger, then runs every command in the script from the top and prints each one's output. The script has no answer yet, so it only looks.

Find the first visible difference

Add these lines at the end of project/investigations/1.txt:

Step 1: the first call after which a getter differsexamples/investigation-1.txt · symptom

Add at the end of project/investigations/1.txt.

# The second shell lands 10 paces short; lob.wasm says HIT! on the same calls.
diverge
Select code to copy. Scroll horizontally if needed.

Run the script:

Observed output
node debug.mjs project 1 project/investigations/1.txt
Select code to copy. Scroll horizontally if needed.

game_tick is the function called once to advance the game by one frame.

After step 1examples/investigation-step1-output.txt
Build 1: 241 calls, 265287 instructions. Type help for commands.
> diverge
after call 237 (game_tick): r_result is 2 here, 1 in lob.wasm
Select code to copy. Scroll horizontally if needed.

Call 237 is the game frame in which the second shell lands, and r_result is the kind of landing: 1 a hit, 2 short. The first line is your Debugger opening the recording, a replay of all 265,287 instructions. diverge itself ran the two builds in Node's engine, not on your machine.

Find the address

Add:

Step 2: where r_result reads, at the call after the differenceexamples/investigation-1.txt · address

Add at the end of project/investigations/1.txt.

# r_result reads the pointer at 72992, then 4 bytes at offset 0 from it.
listing r_result:0 4
call 238
read 72992 4 i32
Select code to copy. Scroll horizontally if needed.

Run the script again:

Observed output
node debug.mjs project 1 project/investigations/1.txt
Select code to copy. Scroll horizontally if needed.

The listing uses two WebAssembly stack operations. i32.const 0 pushes the 32-bit integer 0. i32.load takes an address from the stack, adds the shown byte offset, and reads 4 bytes as a 32-bit integer. The first load reads the state pointer; the second reads the result stored at that pointer.

After step 2examples/investigation-step2-output.txt
Build 1: 241 calls, 265287 instructions. Type help for commands.
> diverge
after call 237 (game_tick): r_result is 2 here, 1 in lob.wasm
> listing r_result:0 4
function 18 (r_result)
>     0  i32.const 0
      1  i32.load 2 72992
      2  i32.load 2 0
      3  end
> call 238
tick 262788, call 238 (game_tick), next: function 8 (game_tick), instruction 0: global.get 0
> read 72992 4 i32
65928
Select code to copy. Scroll horizontally if needed.

The getter loads the pointer at 72,992 and reads 4 bytes at offset 0 from it. call 238 stands where call 238 begins, between calls, after call 237 has finished. After call 237 the pointer holds 65,928, so the result lives at 65,928 in this run. This build lays out its state differently from lob.wasm, so in another build find both addresses again.

Find who wrote it

Add:

Step 3: the last store to the resultexamples/investigation-1.txt · writer

Add at the end of project/investigations/1.txt.

# The pointer holds 65928, so the result lives there. Who wrote it?
last-write 65928
Select code to copy. Scroll horizontally if needed.

Run the script again:

Observed output
node debug.mjs project 1 project/investigations/1.txt
Select code to copy. Scroll horizontally if needed.
After step 3examples/investigation-step3-output.txt
Build 1: 241 calls, 265287 instructions. Type help for commands.
> diverge
after call 237 (game_tick): r_result is 2 here, 1 in lob.wasm
> listing r_result:0 4
function 18 (r_result)
>     0  i32.const 0
      1  i32.load 2 72992
      2  i32.load 2 0
      3  end
> call 238
tick 262788, call 238 (game_tick), next: function 8 (game_tick), instruction 0: global.get 0
> read 72992 4 i32
65928
> last-write 65928
tick 261685: function 8 (game_tick), instruction 304: i32.store 2 0 wrote 4 bytes at 65928
Select code to copy. Scroll horizontally if needed.

tick 261685: function 8 (game_tick), instruction 304: i32.store is the landing code storing 2, short, into the result. last-write moved the debugger to that tick, right after the store.

Tour what debug.mjs supplies for judging

Step 4 judges this store: were its inputs right? Two supplied commands answer that. examples/ladder-tour.txt runs them on build 1 at the places this investigation has reached:

Observed output
node debug.mjs project 1 examples/ladder-tour.txt
Select code to copy. Scroll horizontally if needed.
compare and sources on build 1examples/ladder-tour-output.txt
Build 1: 241 calls, 265287 instructions. Type help for commands.
> call 238
tick 262788, call 238 (game_tick), next: function 8 (game_tick), instruction 0: global.get 0
> compare
r_angle        this build 45             lob.wasm 45
r_power        this build 58             lob.wasm 58
r_cannon_x     this build 80             lob.wasm 80
r_target_x     this build 456.575927734375 lob.wasm 456.575927734375
r_flying       this build 0              lob.wasm 0
r_px           this build 446.37762451171875 lob.wasm 446.37762451171875
r_py           this build 0.11890347301959991 lob.wasm 0.11890347301959991
r_impact_x     this build 446.4408874511719 lob.wasm 446.4408874511719
r_impact_age   this build 0              lob.wasm 0
r_result       this build 2              lob.wasm 1   <- differs
r_wind_level   this build -3             lob.wasm -3
r_cloud        this build 292.3744812011719 lob.wasm 292.3744812011719
r_trail_ptr    this build 66024          lob.wasm 65992   <- differs
r_trail_n      this build 35             lob.wasm 35
r_trail_head   this build 35             lob.wasm 35
r_line_ptr     this build 68660          lob.wasm 71976   <- differs
r_msg_ptr      this build 68224          lob.wasm 72040   <- differs
r_help_ptr     this build 68260          lob.wasm 72072   <- differs
r_mode         this build 0              lob.wasm 0
r_state        this build 65928          lob.wasm 65888   <- differs
status line    this build "ANGLE 45  POWER 58  WIND -4.5  SCORE 0/2"
               lob.wasm   "ANGLE 45  POWER 58  WIND -4.5  SCORE 1/2"   <- differs
message line   this build "SHORT BY 10"
               lob.wasm   "HIT!"   <- differs
help text      the same in both builds: "LOB, a tiny artillery range.\nRIGHT raises the barrel and LEFT lowers it (angle 5 to 85).\nUP adds power and DOWN takes it away (power 10 to 100).\nSPACE fires. N starts a new round with a new flag position and new wind.\nLand within 12 paces of the flag to score.\n"
> seek 261685
tick 261685, call 237 (game_tick), next: function 8 (game_tick), instruction 305: i32.const 0
> sources
stores: 436 on the chain; the newest 8, newest first (sources N shows N, sources all every one):
  tick 260734: function 8 (game_tick), instruction 539: f32.store 2 52 wrote 4 bytes at 65980
  tick 260718: function 8 (game_tick), instruction 523: f32.store 2 36 wrote 4 bytes at 65964
  tick 260709: function 8 (game_tick), instruction 514: f32.store 2 48 wrote 4 bytes at 65976
  tick 260704: function 8 (game_tick), instruction 509: f32.store 2 608 wrote 4 bytes at 66536
  tick 259799: function 8 (game_tick), instruction 539: f32.store 2 52 wrote 4 bytes at 65980
  tick 259783: function 8 (game_tick), instruction 523: f32.store 2 36 wrote 4 bytes at 65964
  tick 259774: function 8 (game_tick), instruction 514: f32.store 2 48 wrote 4 bytes at 65976
  tick 259769: function 8 (game_tick), instruction 509: f32.store 2 608 wrote 4 bytes at 66536
answers: 2 (cos) 3 (sin)
call arguments: call 0 argument 0
initial bytes: none
Select code to copy. Scroll horizontally if needed.

compare runs both builds through calls 0 to 237 in Node's engine, in the supplied nodeGetters function, and prints every getter side by side, then the texts. The shell's landing place and the flag agree with lob.wasm's (r_impact_x and r_target_x), about 10.1 apart, within 12, and so do the angle, power and wind. Only r_result, the status line and the message differ, besides the getters that return addresses, which differ by design. So the store's inputs were right and the decision it stored is wrong.

EvidenceBuild 1Good build
Landing gapAbout 10.1About 10.1
r_result2, short1, hit
MessageSHORT BY 10HIT!

sources asks your index for the chain of the store at the current tick. The supplied chainStores prints how many stores the chain holds, then the newest 8, newest first, each found through your index's lastWriter so that its function and address can be shown; sources N shows the newest N and sources all every one. This chain holds 436 stores, reaching back through the shell's flight to the cosine and sine of the barrel's angle and the seed, call 0's argument 0. Building the index replayed the run once more on your machine, which is why this tour isn't part of the script: the script's budget doesn't need it.

Chain endEvidence shown by sources
NewestRecent stores with ticks and addresses
OldestImport answers and call 0's seed argument

Answer at the result store

A store whose inputs are right and whose value is wrong looks like the planted change at work, so you might name it now. Add one line, answer, at the end of project/investigations/1.txt, after last-write 65928.

Question 13d: with that answer, will 13.build-1 pass or fail? Before you run anything, write in project/report.md which unit 13 checks you expect to pass and fail, and why, then commit pass or fail. Then run the checks:

Terminal command
node lab.mjs predict project 13d YOUR_ANSWER
node lab.mjs check project 13 --help-used "worked investigation of build 1; answer at the result store"
Select code to copy. Scroll horizontally if needed.

Compare what the check printed with what the lab said after your prediction. Keep this attempt and delete the answer line you added.

Look before it

Add:

Step 5: the stores just before the resultexamples/investigation-1.txt · before

Add at the end of project/investigations/1.txt.

# The result store's inputs are right. Did the same decision store anything
# wrong just before it?
back 12
writes 12
Select code to copy. Scroll horizontally if needed.

Run the script again:

Observed output
node debug.mjs project 1 project/investigations/1.txt
Select code to copy. Scroll horizontally if needed.
After step 5examples/investigation-step5-output.txt
Build 1: 241 calls, 265287 instructions. Type help for commands.
> diverge
after call 237 (game_tick): r_result is 2 here, 1 in lob.wasm
> listing r_result:0 4
function 18 (r_result)
>     0  i32.const 0
      1  i32.load 2 72992
      2  i32.load 2 0
      3  end
> call 238
tick 262788, call 238 (game_tick), next: function 8 (game_tick), instruction 0: global.get 0
> read 72992 4 i32
65928
> last-write 65928
tick 261685: function 8 (game_tick), instruction 304: i32.store 2 0 wrote 4 bytes at 65928
> back 12
tick 261673, call 237 (game_tick), next: function 8 (game_tick), instruction 293: i32.trunc_sat_f32_s
> writes 12
tick 261676: function 8 (game_tick), instruction 295: i32.store 2 612 wrote 4 bytes at 66540: 13 0 0 0 -> 10 0 0 0
tick 261685: function 8 (game_tick), instruction 304: i32.store 2 0 wrote 4 bytes at 65928: 0 0 0 0 -> 2 0 0 0
Select code to copy. Scroll horizontally if needed.

back 12 steps back from the result store, and writes 12 steps the debugger forward again over the same 12 instructions and lists the bytes each one wrote. To see an instruction's writes, it runs that instruction once more on a copy of the state, then moves the debugger on, so after writes 12 the debugger stands 12 instructions later, at tick 261,685, right after the result store. There are two stores: at tick 261,676, instruction 295 stored 10 at 66,540, and at tick 261,685 the result. 10 is the miss distance the message prints, and the 13 it replaced was the first shell's, which landed 13 paces long. A hit stores 0 there. Both stores are wrong, and the miss distance came first.

Name it

Add:

Step 7: stand right after the first bad write and name itexamples/investigation-1.txt · answer

Add at the end of project/investigations/1.txt.

# The miss distance, stored at tick 261676, nine instructions before the
# result: the first wrong store.
seek 261676
answer
Select code to copy. Scroll horizontally if needed.

Run it as the check does, with the lab, which prints the answer and what the script cost:

Observed output
node lab.mjs investigate project 1
Select code to copy. Scroll horizontally if needed.
The finished investigation of build 1examples/investigate-1-output.txt
> diverge
after call 237 (game_tick): r_result is 2 here, 1 in lob.wasm
> listing r_result:0 4
function 18 (r_result)
>     0  i32.const 0
      1  i32.load 2 72992
      2  i32.load 2 0
      3  end
> call 238
tick 262788, call 238 (game_tick), next: function 8 (game_tick), instruction 0: global.get 0
> read 72992 4 i32
65928
> last-write 65928
tick 261685: function 8 (game_tick), instruction 304: i32.store 2 0 wrote 4 bytes at 65928
> back 12
tick 261673, call 237 (game_tick), next: function 8 (game_tick), instruction 293: i32.trunc_sat_f32_s
> writes 12
tick 261676: function 8 (game_tick), instruction 295: i32.store 2 612 wrote 4 bytes at 66540: 13 0 0 0 -> 10 0 0 0
tick 261685: function 8 (game_tick), instruction 304: i32.store 2 0 wrote 4 bytes at 65928: 0 0 0 0 -> 2 0 0 0
> seek 261676
tick 261676, call 237 (game_tick), next: function 8 (game_tick), instruction 296: local.get 1
> answer
answer: function 8 (game_tick), instruction 295 (i32.store), address 66540, tick 261676

Instructions replayed: 278551 of a budget of 856000.
Your answer: function 8 (game_tick), instruction 295, address 66540, tick 261676.
Select code to copy. Scroll horizontally if needed.

answer names the write made by the instruction at the current tick, instruction 295 stored 10, at 66,540. The script replayed 278,551 instructions, most of them the opening replay, against a budget of 856,000. Run node lab.mjs check project 13 with --help-used again: 13.build-1 now passes, and builds 2 to 6 still say not written yet.

The symptom you start from decides which wrong store you meet first. Start from the message text, SHORT BY 10, which the getter r_msg_ptr finds through the pointer held at 72,996. last-write on the digit 1 finds the store that wrote it, and sources on that store lists the miss distance's store, tick 261,676, among the newest on its chain. The route from r_result, as above, leads to the result, nine instructions too late. Step 5 is what turns the route from r_result into the right answer.

Question 13b: your debugger keeps a snapshot every 2,000 instructions. Build 5's run is 647,416 instructions long. At most how many instructions can one stepBack(1) replay? Commit:

Observed output
node lab.mjs predict project 13b YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Your investigations

To explore a build, open it in your debugger by its number. node debug.mjs project N loads build N's recording and listing and knows its good build, so diverge and compare work. Try commands there, then copy the ones that lead to the answer into a script. With no keyboard, put the commands you want to try in a file, one per line, and pass it as the last argument: node debug.mjs project N FILE.

Write each investigation in project/investigations/N.txt, one command per line, and run it:

Observed output
node lab.mjs investigate project N
Select code to copy. Scroll horizontally if needed.

The lab prints every command's output, the answer, and how many instructions your machine replayed. The budget counts everything your debugger and index run, from opening the recording to the answer. It leaves room for one index build, a first pass of your debugger and a few dozen backward questions. Replaying from the start for each question doesn't fit.

BuildsSearch shape
1 and 2Bad write is near the symptom
3Find the first wrong store in one unwanted run
4 to 6Trace through later overwrites or copied values

The builds rise in difficulty. Builds 1 and 2 are a short way back from the symptom. Build 3 makes a run of stores in one call that shouldn't have happened at all, and you need the first of them that left a byte different from a correct build's. Builds 4 to 6 hide the first bad write behind later writes, so either the symptom's last writer isn't the answer or the corrupted value travels through other stores before anything visible goes wrong. In every build here the run first goes wrong at a store the build makes, never by leaving out a store a correct build makes (API.md says so under "investigations/N.txt"). So a store that finds its byte already wrong can't be the first bad write, which came earlier.

Checks 13.build-1, 13.build-2, 13.build-3, 13.build-4, 13.build-5 and 13.build-6 run your scripts the same way and compare your answers with the first bad writes. One command runs all six:

Terminal command
node lab.mjs check project 13 --help-used "describe what helped"
Select code to copy. Scroll horizontally if needed.

A wrong answer says only that it's wrong. The checks keep each answer only as a slow salted hash, a fingerprint the checks can compare your answer with but can't read the answer from, so they can't show it to you.

Question 13c: in project/run42.json the shot counter is stored by the first shot, in call 19, and the second shot's increment, in call 396, loads it. How did the first count reach the second shot's code? (a) as an argument of the call to game_key, (b) the first shot stored it in memory and the second loaded it, or (c) through an import's answer. Answer a, b or c, and commit:

Observed output
node lab.mjs predict project 13c YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Use it on a new case: list every change

Step 6 of the method lists every change to a byte by hand: clear, watch ADDR, seek 0, then continue again and again, reading the byte at each stop. Write it as a function you can call on any bytes: changesOf(debugger, { address, size }) in project/changes.mjs, which node examples/start-changes.mjs project added at the start of this lesson. If you skipped it, run it now; it never replaces an existing changes.mjs. No finished version is supplied, and nothing in the worked investigation does this. Its contract:

Starting caseRequired result
Position 0Empty list
Store rewrites the same bytesNo entry
Invalid rangeError before movement
Valid rangeRestore the starting position before return

The budget holds for every question, whatever the bytes and the position: one call may replay at most the whole run once, end instructions, plus 2,000. Watching forward from position 0 costs at most the run's length, and the 2,000 leave room for one restore from a snapshot and a short replay back to where the question started. Going back to position 0 again for each change doesn't fit.

Replay phaseMaximum cost
Scan forward from 0end instructions
Restore the original position2,000 instructions

Before you write code, answer two questions in project/report.md. Your function stops right after a change: how do you know what the bytes held before it without stepping back? A change happens one instruction after your starting position: is it in the list, and how do you avoid it? Keep that first reasoning. Then run the checker on the unfinished file, implement, and run it again, describing assistance honestly each time:

Terminal command
node examples/check-changes.mjs project --help-used "initial attempt; nothing written"
node examples/check-changes.mjs project --help-used "describe what helped your implementation"
Select code to copy. Scroll horizontally if needed.

The checker copies machine.mjs, recorder.mjs, debugger.mjs, changes.mjs, PROJECT.json and your report.md into a new folder under project/attempts/ before it runs anything, and saves its results beside them in changes-receipt.json. A failure never replaces an earlier attempt, and node lab.mjs status project lists every attempt under "New-application attempts". It replays two of unit 10's check recordings, a Lob run and a Lob II run, once on your machine, keeping every change to every byte, and asks six groups of questions: bad questions; the pointer at 78,112, which only game_init changes; a counter every game frame changes, asked from the middle of the run; the same counter at position 0; a byte some stores rewrite with the value it already holds; and a Lob II value that changes a few times. None of them is about a ladder build.

Checker caseWhat it tests
Pointer at 78,112One early change
Frame counterMany changes before a middle position
Same counter at position 0Empty prefix
Rewritten byteSame-value stores omitted
Lob II valueSeveral changes in another program

As a stretch, add a changes ADDR SIZE command to your own copy of debug.mjs that calls changesOf, and use it on the builds.

Report

For each build, write in project/report.md the chain from the symptom to the first bad write, with the tick and value of each store on it, and what you think the planted change was. The checks don't read the report; it is your record of the reasoning.

Earlier ideas, new cases

Question 11a3: in Lob, seed 3, mode 0, how many times is the byte at g + 84 written during game_init and the first 5 game frames, where g is the 4 bytes at 78,112? g + 84 is the lowest byte of the game's mode, which the getter r_mode reads. game_init stores its second argument, the mode, there with a 4-byte store, and no game frame stores to it.

Observed output
node lab.mjs predict project 11a3 YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Question 12a3: in the name section of targets/lob-names.wasm, one entry is the bytes 13 0C 72 5F 77 69 6E 64 5F 6C 65 76 65 6C. Which function index does it name, and what name does it give it? Answer as INDEX NAME.

Observed output
node lab.mjs predict project 12a3 YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Question 12b3: in lesson 09's recording, call 5 is a key press, a call to game_key, function 7. You set a function stop on update_hud, function 6, and continue from the start of call 5. The debugger stops inside call 5, where update_hud begins. How many entries does stack() return?

Observed output
node lab.mjs predict project 12b3 YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Question 12c3: instruction 5 of new_round, function 5, is at file offset 1,107. In lines/lob.json, the row at offset 1,083 says line 200, and the next row, at offset 1,107, says line 201. What line does lineAt give instruction 5?

Observed output
node lab.mjs predict project 12c3 YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Original deterministic VM: frozen behavioral contract v1

Learner contract v1, adopted 2026-10-27. Implement the debugger behavior defined here over the supplied original VM. This course does not access native processes.

VM

State is {pc,tick,regs:{a,b,c,d},mem,output,halted}. Initially pc=0, tick=0, all four registers and all eight memory cells are 0, output=[], halted=false. Registers hold JavaScript safe integers; overflow raises an execution error before state changes. Memory addresses are integer 0–7. Programs have 1–256 instructions. No clock, randomness, I/O inputs or external side effects.

Operands called value are a safe integer literal or one of the register names. Instructions:

Every executed instruction increments tick once. Normally pc advances by one; taken jnz replaces that next pc. Halt also advances pc and tick. Falling off a program without halt raises an error. A halted step is a no-op returning null.

Debugger interface and boundaries

Construct new Debugger(program). The program and returned observations are deep copies. inspect() returns the detached current state. step() bypasses breakpoints, executes one instruction and returns its event, or null if already halted.

addBreakpoint({pc,condition?}) adds a breakpoint. Conditions are {kind:"reg",name:"a",equals:2} or {kind:"mem",address:0,equals:2}. run(limit=1000) checks breakpoints before execution, including at the current pc. A false condition does not stop. An immediate rerun at the same breakpoint stops again; step bypasses it. Explicit run limit is integer 1–10000 and counts only instructions executed by that call.

watch(address) stops after a store changes that watched cell. Same-value stores are events but do not stop. Stops are {reason,tick,pc} where reason is breakpoint, watchpoint, halt or limit. A watchpoint additionally has write:{address,before,after}. A run executing halt reports halt even if halt was the last budgeted instruction. Already halted run reports halt without execution. Watchpoint pc is the next instruction, and tick includes the store.

Events are {tick,pc,op,writes,emitted}. Event tick is the post-instruction tick; event pc is the executed instruction's pre-state pc. A store includes one {address,before,after} even for a same-value store. Only emit populates emitted. trace() returns detached events from the farthest recorded frontier in tick order. Seeking does not shrink that frontier; re-executing known ticks does not duplicate events.

Replay, checkpoints and sessions

checkpoint(nonemptyLabel) stores an internal deep snapshot and returns {label,tick,state} detached from it. seek(tick) accepts integer 0 through recorded frontier inclusive, replays from an internal checkpoint or genesis, replaces current state and returns detached state. Seeking beyond recorded history is an error. A checkpoint is an observation, not a portable restore token. No external checkpoint/session import API exists.

reverseFind(condition,beforeTick=currentTick) searches strictly earlier ticks in descending order, including tick0. Valid explicit bound is 0 through frontier+1. It returns the nearest matching tick and positions the debugger there. With no match it returns null and preserves the state before the call. It uses the same condition forms as breakpoints.

Each debugger instance owns its program, trace and checkpoints. A new instance starts at genesis and cannot consume another instance's session. No persisted execution sessions, source replacement or branching external input are supported in v1. The supported interface cannot import an external session. Learner check receipts separately bind exact solution and assessment hashes and label changed source historical.

There is no dedicated reverse-last-write method. A debugger user can search the detached trace backwards for a write to an address and seek to the event tick minus one to inspect the cause. reverseFind is not an event/write search.

Tiny supplied program for independent fixture design

This is original public input, with no answer trace:

[
  {"op":"set","reg":"a","value":2},
  {"op":"store","address":3,"value":"a"},
  {"op":"add","reg":"a","value":-1},
  {"op":"jnz","value":"a","target":1},
  {"op":"emit","value":"a"},
  {"op":"halt"}
]

Use exact command sequences and observed states in your report. These requirements define the project, not a guarantee that finite checks prove correctness or learning.

Act II: WebAssembly debugger API

Every function you write, with its inputs and outputs. The course supplies the files under public/, the program listings under programs/ and the game files under targets/. You write the files under "Your files". Each starter function throws an error containing "not written yet" until you write it.

Words used here

An instruction is named by its function index and its at: (8, 112). This is part one's pc, one per function.

moment between instructions: position t is the state after t instructions, so a tick number also names a position (tick 96,568 is the moment just after instruction 96,568). The instruction executed next is instruction number t + 1, and its event says tick: t + 1.

game_key, game_tick or one of the getters such as r_px. A game frame is one call to game_tick, 1/60 of a second of game time. A bare frame is always a call frame: one function call in progress, an entry of state.frames.

getter: the status line (r_line_ptr: angle, power, wind and score), the message line (r_msg_ptr: ROUND 1, HIT!, SHORT BY 10) and the help text (r_help_ptr). Lob II keeps the same three texts in memory, but its eight getters, g0 to g7, are named so they don't say what they hold, and none of them returns its help text's address.

{ address, size, before, after }, where before and after are arrays of size byte values.

(two WebAssembly pages of 64 KiB; your debugger's snapshot pages in lesson 10 are its own, smaller choice). An address is an index into it.

Supplied by the course

programs/NAME.json and public/program.mjs

A program listing is the .wasm file decoded into JSON when the course was built:

{ format: 'ttd2-program-1', name, sha256,
  types: [{ params, results }],      // type names: 'i32', 'i64', 'f32', 'f64'
  imports: [{ module, name, type }], // functions only; they take indexes 0, 1, ...
  functions: [{ index, type, locals, code, offsets }],
  exports: [{ name, kind, index }],  // kind 'func' or 'memory'
  globals: [{ type, mutable, init }],
  memory: { min, max },              // in 64 KiB pages
  data: [{ offset, bytes }],         // bytes as hex text in the file
  codeSectionStart }

code holds one array per instruction, its name first and its immediates after it: ['i32.const', 5], ['local.get', 2], ['call', 6], ['br_if', 1], ['block', null] (null: the block leaves no value), ['f32.store', 2, 20] (alignment, then offset). offsets[k] is the file offset of instruction k's first byte in the .wasm file. locals lists the types of the function's locals after its parameters.

loadProgram(json) turns a listing into the object your machine receives. It adds program.func(index), program.typeOf(index) and program.exportIndex(name), turns "42n" constants into BigInts and data hex into Uint8Arrays. readProgram('lob') reads and loads programs/lob.json.

public/world.mjs

makeWorld(seed) returns { imports, answered }. imports has the four functions the games import: sin(x), cos(x), server_round(round) and server_wind(). The two server functions answer from a seed the game never sees, and their answers change from call to call.

public/hash.mjs

hashMemory(memory) is the SHA-256 of the memory bytes as hex text. Every recording, check and lab command uses it.

public/sessions.mjs

session({ seed, mode, shots, ... }) returns a list of calls, [{ name, args }], that plays a game: game_init(seed, mode), then key presses and frames. Key codes: 1 left, 2 right, 3 up, 4 down, 5 space (fire), 6 N (new round).

mode adds up the game's defences, tricks a real game uses: 1 asks the server for the wind (server_wind), so its exact value never enters memory; 2 moves the game's state to a new address at every new round after the first, and changes the pointer to it; 4 stores angle, power, wind and flag combined with a key that changes every round (XOR in Lob, addition in Lob II); 8, in Lob only, slides the flag along the ground. Mode 0 has none.

Your files

machine.mjs (lesson 08)

export class Machine {
  constructor(program, imports)
  state                 // everything the machine knows, one plain object
  running               // true while a call is unfinished
  begin(name, args)     // start a call to an export; runs nothing yet
  step()                // run one instruction; returns its event
  invoke(name, args)    // begin, then step until the call returns; returns its result
}

imports has one function per import name.

segment copied in at its offset, and each global holds its init.

array), frames (one entry per function call in progress, outermost first, each with func and at: the function and the at of the next instruction it will run), tick (instructions run so far) and calls (calls begun so far). Anything else your machine needs goes in state too.

machine.state = copy the machine must carry on from the copied moment exactly. Lessons 09 to 13 rely on this.

instruction, which instruction it was, its name, and the writes it made ([] for most instructions; one write for a store). Every instruction the machine runs is one tick, block, loop, br and end included; a branch runs no instruction on its way to its target. A branch to a loop goes to the instruction after the loop, which doesn't run again, so the branch's own tick is the only one.

function returns nothing. An f32 value is a JavaScript number rounded with Math.fround. An i32 value is signed, as Node's engine returns it, so the bits of 4,294,967,295 come back as -1.

message starts with trap:. A load or store that traps reads or writes nothing (check 08.memory looks at memory afterwards). The checks start a new machine after a trap, so the rest of what it leaves in state (stack, frames, tick) is up to you.

calls to step() to measure replay costs.

recorder.mjs (lesson 09)

export function record(program, imports, calls)          // returns a recording
export function replay(program, recording, { check })    // returns { machine, results, hashes }
export function firstDivergence(program, original, tampered)  // returns a tick or null

A recording is plain JSON:

{ format: 'ttd2-recording-1', program, sha256,
  calls:   [{ name, args }],          // every call into the game, in order
  results: [value or null],           // what each call returned
  answers: [{ name, args, result }],  // every import call the game made, in order
  hashes:  [hex] }                    // hashMemory after each call

debug.mjs uses to find programs/NAME.json, and sha256 is the listing's sha256.

machine converts it to the import's type. The course's worlds return values that already have that type.

its answers with -0 and 0 counted as one number. The world's answers are always finite.

keeping every answer they return.

call from answers, in order, without any world. If the game's next import call does not match the next entry of answers (another import, or other arguments), replay throws an error with a divergence field { tick, call, reason }. Its tick is the number of instructions the machine had finished before the call instruction that asked; that instruction's own event would have tick + 1. With check: true (the default) a call whose result or memory hash differs from the recording also throws, with the tick at which that call returned.

recording's replay has different memory from the original's, or null when the two never differ, even if an answer or a call was changed (a key the game ignores, an answer changed to the value it had). The tick is counted in the tampered replay. tampered is a copy of original with some answers or calls changed; its hashes are the original's. The checks' tampers change memory in a way that lasts at least to the end of the call where it starts, so comparing hashes at the ends of calls and then bisecting inside the first call that ends differently finds their ticks. The checks count the instructions it runs. If, before memory differs, the tampered replay asks for an import its recording can't answer, the checks don't test the result. The course's worked solution then counts memory as different from the call instruction that asked, and returns that instruction's tick.

debugger.mjs (lessons 10 and 12)

export class Debugger {
  constructor(program, recording, options)
  tick                  // the current position
  end                   // the position after the run's last instruction
  seek(tick)            // move there; returns the new position
  step(n = 1)           // forward n instructions, stopping at end
  stepBack(n = 1)       // back n instructions, stopping at 0
  read(address, size)   // the memory bytes at the current position, a Uint8Array
  state()               // a structuredClone of the machine's whole state at the current position
  where()               // { tick, call, func, at }: what runs next
  continue(stops)       // forward to the next stop: { reason, tick }
  continueBack(stops)   // backward to the previous stop: { reason, tick }
  lastWrite(address)    // the last write to that byte at or before here, or null
  stack()               // lesson 12: [{ func, at }], outermost first
  stepOut()             // lesson 12: forward until the current function has returned
  snapshots             // [{ tick, pages }], see below
}
// stops = { breakpoints: [{ func, at }], watches: [{ address, size }], functions: [index] }

stepOut return the new position. The course's worked solution throws a RangeError when seek is given a position outside 0 to end, and the checks never ask for one.

instruction number t + 1. Between two calls it is the first instruction of the next call. where() names it: { tick, call, func, at }, where tick is the current position t and call is the index in recording.calls of the call the next instruction belongs to. At end, func and at are null and call is recording.calls.length.

the machine with no frames, before the next call has begun.

that one. A function stop (lesson 12) stops where a call to that function begins: the next instruction is (func, 0).

at least one byte in [address, address + size) and changed it.

after, or strictly before, the current one, and stop at the nearest match. With no match they stop at end (reason: 'end') or at 0 (reason: 'start'). Otherwise reason is 'breakpoint', 'watchpoint' or 'function'. (Part one's run stopped without moving when it stood on a breakpoint; continue does not.)

first instruction fires there, and continueBack reports it rather than 'start'. No watch fires at 0, because no instruction comes before it.

reasons. The worked solution reports 'watchpoint' first, then 'breakpoint', then 'function'.

instruction with the greatest tick at or before the current position that wrote the byte at address, whether or not the value changed. address in the result is where that write starts. The method does not move the debugger; the last-write and who commands of debug.mjs then move to the write's tick, so answer can name it.

order of tick. pages is an array of Uint8Arrays whose concatenation is the memory at that tick. A page no instruction wrote since the previous snapshot must be the very same Uint8Array object as in the previous snapshot. You choose how often to take a snapshot, and the page size, up to 16 KiB: with larger pages nearly every snapshot copies most of memory. All your snapshots together may hold at most a quarter of the bytes that a full copy of memory per snapshot would, counting a page that several snapshots share once.

Between calls it's yours to define (lesson 12). The worked solution runs the whole next call and stops where it has returned.

After that, going back one instruction, or continuing back to a stop a few thousand instructions away, may replay at most 20,000 instructions, which a snapshot every few thousand instructions meets and a replay from the start does not. The checks count instructions through step(), and a debugger that stands at position t must have counted at least t.

query.mjs (lesson 11)

export function buildIndex(program, recording)   // returns an index
index.end                                         // instructions in the run
index.lastWriter(address, beforeTick)             // { tick, func, at, address, size } or null
index.sources(tick)                               // { stores, answers, args, initial }

by the instruction with the greatest tick below beforeTick, or null.

throws) and returns where the value it stored came from: - stores: the ticks of every earlier store on the value's chain; - answers: indexes into recording.answers of import results on the chain; - args: [call, index] pairs, arguments of calls into the game on the chain (the call's index in recording.calls, the argument's index in its args); - initial: addresses of bytes on the chain that were loaded before any store had written them. Each list is sorted in increasing order, without repeats.

of the instruction that produced it, except the address operand of a load or store. A load depends on the bytes it read, so on the stores that last wrote them. local.get, local.set, local.tee, global.get and global.set pass a value along unchanged, and so does a call to a defined function (arguments into its parameters, its result back out). A call to an import gives a value that depends only on that answer: its arguments are not followed. Constants depend on nothing.

- select depends on all three of its operands, the two values and the condition, whichever value it picks. - A store depends on its whole value operand, even when it writes only its low 1 or 2 bytes, and it becomes the last writer of every byte it writes, changed or not. - A load depends on each byte it reads separately: on several stores if several wrote those bytes, and on initial addresses for bytes no store wrote before it (zero bytes and data-segment bytes alike). - Comparisons, conversions and reinterpretations follow their operands like arithmetic. - Decisions are not followed: a br_if condition and which way a branch went are on no chain. A branch or return passes on only the values it keeps. - A call to a defined function makes argument i its local i; locals beyond the parameters, a global's starting value and constants depend on nothing. - The store asked about is not in its own stores list. args is sorted by call, then argument index.

whole write, its start and size, even for a byte inside a wider store; the debugger's lastWrite at position p is lastWriter(address, p + 1).

is of Lob or Lob II, whose memory is 131,072 bytes (see "Memory" above), so code built on an index can take that size as fixed. What lastWriter does for an address outside memory is not part of this contract and no check asks it (the supplied examples/query-checkpoint.mjs throws), so code that must refuse such an address tests it against 131,072 itself.

must not replay it again; the checks count instructions.

names.mjs (lesson 12)

export function functionNames(bytes)   // { [index]: name } from the file's "name" section, {} if it has none
export function lineAt(lines, offset)  // { line, column } of the last row at or before offset, or null

layout of its sections and of the name section.

{ offset, line, column } in increasing offset, where offset is a file offset like the listing's offsets.

investigations/N.txt (lesson 13)

One debugger command per line, for node debug.mjs. The last answer command the script runs is your answer for ladder build N.

The first bad write of a ladder build is the earliest store in its run that leaves a byte of memory holding a value a correct build wouldn't hold there at the same point of the run. In every build here, the run first goes wrong at a store the build makes, never by leaving out a store a correct build makes. Up to that store the build makes the same stores as a correct build, store for store, so the same point of the run means after the same earlier stores.

debug.mjs (lessons 10 to 13)

node debug.mjs PROJECT TARGET [SCRIPT] runs your files on a recording, or on ladder build N, and help lists its commands. It wraps Machine.prototype.step, so it counts every step() of every machine of your Machine class, whoever makes it. That includes your Debugger's first pass, the index that who and sources build, and the machines that getters, answer and writes run on a copy of the state. The count is what cost shows and what the ladder's budgets limit. diverge and compare run Node's engine and add nothing to it.

The 62 instructions

Both games use exactly these. a and b are the two operands, b the one on top of the stack; a comparison pushes 1 or 0.

| Instructions | What they do | | --- | --- | | block T, loop T, end | open a block or a loop (T: null, or the type of the value it leaves); end closes the innermost one, or returns from the function at its last end | | br N, br_if N, return | branch to the block N levels out (br_if pops a condition and branches if it is not 0); return leaves the function | | call F | call function F: an import runs outside and its result is pushed; a defined function gets a new frame | | local.get, local.set, local.tee, global.get, global.set | read or write a local or a global; tee writes and keeps the value | | select | pop a condition c, then b, then a; push a if c is not 0, else b | | i32.const, i64.const, f32.const | push a constant | | i32.load, f32.load, i32.load8_u | load 4 bytes as an integer, 4 bytes as a float, or 1 byte as 0 to 255 | | i32.store, f32.store, i32.store8, i32.store16, i64.store | store 4, 4, 1, 2 or 8 bytes, lowest byte first | | i32.add, i32.sub, i32.mul | wrap to 32 bits | | i32.div_s, i32.div_u, i32.rem_s, i32.rem_u | divide or take the remainder, signed or unsigned; divide by 0 traps, and so does div_s of -2,147,483,648 by -1 | | i32.and, i32.or, i32.xor | bitwise | | i32.shl, i32.shr_s, i32.shr_u | shift by the low 5 bits of b; shr_s copies the sign bit in, shr_u zeros | | i32.eqz, i32.ne | is a zero; are a and b different | | i32.lt_s, i32.gt_s, i32.le_s, i32.ge_s | signed comparisons | | i32.lt_u, i32.gt_u | unsigned comparisons | | f32.add, f32.sub, f32.mul, f32.div, f32.sqrt | 32-bit float arithmetic, rounded with Math.fround | | f32.neg | flip the sign, so 0 becomes -0 | | f32.lt, f32.gt, f32.le, f32.ge | float comparisons (false when either is NaN) | | f32.convert_i32_s, f32.convert_i32_u | integer to float, reading the integer as signed or unsigned | | f64.promote_f32, f32.demote_f64 | to and from 64-bit floats, used only around sin and cos | | i32.reinterpret_f32, f32.reinterpret_i32 | keep the 32 bits, read them as the other type | | i32.trunc_sat_f32_s | drop the fraction; NaN gives 0, and values beyond the i32 range give its largest or smallest |

Capstone: a fresh diagnosis and a familiar rehearsal

The earlier dispatch.json task is a familiar rehearsal, not an unfamiliar transfer. A dispatch summary starts with four quantities: 12, 9, 6 and 3. The intended report is their sum, but a reviewer reports that the final shipment is missing. programs/dispatch.json is the original program to investigate; its intended loop should account for every listed quantity. Verify the reported symptom rather than assuming it is true. If the program satisfies the stated expectation, report that finding with evidence and propose a different falsifiable explanation for the complaint. A diagnosis is allowed to conclude that the supplied complaint is unsupported.

Your fresh supplied investigation is programs/transfer.json, which the earlier lessons do not assign: it should emit the last value written to cell 5 after a three-visit update loop. It emits a different value. Diagnose this case without a walkthrough. Preserve the original input. Put any proposed repair in a new file and confirm both the observed symptom and the changed result.

Deliver your debugger and a report containing: expected behavior; source/program identity; reproducible commands from a fresh instance; first observed divergence; relevant trace segment and state; causal hypothesis; at least one counterexperiment; corrected-program experiment if appropriate; limits and help used. An unsupported bug claim is a failure even if a patch changes output.

Build one debugging query of your own over the debugger's trace or state. State the question it answers and retain the query, input and reproducible result; explain how the result supports or challenges your diagnosis. A small client helper using existing methods is sufficient.

Rubric: evidence must reproduce; state and event boundaries must be used correctly; cause must explain the symptom; the counterexperiment must distinguish the hypothesis from another explanation; the new query must answer its stated question and contribute evidence to the investigation; conclusions must fit the observations. Alternative valid investigations may use breakpoints, watchpoints or trace search in different orders. Stage 07 only checks debugger behavior, not this report's reasoning.

Finally create a small program of your own with an explicit intended behavior and a plausible bug. Provide its input and diagnosis as a separate investigation. Do not submit author controls or a copied implementation as your work. There is no automated mastery certificate or required model critique.

If you already read the earlier teaching-v3 exercise07b, retain that attempt and treat this supplied investigation as assisted rehearsal. Use a new program of your own for fresh diagnosis practice. The revised exercise does not turn earlier exposed work into an unaided first attempt.

Optional critique using your own LLM account

You can complete this course offline without a model. If you choose to ask one for feedback, review the export and select what you want to share through your own account. Nothing in this package uploads files, starts inference or sends messages. Do not share private data, credentials or third-party material you lack permission to send.

Copy the following prompt, the relevant public contract, the specific failing input and selected code/report. Describe assistance accurately in later attempts. A model's opinion does not replace deterministic results or certify mastery.

Review this project against the attached public contract and report rubric. Separate observations supported by code or recorded output from hypotheses. Identify a concrete failing case, the expected behavior under the contract, and an experiment I can run locally. If evidence is insufficient, say what is missing. Ask for my prediction before revealing a project solution. Prefer a small diagnostic question or sibling example to a replacement implementation. Do not invent executed results, claim that a passing finite test proves correctness, or broaden the stated VM/persistence assumptions. Give advice I can test; keep your critique distinct from the course checker's verdict.

After critique, write your prediction, run the experiment and retain both first and revised attempts. State the model/account and scope of help if you used one. Model compliance with this prompt has not been tested.

Sources and boundaries

This course defines an original executable teaching model. Its primary local sources are contracts.md, the supplied runtime, the public behavioral cases and reference-produced examples.json. No purchased book source, exercise, quotation, diagram, paid service or external packet was used. The course is not an adaptation of a named book.

All numeric worked-example output in examples.json is generated by running the local author reference on original inputs. Public cases are finite requirements checks. Author verification records contain valid alternatives and deliberately broken implementations, and are excluded from the learner archive. Source-aware author testing is not an independent cold tryout or evidence of learning.

The tested environment is Node v26.5.1 on macOS. Other Node versions and operating systems remain unqualified. Minimum-runtime qualification, other operating systems, browser download identity, visual/accessibility acceptance, human duration and learning effectiveness have not been measured. No network call or inference is part of the learner's default route.