@henols/c64-re-tools 2.1.2 → 2.1.4

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.
Files changed (50) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +1 -1
  3. package/skills/c64-assembler/scripts/assembler.ts +2 -2
  4. package/skills/c64-disk/scripts/lib/containers.ts +2 -1
  5. package/skills/c64-docs/SKILL.md +1 -1
  6. package/skills/c64-docs/scripts/docs.ts +5 -3
  7. package/skills/c64-emulator/SKILL.md +4 -0
  8. package/skills/c64-knowledge/SKILL.md +7 -2
  9. package/skills/c64-knowledge/scripts/knowledge.ts +6 -12
  10. package/skills/c64-knowledge/scripts/lib/listing.ts +8 -1
  11. package/skills/c64-memory-map/SKILL.md +3 -1
  12. package/skills/c64-memory-map/scripts/memory-map.ts +26 -5
  13. package/skills/c64-provenance/SKILL.md +5 -4
  14. package/skills/c64-provenance/scripts/lib/compare.ts +12 -0
  15. package/skills/c64-provenance/scripts/lib/library.ts +33 -5
  16. package/skills/c64-provenance/scripts/lib/separate.ts +34 -6
  17. package/skills/c64-provenance/scripts/provenance.ts +26 -11
  18. package/skills/c64-source/SKILL.md +3 -2
  19. package/skills/c64-source/scripts/lib/source.ts +18 -4
  20. package/skills/c64-source/scripts/source.ts +40 -28
  21. package/skills/c64-static-analysis/SKILL.md +4 -3
  22. package/skills/c64-static-analysis/scripts/lib/findings.ts +47 -10
  23. package/skills/c64-static-analysis/scripts/lib/pointers.ts +38 -25
  24. package/skills/c64-static-analysis/scripts/static-analysis.ts +17 -14
  25. package/skills/c64-testing/SKILL.md +6 -3
  26. package/skills/c64-testing/references/scenario-format.md +7 -3
  27. package/skills/c64-testing/scripts/lib/diff-files.ts +27 -8
  28. package/skills/c64-testing/scripts/lib/runs.ts +24 -8
  29. package/skills/c64-testing/scripts/lib/scenario.ts +133 -83
  30. package/skills/c64-testing/scripts/testing.ts +6 -3
  31. package/skills/c64-unpacker/SKILL.md +5 -4
  32. package/skills/c64-unpacker/scripts/lib/loads.ts +9 -3
  33. package/skills/c64-unpacker/scripts/lib/machine.ts +31 -0
  34. package/skills/c64-unpacker/scripts/unpacker.ts +4 -1
  35. package/src/host/vice/session.ts +118 -11
  36. package/src/host-client/image.ts +22 -8
  37. package/src/host-client/steps.ts +2 -2
  38. package/src/host-client/tools.ts +4 -3
  39. package/src/host-client/transfer.ts +8 -3
  40. package/src/host-client/vice-session.ts +3 -3
  41. package/src/knowledge/write.ts +110 -29
  42. package/src/mcp/output.ts +1 -1
  43. package/src/mcp/server.ts +7 -0
  44. package/src/mcp/tools/debug.ts +2 -1
  45. package/src/mcp/tools/media.ts +8 -5
  46. package/src/media.ts +18 -0
  47. package/src/opcodes.ts +31 -1
  48. package/src/platform.ts +14 -1
  49. package/src/project.ts +14 -3
  50. package/src/script.ts +71 -2
@@ -47,7 +47,7 @@ Before the first step of each side, the script does a hard reset. The CPU stops
47
47
  | `{ "type": { "mode": "text", "text": "RUN\n" } }` | Put at most 1024 keys into the keyboard queue of the KERNAL. A program that reads the keyboard hardware does not see them. |
48
48
  | `{ "type": { "mode": "petscii", "bytes": [147] } }` | Put PETSCII codes from 1 to 255 into the keyboard queue of the KERNAL. Use it for keys that mode `text` does not have. |
49
49
  | `{ "runUntil": { "target": { "kind": "address", "address": "main_loop" }, "timeoutFrames": 600 } }` | Run until the CPU gets to an address. |
50
- | `{ "runUntil": { "target": { "kind": "memory", "address": "game_state", "operator": "eq", "value": 2 }, "timeoutFrames": 600 } }` | Run until a byte in memory compares true with `value`. `operator` is `eq`, `ne`, `lt`, `lte`, `gt` or `gte`. |
50
+ | `{ "runUntil": { "target": { "kind": "memory", "address": "game_state", "operator": "eq", "value": 2 }, "timeoutFrames": 600 } }` | Run until a write to the byte makes the comparison with `value` true. `operator` is `eq`, `ne`, `lt`, `lte`, `gt` or `gte`. The run does not stop for a byte that is already true at the start. It also does not stop for a register that the hardware changes, for example `$d012`. For a raster line, use a `raster` target. |
51
51
  | `{ "runUntil": { "target": { "kind": "raster", "line": 250 }, "timeoutFrames": 5 } }` | Run until the raster beam gets to a line (0 to 311 for PAL, 0 to 262 for NTSC). Optional: `cycle` from 0 to 64. |
52
52
  | `{ "runUntil": { "target": { "kind": "address", "address": "irq_tick", "condition": { "kind": "raster", "line": 250 } }, "timeoutFrames": 600 } }` | Run until the CPU gets to an address while the condition is true. |
53
53
  | `{ "snapshot": "snapshots/start.vsf" }` | Restore a snapshot file. Usually with `side`: the snapshot of one program is not a state of the other. |
@@ -90,12 +90,14 @@ A run file (for `testing.ts run`) has:
90
90
 
91
91
  - `name`: a short name.
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
- - `symbols`: optional, `knowledge`, `none` (default), or a JSON file as for a subject.
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
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`.
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
 
99
+ In a run, an `observe` step can have `memory`, `registers`, `vicii` and `sprites`. `registers` and `vicii` are `true` or `false`, not a list. `"registers": true` gives all registers. A scenario takes a list of register names, a run does not. `sprites` is a list of sprite numbers from 0 to 7.
100
+
99
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`.
100
102
 
101
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.
@@ -124,7 +126,9 @@ Example: visit two rooms from the same start.
124
126
 
125
127
  The script checks the scenario before it starts the emulator. A step with an unknown key or a wrong value stops the script with `invalid-input`. The message names the step.
126
128
 
127
- The script also examines each file before it starts the emulator: the program and the symbols of each side, and each snapshot file. A missing file stops the script with `not-found`. A program that is not a PRG, for example a disk image, stops the script with `invalid-input`.
129
+ The script also examines each file before it starts the emulator: the program and the symbols of each side, and each snapshot file. A missing file stops the script with `not-found`. A program that is not a PRG, for example a disk image, stops the script with `invalid-input`. A snapshot file that does not start with the signature of a VICE snapshot file also stops the script with `invalid-input`. The message names the step and the file.
130
+
131
+ A run also examines each name of its steps before it starts the emulator. An unknown name stops the run with `invalid-input`, and the message names the step. In a scenario, a side that does not have a name gives INCONCLUSIVE, and `reason` names the step.
128
132
 
129
133
  A step in the form of version 2.0 stops the script with `invalid-input`. The message names the old field and gives the step to write. For example, the script refuses `{ "runUntil": { "at": "main_loop" }, "timeoutFrames": 300 }` and gives `{"runUntil": {"target": {"kind": "address", "address": "main_loop"}, "timeoutFrames": 300}}`. A memory item with `at` gets the same refusal: write `address`.
130
134
 
@@ -10,6 +10,7 @@ import { isObject } from "#src/host-client/steps.ts";
10
10
  import { WireFailure } from "#src/host-client/tools.ts";
11
11
  import { readProjectFile, writeReported } from "#src/host-client/transfer.ts";
12
12
  import { readMemoryInParts, ViceSessionClient } from "#src/host-client/vice-session.ts";
13
+ import { checkSnapshotFile, hasSignature, VSF_SIGNATURE } from "#src/media.ts";
13
14
  import { listed, UsageError } from "#src/script.ts";
14
15
  import { diffStates, type ChangedRange, type MachineState } from "./diff.ts";
15
16
 
@@ -59,30 +60,40 @@ function cpuValues(registers: Record<string, unknown>): Record<string, number |
59
60
 
60
61
  /** The size of the header of a module in a VICE snapshot file: the name (16 bytes), the version (2 bytes) and the size (4 bytes). */
61
62
  const MODULE_HEADER = 22;
62
- const VSF_MAGIC = "VICE Snapshot File\x1a";
63
63
  const VSF_VERSION = "VICE Version\x1a";
64
64
 
65
65
  /**
66
- * The 64 KiB of C64 RAM that a VICE snapshot file holds: the C64MEM module,
67
- * after the CPU port and the cartridge lines (4 bytes). Undefined when the
68
- * file has no such module.
66
+ * The data of the C64MEM module of a VICE snapshot file: the data and the
67
+ * direction register of the CPU port, the cartridge lines (2 bytes), then
68
+ * the 64 KiB of RAM. Undefined when the file has no such module.
69
69
  */
70
- export function snapshotRam(file: Uint8Array): Uint8Array | undefined {
70
+ function c64Memory(file: Uint8Array): Buffer | undefined {
71
71
  const bytes = Buffer.from(file);
72
- if (bytes.subarray(0, VSF_MAGIC.length).toString("latin1") !== VSF_MAGIC) return undefined;
72
+ if (!hasSignature("vsf", bytes)) return undefined;
73
73
  // The magic, the version (2 bytes) and the machine name (16 bytes); a newer VICE adds its own version (8 bytes).
74
- let at = VSF_MAGIC.length + 2 + 16;
74
+ let at = VSF_SIGNATURE.length + 2 + 16;
75
75
  if (bytes.subarray(at, at + VSF_VERSION.length).toString("latin1") === VSF_VERSION) at += VSF_VERSION.length + 8;
76
76
  while (at + MODULE_HEADER <= bytes.length) {
77
77
  const name = bytes.subarray(at, at + 16).toString("latin1").replace(/\0+$/, "");
78
78
  const size = bytes.readUInt32LE(at + 18);
79
79
  if (size < MODULE_HEADER) return undefined;
80
- if (name === "C64MEM") return at + MODULE_HEADER + 4 + 0x10000 <= bytes.length ? bytes.subarray(at + MODULE_HEADER + 4, at + MODULE_HEADER + 4 + 0x10000) : undefined;
80
+ if (name === "C64MEM") return at + MODULE_HEADER + 4 + 0x10000 <= bytes.length ? bytes.subarray(at + MODULE_HEADER, at + MODULE_HEADER + 4 + 0x10000) : undefined;
81
81
  at += size;
82
82
  }
83
83
  return undefined;
84
84
  }
85
85
 
86
+ /** The 64 KiB of C64 RAM that a VICE snapshot file holds, also the RAM under the CPU port at $00/$01. Undefined when the file has no C64MEM module. */
87
+ export function snapshotRam(file: Uint8Array): Uint8Array | undefined {
88
+ return c64Memory(file)?.subarray(4);
89
+ }
90
+
91
+ /** The CPU port of a VICE snapshot file: the direction register ($00) and the data register ($01). Undefined when the file has no C64MEM module. */
92
+ export function snapshotCpuPort(file: Uint8Array): { direction: number; data: number } | undefined {
93
+ const memory = c64Memory(file);
94
+ return memory === undefined ? undefined : { data: memory[0]!, direction: memory[1]! };
95
+ }
96
+
86
97
  /**
87
98
  * The state of a snapshot: restored in the session, then read with the
88
99
  * readers of the runs. The RAM must be the RAM of the file: else the
@@ -101,6 +112,10 @@ async function snapshotState(client: ViceSessionClient, path: string, ntsc: bool
101
112
  `${path} did not restore: the RAM after the restore is not the RAM of the file. A snapshot restores only in a machine of the video standard that saved it. ${ntsc ? "Leave out --ntsc for a PAL snapshot" : "Give --ntsc for an NTSC snapshot"}, or use the emulator version that saved it.`,
102
113
  );
103
114
  }
115
+ // $00 and $01 are the CPU port of the file, not the RAM under it: a program reads and writes the port there.
116
+ const port = snapshotCpuPort(file)!;
117
+ memory[0] = port.direction;
118
+ memory[1] = port.data;
104
119
  const colorRam = Buffer.from((await client.ioRead(0xd800, 0x400)).data, "hex").map((value) => value & 0x0f);
105
120
  const vic = Buffer.from((await client.ioRead(0xd000, 0x2f)).data, "hex");
106
121
  const values: Record<string, number | boolean> = {};
@@ -134,6 +149,8 @@ export function comparedItems(what: string, a: readonly string[], b: readonly st
134
149
  export async function diffFiles(first: string, second: string, options: { gap: number; max: number; ntsc: boolean; at?: number; out?: string }): Promise<Record<string, unknown>> {
135
150
  const kind = kindOf(first);
136
151
  if (kindOf(second) !== kind) throw new UsageError("give two states of one kind: two snapshots, two memory files or two observations");
152
+ if (options.at !== undefined && kind !== "memory") throw new UsageError(`--address is only for two memory files (.bin). ${kind === "snapshot" ? "A snapshot file holds all 64 KiB" : "An observation gives the address of each item"}: leave out --address`);
153
+ if (options.ntsc && kind !== "snapshot") throw new UsageError(`--ntsc is only for two snapshot files (.vsf), which restore in an emulator. ${kind === "memory" ? "Memory files" : "Observations"} compare as they are: leave out --ntsc`);
137
154
  const { gap, max } = options;
138
155
  let a: MachineState;
139
156
  let b: MachineState;
@@ -149,6 +166,8 @@ export async function diffFiles(first: string, second: string, options: { gap: n
149
166
  a = { memory: { base, bytes: left } };
150
167
  b = { memory: { base, bytes: right } };
151
168
  } else {
169
+ // Both files are snapshot files before the emulator starts.
170
+ for (const path of [first, second]) checkSnapshotFile(path, readProjectFile(path).bytes);
152
171
  const client = await ViceSessionClient.open({ videoStandard: options.ntsc ? "ntsc" : "pal" });
153
172
  try {
154
173
  a = await snapshotState(client, first, options.ntsc);
@@ -12,6 +12,7 @@ import { readPrg } from "#src/host-client/image.ts";
12
12
  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
13
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
14
14
  import { readMemoryInParts, ViceSessionClient } from "#src/host-client/vice-session.ts";
15
+ import { checkSnapshotFile } from "#src/media.ts";
15
16
  import { UsageError } from "#src/script.ts";
16
17
  import { namesOf } from "./scenario.ts";
17
18
 
@@ -151,7 +152,7 @@ function readRun(path: string): Run {
151
152
  if (step.memory !== undefined && step.memory !== "all" && (!Array.isArray(step.memory) || !step.memory.every(memoryItem))) {
152
153
  fail(`${at}: memory is "all", or a list of names, $ addresses, or objects with address, size (1 to 65536) and view (cpu or ram)`);
153
154
  }
154
- if (step.registers !== undefined && typeof step.registers !== "boolean") fail(`${at}: registers must be true or false`);
155
+ if (step.registers !== undefined && typeof step.registers !== "boolean") fail(`${at}: registers must be true or false in a run. true gives all registers. A list of register names is for a scenario`);
155
156
  if (step.vicii !== undefined && typeof step.vicii !== "boolean") fail(`${at}: vicii must be true or false`);
156
157
  if (step.sprites !== undefined && (!Array.isArray(step.sprites) || !step.sprites.every((sprite) => isInteger(sprite, 0, 7)))) fail(`${at}: sprites is a list of numbers from 0 to 7`);
157
158
  });
@@ -162,7 +163,7 @@ function readRun(path: string): Run {
162
163
  /** The remedy for a start program that is no PRG. */
163
164
  const PROGRAM_REMEDY = "A run starts a PRG. Get the PRG out of the disk, tape or cartridge with disk.ts read (or disk.ts crt) of the c64-disk skill";
164
165
 
165
- /** Checks each file that the run reads before the emulator starts: the start program or snapshot, and each snapshot step. A refusal names the run file and the step. */
166
+ /** Checks each file that the run reads before the emulator starts: the start program, and the start snapshot and each snapshot step, which must be VICE snapshot files. A refusal names the run file and the step. */
166
167
  function checkRunFiles(path: string, run: Run): void {
167
168
  const named = (where: string, check: () => unknown) => {
168
169
  try {
@@ -177,10 +178,10 @@ function checkRunFiles(path: string, run: Run): void {
177
178
  named("start.program", () => readPrg(program, PROGRAM_REMEDY));
178
179
  } else {
179
180
  const { snapshot } = run.start;
180
- named("start.snapshot", () => readProjectFile(snapshot));
181
+ named("start.snapshot", () => checkSnapshotFile(snapshot, readProjectFile(snapshot).bytes));
181
182
  }
182
183
  run.steps.forEach((step, index) => {
183
- if ("snapshot" in step) named(`step ${index + 1}: snapshot`, () => readProjectFile(step.snapshot));
184
+ if ("snapshot" in step) named(`step ${index + 1}: snapshot`, () => checkSnapshotFile(step.snapshot, readProjectFile(step.snapshot).bytes));
184
185
  });
185
186
  }
186
187
 
@@ -197,12 +198,27 @@ export async function runFile(path: string, out: string): Promise<{ output: Reco
197
198
  const at = (location: string): number => {
198
199
  if (location.startsWith("$")) return parseC64Address(location);
199
200
  const address = symbols.get(location);
200
- if (address === undefined) throw new UsageError(`the symbols have no ${location}`);
201
- return address;
201
+ if (address !== undefined) return address;
202
+ if (run.symbols === undefined || run.symbols === "none") {
203
+ throw new UsageError(`${location} is a name, and the run file has no symbols. A run file has no symbols unless it gives "symbols": "knowledge" for the names of the knowledge, or "symbols": "<file>" for a JSON file of names. Give one of them, or a $ address`);
204
+ }
205
+ throw new UsageError(`the symbols ${run.symbols} have no ${location}`);
202
206
  };
203
- // The names of the action steps resolve before the emulator starts.
207
+ // Every name of the steps resolves before the emulator starts. A refusal names the step.
204
208
  run.steps.forEach((step, index) => {
205
- if ((ACTION_STEP_KINDS as readonly string[]).some((kind) => kind in step) && !("observe" in step) && !("trace" in step)) checkStepNames([step as ActionStep], at, `run ${path}`, index + 1);
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));
211
+ for (const name of names) {
212
+ try {
213
+ at(name);
214
+ } catch (error) {
215
+ if (isRefusal(error)) throw new Refusal("invalid-input", `run ${path}: step ${index + 1}: ${error.message}`);
216
+ throw error;
217
+ }
218
+ }
219
+ } else if ((ACTION_STEP_KINDS as readonly string[]).some((kind) => kind in step)) {
220
+ checkStepNames([step as ActionStep], at, `run ${path}`, index + 1);
221
+ }
206
222
  });
207
223
  const files: string[] = [];
208
224
  const written: Written[] = [];
@@ -12,10 +12,12 @@ import { applyEntryState, parseEntryState } from "#src/host-client/entry-state.t
12
12
  import { readPrg } from "#src/host-client/image.ts";
13
13
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
14
14
  import { readMemoryInParts, type ViceSessionClient } from "#src/host-client/vice-session.ts";
15
+ import { checkSnapshotFile } from "#src/media.ts";
15
16
  import { openForRead } from "#src/knowledge/database.ts";
16
17
  import { nameTable } from "#src/knowledge/names.ts";
17
18
  import { DEFAULT_SPACE } from "#src/knowledge/schema.ts";
18
19
  import { programImage } from "#src/knowledge/program.ts";
20
+ import { listed } from "#src/script.ts";
19
21
 
20
22
  export type Side = "original" | "rebuild";
21
23
  export const SIDES: Side[] = ["original", "rebuild"];
@@ -70,11 +72,24 @@ export interface Scenario {
70
72
 
71
73
  export type Outcome = "PASS" | "FAIL" | "INCONCLUSIVE";
72
74
 
75
+ /** A byte of a memory item that differs: its address, and its value on each side as two hex digits. */
76
+ export interface DifferingByte {
77
+ address: string;
78
+ original: string;
79
+ rebuild: string;
80
+ }
81
+
82
+ /**
83
+ * A difference at a checkpoint. A memory item gives the bytes that differ
84
+ * (at most --max-listed of them, and their count); every other item gives
85
+ * its value on each side.
86
+ */
73
87
  export interface Difference {
74
88
  checkpoint: string;
75
89
  what: string;
76
- original: unknown;
77
- rebuild: unknown;
90
+ original?: unknown;
91
+ rebuild?: unknown;
92
+ bytes?: { count: number; listed: DifferingByte[]; rest?: string };
78
93
  }
79
94
 
80
95
  export interface ScenarioResult {
@@ -290,16 +305,18 @@ const PROGRAM_REMEDY = "A scenario program is a PRG. Get the PRG out of the disk
290
305
  /**
291
306
  * Checks each file that the scenario names before an emulator starts: the
292
307
  * program and the symbols of each side, and each snapshot file. A missing
293
- * file is not-found; a program that is no PRG and a symbols file with no
294
- * names are invalid-input. Gives the names of each side.
308
+ * file is not-found; a program that is no PRG, a symbols file with no names
309
+ * and a snapshot step whose file is no VICE snapshot file are invalid-input.
310
+ * A refusal starts with the scenario file, as the other scenario errors do,
311
+ * and names the field or the step. Gives the names of each side.
295
312
  */
296
- export function scenarioNames(scenario: Scenario): Map<Side, Map<string, number>> {
313
+ export function scenarioNames(scenario: Scenario, path: string): Map<Side, Map<string, number>> {
297
314
  const names = new Map<Side, Map<string, number>>();
298
315
  const named = <T>(field: string, read: () => T): T => {
299
316
  try {
300
317
  return read();
301
318
  } catch (error) {
302
- if (isRefusal(error)) throw new Refusal(error.code, `${field}: ${error.message}`);
319
+ if (isRefusal(error)) throw new Refusal(error.code, `scenario ${path}: ${field}: ${error.message}`);
303
320
  throw error;
304
321
  }
305
322
  };
@@ -307,7 +324,9 @@ export function scenarioNames(scenario: Scenario): Map<Side, Map<string, number>
307
324
  named(`${side}.program`, () => readPrg(scenario[side].program, PROGRAM_REMEDY));
308
325
  names.set(side, named(`${side}.symbols`, () => namesOf(scenario[side].symbols)));
309
326
  }
310
- for (const step of scenario.steps) if ("snapshot" in step) readProjectFile(step.snapshot);
327
+ scenario.steps.forEach((step, index) => {
328
+ if ("snapshot" in step) named(`step ${index + 1}: snapshot`, () => checkSnapshotFile(step.snapshot, readProjectFile(step.snapshot).bytes));
329
+ });
311
330
  return names;
312
331
  }
313
332
 
@@ -368,7 +387,6 @@ async function startProgram(client: ViceSessionClient, program: string, side: Si
368
387
  }
369
388
 
370
389
  async function runSide(client: ViceSessionClient, scenario: Scenario, side: Side, symbols: Map<string, number>, files: boolean): Promise<Map<string, Observation>> {
371
- const subject = scenario[side];
372
390
  const observations = new Map<string, Observation>();
373
391
  const at = (location: Location) => resolve(location, symbols, side);
374
392
  // Each side starts from a hard reset, stopped at the reset vector, with the control ports released.
@@ -376,84 +394,117 @@ async function runSide(client: ViceSessionClient, scenario: Scenario, side: Side
376
394
  await client.joystick({ port: 1, direction: "center", fire: false });
377
395
  await client.joystick({ port: 2, direction: "center", fire: false });
378
396
  let checkpoint = 0;
379
- for (const step of scenario.steps) {
397
+ for (const [index, step] of scenario.steps.entries()) {
380
398
  if (step.side !== undefined && step.side !== side) continue;
381
- // Observe first: an observe step may also carry "registers" or "memory".
382
- if ("observe" in step) {
383
- checkpoint++;
384
- const observation: Observation = { memory: [], registers: {} };
385
- for (const item of step.memory ?? []) {
386
- const spec: MemoryObservation = typeof item === "string" ? { address: item } : item;
387
- const address = at(spec.address);
388
- const size = spec.size ?? 1;
389
- const read = { data: (await readMemoryInParts(client, address, size, spec.view ?? "cpu")).toString("hex") };
390
- const excluded = (spec.exclude ?? []).map((exclude) => {
391
- const offset = at(exclude.address) - address;
392
- if (offset < 0 || offset >= size) throw new Refusal("invalid-input", `the exclude ${exclude.address} lies outside the observed ${spec.address} (${size} bytes)`);
393
- return { offset, address: exclude.address, reason: exclude.reason };
394
- });
395
- observation.memory.push({ label: size > 1 ? `${spec.address} (${size} bytes)` : spec.address, address, bytes: [...Buffer.from(read.data, "hex")], tolerance: spec.tolerance ?? 0, excluded });
396
- }
397
- if (step.registers !== undefined) {
398
- const registers = await client.registersGet("c64");
399
- for (const name of step.registers) observation.registers[name] = name === "pc" ? formatC64Address(registers.pc) : registers[name];
400
- }
401
- if (step.vicii) {
402
- // The raster line changes from one moment to the next; the comparison leaves it out.
403
- const { rasterLine: _rasterLine, ...state } = await client.vicii();
404
- observation.vicii = formatVicii(state);
405
- }
406
- if (step.sprites !== undefined) observation.sprites = (await client.sprites(step.sprites)).sprites.map(formatSprite);
407
- if (step.screen !== undefined) {
408
- const baseline = baselineName(checkpoint, step.observe);
409
- if (side === "original") {
410
- const shot = await client.screenCapture(baseline);
411
- if (files) observation.png = shot.png;
412
- } else {
413
- const compared = await client.screenCompare({ baseline, maxMismatchRatio: step.screen.maxMismatchRatio ?? 0, mask: step.screen.mask ?? [], includeDiff: files });
414
- observation.screen = { match: compared.match, mismatchingPixels: compared.mismatchingPixels, comparedPixels: compared.comparedPixels, mismatchRatio: compared.mismatchRatio, ...(compared.bounds === undefined ? {} : { bounds: compared.bounds }) };
415
- if (files) {
416
- observation.png = (await client.screenCapture()).png;
417
- if (compared.diffPng !== undefined) observation.diffPng = compared.diffPng;
418
- }
419
- await client.screenDiscard(baseline);
399
+ try {
400
+ checkpoint = await runStep(client, scenario, side, step, at, checkpoint, files, observations);
401
+ } catch (error) {
402
+ // The step in the reason or the message: the scenario file has many steps.
403
+ const where = `step ${index + 1} (${stepKindOf(step)})`;
404
+ if (error instanceof Inconclusive) throw new Inconclusive(`${where}: ${error.message}`);
405
+ if (error instanceof WireFailure) throw new WireFailure(error.code, `${where}: ${error.message}`);
406
+ if (error instanceof Refusal) throw new Refusal(error.code, `${where}: ${error.message}`);
407
+ throw error;
408
+ }
409
+ }
410
+ return observations;
411
+ }
412
+
413
+ /** The kind of a checked step: its one key from the step kinds. */
414
+ const stepKindOf = (step: Step) => Object.keys(step).find((key) => STEP_KINDS.includes(key)) ?? "step";
415
+
416
+ /** Runs one step of one side. Gives the number of the last checkpoint. */
417
+ async function runStep(client: ViceSessionClient, scenario: Scenario, side: Side, step: Step, at: (location: Location) => number, last: number, files: boolean, observations: Map<string, Observation>): Promise<number> {
418
+ const subject = scenario[side];
419
+ let checkpoint = last;
420
+ // Observe first: an observe step may also carry "registers" or "memory".
421
+ if ("observe" in step) {
422
+ checkpoint++;
423
+ const observation: Observation = { memory: [], registers: {} };
424
+ for (const item of step.memory ?? []) {
425
+ const spec: MemoryObservation = typeof item === "string" ? { address: item } : item;
426
+ const address = at(spec.address);
427
+ const size = spec.size ?? 1;
428
+ const read = { data: (await readMemoryInParts(client, address, size, spec.view ?? "cpu")).toString("hex") };
429
+ const excluded = (spec.exclude ?? []).map((exclude) => {
430
+ const offset = at(exclude.address) - address;
431
+ if (offset < 0 || offset >= size) throw new Refusal("invalid-input", `the exclude ${exclude.address} lies outside the observed ${spec.address} (${size} bytes)`);
432
+ return { offset, address: exclude.address, reason: exclude.reason };
433
+ });
434
+ observation.memory.push({ label: size > 1 ? `${spec.address} (${size} bytes)` : spec.address, address, bytes: [...Buffer.from(read.data, "hex")], tolerance: spec.tolerance ?? 0, excluded });
435
+ }
436
+ if (step.registers !== undefined) {
437
+ const registers = await client.registersGet("c64");
438
+ for (const name of step.registers) observation.registers[name] = name === "pc" ? formatC64Address(registers.pc) : registers[name];
439
+ }
440
+ if (step.vicii) {
441
+ // The raster line changes from one moment to the next; the comparison leaves it out.
442
+ const { rasterLine: _rasterLine, ...state } = await client.vicii();
443
+ observation.vicii = formatVicii(state);
444
+ }
445
+ if (step.sprites !== undefined) observation.sprites = (await client.sprites(step.sprites)).sprites.map(formatSprite);
446
+ if (step.screen !== undefined) {
447
+ const baseline = baselineName(checkpoint, step.observe);
448
+ if (side === "original") {
449
+ const shot = await client.screenCapture(baseline);
450
+ if (files) observation.png = shot.png;
451
+ } else {
452
+ const compared = await client.screenCompare({ baseline, maxMismatchRatio: step.screen.maxMismatchRatio ?? 0, mask: step.screen.mask ?? [], includeDiff: files });
453
+ observation.screen = { match: compared.match, mismatchingPixels: compared.mismatchingPixels, comparedPixels: compared.comparedPixels, mismatchRatio: compared.mismatchRatio, ...(compared.bounds === undefined ? {} : { bounds: compared.bounds }) };
454
+ if (files) {
455
+ observation.png = (await client.screenCapture()).png;
456
+ if (compared.diffPng !== undefined) observation.diffPng = compared.diffPng;
420
457
  }
421
- }
422
- observations.set(step.observe, observation);
423
- } else if ("reset" in step) {
424
- // Stopped at the reset vector, so frame counts from here are exact.
425
- await client.reset({ mode: step.reset, run: false });
426
- } else if ("load" in step) {
427
- await client.programLoad({ path: subject.program });
428
- } else if ("autostart" in step) {
429
- await startProgram(client, subject.program, side);
430
- } else if ("snapshot" in step) {
431
- await client.snapshotRestore(readProjectFile(step.snapshot).bytes);
432
- } else if ("normalize" in step) {
433
- await normalize(client);
434
- } else {
435
- const { side: _side, ...action } = step;
436
- const notReached = await runActionStep(client, action as ActionStep, at);
437
- if (notReached !== undefined && "runUntil" in step) {
438
- throw new Inconclusive(`the ${side} side did not reach the checkpoint before ${step.runUntil.timeoutFrames} frames (it stopped by ${notReached.stopReason} at ${formatC64Address(notReached.pc)})`);
458
+ await client.screenDiscard(baseline);
439
459
  }
440
460
  }
461
+ observations.set(step.observe, observation);
462
+ } else if ("reset" in step) {
463
+ // Stopped at the reset vector, so frame counts from here are exact.
464
+ await client.reset({ mode: step.reset, run: false });
465
+ } else if ("load" in step) {
466
+ await client.programLoad({ path: subject.program });
467
+ } else if ("autostart" in step) {
468
+ await startProgram(client, subject.program, side);
469
+ } else if ("snapshot" in step) {
470
+ await client.snapshotRestore(readProjectFile(step.snapshot).bytes);
471
+ } else if ("normalize" in step) {
472
+ await normalize(client);
473
+ } else {
474
+ const { side: _side, ...action } = step;
475
+ const notReached = await runActionStep(client, action as ActionStep, at);
476
+ if (notReached !== undefined && "runUntil" in step) {
477
+ throw new Inconclusive(`the ${side} side did not reach the checkpoint before ${step.runUntil.timeoutFrames} frames (it stopped by ${notReached.stopReason} at ${formatC64Address(notReached.pc)})`);
478
+ }
441
479
  }
442
- return observations;
480
+ return checkpoint;
443
481
  }
444
482
 
445
- /** The differences between the two sides' observations at each checkpoint, under the scenario's rules. */
446
- export function compare(original: Map<string, Observation>, rebuild: Map<string, Observation>): Difference[] {
483
+ type MemoryItem = Observation["memory"][number];
484
+
485
+ /** The bytes of a memory item that differ by more than its tolerance, without the excluded bytes. */
486
+ function differingBytes(item: MemoryItem, other: MemoryItem): DifferingByte[] {
487
+ const hex = (byte: number) => byte.toString(16).padStart(2, "0");
488
+ const skipped = new Set(item.excluded.map((excluded) => excluded.offset));
489
+ return item.bytes.flatMap((byte, offset) => (!skipped.has(offset) && Math.abs(byte - other.bytes[offset]!) > item.tolerance ? [{ address: formatC64Address(item.address + offset), original: hex(byte), rebuild: hex(other.bytes[offset]!) }] : []));
490
+ }
491
+
492
+ /** The most differing bytes of one memory item that a result lists when no --max-listed is given. */
493
+ export const DEFAULT_LISTED_BYTES = 50;
494
+
495
+ /**
496
+ * The differences between the two sides' observations at each checkpoint,
497
+ * under the scenario's rules. A memory item lists at most `max` differing
498
+ * bytes; `rest` tells where the others are.
499
+ */
500
+ export function compare(original: Map<string, Observation>, rebuild: Map<string, Observation>, options: { max?: number; rest?: string } = {}): Difference[] {
447
501
  const differences: Difference[] = [];
502
+ const max = options.max ?? DEFAULT_LISTED_BYTES;
448
503
  for (const [checkpoint, left] of original) {
449
504
  const right = rebuild.get(checkpoint)!;
450
505
  left.memory.forEach((item, index) => {
451
- const other = right.memory[index]!;
452
- const skipped = new Set(item.excluded.map((excluded) => excluded.offset));
453
- if (item.bytes.some((byte, at) => !skipped.has(at) && Math.abs(byte - other.bytes[at]!) > item.tolerance)) {
454
- const show = (bytes: number[]) => Buffer.from(bytes).toString("hex");
455
- differences.push({ checkpoint, what: `memory ${item.label}`, original: show(item.bytes), rebuild: show(other.bytes) });
456
- }
506
+ const bytes = differingBytes(item, right.memory[index]!);
507
+ if (bytes.length > 0) differences.push({ checkpoint, what: `memory ${item.label}`, bytes: listed(bytes, max, undefined, options.rest) });
457
508
  });
458
509
  for (const [name, value] of Object.entries(left.registers)) {
459
510
  const other = right.registers[name as ObservedRegister];
@@ -469,15 +520,15 @@ export function compare(original: Map<string, Observation>, rebuild: Map<string,
469
520
 
470
521
  /**
471
522
  * Writes the files of a FAIL into `out`: for a screen difference both
472
- * screens and the difference image, and memory.json with each differing byte.
523
+ * screens and the difference image, and memory.json with each differing
524
+ * memory item: all its bytes on each side, and each byte that differs.
473
525
  */
474
526
  function writeFailFiles(out: string, original: Map<string, Observation>, rebuild: Map<string, Observation>, differences: Difference[]): Written[] {
475
527
  const files: Written[] = [];
476
528
  const write = (name: string, bytes: Uint8Array) => {
477
529
  files.push(writeReported(`${out}/${name}`, bytes, { what: "--out" }));
478
530
  };
479
- const memory: Array<{ checkpoint: string; what: string; bytes: Array<{ address: string; original: string; rebuild: string }> }> = [];
480
- const hex = (byte: number) => byte.toString(16).padStart(2, "0");
531
+ const memory: Array<{ checkpoint: string; what: string; address: string; original: string; rebuild: string; bytes: DifferingByte[] }> = [];
481
532
  for (const difference of differences) {
482
533
  const left = original.get(difference.checkpoint)!;
483
534
  const right = rebuild.get(difference.checkpoint)!;
@@ -491,9 +542,8 @@ function writeFailFiles(out: string, original: Map<string, Observation>, rebuild
491
542
  const index = left.memory.findIndex((item) => `memory ${item.label}` === difference.what);
492
543
  const item = left.memory[index]!;
493
544
  const other = right.memory[index]!;
494
- const skipped = new Set(item.excluded.map((excluded) => excluded.offset));
495
- const bytes = item.bytes.flatMap((byte, offset) => (!skipped.has(offset) && Math.abs(byte - other.bytes[offset]!) > item.tolerance ? [{ address: formatC64Address(item.address + offset), original: hex(byte), rebuild: hex(other.bytes[offset]!) }] : []));
496
- memory.push({ checkpoint: difference.checkpoint, what: difference.what, bytes });
545
+ const show = (bytes: number[]) => Buffer.from(bytes).toString("hex");
546
+ memory.push({ checkpoint: difference.checkpoint, what: difference.what, address: formatC64Address(item.address), original: show(item.bytes), rebuild: show(other.bytes), bytes: differingBytes(item, other) });
497
547
  }
498
548
  }
499
549
  if (memory.length > 0) write("memory.json", Buffer.from(`${JSON.stringify(memory, null, 2)}\n`));
@@ -501,7 +551,7 @@ function writeFailFiles(out: string, original: Map<string, Observation>, rebuild
501
551
  }
502
552
 
503
553
  /** Runs the scenario on the original, then on the rebuild, in one VICE session. With out, a FAIL leaves files there. */
504
- export async function runScenario(client: ViceSessionClient, scenario: Scenario, options: { out?: string; names?: Map<Side, Map<string, number>> } = {}): Promise<ScenarioResult> {
554
+ export async function runScenario(client: ViceSessionClient, scenario: Scenario, options: { out?: string; names?: Map<Side, Map<string, number>>; max?: number } = {}): Promise<ScenarioResult> {
505
555
  const checkpoints = scenario.steps.flatMap((step) => ("observe" in step ? [step.observe] : []));
506
556
  const observed = new Map<Side, Map<string, Observation>>();
507
557
  // The names of both sides before either side runs: a bad symbols file is an error, not a result.
@@ -519,7 +569,7 @@ export async function runScenario(client: ViceSessionClient, scenario: Scenario,
519
569
  }
520
570
  const original = observed.get("original")!;
521
571
  const rebuild = observed.get("rebuild")!;
522
- const differences = compare(original, rebuild);
572
+ const differences = compare(original, rebuild, { ...(options.max === undefined ? {} : { max: options.max }), rest: options.out === undefined ? "a larger --max-listed, or --out <dir> for memory.json with every byte" : `${options.out}/memory.json` });
523
573
  const excluded = [...original].flatMap(([checkpoint, observation]) => observation.memory.flatMap((item) => item.excluded.map((excluded) => ({ checkpoint, address: excluded.address, reason: excluded.reason }))));
524
574
  const files = differences.length > 0 && options.out !== undefined ? writeFailFiles(options.out, original, rebuild, differences) : [];
525
575
  return {
@@ -38,7 +38,7 @@ async function test(call: Call): Promise<ScenarioResult> {
38
38
  const scenario = readScenario(call.subject(0));
39
39
  const out = call.string("out");
40
40
  // Every file of the scenario is checked before the emulator starts.
41
- const names = scenarioNames(scenario);
41
+ const names = scenarioNames(scenario, call.subject(0));
42
42
  let client: ViceSessionClient;
43
43
  try {
44
44
  client = await ViceSessionClient.open({ videoStandard: scenario.videoStandard ?? "pal" });
@@ -47,7 +47,7 @@ async function test(call: Call): Promise<ScenarioResult> {
47
47
  return { result: "INCONCLUSIVE", scenario: scenario.name, reason: `no emulator: ${error.message}`, checkpoints: [], differences: [] };
48
48
  }
49
49
  try {
50
- return await runScenario(client, scenario, { names, ...(out === undefined ? {} : { out }) });
50
+ return await runScenario(client, scenario, { names, max: call.count("max-listed")!, ...(out === undefined ? {} : { out }) });
51
51
  } finally {
52
52
  await client.close();
53
53
  }
@@ -123,7 +123,10 @@ const COMMANDS: CommandSpec[] = [
123
123
  name: "test",
124
124
  summary: "Runs a scenario on the original and then on the rebuild in one emulator. result is PASS, FAIL with the differences, or INCONCLUSIVE with the reason.",
125
125
  subjects: [{ name: "<scenario.json>", help: "a scenario file, relative to the project folder. See references/scenario-format.md" }],
126
- options: { out: { ...OPTIONS.out, output: "folder", value: "<dir>", help: "with a FAIL, write both screens, the difference image and memory.json with each differing byte into this folder" } },
126
+ options: {
127
+ out: { ...OPTIONS.out, output: "folder", value: "<dir>", help: "with a FAIL, write both screens, the difference image and memory.json into this folder: each differing memory item with all its bytes, and each byte that differs" },
128
+ "max-listed": { ...OPTIONS["max-listed"], help: "list at most n differing bytes of each memory item (default 50). The count is always given" },
129
+ },
127
130
  run: test,
128
131
  },
129
132
  {
@@ -109,7 +109,7 @@ The scripts refuse a step in the form of version 2.0, for example `{ "runUntil":
109
109
  4. Run `capture` with that address and a directory in `--out`. Give the same `--steps` as before. The directory gets:
110
110
  - `image.bin`: all 64 KiB of RAM at the entry.
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
- - One PRG for each segment.
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
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.
115
115
  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.
@@ -117,7 +117,7 @@ The scripts refuse a step in the form of version 2.0, for example `{ "runUntil":
117
117
 
118
118
  ## Multi-load programs
119
119
 
120
- A multi-load program loads more parts from the disk while it runs, for example one part for each level. Use `loads` to capture each part. The program can be a PRG, or a disk, tape or cartridge image that VICE starts.
120
+ A multi-load program loads more parts from the disk while it runs, for example one part for each level. Use `loads` to capture each part. The program can be a PRG, or a disk, tape or cartridge image that VICE starts. `loads` starts a PRG with RUN. Thus the PRG must have a BASIC start line. For a PRG without a BASIC start line, use `capture` with `--entry`.
121
121
 
122
122
  1. Write a steps file. Put a `capture` step after each point where a part is in memory, for example:
123
123
 
@@ -132,7 +132,7 @@ A multi-load program loads more parts from the disk while it runs, for example o
132
132
  ```
133
133
 
134
134
  2. Run `loads` with the steps file and a directory in `--out`. Add `--drive` when the program has its own drive code, for example a fast loader.
135
- 3. Each capture writes `<out>/<name>/` with `image.bin`, `image.json`, `entry_state.json` and a PRG for each segment. A segment is a block of RAM from `$0400` that the program changed after the capture before. The first capture also has the program itself.
135
+ 3. Each capture writes `<out>/<name>/` with `image.bin`, `image.json`, `entry_state.json` and a PRG for each segment. It removes the segment PRGs and the `drive8.prg` of an earlier capture that the new `image.json` does not list. A segment is a block of RAM from `$0400` that the program changed after the capture before. The first capture also has the program itself.
136
136
  4. Put the part that you work on into the knowledge with `image <out>/<name>/image.json` of the c64-knowledge skill.
137
137
  5. With `--drive`, `drive8.prg` is the drive RAM at `$0000`-`$07ff`. Put it into the knowledge with `image <out>/<name>/drive8.prg --space drive8`. Then analyze it with c64-static-analysis and `--space drive8`.
138
138
 
@@ -161,7 +161,8 @@ For `loads`: `captures`, with the name, the PC, the segments, `differsFromReset`
161
161
  - `traced: false` or `followed: false` with `stopReason`: the CPU stopped before the frames ran, for example at a JAM instruction. `pc` gives the address. Make sure that `--entry` is the start of the code that the file holds at that time, and that the steps are correct.
162
162
  - `captured: false`: the program did not get to the address in the time limit. The reason tells where it stopped. Find a better address with the c64-emulator skill, or give more frames. If it stopped in a key wait, give `--steps` with a `type` step.
163
163
  - A step did not reach its target: the reason names the step. Change the step or give it more frames.
164
- - `loaded: false` and no capture has a segment: the program did not load a part, or it did not start. `keyWait: true` on a capture tells that the C64 waited at READY. or at an INPUT statement. For a tape image, read `emulatorFlaw`. A known VICE flaw can stop a tape load. Tell the user to install the latest VICE.
164
+ - `loaded: false` with an empty `captures` and the reason `BASIC ran no program line`: the PRG has no BASIC start line. Use `capture` with `--entry`.
165
+ - `loaded: false` and no capture has a segment: the program did not load a part, or it did not start. `keyWait: true` on a capture tells that the C64 waited for a key at the READY prompt or at an INPUT statement. For a tape image, read `emulatorFlaw`. A known VICE flaw can stop a tape load. Tell the user to install the latest VICE.
165
166
  - Do not name a packer from weak evidence. The script never names one.
166
167
  - Some programs unpack in more than one stage. Run `stages` to find each stage. Capture at the entry of the last stage. Make sure that it is the application and not a second unpacker.
167
168
  - `not-found` or `invalid-input`: a path or an argument is wrong. Read the message.