@henols/c64-re-tools 2.1.8 → 2.2.0-rc.2

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) => {
@@ -111,7 +111,10 @@ The scripts refuse a step in the form of version 2.0, for example `{ "runUntil":
111
111
  - `image.json`: the entry, the segments, the vectors and the stages. A segment is a block that a stage wrote, also a small block. A block is not a segment when it holds the entry of a later stage before the program, and no stage wrote over that entry. A block that a stage before the program wrote in such a block is also not a segment, for example a variable of a loader. A block that is fully in pages 0 to 3 is not a segment, because `entry_state.json` holds these pages. The block with the capture entry is always a segment. Segments do not overlap. `writtenBy` tells the last stage that wrote into the segment.
112
112
  - One PRG for each segment. A capture into a directory that has a capture removes the segment PRGs that the new `image.json` does not list. `removed` in the result names them. The capture keeps all other files.
113
113
  - `entry_state.json`: the registers, `$00` and `$01`, pages 0 to 3, the VIC, SID and CIA registers, and the vectors. `cia` gives the CIA timer latches and interrupt masks. `differsFromReset` lists the bytes that are not as a clean C64 has them at READY. A rebuild must make these bytes the same, because the program can read them.
114
- 5. Make sure that the result is the application: the code at the entry must not be the unpacker again. A segment can be data that a loader left, for example intro graphics. Keep it until other evidence shows that the program does not use it. Then capture again with `--exclude` for that range. Thus the source and the loader do not include the range.
114
+ 5. Make sure that the result is the application: the code at the entry must not be the unpacker again. A segment can be data that a loader or a cracktro left, for example intro graphics. Keep it until other evidence shows that the program does not use it. Then capture again with `--exclude` for that range. Thus the source and the loader do not include the range.
115
+ - Cut each range of a cracktro that the program does not read. A rebuild has no cracktro.
116
+ - Do not cut other unused bytes, for example leftovers of the development or an old copy of a routine. A rebuild keeps them.
117
+ - A crack change that the program reads, for example a credit text in the game, stays. Record it as a `crack` switch with the c64-knowledge skill.
115
118
  6. Put the capture into the knowledge with `image <out>/image.json` of the c64-knowledge skill. The knowledge keeps the segments, the entry, the entry state and the stages. The other skills read them there. The files in `<out>` are not necessary after that.
116
119
  7. Use `--range` only when you know the area of the program. Then the capture writes that one segment.
117
120
 
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
 
@@ -15,6 +15,8 @@ import {
15
15
  OPERAND_COLUMNS,
16
16
  PATCH_COLUMNS,
17
17
  REFERENCE_COLUMNS,
18
+ RELEASE_COLUMNS,
19
+ SWITCH_COLUMNS,
18
20
  REGION_COLUMNS,
19
21
  SUPPRESSION_COLUMNS,
20
22
  SYMBOL_COLUMNS,
@@ -25,6 +27,8 @@ import {
25
27
  toOperand,
26
28
  toPatch,
27
29
  toReference,
30
+ toRelease,
31
+ toSwitch,
28
32
  toRegion,
29
33
  toSuppression,
30
34
  toSymbol,
@@ -47,7 +51,11 @@ export const CONFLICT_RULES = {
47
51
  "suppression-symbol": "the same symbol suppression two times",
48
52
  "suppression-reference": "the same reference suppression two times",
49
53
  "suppression-region": "region suppressions that overlap",
50
- patch: "patches that overlap",
54
+ patch: "patches that overlap and do not have the same range",
55
+ "patch-switch": "two patches of one switch at one range",
56
+ switch: "two switches with one name",
57
+ release: "two releases with one label",
58
+ "release-base": "two base releases",
51
59
  macro: "two macros with one name",
52
60
  "macro-use": "macro uses that overlap",
53
61
  } as const;
@@ -71,8 +79,11 @@ interface TableRule {
71
79
  entity: HistoryEntry["entity"];
72
80
  columns: string;
73
81
  map: (raw: Raw) => HistoryEntry["row"];
74
- /** The columns that must differ between current rows, or "overlap" for address ranges. */
75
- key: readonly string[] | "overlap";
82
+ /**
83
+ * The columns that must differ between current rows, "overlap" for address
84
+ * ranges, or "partial" for ranges that may only overlap when they are equal.
85
+ */
86
+ key: readonly string[] | "overlap" | "partial";
76
87
  /** Rows of the table that the rule is about. */
77
88
  where?: string;
78
89
  }
@@ -99,7 +110,12 @@ const RULES: readonly TableRule[] = [
99
110
  where: "entity = 'reference'",
100
111
  },
101
112
  { rule: "suppression-region", table: "suppressions", entity: "suppression", columns: SUPPRESSION_COLUMNS, map: toSuppression, key: "overlap", where: "entity = 'region'" },
102
- { rule: "patch", table: "patches", entity: "patch", columns: PATCH_COLUMNS, map: toPatch, key: "overlap" },
113
+ // Patches of different switches at the same range are alternatives; any other overlap is a conflict.
114
+ { rule: "patch", table: "patches", entity: "patch", columns: PATCH_COLUMNS, map: toPatch, key: "partial" },
115
+ { rule: "patch-switch", table: "patches", entity: "patch", columns: PATCH_COLUMNS, map: toPatch, key: ["start_address", "end_address", "switch_name"] },
116
+ { rule: "switch", table: "switches", entity: "switch", columns: SWITCH_COLUMNS, map: toSwitch, key: ["name"] },
117
+ { rule: "release", table: "releases", entity: "release", columns: RELEASE_COLUMNS, map: toRelease, key: ["label"] },
118
+ { rule: "release-base", table: "releases", entity: "release", columns: RELEASE_COLUMNS, map: toRelease, key: ["base"], where: "base = 1" },
103
119
  { rule: "macro", table: "macros", entity: "macro", columns: MACRO_COLUMNS, map: toMacro, key: ["name"] },
104
120
  { rule: "macro-use", table: "macro_uses", entity: "macro-use", columns: MACRO_USE_COLUMNS, map: toMacroUse, key: "overlap" },
105
121
  ];
@@ -127,8 +143,12 @@ function sameKey(db: DatabaseSync, rule: TableRule, key: readonly string[]): Con
127
143
  return [...groups.values()];
128
144
  }
129
145
 
130
- /** The current rows of one rule whose address ranges overlap, in groups of rows that overlap in a chain. */
131
- function overlapping(db: DatabaseSync, rule: TableRule): Conflict[] {
146
+ /**
147
+ * The current rows of one rule whose address ranges overlap, in groups of rows
148
+ * that overlap in a chain. With `sameRange`, a group whose rows all have one
149
+ * range is no conflict.
150
+ */
151
+ function overlapping(db: DatabaseSync, rule: TableRule, sameRange = false): Conflict[] {
132
152
  const rows = db
133
153
  .prepare(`SELECT ${rule.columns}, id FROM ${sqlName(rule.table)} WHERE valid_to_revision IS NULL${rule.where === undefined ? "" : ` AND ${rule.where}`} ORDER BY space, start_address, end_address`)
134
154
  .all() as Raw[];
@@ -146,13 +166,17 @@ function overlapping(db: DatabaseSync, rule: TableRule): Conflict[] {
146
166
  end = raw.end_address as number;
147
167
  }
148
168
  if (group !== undefined && group.rows.length > 1) conflicts.push(group);
149
- return conflicts;
169
+ if (!sameRange) return conflicts;
170
+ return conflicts.filter((conflict) => {
171
+ const [first, ...rest] = conflict.rows.map((entry) => entry.row as { start: number; end: number });
172
+ return rest.some((row) => row.start !== first!.start || row.end !== first!.end);
173
+ });
150
174
  }
151
175
 
152
176
  /** Every conflict of the knowledge, rule by rule; the rows of each, oldest first. */
153
177
  export function conflicts(db: DatabaseSync | undefined): Conflict[] {
154
178
  if (db === undefined) return [];
155
- return RULES.flatMap((rule) => (rule.key === "overlap" ? overlapping(db, rule) : sameKey(db, rule, rule.key))).map((conflict) => ({ ...conflict, rows: conflict.rows.sort(byAge) }));
179
+ return RULES.flatMap((rule) => (rule.key === "overlap" || rule.key === "partial" ? overlapping(db, rule, rule.key === "partial") : sameKey(db, rule, rule.key))).map((conflict) => ({ ...conflict, rows: conflict.rows.sort(byAge) }));
156
180
  }
157
181
 
158
182
  /** The table of a conflict rule. */
@@ -12,6 +12,8 @@ import {
12
12
  OPERAND_COLUMNS,
13
13
  PATCH_COLUMNS,
14
14
  REFERENCE_COLUMNS,
15
+ RELEASE_COLUMNS,
16
+ SWITCH_COLUMNS,
15
17
  REGION_COLUMNS,
16
18
  resolveRevision,
17
19
  SUPPRESSION_COLUMNS,
@@ -23,6 +25,8 @@ import {
23
25
  toOperand,
24
26
  toPatch,
25
27
  toReference,
28
+ toRelease,
29
+ toSwitch,
26
30
  toRegion,
27
31
  toSuppression,
28
32
  toSymbol,
@@ -33,6 +37,8 @@ import {
33
37
  type OperandRow,
34
38
  type PatchRow,
35
39
  type ReferenceRow,
40
+ type ReleaseRow,
41
+ type SwitchRow,
36
42
  type RegionRow,
37
43
  type SuppressionRow,
38
44
  type SymbolRow,
@@ -101,6 +107,8 @@ export type HistoryEntry =
101
107
  | { entity: "module"; row: ModuleRow; from: string; to?: string }
102
108
  | { entity: "operand"; row: OperandRow; from: string; to?: string }
103
109
  | { entity: "patch"; row: PatchRow; from: string; to?: string }
110
+ | { entity: "switch"; row: SwitchRow; from: string; to?: string }
111
+ | { entity: "release"; row: ReleaseRow; from: string; to?: string }
104
112
  | { entity: "macro"; row: MacroRow; from: string; to?: string }
105
113
  | { entity: "macro-use"; row: MacroUseRow; from: string; to?: string };
106
114
 
@@ -170,6 +178,14 @@ export function historyOfMacro(db: DatabaseSync | undefined, name: string, space
170
178
  return [...macros, ...uses].sort(bySequence);
171
179
  }
172
180
 
181
+ /** Every row of a switch with this name and every patch of it, oldest first. */
182
+ export function historyOfSwitch(db: DatabaseSync | undefined, name: string, space: Space = DEFAULT_SPACE): HistoryEntry[] {
183
+ if (db === undefined) return [];
184
+ const switches = (db.prepare(`SELECT ${SWITCH_COLUMNS}, valid_to_revision FROM switches WHERE space = ? AND name = ?`).all(space, name) as Raw[]).map((raw) => entry("switch", toSwitch(raw), raw));
185
+ const patches = (db.prepare(`SELECT ${PATCH_COLUMNS}, valid_to_revision FROM patches WHERE space = ? AND switch_name = ?`).all(space, name) as Raw[]).map((raw) => entry("patch", toPatch(raw), raw));
186
+ return [...switches, ...patches].sort(bySequence);
187
+ }
188
+
173
189
  /** Every symbol row of a space that ever had this name, oldest first: a name can move between addresses. */
174
190
  export function historyNamed(db: DatabaseSync | undefined, name: string, space: Space = DEFAULT_SPACE): HistoryEntry[] {
175
191
  if (db === undefined) return [];
@@ -247,6 +263,8 @@ export function revision(db: DatabaseSync | undefined, text: string): RevisionCh
247
263
  ["module", "modules", MODULE_COLUMNS, toModule],
248
264
  ["operand", "operands", OPERAND_COLUMNS, toOperand],
249
265
  ["patch", "patches", PATCH_COLUMNS, toPatch],
266
+ ["switch", "switches", SWITCH_COLUMNS, toSwitch],
267
+ ["release", "releases", RELEASE_COLUMNS, toRelease],
250
268
  ["macro", "macros", MACRO_COLUMNS, toMacro],
251
269
  ["macro-use", "macro_uses", MACRO_USE_COLUMNS, toMacroUse],
252
270
  ] as const;