@henols/c64-re-tools 2.3.0-rc.5 → 2.3.0-rc.6

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 (61) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +149 -78
  3. package/skills/c64-assembler/scripts/assembler.ts +18 -11
  4. package/skills/c64-basic/SKILL.md +90 -52
  5. package/skills/c64-basic/scripts/basic.ts +15 -6
  6. package/skills/c64-development/SKILL.md +46 -73
  7. package/skills/c64-disk/SKILL.md +145 -73
  8. package/skills/c64-disk/scripts/disk.ts +11 -6
  9. package/skills/c64-docs/SKILL.md +199 -118
  10. package/skills/c64-docs/references/page-types.md +3 -3
  11. package/skills/c64-docs/references/style.md +9 -13
  12. package/skills/c64-docs/scripts/docs.ts +39 -15
  13. package/skills/c64-docs/scripts/lib/links.ts +1 -1
  14. package/skills/c64-docs/scripts/lib/reference.ts +2 -2
  15. package/skills/c64-docs/scripts/lib/source-map.ts +2 -2
  16. package/skills/c64-export/SKILL.md +21 -45
  17. package/skills/c64-knowledge/SKILL.md +489 -233
  18. package/skills/c64-knowledge/scripts/knowledge.ts +31 -26
  19. package/skills/c64-memory-map/SKILL.md +131 -65
  20. package/skills/c64-memory-map/scripts/memory-map.ts +19 -11
  21. package/skills/c64-packer/SKILL.md +120 -72
  22. package/skills/c64-packer/scripts/packer.ts +10 -3
  23. package/skills/c64-provenance/SKILL.md +301 -173
  24. package/skills/c64-provenance/scripts/lib/library.ts +6 -6
  25. package/skills/c64-provenance/scripts/provenance.ts +85 -36
  26. package/skills/c64-reverse-engineering/SKILL.md +55 -72
  27. package/skills/c64-source/SKILL.md +316 -224
  28. package/skills/c64-source/scripts/lib/export.ts +9 -14
  29. package/skills/c64-source/scripts/lib/loader.ts +5 -5
  30. package/skills/c64-source/scripts/lib/source.ts +5 -5
  31. package/skills/c64-source/scripts/source.ts +106 -21
  32. package/skills/c64-static-analysis/SKILL.md +188 -112
  33. package/skills/c64-static-analysis/scripts/static-analysis.ts +29 -9
  34. package/skills/c64-testing/SKILL.md +272 -166
  35. package/skills/c64-testing/references/recording-format.md +11 -12
  36. package/skills/c64-testing/references/scenario-format.md +20 -5
  37. package/skills/c64-testing/scripts/lib/diff-files.ts +8 -8
  38. package/skills/c64-testing/scripts/lib/recording.ts +7 -7
  39. package/skills/c64-testing/scripts/lib/replay.ts +7 -7
  40. package/skills/c64-testing/scripts/lib/runs.ts +6 -7
  41. package/skills/c64-testing/scripts/lib/scenario.ts +12 -6
  42. package/skills/c64-testing/scripts/testing.ts +35 -15
  43. package/skills/c64-unpacker/SKILL.md +273 -127
  44. package/skills/c64-unpacker/scripts/lib/loads.ts +3 -3
  45. package/skills/c64-unpacker/scripts/unpacker.ts +70 -11
  46. package/skills/emulator/SKILL.md +12 -12
  47. package/src/errors.ts +22 -2
  48. package/src/host/vice/session.ts +1 -1
  49. package/src/host-client/entry-state.ts +1 -1
  50. package/src/host-client/image.ts +3 -3
  51. package/src/host-client/steps.ts +1 -1
  52. package/src/knowledge/expression.ts +1 -1
  53. package/src/knowledge/names.ts +2 -3
  54. package/src/knowledge/program.ts +2 -3
  55. package/src/knowledge/write.ts +2 -2
  56. package/src/mcp/inputs.ts +1 -1
  57. package/src/mcp/tools/input.ts +1 -1
  58. package/src/mcp/tools/media.ts +1 -1
  59. package/src/native/exomizer.ts +2 -2
  60. package/src/project.ts +2 -2
  61. package/src/script.ts +164 -75
@@ -1,8 +1,10 @@
1
1
  # Recording format
2
2
 
3
+ This file gives the format of a record file and of a recording folder. For the commands, see the sections ``### `record <record.json>` `` and ``### `replay <recording>` `` of `SKILL.md`.
4
+
3
5
  ## Record file
4
6
 
5
- A record file (for `testing.ts record`) is one JSON object in a project file.
7
+ A record file is one JSON object in a project file.
6
8
 
7
9
  ```json
8
10
  {
@@ -20,7 +22,7 @@ A record file (for `testing.ts record`) is one JSON object in a project file.
20
22
 
21
23
  - `name`: a short text.
22
24
  - `program`: a PRG file, relative to the project folder.
23
- - `symbols`: optional. `knowledge` (default), `none`, or a JSON file: the output of the c64-assembler skill, or an object of names and `$` addresses. The steps use these names.
25
+ - `symbols`: optional. `knowledge` (default), `none`, or a JSON file: the symbol file of a build, or an object of names and `$` addresses. The steps use these names.
24
26
  - `load`: optional. With `false` (default), the program must load at `$0801` with a BASIC start line, and the C64 types `RUN`. With `true`, the program goes into memory and the C64 stays at READY. Then a `registers` step with `pc` starts the program.
25
27
  - `checkpoint`, `state` and `pin`: optional. The comparison that a replay uses when the replay gives none. `checkpoint` is the name or `$` address of a routine. Each entry of the routine is a checkpoint. `state` is 1 to 16 memory items that the checkpoints compare. `pin` is the random state in RAM. An item is a name, a `$` address, or `{ "address", "size" }` with a size from 1 to 4096. Give `checkpoint` and `state` together.
26
28
  - `inputs`: optional. The I/O addresses (or ranges such as `$de00-$dfff`) whose reads are input. The default is `$dc00` and `$dc01`: the joystick ports and the keyboard matrix. It also has `$d419` to `$d41c` (the paddles, and the noise and envelope of SID voice 3), and `$de00-$dfff` (no device: the last byte on the bus). Add `$d012` or a CIA timer only for a program that reads a seed there and does not wait in a loop on it.
@@ -56,14 +58,14 @@ The keyboard queue of the KERNAL holds 10 keys. If the keys of a `type` step and
56
58
 
57
59
  ## Play
58
60
 
59
- With `--play`, `testing.ts record` does the steps, then a person plays. The page on `http://localhost:<port>/` (`--http-port`, default 6465) shows the screen at 50 frames each second. It has no sound.
61
+ With `--play`, `record` does the steps, then a person plays. The page on `http://localhost:<port>/` (`--http-port`) shows the screen at 50 frames each second. It has no sound.
60
62
 
61
63
  | Button | Key | Effect |
62
64
  |---|---|---|
63
65
  | Start | Enter, on the start screen | The C64 runs. Before Start, the page shows the screen after the steps, and the C64 is frozen. The time before Start is not in the recording. |
64
66
  | End and save | F12 | The C64 stops at the frame on the page, and the screen stays frozen. The script writes the recording folder. |
65
67
  | Cancel | F11 | The session stops before or during the play. The script writes no folder and gives `recorded: false`. |
66
- | Port | F9 | The joystick goes to the other port. `--joystick` gives the first port (default 2). |
68
+ | Port | F9 | The joystick goes to the other port. `--joystick` gives the first port. |
67
69
  | Arrows | F10 | The arrow keys and space change between the joystick and the C64 keys. At the start, they are the joystick. |
68
70
  | Keys | | The keyboard changes between the symbolic map (the default) and the positional map. |
69
71
 
@@ -91,7 +93,7 @@ The page sends input only between Start and End. The input of the page goes into
91
93
 
92
94
  ## Recording folder
93
95
 
94
- `testing.ts record` writes these files into the `--out` folder:
96
+ `record` writes these files into the `--out` folder:
95
97
 
96
98
  | File | Content |
97
99
  |---|---|
@@ -101,20 +103,17 @@ The page sends input only between Start and End. The input of the page goes into
101
103
 
102
104
  A site is the address of the instruction that reads. The values are hex. `<from>` and `<count>` are decimal.
103
105
 
104
- `testing.ts replay` checks `recording.json` before the replay starts. A recording of version 2.0 can have events or a comparison in the old form, for example `"at"` in place of `"address"`. The script refuses it with `invalid-input`. The message names the event, the old field and the form to write. Record the session again.
106
+ `replay` examines `recording.json` before the replay starts. A recording of version 2.0 can have events or a comparison in the old form, for example `"at"` in place of `"address"`. The script refuses it with `invalid-input`. The message names the event, the old field and the form to write. Record the session again.
105
107
 
106
108
  ## Replay
107
109
 
108
- `testing.ts replay` replays a recording folder:
109
-
110
- 1. It replays the recording on the original program. The session must end with the recorded cycles and state hash. Else the result is INCONCLUSIVE. It also takes the state at each checkpoint of the original.
111
- 2. With `--rebuild`, it replays the recording on the rebuild. At each checkpoint, the rebuild first gets the pinned values of the original. Then the script compares the state. The cycles can be different.
110
+ `replay` replays the recording on the original program first. The session must end with the recorded cycles and state hash. Else the result is INCONCLUSIVE. With `--rebuild`, `replay` then replays the recording on the rebuild. At each checkpoint, the rebuild first gets the pinned values of the original. Then the script compares the state. The cycles can be different.
112
111
 
113
- The comparison comes from `--checkpoint`, `--state` and `--pin`, or else from the record file. A recording without names (`symbols` is `none`) takes the names of the knowledge at the time of the replay.
112
+ A recording without names (`symbols` is `none`) takes the names of the project knowledge at the time of the replay.
114
113
 
115
114
  For the rebuild, the script finds each name with the names of the rebuild (`--symbols`). A `$` address is an address of the original. It moves with the name before it in the original: the script finds the same name in the rebuild and adds the same offset. Code moves with a code label, and data with any name. A site in ROM does not move. Give a state item a name, or the state moves with the code before it.
116
115
 
117
- The result is one JSON object:
116
+ The body of the envelope of `replay` has these fields:
118
117
 
119
118
  - `result`: PASS, FAIL or INCONCLUSIVE.
120
119
  - `side`: `original` for the check of the original only, `rebuild` with `--rebuild`.
@@ -1,5 +1,7 @@
1
1
  # Scenario format
2
2
 
3
+ This file gives the format of a scenario file and of a run file. For the commands, see the sections ``### `test <scenario.json>` `` and ``### `run <run.json>` `` of `SKILL.md`.
4
+
3
5
  A scenario is one JSON object in a project file.
4
6
 
5
7
  ```json
@@ -26,7 +28,7 @@ A scenario is one JSON object in a project file.
26
28
  - `program`: a PRG file, relative to the project folder.
27
29
  - `symbols`: where the names come from:
28
30
  - `knowledge`: the project knowledge.
29
- - A JSON file: the output of the c64-assembler skill, or an object of names and `$` addresses.
31
+ - A JSON file: the symbol file of a build, or an object of names and `$` addresses.
30
32
  - `none`: no names.
31
33
 
32
34
  Optional: `videoStandard`, `pal` (default) or `ntsc`.
@@ -51,7 +53,7 @@ Before the first step of each side, the script does a hard reset. The CPU stops
51
53
  | `{ "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
54
  | `{ "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
55
  | `{ "snapshot": "snapshots/start.vsf" }` | Restore a snapshot file. Usually with `side`: the snapshot of one program is not a state of the other. |
54
- | `{ "normalize": true }` | Write pages 0 to 3 and `$00`/`$01` from the entry state in the knowledge. The entry state comes from a capture of the c64-unpacker skill, which `image` of the c64-knowledge skill put in. Then both sides have the same zero page, stack and KERNAL work area. |
56
+ | `{ "normalize": true }` | Write pages 0 to 3 and `$00`/`$01` from the entry state in the project knowledge. The entry state comes from a capture of the unpacked program. Then both sides have the same zero page, stack and KERNAL work area. |
55
57
  | `{ "observe": "moved", ... }` | Record a checkpoint. |
56
58
 
57
59
  The `port` of a joystick is 1 or 2. The `direction` is `center`, `up`, `down`, `left`, `right`, `up-left`, `up-right`, `down-left` or `down-right`.
@@ -86,7 +88,7 @@ A `pc` value is an address. Compare `pc` only when both programs have the code a
86
88
 
87
89
  ## Runs
88
90
 
89
- A run file (for `testing.ts run`) has:
91
+ A run file is one JSON object in a project file. It has:
90
92
 
91
93
  - `name`: a short name.
92
94
  - `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" }`.
@@ -94,11 +96,24 @@ A run file (for `testing.ts run`) has:
94
96
  - `videoStandard`: optional, `pal` (default) or `ntsc`.
95
97
  - `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
98
 
99
+ The run steps have these effects:
100
+
101
+ | Step | Effect |
102
+ |---|---|
103
+ | `{ "snapshot": ".c64-re-tools/local/snapshots/room0.vsf" }` | Restore a snapshot file. |
104
+ | `{ "save": "room3" }` | Write the state now to `room3.vsf` in the `--out` folder. |
105
+ | `{ "screen": "room3" }` | Write the screen to `room3.png`. |
106
+ | `{ "coverage": "room3" }` | Write the coverage map since the start or the last `coverage` step to `room3.bin`. Then clear the map. |
107
+ | `{ "observe": "room3", "memory": ["$c100"], "registers": true }` | Record memory, registers, `vicii` or `sprites` in `results.json`. |
108
+ | `{ "observe": "all3", "memory": "all" }` | Write all 64 KiB of RAM to `all3.bin`, also the RAM under the ROMs and the I/O area. |
109
+ | `{ "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. |
110
+ | `{ "expect": "title", "memory": [{ "address": "$0400", "text": "HELLO" }] }` | Compare memory and registers with the expected values. See the section "Expected values". |
111
+
97
112
  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
113
 
99
114
  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
115
 
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`.
116
+ 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 `$`. `results.json` gives the file name.
102
117
 
103
118
  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
119
 
@@ -158,7 +173,7 @@ Example: visit two rooms from the same start.
158
173
 
159
174
  The script checks the scenario before it does a step. A step with an unknown key or a wrong value stops the script with `invalid-input`. The message names the step.
160
175
 
161
- The script also examines each file before it does a step: 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.
176
+ The script also examines each file before it does a step: 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 is not a `.vsf` snapshot file also stops the script with `invalid-input`. The message names the step and the file.
162
177
 
163
178
  A run also examines each name of its steps before it does a step. 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.
164
179
 
@@ -31,10 +31,10 @@ function observation(path: string): MachineState {
31
31
  results = JSON.parse(readProjectFile(file).bytes.toString("utf8")) as typeof results;
32
32
  } catch (error) {
33
33
  if (error instanceof WireFailure) throw error;
34
- throw new UsageError(`${file} is not JSON: ${(error as Error).message}`);
34
+ throw new Refusal("invalid-input", `${file} is not JSON: ${(error as Error).message}`);
35
35
  }
36
36
  const seen = results.observations?.[name];
37
- if (seen === undefined) throw new UsageError(`${file} has no observation ${name}; it has ${Object.keys(results.observations ?? {}).join(", ") || "none"}`);
37
+ if (seen === undefined) throw new Refusal("not-found", `${file} has no observation ${name}. It has ${Object.keys(results.observations ?? {}).join(", ") || "none"}.`);
38
38
  const observed: Record<string, string> = {};
39
39
  for (const [at, value] of Object.entries(seen.memory ?? {})) {
40
40
  // A memory item in a file of its own: compare its bytes.
@@ -102,7 +102,7 @@ export function snapshotCpuPort(file: Uint8Array): { direction: number; data: nu
102
102
  async function snapshotState(client: ViceSessionClient, path: string, ntsc: boolean): Promise<MachineState> {
103
103
  const file = readProjectFile(path).bytes;
104
104
  const saved = snapshotRam(file);
105
- if (saved === undefined) throw new Refusal("invalid-input", `${path} is not a snapshot of a C64: it has no C64 memory. Give a file that c64_snapshot save or a save step of a run wrote.`);
105
+ if (saved === undefined) throw new Refusal("invalid-input", `${path} is not a snapshot of a C64: it has no C64 memory. Give a file that a snapshot save in the emulator or a save step of a run wrote.`);
106
106
  const restored = await client.snapshotRestore(file);
107
107
  const memory = await readMemoryInParts(client, 0x0000, 0x10000, "ram");
108
108
  // $00 and $01 are the CPU port: the file keeps them apart from the RAM.
@@ -148,9 +148,9 @@ export function comparedItems(what: string, a: readonly string[], b: readonly st
148
148
  /** The differences of two states of one kind: snapshots, memory files or observations of runs. */
149
149
  export async function diffFiles(first: string, second: string, options: { gap: number; max: number; ntsc: boolean; at?: number; out?: string }): Promise<Record<string, unknown>> {
150
150
  const kind = kindOf(first);
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`);
151
+ if (kindOf(second) !== kind) throw new UsageError("The two states are not of one kind. Give two snapshot files, 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.`);
154
154
  const { gap, max } = options;
155
155
  let a: MachineState;
156
156
  let b: MachineState;
@@ -161,8 +161,8 @@ export async function diffFiles(first: string, second: string, options: { gap: n
161
161
  const base = options.at ?? 0;
162
162
  const read = (path: string) => readProjectFile(path).bytes;
163
163
  const [left, right] = [read(first), read(second)];
164
- if (left.length !== right.length) throw new UsageError(`the memory files have ${left.length} and ${right.length} bytes; give two of one size`);
165
- if (base + left.length > 0x10000) throw new UsageError("the memory file goes past $ffff from --address");
164
+ if (left.length !== right.length) throw new UsageError(`The memory files have ${left.length} and ${right.length} bytes. Give two files of one size.`);
165
+ if (base + left.length > 0x10000) throw new UsageError("The memory file goes past $ffff from --address. Give a lower --address.");
166
166
  a = { memory: { base, bytes: left } };
167
167
  b = { memory: { base, bytes: right } };
168
168
  } else {
@@ -50,7 +50,7 @@ export interface StateItem {
50
50
  export interface RecordFile {
51
51
  name: string;
52
52
  program: string;
53
- /** "knowledge", "none", or a project JSON file (c64-assembler output or a name → "$xxxx" map). */
53
+ /** "knowledge", "none", or a project JSON file (the symbol file of a build or a name → "$xxxx" map). */
54
54
  symbols: string;
55
55
  /** true: load the program with the CPU at READY and no RUN; a registers step starts it. */
56
56
  load?: boolean;
@@ -134,7 +134,7 @@ const KEY_CODES = new Map<string, number>([
134
134
  export function keyCodes(text: string): number[] {
135
135
  return [...text.replace(/\r\n?/g, "\n")].map((character) => {
136
136
  const code = KEY_CODES.get(character.toUpperCase());
137
- if (code === undefined) throw new Refusal("invalid-input", `press cannot press ${JSON.stringify(character)} on the keyboard of the replay core`);
137
+ if (code === undefined) throw new Refusal("invalid-input", `press cannot press ${JSON.stringify(character)} on the C64 keyboard`);
138
138
  return code;
139
139
  });
140
140
  }
@@ -225,7 +225,7 @@ export function readRecordFile(path: string): RecordFile {
225
225
 
226
226
  /** What the replay core cannot do of a step that is right for VICE: it has the C64 alone, no raster wait and no conditions. */
227
227
  function checkCoreStep(step: ActionStep, at: string, fail: (message: string) => never): void {
228
- if ("write" in step && step.write.space !== "c64") fail(`${at}: the replay core has the C64 alone, not ${step.write.space}`);
228
+ if ("write" in step && step.write.space !== "c64") fail(`${at}: a recording has the C64 alone, not ${step.write.space}`);
229
229
  if ("press" in step) {
230
230
  try {
231
231
  keyCodes(step.press);
@@ -240,9 +240,9 @@ function checkCoreStep(step: ActionStep, at: string, fail: (message: string) =>
240
240
  }
241
241
  if ("runUntil" in step) {
242
242
  const { target } = step.runUntil;
243
- if (target.kind === "raster") fail(`${at}: the replay core has no raster target; use an address or a memory target`);
244
- else if (target.space !== "c64") fail(`${at}: the replay core has the C64 alone, not ${target.space}`);
245
- else if (target.kind === "address" && target.condition !== undefined) fail(`${at}: the replay core has no condition at an address target`);
243
+ if (target.kind === "raster") fail(`${at}: a recording has no raster target. Use an address or a memory target`);
244
+ else if (target.space !== "c64") fail(`${at}: a recording has the C64 alone, not ${target.space}`);
245
+ else if (target.kind === "address" && target.condition !== undefined) fail(`${at}: a recording has no condition at an address target`);
246
246
  }
247
247
  }
248
248
 
@@ -429,7 +429,7 @@ async function doAction(core: C64RunSession, step: ActionStep | RestoreAction, a
429
429
  await core.status(`run ${tick + PAL_FRAME_CYCLES}`);
430
430
  }
431
431
  }
432
- if (target.kind !== "address") return "the replay core has no raster target";
432
+ if (target.kind !== "address") return "a recording has no raster target";
433
433
  const reached = await core.status(`run-pc ${hex(at.code(target.address))} ${until}`);
434
434
  if (reached.word !== "reached") return `the program did not reach ${target.address} within ${timeoutFrames} frames`;
435
435
  }
@@ -30,16 +30,16 @@ export interface ReplayOptions {
30
30
 
31
31
  /** Replays the recording on the original, and with `rebuild` on the rebuild: PASS, FAIL or INCONCLUSIVE. */
32
32
  export async function replay(values: ReplayOptions): Promise<ReplayResult> {
33
- if (values.symbols !== undefined && values.rebuild === undefined) throw new UsageError("--symbols is for the rebuild: give --rebuild too");
34
- if ((values.checkpoint === undefined) !== (values.state.length === 0)) throw new UsageError("give --checkpoint and --state together");
35
- if (values.state.length + values.pin.length > MAX_STATE_ITEMS) throw new UsageError(`give at most ${MAX_STATE_ITEMS} --state and --pin items`);
36
- if (values.pin.length > 0 && values.checkpoint === undefined) throw new UsageError("--pin needs --checkpoint and --state");
33
+ if (values.symbols !== undefined && values.rebuild === undefined) throw new UsageError("--symbols gives the names of the rebuild, and --rebuild is missing. Give --rebuild too, or leave out --symbols.");
34
+ if ((values.checkpoint === undefined) !== (values.state.length === 0)) throw new UsageError("--checkpoint and --state go together. Give both of them, or neither.");
35
+ if (values.state.length + values.pin.length > MAX_STATE_ITEMS) throw new UsageError(`There are more than ${MAX_STATE_ITEMS} --state and --pin items. Give at most ${MAX_STATE_ITEMS} of them.`);
36
+ if (values.pin.length > 0 && values.checkpoint === undefined) throw new UsageError("--pin needs --checkpoint and --state. Give them too, or leave out --pin.");
37
37
  const folder = values.folder.replace(/\/+$/, "").replace(/\/recording\.json$/, "");
38
38
  const recording = readRecording(folder);
39
39
  const given: Comparison | undefined =
40
40
  values.checkpoint === undefined ? undefined : { checkpoint: values.checkpoint, state: values.state.map((item) => parseStateItem(item, "--state")), ...(values.pin.length === 0 ? {} : { pin: values.pin.map((item) => parseStateItem(item, "--pin")) }) };
41
41
  const compare = given ?? recording.compare;
42
- if (values.rebuild !== undefined && compare === undefined) throw new UsageError("the recording has no checkpoint and state: give --checkpoint and --state");
42
+ if (values.rebuild !== undefined && compare === undefined) throw new UsageError("The recording has no checkpoint and state for --rebuild. Give --checkpoint and --state.");
43
43
  const result = (outcome: ReplayResult["result"], side: ReplayResult["side"], fields: Partial<ReplayResult> = {}): ReplayResult => ({
44
44
  result: outcome,
45
45
  recording: folder,
@@ -73,10 +73,10 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
73
73
  const self = await side(original, { ...(compare === undefined ? {} : { compare }) });
74
74
  if (self.problem !== undefined) return result("INCONCLUSIVE", "original", { reason: `the recording does not reproduce on the original: ${self.problem}` });
75
75
  if (self.unknown > 0 || self.misses > 0) {
76
- return result("INCONCLUSIVE", "original", { reason: `the recording does not reproduce on the original: ${self.unknown + self.misses} input reads had no recorded value; record the session again with this c64run` });
76
+ return result("INCONCLUSIVE", "original", { reason: `the recording does not reproduce on the original: ${self.unknown + self.misses} input reads had no recorded value; record the session again with this version of the toolkit` });
77
77
  }
78
78
  if (self.end.tick !== recording.ticks || self.end.hash !== recording.hash) {
79
- return result("INCONCLUSIVE", "original", { reason: "the recording does not reproduce on the original: the state at its end is different; record the session again with this c64run" });
79
+ return result("INCONCLUSIVE", "original", { reason: "the recording does not reproduce on the original: the state at its end is different; record the session again with this version of the toolkit" });
80
80
  }
81
81
  const expected = self.samples;
82
82
  if (compare !== undefined && expected.length === 0) return result("INCONCLUSIVE", "original", { reason: `the original never came to the checkpoint ${compare.checkpoint} in the session` });
@@ -15,7 +15,6 @@ import { MAX_MEMORY_READ, MAX_TRACE_FRAMES, MAX_TRACE_HITS, MAX_TRACE_POINTS, TR
15
15
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
16
16
  import { readMemoryInParts, ViceSessionClient } from "#src/host-client/vice-session.ts";
17
17
  import { checkSnapshotFile } from "#src/media.ts";
18
- import { UsageError } from "#src/script.ts";
19
18
  import { namesOf } from "./scenario.ts";
20
19
 
21
20
  type RunStep =
@@ -107,10 +106,10 @@ function readRun(path: string): Run {
107
106
  value = JSON.parse(readProjectFile(path).bytes.toString("utf8"));
108
107
  } catch (error) {
109
108
  if (error instanceof WireFailure) throw error;
110
- throw new UsageError(`the run ${path} is not JSON: ${(error as Error).message}`);
109
+ throw new Refusal("invalid-input", `the run ${path} is not JSON: ${(error as Error).message}`);
111
110
  }
112
111
  const fail = (message: string): never => {
113
- throw new UsageError(`run ${path}: ${message}`);
112
+ throw new Refusal("invalid-input", `run ${path}: ${message}`);
114
113
  };
115
114
  if (!isObject(value)) return fail("is not a JSON object");
116
115
  if (typeof value.name !== "string" || value.name === "") fail("needs a name");
@@ -216,7 +215,7 @@ function readRun(path: string): Run {
216
215
  }
217
216
 
218
217
  /** The remedy for a start program that is no PRG. */
219
- 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";
218
+ const PROGRAM_REMEDY = "A run starts a PRG. Extract the program file from the disk, tape or cartridge image, and give that PRG";
220
219
 
221
220
  /** 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. */
222
221
  function checkRunFiles(path: string, run: Run): void {
@@ -286,9 +285,9 @@ export async function runFile(path: string, out: string): Promise<{ output: Reco
286
285
  const address = symbols.get(location);
287
286
  if (address !== undefined) return address;
288
287
  if (run.symbols === undefined || run.symbols === "none") {
289
- 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`);
288
+ throw new Refusal("invalid-input", `${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`);
290
289
  }
291
- throw new UsageError(`the symbols ${run.symbols} have no ${location}`);
290
+ throw new Refusal("not-found", `the symbols ${run.symbols} have no ${location}`);
292
291
  };
293
292
  // Every name of the steps resolves before the emulator starts. A refusal names the step.
294
293
  run.steps.forEach((step, index) => {
@@ -352,7 +351,7 @@ export async function runFile(path: string, out: string): Promise<{ output: Reco
352
351
  } else if ("trace" in step) {
353
352
  // A trace: every hit of the points while the program runs on, to <name>.json.
354
353
  const points = step.points.map((point) => ({ kind: point.kind, start: at(point.start), end: at(point.end ?? point.start) }));
355
- if (points.some((point) => point.end < point.start)) throw new UsageError(`the trace ${step.trace} has a point whose end is before its start`);
354
+ if (points.some((point) => point.end < point.start)) throw new Refusal("invalid-input", `the trace ${step.trace} has a point whose end is before its start`);
356
355
  const traced = await client.trace({ points, frames: step.frames, maxHits: step.maxHits ?? MAX_TRACE_HITS });
357
356
  write(`${step.trace}.json`, Buffer.from(`${JSON.stringify({ points: step.points, frames: traced.frames, end: traced.end, hits: traced.hits.map(showHit) }, null, 1)}\n`));
358
357
  traces[step.trace] = { file: `${step.trace}.json`, hits: traced.hits.length, frames: traced.frames, end: traced.end };
@@ -58,7 +58,7 @@ export type Step = StepBody & { side?: Side };
58
58
 
59
59
  export interface Subject {
60
60
  program: string;
61
- /** "knowledge" for the project knowledge, a project JSON file (c64-assembler output or a name → "$xxxx" map), or "none". */
61
+ /** "knowledge" for the project knowledge, a project JSON file (the symbol file of a build or a name → "$xxxx" map), or "none". */
62
62
  symbols: string;
63
63
  }
64
64
 
@@ -257,7 +257,7 @@ function checkObserve(step: Record<string, unknown>, at: string, fail: (message:
257
257
 
258
258
  /**
259
259
  * Name → address from a source of names: none; the knowledge (its symbols and
260
- * the analyzer names that only one address has); the c64-assembler output; or
260
+ * the analyzer names that only one address has); the symbol file of a build; or
261
261
  * a JSON map of name to $ address. With kinds "code", only the names that move
262
262
  * with the code: labels and routines of the knowledge, and the labels of the
263
263
  * assembler output. With "all", also the data names and the assembler
@@ -300,7 +300,7 @@ export function namesOf(source: string, kinds: "code" | "all" = "all"): Map<stri
300
300
  }
301
301
 
302
302
  /** The remedy for a scenario program that is no PRG. */
303
- const PROGRAM_REMEDY = "A scenario program is 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";
303
+ const PROGRAM_REMEDY = "A scenario program is a PRG. Extract the program file from the disk, tape or cartridge image, and give that PRG";
304
304
 
305
305
  /**
306
306
  * Checks each file that the scenario names before an emulator starts: the
@@ -366,7 +366,7 @@ async function normalize(client: ViceSessionClient): Promise<void> {
366
366
  } finally {
367
367
  db?.close();
368
368
  }
369
- if (state === undefined) throw new Refusal("invalid-input", "normalize needs the entry state of a c64-unpacker capture in the knowledge: put the capture in with knowledge.ts image <image.json> of the c64-knowledge skill");
369
+ if (state === undefined) throw new Refusal("invalid-input", "normalize needs the entry state of a capture in the project knowledge, and the knowledge has none. Capture the unpacked program at its entry point, and put the capture image into the project knowledge");
370
370
  await applyEntryState(client, parseEntryState(state, "the entry state of the knowledge"), { registers: false });
371
371
  }
372
372
 
@@ -391,8 +391,14 @@ async function runSide(client: ViceSessionClient, scenario: Scenario, side: Side
391
391
  const at = (location: Location) => resolve(location, symbols, side);
392
392
  // Each side starts from a hard reset, stopped at the reset vector, with the control ports released.
393
393
  await client.reset({ mode: "hard", run: false });
394
- await client.joystick({ port: 1, direction: "center", fire: false });
395
- await client.joystick({ port: 2, direction: "center", fire: false });
394
+ for (const port of [1, 2] as const) {
395
+ try {
396
+ await client.joystick({ port, direction: "center", fire: false });
397
+ } catch (error) {
398
+ // A VICE whose joystick input is broken refuses it, and so holds no joystick: the port is released already.
399
+ if (!isRefusal(error) || error.code !== "not-implemented") throw error;
400
+ }
401
+ }
396
402
  let checkpoint = 0;
397
403
  for (const [index, step] of scenario.steps.entries()) {
398
404
  if (step.side !== undefined && step.side !== side) continue;
@@ -14,9 +14,9 @@ import { C64RunSession, PAL_FRAME_CYCLES } from "#src/native/c64run.ts";
14
14
  import { localToolContext } from "#src/native/local.ts";
15
15
  import { Workspace } from "#src/native/staging.ts";
16
16
  import { knowledgeNames } from "#src/knowledge/names.ts";
17
- import { OPTIONS, runScript, UsageError, type Call, type CommandSpec } from "#src/script.ts";
17
+ import { OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec, type Reply } from "#src/script.ts";
18
18
  import { diffFiles } from "./lib/diff-files.ts";
19
- import { play } from "./lib/play.ts";
19
+ import { CANCELLED, play } from "./lib/play.ts";
20
20
  import { readRecordFile, record, RECORDING_FILES } from "./lib/recording.ts";
21
21
  import { replay } from "./lib/replay.ts";
22
22
  import { runFile } from "./lib/runs.ts";
@@ -34,7 +34,10 @@ const ALWAYS = [
34
34
  "Nothing unexpected happens outside the tested scenarios.",
35
35
  ];
36
36
 
37
- async function test(call: Call): Promise<ScenarioResult> {
37
+ /** The hint of a test or replay verdict: what to do after a FAIL or an INCONCLUSIVE. */
38
+ const INCONCLUSIVE_HINT = "reason tells why the script could not compare. This is not a failure of the program. Correct the cause, then run the command again.";
39
+
40
+ async function test(call: Call): Promise<ScenarioResult | Reply> {
38
41
  const scenario = readScenario(call.subject(0));
39
42
  const out = call.string("out");
40
43
  // Every file of the scenario is checked before the emulator starts.
@@ -44,18 +47,21 @@ async function test(call: Call): Promise<ScenarioResult> {
44
47
  client = await ViceSessionClient.open({ videoStandard: scenario.videoStandard ?? "pal" });
45
48
  } catch (error) {
46
49
  if (!(error instanceof WireFailure)) throw error;
47
- return { result: "INCONCLUSIVE", scenario: scenario.name, reason: `no emulator: ${error.message}`, checkpoints: [], differences: [] };
50
+ return reply({ result: "INCONCLUSIVE", scenario: scenario.name, reason: `no emulator: ${error.message}`, checkpoints: [], differences: [] }, { hint: "The emulator did not start. Give error and reason to the user." });
48
51
  }
49
52
  try {
50
- return await runScenario(client, scenario, { names, max: call.count("max-listed")!, ...(out === undefined ? {} : { out }) });
53
+ const result = await runScenario(client, scenario, { names, max: call.count("max-listed")!, ...(out === undefined ? {} : { out }) });
54
+ if (result.result === "INCONCLUSIVE") return reply(result, { hint: INCONCLUSIVE_HINT });
55
+ if (result.result === "FAIL") return reply(result, { hint: `Examine the first difference in the emulator at its checkpoint.${out === undefined ? " Give --out to get the screens and all differing bytes as files." : ""}` });
56
+ return result;
51
57
  } finally {
52
58
  await client.close();
53
59
  }
54
60
  }
55
61
 
56
- async function recordCommand(call: Call): Promise<Record<string, unknown>> {
62
+ async function recordCommand(call: Call): Promise<Reply> {
57
63
  const playing = call.flag("play");
58
- if (!playing && (call.count("joystick") !== undefined || call.count("http-port") !== undefined)) throw new UsageError("--joystick and --http-port are for --play");
64
+ if (!playing && (call.count("joystick") !== undefined || call.count("http-port") !== undefined)) throw new UsageError("--joystick and --http-port need --play. Give --play, or leave out these flags.");
59
65
  const joystick = (call.count("joystick") ?? 2) as 1 | 2;
60
66
  const httpPort = call.count("http-port") ?? DEFAULT_HTTP_PORT;
61
67
  const out = call.string("out")!;
@@ -89,13 +95,17 @@ async function recordCommand(call: Call): Promise<Record<string, unknown>> {
89
95
  // The instructions in the coverage map: 0 when the program never read its input from RAM.
90
96
  executed: outcome.coverage.reduce((count, byte) => count + ((byte & COVERAGE.ramExecute) === 0 ? 0 : 1), 0),
91
97
  };
92
- if (outcome.reason !== undefined) return { result: "FAIL", recorded: false, reason: outcome.reason, ...summary };
98
+ if (outcome.reason === CANCELLED) return reply({ result: "FAIL", recorded: false, reason: outcome.reason, ...summary }, { hint: "Ask the user what to do. Do not make a scripted recording in place of the session of the user." });
99
+ if (outcome.reason !== undefined) return reply({ result: "FAIL", recorded: false, reason: outcome.reason, ...summary }, { hint: "reason names the step that did not complete. Change that step, then record again." });
93
100
  const files = [
94
101
  writeReported(`${out}/${RECORDING_FILES.recording}`, `${JSON.stringify(outcome.recording, null, 2)}\n`, { what: "--out" }),
95
102
  writeReported(`${out}/${RECORDING_FILES.reads}`, outcome.reads, { what: "--out" }),
96
103
  writeReported(`${out}/${RECORDING_FILES.coverage}`, outcome.coverage, { what: "--out" }),
97
104
  ];
98
- return { result: "PASS", recorded: true, out, ...summary, files };
105
+ return reply(
106
+ { result: "PASS", recorded: true, out, ...summary, files },
107
+ { hint: `Commit ${out} with the scenarios. Add ${out}/${RECORDING_FILES.coverage} to the project knowledge as coverage. To make sure that the recording replays, run nextAction.`, nextAction: call.next("replay", out) },
108
+ );
99
109
  } finally {
100
110
  await core.close();
101
111
  workspace.remove();
@@ -136,12 +146,14 @@ const COMMANDS: CommandSpec[] = [
136
146
  options: { out: { ...OPTIONS.out, output: "folder", value: "<dir>", required: true, help: "the folder for the files of the steps and results.json" } },
137
147
  run: async (call) => {
138
148
  const { output, failed } = await runFile(call.subject(0), call.string("out")!);
139
- return { result: failed ? "FAIL" : "PASS", ...output };
149
+ if (!failed) return { result: "PASS", ...output };
150
+ const hint = output.reason !== undefined ? "reason tells why a step did not run. Correct the step or the start, then run again." : "failedExpectations names the expect steps that failed. expectations in results.json gives the expected and the actual values.";
151
+ return reply({ result: "FAIL", ...output }, { hint });
140
152
  },
141
153
  },
142
154
  {
143
155
  name: "record",
144
- summary: "Plays the steps of a record file on the original in the replay core (c64run), and writes the session as a recording folder: recording.json, reads.txt and coverage.bin. result is FAIL when the session did not complete.",
156
+ summary: "Plays the steps of a record file on the original, and writes the session as a recording folder: recording.json, reads.txt and coverage.bin. result is FAIL when the session did not complete.",
145
157
  subjects: [{ name: "<record.json>", help: "a record file, relative to the project folder. See references/recording-format.md" }],
146
158
  options: {
147
159
  out: { ...OPTIONS.out, output: "folder", value: "<dir>", required: true, help: "the recording folder, for example tests/recordings/<name>" },
@@ -160,13 +172,21 @@ const COMMANDS: CommandSpec[] = [
160
172
  state: { kind: "text", value: "<item>", multiple: true, help: `the state to compare at each checkpoint: ${STATE_ITEM}` },
161
173
  pin: { kind: "text", value: "<item>", multiple: true, help: `random state in RAM, in the form of --state: at each checkpoint the rebuild gets the original's values there` },
162
174
  rebuild: { kind: "path", value: "<prg>", help: "the rebuild to compare with the original" },
163
- symbols: { ...OPTIONS.symbols, help: "the names of the rebuild: the c64-assembler output (default: the symbols of the recording)" },
175
+ symbols: { ...OPTIONS.symbols, help: "the names of the rebuild: the symbol file of its build (default: the symbols of the recording)" },
164
176
  out: { ...OPTIONS.out, output: "folder", value: "<dir>", help: "with a FAIL, write the RAM of both sides at the first different checkpoint into this folder" },
165
177
  },
166
178
  notes: "A recording without names takes the names of the knowledge for the original. A $ address is an address of the original: on the rebuild it moves with the name before it.",
167
- run: (call) => {
179
+ run: async (call) => {
168
180
  const [checkpoint, rebuild, symbols, out] = [call.string("checkpoint"), call.string("rebuild"), call.string("symbols"), call.string("out")];
169
- return replay({ folder: call.subject(0), state: call.strings("state"), pin: call.strings("pin"), ...(checkpoint === undefined ? {} : { checkpoint }), ...(rebuild === undefined ? {} : { rebuild }), ...(symbols === undefined ? {} : { symbols }), ...(out === undefined ? {} : { out }) });
181
+ const result = await replay({ folder: call.subject(0), state: call.strings("state"), pin: call.strings("pin"), ...(checkpoint === undefined ? {} : { checkpoint }), ...(rebuild === undefined ? {} : { rebuild }), ...(symbols === undefined ? {} : { symbols }), ...(out === undefined ? {} : { out }) });
182
+ if (result.result === "INCONCLUSIVE") return reply(result, { hint: INCONCLUSIVE_HINT });
183
+ if (result.result !== "FAIL") return result;
184
+ const [original, rebuilt] = result.files ?? [];
185
+ if (original !== undefined && rebuilt !== undefined) {
186
+ return reply(result, { hint: "files holds the RAM of each side at the first different checkpoint. Run nextAction to compare them. Then examine the first different state item in the emulator.", nextAction: call.next("diff", original.out, rebuilt.out) });
187
+ }
188
+ if (result.firstDifference === undefined) return reply(result, { hint: "reason tells how many checkpoints the rebuild came to. Examine the rebuild in the emulator after its last checkpoint." });
189
+ return reply(result, { hint: `A difference in a random value with the same input often shows a missing --pin.${out === undefined ? " Give --out to get the RAM of each side at the first different checkpoint." : ""}` });
170
190
  },
171
191
  },
172
192
  {
@@ -199,7 +219,7 @@ const COMMANDS: CommandSpec[] = [
199
219
 
200
220
  await runScript({
201
221
  name: "testing",
202
- summary: "Tests a rebuild against the original: scenarios in VICE, runs, recorded play sessions in the replay core, state differences, and a checklist for a human tester.",
222
+ summary: "Tests a rebuild against the original: scenarios in an emulator, runs, recorded play sessions, state differences, and a checklist for a human tester.",
203
223
  names: knowledgeNames,
204
224
  commands: COMMANDS,
205
225
  });