@henols/c64-re-tools 2.2.0-rc.1 → 2.2.0-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,13 @@
1
1
  ---
2
2
  name: c64-testing
3
- description: Use this skill to test if a rebuilt or changed C64 program behaves as the original. It runs one scenario on the original and then on the rebuild in an emulator. It compares memory, registers, chip state and the screen with explicit rules, and gives PASS, FAIL or INCONCLUSIVE. It also makes a checklist for a human playtest. Use its run command to explore a program with many steps, for example to visit each room or level. A run keeps screens, coverage maps and snapshots as files. Use its record and replay commands to keep a long play session of the original and replay it on each rebuild. Do not use it to find the cause of a difference.
3
+ description: Use this skill to test if a rebuilt or changed C64 program behaves as the original. It runs one scenario on the original and then on the rebuild in an emulator. It compares memory, registers, chip state and the screen with explicit rules, and gives PASS, FAIL or INCONCLUSIVE. It also makes a checklist for a human playtest. Use its run command to explore a program with many steps, for example to visit each room or level. A run keeps screens, coverage maps and snapshots as files. An expect step in a run compares memory and registers with expected values, for a new program or a fix that has no original. Use its record and replay commands to keep a long play session of the original and replay it on each rebuild. Do not use it to find the cause of a difference.
4
4
  ---
5
5
 
6
6
  # c64-testing
7
7
 
8
8
  ## Purpose
9
9
 
10
- Test if a rebuild or a changed program behaves as the original in a scenario. Give one result: PASS, FAIL or INCONCLUSIVE.
10
+ Test if a rebuild or a changed program behaves as the original in a scenario. Test if a program has the expected values in a run. Give one result: PASS, FAIL or INCONCLUSIVE.
11
11
 
12
12
  A PASS proves only the behavior that the scenario does and observes. It does not prove that the two programs are equal in all behavior.
13
13
 
@@ -51,12 +51,13 @@ The run file gives where to start (a program, or a snapshot file), the steps, an
51
51
  | `{ "observe": "room3", "memory": ["$c100"], "registers": true }` | Record memory, registers, `vicii` or `sprites` in `results.json`. |
52
52
  | `{ "trace": "d011", "points": [{ "kind": "write", "start": "$d011" }], "frames": 100 }` | Record each hit of the points for 100 frames in `d011.json`: the instruction, its registers and the raster line and cycle. A point has the `kind` `exec`, `read` or `write`, a `start` and an optional `end`. `maxHits` limits the hits. |
53
53
  | `{ "observe": "all3", "memory": "all" }` | Write all 64 KiB of RAM to `all3.bin`, also the RAM under the ROMs and the I/O area. |
54
+ | `{ "expect": "title", "memory": [{ "address": "$0400", "text": "HELLO" }], "registers": { "a": 0 } }` | Compare memory and registers with the expected values. `data` gives hex bytes, `text` gives screen codes. `mask` compares only some bits. A value that is not equal does not stop the run. |
54
55
 
55
56
  Each step that writes a file must have its own file name. The script refuses a run where two steps write the same file, for example `{ "coverage": "x" }` and `{ "observe": "x", "memory": "all" }`, which both write `x.bin`. The script also examines the start program and each snapshot file before the emulator starts.
56
57
 
57
58
  A memory item can have `"view": "ram"`. Then it reads the RAM under the ROMs and the I/O area, for example code at `$e000` under the KERNAL. The default view `cpu` reads as the CPU sees memory. An item larger than 4096 bytes goes into its own `.bin` file, and `results.json` gives the file name.
58
59
 
59
- See [references/scenario-format.md](references/scenario-format.md), section Runs. `result` is PASS when all steps ran, and FAIL when a step did not run. `reason` tells why. A long run can need more time than one shell call. Then run it in the background.
60
+ See [references/scenario-format.md](references/scenario-format.md), section Runs. `result` is PASS when all steps ran and each `expect` step passed. It is FAIL when a step did not run, and `reason` tells why. It is also FAIL when an `expect` step found a value that is not equal. Then `failedExpectations` names the steps, and `expectations` gives the expected and the actual values. A long run can need more time than one shell call. Then run it in the background.
60
61
 
61
62
  ### Recordings
62
63
 
@@ -218,4 +219,5 @@ Do not add a mask or a tolerance only to make a test pass. A tolerance must have
218
219
  - Find the cause of a difference → c64-emulator
219
220
  - Find the code that causes it → c64-static-analysis
220
221
  - Rebuild after a correction → c64-assembler
222
+ - Write or change a program, with expect steps as its tests → c64-development
221
223
  - Record a confirmed conclusion → c64-knowledge
@@ -92,7 +92,7 @@ A run file (for `testing.ts run`) has:
92
92
  - `start`: `{ "program": "game.prg" }` to autostart a program with a BASIC start line, `{ "program": "game.prg", "load": true }` to load it with the CPU stopped (set `pc` in a step), or `{ "snapshot": ".c64-re-tools/local/snapshots/room0.vsf" }`.
93
93
  - `symbols`: optional, `knowledge`, `none` (default), or a JSON file as for a subject. Without `symbols`, a run has no names: give `"symbols": "knowledge"` to use the names of the knowledge.
94
94
  - `videoStandard`: optional, `pal` (default) or `ntsc`.
95
- - `steps`: the steps `write`, `registers`, `joystick`, `type`, `frames` and `runUntil` of a scenario, and the run steps `snapshot`, `save`, `screen`, `coverage`, `trace` and `observe`.
95
+ - `steps`: the steps `write`, `registers`, `joystick`, `type`, `frames` and `runUntil` of a scenario, and the run steps `snapshot`, `save`, `screen`, `coverage`, `trace`, `observe` and `expect`.
96
96
 
97
97
  A `trace` step has a name, `points` (1 to 8), `frames` (1 to 3000) and an optional `maxHits` (at most 20000). A point has `kind` (`exec`, `read` or `write`), `start` and an optional `end`. The step writes `<name>.json` with each hit. `results.json` gives the file, the count of hits, the frames and why the trace ended. A trace that a breakpoint, a watchpoint or a JAM ends also ends the run.
98
98
 
@@ -100,7 +100,39 @@ In a run, an `observe` step can have `memory`, `registers`, `vicii` and `sprites
100
100
 
101
101
  In a run, a memory item has `address`, `size` (1 to 65536) and `view`. An item larger than 4096 bytes goes into the file `<observe>-<address>.bin`, without the `$`. `"memory": "all"` writes all 64 KiB of RAM to `<observe>.bin`.
102
102
 
103
- A name in `save`, `screen`, `coverage` and `observe` has 1 to 64 letters, digits, dots, underscores or hyphens. The files go into the `--out` directory, with `results.json`. It has the observations, the files and the steps done. If a `runUntil` step did not reach its target, it also tells why the run stopped.
103
+ A name in `save`, `screen`, `coverage`, `observe` and `expect` has 1 to 64 letters, digits, dots, underscores or hyphens. The files go into the `--out` directory, with `results.json`. It has the observations, the expectations, the files and the steps done. If a `runUntil` step did not reach its target, it also tells why the run stopped.
104
+
105
+ ### Expected values
106
+
107
+ An `expect` step compares the memory and the registers with the values that the step gives. It writes no file. Use it to test a program that has no original, for example a new program or a fix.
108
+
109
+ ```json
110
+ { "expect": "title",
111
+ "memory": [
112
+ { "address": "$0400", "text": "HELLO FROM C64" },
113
+ { "address": "score", "data": "0000" },
114
+ { "address": "$d020", "data": "01", "mask": "0f" }
115
+ ],
116
+ "registers": { "pc": "main_loop", "a": 0, "flags": { "i": true } } }
117
+ ```
118
+
119
+ The step has a name, and `memory`, `registers` or both.
120
+
121
+ A memory item has `address` and one of these two keys:
122
+
123
+ - `data`: the bytes as hex. The step compares each byte.
124
+ - `text`: characters on the screen, as screen codes of the upper-case set. The step reads one byte for each character. It compares the text, not the reverse video. A graphics character reads as a dot. Write letters in upper case.
125
+
126
+ A memory item can also have:
127
+
128
+ - `mask`: hex bytes with the same length as `data`. The step compares only the bits that are 1 in the mask. Use it for an I/O register with bits that read as 1, for example `$d020`.
129
+ - `view`: `cpu` (default) or `ram`.
130
+
131
+ A memory item has at most 4096 bytes.
132
+
133
+ `registers` has the fields of a `registers` step: `pc`, `a`, `x`, `y`, `sp` and `flags`. Only `pc` can be a name.
134
+
135
+ A value that is not equal does not stop the run. The later steps run. `results.json` and the result have `expectations`. For each step, it gives `pass` and the count of values that are not equal. It also lists at most 16 of them, with the expected and the actual value. `failedExpectations` names each step that did not pass. The result is FAIL when an expectation did not pass.
104
136
 
105
137
  Example: visit two rooms from the same start.
106
138
 
@@ -1,13 +1,15 @@
1
1
  // The runs of c64-testing: steps in their own emulator, from a program or a
2
2
  // snapshot file, and what the steps ask for written into a folder: screens,
3
3
  // coverage maps, snapshot files, and results.json with the observations. One
4
- // side, no comparison.
4
+ // side, no comparison with another program: an expect step checks the memory
5
+ // and registers against the values that the run file gives.
5
6
 
6
- import { formatC64Address, formatSprite, formatVicii, parseC64Address } from "#src/c64.ts";
7
+ import { formatC64Address, formatC64Byte, formatSprite, formatVicii, parseC64Address } from "#src/c64.ts";
8
+ import { screenText } from "#src/graphics.ts";
7
9
  import { runProgram } from "#src/host-client/autostart.ts";
8
10
  import { isRefusal, Refusal } from "#src/errors.ts";
9
11
  import { readCoverage } from "#src/host-client/coverage.ts";
10
- import { ACTION_STEP_KINDS, checkActionStep, checkStepNames, isInteger, isObject, refuseOldStep, renamedField, runActionStep, VICE_STEP_KINDS, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
12
+ import { ACTION_STEP_KINDS, checkActionStep, checkLocation, checkStepNames, isInteger, isObject, refuseOldStep, renamedField, runActionStep, VICE_STEP_KINDS, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
11
13
  import { readPrg } from "#src/host-client/image.ts";
12
14
  import { MAX_MEMORY_READ, MAX_TRACE_FRAMES, MAX_TRACE_HITS, MAX_TRACE_POINTS, TRACE_KINDS, WireFailure, type TraceHit, type TraceKind } from "#src/host-client/tools.ts";
13
15
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
@@ -23,7 +25,27 @@ type RunStep =
23
25
  | { screen: string }
24
26
  | { coverage: string }
25
27
  | { trace: string; points: Array<{ kind: TraceKind; start: string; end?: string }>; frames: number; maxHits?: number }
26
- | { observe: string; memory?: "all" | Array<string | { address: string; size?: number; view?: "cpu" | "ram" }>; registers?: boolean; vicii?: boolean; sprites?: number[] };
28
+ | { observe: string; memory?: "all" | Array<string | { address: string; size?: number; view?: "cpu" | "ram" }>; registers?: boolean; vicii?: boolean; sprites?: number[] }
29
+ | { expect: string; memory?: ExpectedMemory[]; registers?: ExpectedRegisters };
30
+
31
+ /** Expected bytes at an address: hex data, under an optional mask, or text as screen codes. */
32
+ interface ExpectedMemory {
33
+ address: string;
34
+ data?: string;
35
+ text?: string;
36
+ mask?: string;
37
+ view?: "cpu" | "ram";
38
+ }
39
+
40
+ type ExpectedRegisters = Extract<ActionStep, { registers: unknown }>["registers"];
41
+
42
+ /** One value that differs from the expected value. */
43
+ interface Mismatch {
44
+ address?: string;
45
+ register?: string;
46
+ expected: string | number | boolean;
47
+ actual: string | number | boolean;
48
+ }
27
49
 
28
50
  interface Run {
29
51
  name: string;
@@ -33,9 +55,15 @@ interface Run {
33
55
  steps: RunStep[];
34
56
  }
35
57
 
36
- const OWN_KINDS = ["snapshot", "save", "screen", "coverage", "observe", "trace"] as const;
58
+ const OWN_KINDS = ["snapshot", "save", "screen", "coverage", "observe", "expect", "trace"] as const;
37
59
  const TRACE_KEYS = ["trace", "points", "frames", "maxHits"];
38
60
  const OBSERVE_KEYS = ["observe", "memory", "registers", "vicii", "sprites"];
61
+ const EXPECT_KEYS = ["expect", "memory", "registers"];
62
+ const EXPECTED_MEMORY_KEYS = ["address", "data", "text", "mask", "view"];
63
+ /** The characters that screenText gives for the screen codes 0 to 63; a graphics code gives a dot. */
64
+ const SCREEN_TEXT = /^[@A-Z[£\]^< !"#$%&'()*+,\-./0-9:;=>?]+$/;
65
+ /** The most differing bytes that an expectation lists; count gives all of them. */
66
+ const MAX_LISTED_MISMATCHES = 16;
39
67
  /** A name of a file that a step writes: letters, digits, dots, underscores or hyphens. */
40
68
  const NAME = /^[A-Za-z0-9._-]{1,64}$/;
41
69
  /** The file of the observations, which every run writes. */
@@ -96,12 +124,12 @@ function readRun(path: string): Run {
96
124
  (value.steps as unknown[]).forEach((step, index) => {
97
125
  const at = `step ${index + 1}`;
98
126
  if (!isObject(step)) return fail(`${at} must be an object`);
99
- const kinds = "observe" in step ? ["observe"] : "trace" in step ? ["trace"] : Object.keys(step).filter((key) => (ACTION_STEP_KINDS as readonly string[]).includes(key) || (OWN_KINDS as readonly string[]).includes(key));
127
+ const kinds = "observe" in step ? ["observe"] : "expect" in step ? ["expect"] : "trace" in step ? ["trace"] : Object.keys(step).filter((key) => (ACTION_STEP_KINDS as readonly string[]).includes(key) || (OWN_KINDS as readonly string[]).includes(key));
100
128
  if (kinds.length > 1) return fail(`${at} has ${kinds.length} step kinds: ${kinds.join(", ")}. Give each one its own step`);
101
129
  if (kinds.length !== 1) return fail(`${at} must have exactly one of ${[...VICE_STEP_KINDS, ...OWN_KINDS].join(", ")}`);
102
130
  const kind = kinds[0]!;
103
131
  refuseOldStep(kind, step, at, fail);
104
- const allowed = kind === "observe" ? OBSERVE_KEYS : kind === "trace" ? TRACE_KEYS : [kind];
132
+ const allowed = kind === "observe" ? OBSERVE_KEYS : kind === "expect" ? EXPECT_KEYS : kind === "trace" ? TRACE_KEYS : [kind];
105
133
  for (const key of Object.keys(step)) if (!allowed.includes(key)) fail(`${at} has the key ${key}, which a ${kind} step does not have`);
106
134
  if ((ACTION_STEP_KINDS as readonly string[]).includes(kind)) {
107
135
  // The step with its defaults filled in, as the shared schema of the action steps gives it.
@@ -129,6 +157,33 @@ function readRun(path: string): Run {
129
157
  if (step.maxHits !== undefined && !isInteger(step.maxHits, 1, MAX_TRACE_HITS)) fail(`${at}: maxHits must be a number from 1 to ${MAX_TRACE_HITS}`);
130
158
  return;
131
159
  }
160
+ if (kind === "expect") {
161
+ if (labels.has(name as string)) fail(`${at} needs a new name`);
162
+ labels.add(name as string);
163
+ if (step.memory === undefined && step.registers === undefined) fail(`${at}: expect needs memory, registers or both`);
164
+ if (step.memory !== undefined) {
165
+ if (!Array.isArray(step.memory) || step.memory.length === 0) return fail(`${at}: memory is a list of objects with address, and data or text`);
166
+ for (const item of step.memory as unknown[]) {
167
+ if (!isObject(item)) return fail(`${at}: memory is a list of objects with address, and data or text`);
168
+ for (const key of Object.keys(item)) if (!EXPECTED_MEMORY_KEYS.includes(key)) fail(`${at}: an expected memory object has the field ${key}. It has address, data or text, mask and view, and nothing else`);
169
+ checkLocation(item.address, `${at}: address`, fail);
170
+ if ((item.data === undefined) === (item.text === undefined)) fail(`${at}: an expected memory object needs data or text, not both`);
171
+ if (item.data !== undefined && (typeof item.data !== "string" || !/^(?:[0-9a-fA-F]{2})+$/.test(item.data))) fail(`${at}: data must be hex bytes, two digits per byte, no separators, for example 0801`);
172
+ if (item.text !== undefined && (typeof item.text !== "string" || !SCREEN_TEXT.test(item.text))) {
173
+ fail(`${at}: text has the characters of the upper-case set: @, A to Z, digits, space, the signs !"#$%&'()*+,-./:;<=>? and [£]^<. Write letters in upper case`);
174
+ }
175
+ const size = typeof item.data === "string" ? item.data.length / 2 : typeof item.text === "string" ? item.text.length : 0;
176
+ if (size > MAX_MEMORY_READ) fail(`${at}: an expected memory object has at most ${MAX_MEMORY_READ} bytes`);
177
+ if (item.mask !== undefined && (item.data === undefined || typeof item.mask !== "string" || !/^(?:[0-9a-fA-F]{2})+$/.test(item.mask) || item.mask.length !== (item.data as string).length)) {
178
+ fail(`${at}: mask needs data, and is hex bytes of the same length as data`);
179
+ }
180
+ if (item.view !== undefined && item.view !== "cpu" && item.view !== "ram") fail(`${at}: view must be cpu or ram`);
181
+ }
182
+ }
183
+ // The registers have the fields of a registers step: only pc can be a name.
184
+ if (step.registers !== undefined) step.registers = (checkActionStep("registers", { registers: step.registers }, at, fail) as { registers: ExpectedRegisters }).registers;
185
+ return;
186
+ }
132
187
  if (kind !== "observe") return;
133
188
  if (labels.has(name as string)) fail(`${at} needs a new observation name`);
134
189
  labels.add(name as string);
@@ -190,7 +245,38 @@ function showHit(hit: TraceHit) {
190
245
  return { ...hit, pc: formatC64Address(hit.pc), ...(hit.address === undefined ? {} : { address: formatC64Address(hit.address) }) };
191
246
  }
192
247
 
193
- /** Runs the run file and writes its files into `out`. failed: a step did not run. */
248
+ /**
249
+ * The values of an expect step that differ: each byte of data (under its
250
+ * mask), the text of screen codes as one string, and each register.
251
+ */
252
+ async function expected(client: ViceSessionClient, step: Extract<RunStep, { expect: string }>, at: (location: string) => number): Promise<Mismatch[]> {
253
+ const mismatches: Mismatch[] = [];
254
+ for (const item of step.memory ?? []) {
255
+ const address = at(item.address);
256
+ if (item.text !== undefined) {
257
+ const actual = screenText(await readMemoryInParts(client, address, item.text.length, item.view ?? "cpu")).join("");
258
+ if (actual !== item.text) mismatches.push({ address: formatC64Address(address), expected: item.text, actual });
259
+ continue;
260
+ }
261
+ const data = Buffer.from(item.data!, "hex");
262
+ const mask = item.mask === undefined ? undefined : Buffer.from(item.mask, "hex");
263
+ const actual = await readMemoryInParts(client, address, data.length, item.view ?? "cpu");
264
+ data.forEach((byte, offset) => {
265
+ const bits = mask?.[offset] ?? 0xff;
266
+ if ((actual[offset]! & bits) !== (byte & bits)) mismatches.push({ address: formatC64Address((address + offset) & 0xffff), expected: formatC64Byte(byte), actual: formatC64Byte(actual[offset]!) });
267
+ });
268
+ }
269
+ if (step.registers !== undefined) {
270
+ const registers = await client.registersGet("c64");
271
+ const { pc, flags, ...bytes } = step.registers;
272
+ if (pc !== undefined && registers.pc !== at(pc)) mismatches.push({ register: "pc", expected: formatC64Address(at(pc)), actual: formatC64Address(registers.pc) });
273
+ for (const [name, value] of Object.entries(bytes) as Array<["a" | "x" | "y" | "sp", number]>) if (registers[name] !== value) mismatches.push({ register: name, expected: value, actual: registers[name] });
274
+ for (const [name, value] of Object.entries(flags ?? {}) as Array<[keyof typeof registers.flags, boolean]>) if (registers.flags[name] !== value) mismatches.push({ register: `flags.${name}`, expected: value, actual: registers.flags[name] });
275
+ }
276
+ return mismatches;
277
+ }
278
+
279
+ /** Runs the run file and writes its files into `out`. failed: a step did not run, or an expect step found a value that differs. */
194
280
  export async function runFile(path: string, out: string): Promise<{ output: Record<string, unknown>; failed: boolean }> {
195
281
  const run = readRun(path);
196
282
  checkRunFiles(path, run);
@@ -206,8 +292,15 @@ export async function runFile(path: string, out: string): Promise<{ output: Reco
206
292
  };
207
293
  // Every name of the steps resolves before the emulator starts. A refusal names the step.
208
294
  run.steps.forEach((step, index) => {
209
- if ("trace" in step || "observe" in step) {
210
- const names = "trace" in step ? step.points.flatMap((point) => [point.start, ...(point.end === undefined ? [] : [point.end])]) : step.memory === undefined || step.memory === "all" ? [] : step.memory.map((item) => (typeof item === "string" ? item : item.address));
295
+ if ("trace" in step || "observe" in step || "expect" in step) {
296
+ const names =
297
+ "trace" in step
298
+ ? step.points.flatMap((point) => [point.start, ...(point.end === undefined ? [] : [point.end])])
299
+ : "expect" in step
300
+ ? [...(step.memory ?? []).map((item) => item.address), ...(step.registers?.pc === undefined ? [] : [step.registers.pc])]
301
+ : step.memory === undefined || step.memory === "all"
302
+ ? []
303
+ : step.memory.map((item) => (typeof item === "string" ? item : item.address));
211
304
  for (const name of names) {
212
305
  try {
213
306
  at(name);
@@ -227,6 +320,7 @@ export async function runFile(path: string, out: string): Promise<{ output: Reco
227
320
  files.push(name);
228
321
  };
229
322
  const observations: Record<string, unknown> = {};
323
+ const expectations: Array<{ expect: string; pass: boolean; count: number; mismatches: Mismatch[] }> = [];
230
324
  const traces: Record<string, unknown> = {};
231
325
  const client = await ViceSessionClient.open({ videoStandard: run.videoStandard ?? "pal" });
232
326
  let done = 0;
@@ -295,6 +389,10 @@ export async function runFile(path: string, out: string): Promise<{ output: Reco
295
389
  if (step.vicii === true) seen.vicii = formatVicii(await client.vicii());
296
390
  if (step.sprites !== undefined) seen.sprites = (await client.sprites(step.sprites)).sprites.map(formatSprite);
297
391
  observations[step.observe] = seen;
392
+ } else if ("expect" in step) {
393
+ // A mismatch does not stop the run: the later steps and expectations still run.
394
+ const mismatches = await expected(client, step, at);
395
+ expectations.push({ expect: step.expect, pass: mismatches.length === 0, count: mismatches.length, mismatches: mismatches.slice(0, MAX_LISTED_MISMATCHES) });
298
396
  } else {
299
397
  const notReached = await runActionStep(client, step, at);
300
398
  if (notReached !== undefined && "runUntil" in step) {
@@ -305,9 +403,21 @@ export async function runFile(path: string, out: string): Promise<{ output: Reco
305
403
  done++;
306
404
  }
307
405
  const pc = (await client.registersGet("c64")).pc;
308
- const results = { name: run.name, completed: reason === undefined, steps: run.steps.length, done, ...(reason === undefined ? {} : { reason }), pc: formatC64Address(pc), files: [...files], observations, ...(Object.keys(traces).length === 0 ? {} : { traces }) };
406
+ const failedExpectations = expectations.filter((item) => !item.pass).map((item) => item.expect);
407
+ const results = {
408
+ name: run.name,
409
+ completed: reason === undefined,
410
+ steps: run.steps.length,
411
+ done,
412
+ ...(reason === undefined ? {} : { reason }),
413
+ pc: formatC64Address(pc),
414
+ files: [...files],
415
+ observations,
416
+ ...(expectations.length === 0 ? {} : { expectations, failedExpectations }),
417
+ ...(Object.keys(traces).length === 0 ? {} : { traces }),
418
+ };
309
419
  write("results.json", Buffer.from(`${JSON.stringify(results, null, 2)}\n`));
310
- return { output: { ...results, files: written, observations: Object.keys(observations), out }, failed: reason !== undefined };
420
+ return { output: { ...results, files: written, observations: Object.keys(observations), out }, failed: reason !== undefined || failedExpectations.length > 0 };
311
421
  } finally {
312
422
  await client.close();
313
423
  }
@@ -131,7 +131,7 @@ const COMMANDS: CommandSpec[] = [
131
131
  },
132
132
  {
133
133
  name: "run",
134
- summary: "Runs the steps of a run file in its own emulator and writes what they ask for into --out: screens, coverage maps, snapshot files, traces, and results.json with the observations. result is FAIL when a step did not run.",
134
+ summary: "Runs the steps of a run file in its own emulator and writes what they ask for into --out: screens, coverage maps, snapshot files, traces, and results.json with the observations and the expectations. result is FAIL when a step did not run or an expect step found a value that differs.",
135
135
  subjects: [{ name: "<run.json>", help: "a run file, relative to the project folder. See references/scenario-format.md, section Runs" }],
136
136
  options: { out: { ...OPTIONS.out, output: "folder", value: "<dir>", required: true, help: "the folder for the files of the steps and results.json" } },
137
137
  run: async (call) => {
package/src/cli/main.ts CHANGED
@@ -29,14 +29,14 @@ Harnesses: claude, codex, pi, opencode, gemini, copilot, cursor, windsurf
29
29
  (comma-separated; default: all). Without --global the files go into the
30
30
  current folder; with --global into your home directory.
31
31
 
32
- Run it once at the root of the repository:
33
- npx -y ${PACKAGE.name}@${PACKAGE.tag} install. Each project folder below
34
- the root uses that install; a project is a folder with .c64-re-tools/. The
35
- VICE MCP declaration starts the latest c64-re-tools-mcp through npx. The Host
36
- Runtime runs on the machine with VICE: start it there with
37
- npx -y --package=${PACKAGE.name}@${PACKAGE.tag} c64-re-tools-host.
32
+ The dev container Feature of c64-re-tools runs install at the root of the
33
+ repository when it creates the container, and update at each start. Each
34
+ project folder below the root uses that install; a project is a folder with
35
+ .c64-re-tools/. The VICE MCP declaration starts the latest c64-re-tools-mcp
36
+ through npx. The Host Runtime runs on the machine with VICE: start it there
37
+ with npx -y --package=${PACKAGE.name}@${PACKAGE.tag} c64-re-tools-host.
38
38
  It runs VICE and the tools that come with it (c1541, petcat). The skill
39
- scripts run ACME, DXA and Ghidra themselves, on the machine of the agent.`;
39
+ scripts run ACME, DXA, Ghidra and c64run in the dev container.`;
40
40
 
41
41
  const here = dirname(fileURLToPath(import.meta.url));
42
42
 
@@ -73,7 +73,7 @@ function rangesWhere(has: (address: number) => boolean): AddressRange[] {
73
73
  }
74
74
 
75
75
  /** The memory rows of the segments: at most MEMORY_ROW bytes, never across a multiple of MEMORY_ROW. */
76
- function memoryRows(segments: readonly AddressRange[], byteAt: (address: number) => number): Map<number, string> {
76
+ export function memoryRows(segments: readonly AddressRange[], byteAt: (address: number) => number): Map<number, string> {
77
77
  const rows = new Map<number, string>();
78
78
  for (const segment of segments) {
79
79
  for (let at = segment.start; at <= segment.end; ) {
@@ -6,7 +6,7 @@
6
6
  // or executes outside the image. Evidence only: nothing here decides what is
7
7
  // original.
8
8
 
9
- import { type AddressRange, COVERAGE, executedRamCode, instructionLength } from "#src/c64.ts";
9
+ import { type AddressRange, COVERAGE, executedRamCode, instructionLength } from "../c64.ts";
10
10
 
11
11
  export type Access = "executed" | "read" | "written" | "read-written" | "untouched";
12
12
 
@@ -21,6 +21,8 @@ export interface SeparationInput {
21
21
  coverage?: Uint8Array;
22
22
  codeRegions: Array<AddressRange & { type: string }>;
23
23
  references: Array<{ from: number; to: number; kind: string }>;
24
+ /** More roots after the entry and the hardware vectors, for example code that a run executed. */
25
+ roots?: Root[];
24
26
  }
25
27
 
26
28
  export interface EvidenceRange extends AddressRange {
@@ -37,14 +39,14 @@ export interface CodeRegionEvidence extends AddressRange {
37
39
  executed?: boolean;
38
40
  }
39
41
 
40
- /** An address where the reachability starts, and why: the entry, or a hardware vector in the image. */
42
+ /** An address where the reachability starts, and why: the entry, a hardware vector in the image, or a root that the caller gives. */
41
43
  export interface Root {
42
44
  address: number;
43
- from: "entry" | "NMI vector $fffa" | "RESET vector $fffc" | "IRQ vector $fffe";
45
+ from: "entry" | "NMI vector $fffa" | "RESET vector $fffc" | "IRQ vector $fffe" | "executed code" | "kept range" | "table entry";
44
46
  }
45
47
 
46
48
  export interface Separation {
47
- /** The roots of the reachability, in the order entry, NMI, RESET, IRQ. */
49
+ /** The roots of the reachability, in the order entry, NMI, RESET, IRQ, then the roots of the input. */
48
50
  roots: Root[];
49
51
  ranges: EvidenceRange[];
50
52
  codeRegions: CodeRegionEvidence[];
@@ -78,7 +80,7 @@ export function reachabilityRoots(segments: readonly AddressRange[], memory: Uin
78
80
  }
79
81
 
80
82
  /** BRK, JMP, RTI, RTS, JMP (indirect) and the JAM opcodes: the CPU does not run on to the next instruction after them. */
81
- const NO_FALL_THROUGH = new Set([0x00, 0x4c, 0x40, 0x60, 0x6c, 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72, 0x92, 0xb2, 0xd2, 0xf2]);
83
+ export const NO_FALL_THROUGH = new Set([0x00, 0x4c, 0x40, 0x60, 0x6c, 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72, 0x92, 0xb2, 0xd2, 0xf2]);
82
84
 
83
85
  /**
84
86
  * The address after a code region where the CPU runs on, or undefined when
@@ -141,13 +143,14 @@ export function separate(input: SeparationInput): Separation {
141
143
  }
142
144
  }
143
145
 
144
- // Reachability: from the regions that hold a root, through call and jump references and the run on
145
- // from the last instruction of a region into the next address, to a fixed point.
146
146
  const regions = input.codeRegions.filter((region) => input.segments.some((segment) => region.start <= segment.end && segment.start <= region.end));
147
- const holding = (address: number) => regions.findIndex((region) => address >= region.start && address <= region.end);
148
- const roots = reachabilityRoots(input.segments, input.memory, input.entry);
149
- const reached = new Set<number>();
150
- for (const root of roots) if (holding(root.address) >= 0) reached.add(holding(root.address));
147
+ // The region of each address: the first region that holds it, as a search in region order finds it.
148
+ const owner = new Int32Array(0x10000).fill(-1);
149
+ regions.forEach((region, index) => {
150
+ for (let address = Math.max(region.start, 0); address <= Math.min(region.end, 0xffff); address++) if (owner[address] === -1) owner[address] = index;
151
+ });
152
+ const holding = (address: number) => (address >= 0 && address <= 0xffff ? owner[address]! : -1);
153
+ const roots = [...reachabilityRoots(input.segments, input.memory, input.entry), ...(input.roots ?? [])];
151
154
  // The CPU runs the bytes after the region as instructions: through bytes of no code region (a dual-use
152
155
  // instruction, for example) into the next code region, unless one of them does not run on.
153
156
  const runOn = (from: number): number | undefined => {
@@ -164,16 +167,27 @@ export function separate(input: SeparationInput): Separation {
164
167
  const to = next === undefined ? undefined : runOn(next);
165
168
  return to === undefined ? [] : [{ from: region.end, to }];
166
169
  });
167
- const flows = [...input.references.filter((reference) => reference.kind === "call" || reference.kind === "jump"), ...runsOn];
168
- for (let grown = true; grown; ) {
169
- grown = false;
170
- for (const flow of flows) {
171
- const from = holding(flow.from);
172
- const to = holding(flow.to);
173
- if (from >= 0 && to >= 0 && reached.has(from) && !reached.has(to)) {
174
- reached.add(to);
175
- grown = true;
176
- }
170
+ // From the regions that hold a root, through call and jump references and the run on, to every region they reach.
171
+ const next = regions.map((): number[] => []);
172
+ for (const flow of [...input.references.filter((reference) => reference.kind === "call" || reference.kind === "jump"), ...runsOn]) {
173
+ const from = holding(flow.from);
174
+ const to = holding(flow.to);
175
+ if (from >= 0 && to >= 0) next[from]!.push(to);
176
+ }
177
+ const reached = new Set<number>();
178
+ const queue: number[] = [];
179
+ for (const root of roots) {
180
+ const index = holding(root.address);
181
+ if (index >= 0 && !reached.has(index)) {
182
+ reached.add(index);
183
+ queue.push(index);
184
+ }
185
+ }
186
+ while (queue.length > 0) {
187
+ for (const to of next[queue.pop()!]!) {
188
+ if (reached.has(to)) continue;
189
+ reached.add(to);
190
+ queue.push(to);
177
191
  }
178
192
  }
179
193
  const codeRegions = regions.map((region, index): CodeRegionEvidence => {
@@ -4,6 +4,7 @@
4
4
  import { existsSync, readFileSync } from "node:fs";
5
5
  import { isAbsolute, join, relative, sep } from "node:path";
6
6
 
7
+ import { formatC64Address } from "../c64.ts";
7
8
  import { WireFailure } from "../protocol/messages.ts";
8
9
  import { isRelativePath } from "../protocol/tools.ts";
9
10
  import type { AcmeParams, AcmeResult, AssembledSymbol, Diagnostic } from "./types.ts";
@@ -11,6 +12,16 @@ import { Workspace } from "./staging.ts";
11
12
  import { ACME, findTool } from "./discover.ts";
12
13
  import { outputTail, runToolOrFail, type ToolContext } from "./run.ts";
13
14
 
15
+ /** A symbol of a build as a person and c64-testing read it: an address as $ and four hex digits, a constant as $ and at least four hex digits. */
16
+ export function showSymbol(symbol: AssembledSymbol) {
17
+ return symbol.kind === "address"
18
+ ? { name: symbol.name, kind: "address", address: formatC64Address(symbol.address), used: symbol.used }
19
+ : { name: symbol.name, kind: "constant", value: `$${symbol.value.toString(16).padStart(4, "0")}`, used: symbol.used };
20
+ }
21
+
22
+ /** The text of a symbols file (--out-symbols): the symbols of a build, which c64-testing reads for the names of a program. */
23
+ export const symbolsFileText = (symbols: readonly AssembledSymbol[]) => `${JSON.stringify({ symbols: symbols.map(showSymbol) }, null, 1)}\n`;
24
+
14
25
  const PROGRAM = "program.prg";
15
26
  const SYMBOLS = "symbols.txt";
16
27
  const TIMEOUT_MS = 60_000;
@@ -127,7 +127,7 @@ export class C64RunSession {
127
127
  if (error instanceof WireFailure && /no ROM/.test(error.message)) {
128
128
  throw new WireFailure(
129
129
  "installation-incomplete",
130
- `${error.message}. c64run needs the C64 ROMs kernal-901227-03.bin, basic-901226-01.bin and chargen-901225-01.bin: set C64RT_C64_ROMS to a folder with them (the C64 folder of VICE has them). ${INSTALL_STEPS}`,
130
+ `${error.message}. c64run needs the C64 ROMs kernal-901227-03.bin, basic-901226-01.bin and chargen-901225-01.bin. ${INSTALL_STEPS}`,
131
131
  );
132
132
  }
133
133
  throw error;
@@ -7,8 +7,8 @@ import { isAbsolute, join, posix, win32 } from "node:path";
7
7
 
8
8
  import { WireFailure } from "../protocol/messages.ts";
9
9
 
10
- /** Where the user finds the install steps of the native tools for each system. */
11
- export const INSTALL_STEPS = "Steps for each system: https://github.com/henols/c64-re-tools/blob/main/docs/install-tools.md. In the dev container of c64-re-tools, restart the container: each start installs the tools of the toolkit version.";
10
+ /** The remedy for a missing native tool: the dev container of c64-re-tools installs every one. */
11
+ export const INSTALL_STEPS = "The dev container of c64-re-tools installs it at each start: restart the container, or rebuild it. Without that dev container, set it up as https://github.com/henols/c64-re-tools#dev-container tells.";
12
12
 
13
13
  export interface ToolSpec {
14
14
  /** Human name, for messages. */
@@ -28,7 +28,7 @@ export const ACME: ToolSpec = {
28
28
  envVar: "C64RT_ACME",
29
29
  binaries: ["acme"],
30
30
  where: "on this machine",
31
- remedy: `Install the ACME cross-assembler on the machine that runs the skill scripts so that acme is on PATH, or set C64RT_ACME to its full path. ${INSTALL_STEPS}`,
31
+ remedy: INSTALL_STEPS,
32
32
  };
33
33
 
34
34
  export const C1541: ToolSpec = {
@@ -52,7 +52,7 @@ export const DXA: ToolSpec = {
52
52
  envVar: "C64RT_DXA",
53
53
  binaries: ["dxa"],
54
54
  where: "on this machine",
55
- remedy: `Install dxa 0.1.5 on the machine that runs the skill scripts so that dxa is on PATH, or set C64RT_DXA to its full path. ${INSTALL_STEPS}`,
55
+ remedy: INSTALL_STEPS,
56
56
  };
57
57
 
58
58
  export const C64RUN: ToolSpec = {
@@ -60,7 +60,7 @@ export const C64RUN: ToolSpec = {
60
60
  envVar: "C64RT_C64RUN",
61
61
  binaries: ["c64run"],
62
62
  where: "on this machine",
63
- remedy: `Install c64run (the replay core of c64-testing, with its C64 ROMs) on the machine that runs the skill scripts so that c64run is on PATH, or set C64RT_C64RUN to its full path. ${INSTALL_STEPS}`,
63
+ remedy: INSTALL_STEPS,
64
64
  };
65
65
 
66
66
  export const VICE: ToolSpec = {
@@ -21,10 +21,6 @@ export const GHIDRA_LANGUAGE = "C64RT_6510:LE:16:nmos";
21
21
  export const LANGUAGE_DIRECTORY = fileURLToPath(new URL("./language/", import.meta.url));
22
22
  export const SCRIPT_DIRECTORY = fileURLToPath(new URL("./scripts/", import.meta.url));
23
23
 
24
- const REMEDY =
25
- "Install Ghidra on the machine that runs the skill scripts and set C64RT_GHIDRA to its installation directory " +
26
- `(the directory that holds support/analyzeHeadless), or put analyzeHeadless on PATH. ${INSTALL_STEPS}`;
27
-
28
24
  export interface GhidraInstallation {
29
25
  /** The installation directory. */
30
26
  root: string;
@@ -46,12 +42,12 @@ function installationAt(root: string, source: string): GhidraInstallation {
46
42
  if (!isExecutableFile(analyzeHeadless)) throw new Refusal("operation-failed", "no analyzeHeadless");
47
43
  properties = readFileSync(join(root, "Ghidra", "application.properties"), "utf8");
48
44
  } catch {
49
- throw new WireFailure("installation-incomplete", `${source} does not point to a Ghidra installation. ${REMEDY}`);
45
+ throw new WireFailure("installation-incomplete", `${source} does not point to a Ghidra installation. ${INSTALL_STEPS}`);
50
46
  }
51
47
  const value = (key: string) => new RegExp(`^${key.replace(/\./g, "\\.")}=(.*)$`, "m").exec(properties)?.[1]?.trim();
52
48
  const version = value("application.version");
53
49
  const release = value("application.release.name");
54
- if (version === undefined || release === undefined) throw new WireFailure("installation-incomplete", `The Ghidra installation at ${source} has no version. ${REMEDY}`);
50
+ if (version === undefined || release === undefined) throw new WireFailure("installation-incomplete", `The Ghidra installation at ${source} has no version. ${INSTALL_STEPS}`);
55
51
  const javaMin = value("application.java.min");
56
52
  return { root, analyzeHeadless, settingsName: `ghidra_${version}_${release}`, version, ...(javaMin === undefined || javaMin === "" ? {} : { javaMin }) };
57
53
  }
@@ -65,12 +61,12 @@ export function ghidraVersion(ghidra: GhidraInstallation): string {
65
61
  export function findGhidra(env: NodeJS.ProcessEnv = process.env): GhidraInstallation {
66
62
  const configured = env.C64RT_GHIDRA;
67
63
  if (configured !== undefined && configured !== "") {
68
- if (!isAbsolute(configured)) throw new WireFailure("installation-incomplete", `C64RT_GHIDRA on this machine is not an absolute path. ${REMEDY}`);
64
+ if (!isAbsolute(configured)) throw new WireFailure("installation-incomplete", `C64RT_GHIDRA on this machine is not an absolute path. ${INSTALL_STEPS}`);
69
65
  return installationAt(configured, "C64RT_GHIDRA");
70
66
  }
71
67
  const found = findOnPath(["analyzeHeadless"], env, [LAUNCHER_SUFFIX]);
72
68
  if (found !== undefined) return installationAt(resolve(dirname(realpathSync(found)), ".."), "analyzeHeadless on PATH");
73
- throw new WireFailure("installation-incomplete", `Ghidra is not installed on this machine. ${REMEDY}`);
69
+ throw new WireFailure("installation-incomplete", `Ghidra is not installed on this machine. ${INSTALL_STEPS}`);
74
70
  }
75
71
 
76
72
  /**
@@ -135,7 +131,7 @@ export function noJdk(ghidra: GhidraInstallation): WireFailure {
135
131
  const java = ghidra.javaMin === undefined ? "a JDK" : `JDK ${ghidra.javaMin} or later`;
136
132
  return new WireFailure(
137
133
  "installation-incomplete",
138
- `${ghidraVersion(ghidra)} found no Java that it can use. It needs ${java}. Install it on the machine that runs the skill scripts and put its java on PATH, or set JAVA_HOME to it. ${INSTALL_STEPS}`,
134
+ `${ghidraVersion(ghidra)} found no Java that it can use. It needs ${java}. ${INSTALL_STEPS}`,
139
135
  );
140
136
  }
141
137
 
@@ -114,7 +114,7 @@ export async function probeC64run(context: ToolContext): Promise<ToolStatus> {
114
114
  context,
115
115
  (output) => {
116
116
  const missing = /^roms=missing (.*)$/m.exec(output)?.[1];
117
- return missing === undefined ? undefined : `It has no C64 ROMs: ${missing}. Set C64RT_C64_ROMS to a folder with kernal-901227-03.bin, basic-901226-01.bin and chargen-901225-01.bin (the C64 folder of VICE has them). ${INSTALL_STEPS}`;
117
+ return missing === undefined ? undefined : `It has no C64 ROMs: ${missing}. ${INSTALL_STEPS}`;
118
118
  },
119
119
  );
120
120
  } catch (error) {