@henols/c64-re-tools 2.8.0-rc.2 → 2.8.0-rc.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 (119) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +5 -2
  3. package/skills/c64-assembler/scripts/assembler.ts +55 -48
  4. package/skills/c64-disk/scripts/disk.ts +3 -3
  5. package/skills/c64-disk/scripts/lib/containers.ts +2 -2
  6. package/skills/c64-docs/SKILL.md +1 -1
  7. package/skills/c64-docs/scripts/docs.ts +12 -20
  8. package/skills/c64-docs/scripts/lib/links.ts +1 -1
  9. package/skills/c64-docs/scripts/lib/markdown.ts +1 -1
  10. package/skills/c64-docs/scripts/lib/reference.ts +59 -13
  11. package/skills/c64-knowledge/SKILL.md +17 -8
  12. package/skills/c64-knowledge/scripts/knowledge.ts +200 -218
  13. package/skills/c64-knowledge/scripts/lib/check.ts +2 -3
  14. package/skills/c64-knowledge/scripts/lib/listing.ts +56 -24
  15. package/skills/c64-packer/scripts/packer.ts +3 -3
  16. package/skills/c64-provenance/SKILL.md +25 -16
  17. package/skills/c64-provenance/scripts/lib/compare.ts +31 -21
  18. package/skills/c64-provenance/scripts/lib/leftovers.ts +17 -35
  19. package/skills/c64-provenance/scripts/lib/library.ts +10 -10
  20. package/skills/c64-provenance/scripts/lib/runtime.ts +3 -14
  21. package/skills/c64-provenance/scripts/provenance.ts +129 -98
  22. package/skills/c64-source/references/loader.md +2 -1
  23. package/skills/c64-source/scripts/lib/export.ts +54 -303
  24. package/skills/c64-source/scripts/lib/loader.ts +31 -51
  25. package/skills/c64-source/scripts/lib/source.ts +51 -41
  26. package/skills/c64-source/scripts/lib/stage.ts +9 -25
  27. package/skills/c64-source/scripts/source.ts +134 -294
  28. package/skills/c64-static-analysis/SKILL.md +12 -7
  29. package/skills/c64-static-analysis/scripts/lib/coverage.ts +1 -3
  30. package/skills/c64-static-analysis/scripts/lib/findings.ts +16 -3
  31. package/skills/c64-static-analysis/scripts/lib/idioms.ts +82 -10
  32. package/skills/c64-static-analysis/scripts/lib/triage.ts +112 -0
  33. package/skills/c64-static-analysis/scripts/static-analysis.ts +239 -147
  34. package/skills/c64-testing/SKILL.md +13 -7
  35. package/skills/c64-testing/scripts/lib/diff-files.ts +6 -13
  36. package/skills/c64-testing/scripts/lib/recording.ts +47 -66
  37. package/skills/c64-testing/scripts/lib/replay.ts +53 -9
  38. package/skills/c64-testing/scripts/lib/runs.ts +11 -29
  39. package/skills/c64-testing/scripts/lib/scenario.ts +30 -31
  40. package/skills/c64-testing/scripts/lib/start-screen.ts +42 -5
  41. package/skills/c64-testing/scripts/testing.ts +32 -7
  42. package/skills/c64-unpacker/SKILL.md +10 -7
  43. package/skills/c64-unpacker/scripts/lib/evidence.ts +23 -38
  44. package/skills/c64-unpacker/scripts/lib/loads.ts +24 -39
  45. package/skills/c64-unpacker/scripts/lib/machine.ts +38 -18
  46. package/skills/c64-unpacker/scripts/lib/stages.ts +142 -41
  47. package/skills/c64-unpacker/scripts/unpacker.ts +85 -68
  48. package/skills/emulator/SKILL.md +1 -0
  49. package/src/c64.ts +117 -10
  50. package/src/cli/ap-sdk.ts +1 -1
  51. package/src/cli/cleanup.ts +4 -2
  52. package/src/compare.ts +36 -16
  53. package/src/errors.ts +10 -1
  54. package/src/host/main.ts +2 -1
  55. package/src/host/server.ts +7 -11
  56. package/src/host/tools/c1541.ts +9 -3
  57. package/src/host/vice/adapter.ts +20 -43
  58. package/src/host/vice/binary-monitor.ts +22 -21
  59. package/src/host/vice/process.ts +31 -40
  60. package/src/host/vice/session.ts +187 -247
  61. package/src/host/vice/text-monitor.ts +3 -3
  62. package/src/host-client/autostart.ts +1 -1
  63. package/src/host-client/connect.ts +2 -1
  64. package/src/host-client/coverage.ts +0 -3
  65. package/src/host-client/entry-state.ts +4 -11
  66. package/src/host-client/image.ts +6 -11
  67. package/src/host-client/steps.ts +13 -113
  68. package/src/host-client/tools.ts +4 -4
  69. package/src/host-client/transfer.ts +10 -0
  70. package/src/host-client/vice-session.ts +10 -6
  71. package/src/knowledge/code-reach.ts +364 -0
  72. package/src/knowledge/conflicts.ts +34 -72
  73. package/src/knowledge/database.ts +40 -28
  74. package/src/knowledge/evidence.ts +2 -2
  75. package/src/knowledge/graph.ts +3 -3
  76. package/src/knowledge/history.ts +50 -90
  77. package/src/knowledge/import.ts +43 -71
  78. package/src/knowledge/join.ts +1 -1
  79. package/src/knowledge/names.ts +12 -7
  80. package/src/knowledge/program.ts +25 -46
  81. package/src/knowledge/read.ts +104 -100
  82. package/src/knowledge/schema.ts +9 -3
  83. package/src/knowledge/separate.ts +47 -19
  84. package/src/knowledge/start-screen.ts +7 -5
  85. package/src/knowledge/text.ts +56 -33
  86. package/src/knowledge/write.ts +274 -515
  87. package/src/loader.ts +7 -25
  88. package/src/mcp/inputs.ts +3 -3
  89. package/src/mcp/server.ts +19 -38
  90. package/src/mcp/session-source.ts +2 -1
  91. package/src/mcp/tools/debug.ts +97 -24
  92. package/src/mcp/tools/execution.ts +1 -1
  93. package/src/mcp/tools/input.ts +3 -3
  94. package/src/mcp/tools/machine.ts +3 -3
  95. package/src/mcp/tools/media.ts +4 -4
  96. package/src/mcp/tools/memory.ts +13 -17
  97. package/src/mcp/tools/video.ts +11 -25
  98. package/src/native/acme.ts +3 -3
  99. package/src/native/c64run.ts +2 -1
  100. package/src/native/decompiler/analyze.ts +10 -7
  101. package/src/native/decompiler/walk.ts +3 -4
  102. package/src/native/decompiler/wasm.ts +2 -2
  103. package/src/native/discover.ts +1 -1
  104. package/src/native/dxa.ts +9 -11
  105. package/src/native/exomizer.ts +1 -1
  106. package/src/native/processes.ts +4 -1
  107. package/src/native/run.ts +3 -3
  108. package/src/native/types.ts +5 -6
  109. package/src/opcodes.ts +3 -0
  110. package/src/platform.ts +9 -10
  111. package/src/program-code.ts +151 -0
  112. package/src/project.ts +8 -5
  113. package/src/protocol/framing.ts +51 -18
  114. package/src/protocol/messages.ts +1 -11
  115. package/src/protocol/tools.ts +0 -3
  116. package/src/protocol/vice.ts +588 -773
  117. package/src/script.ts +9 -14
  118. package/src/time.ts +1 -1
  119. package/src/trace.ts +3 -2
@@ -33,7 +33,8 @@ To get the command list, run the script with no arguments.
33
33
  | Find the input sites and the coverage of a recording | `show tests/recordings/rooms` |
34
34
  | Make sure that a recording replays on the reference | `replay tests/recordings/rooms` |
35
35
  | Keep the screen at the end of a recorded session | `replay tests/recordings/final --screen .c64-re-tools/local/results/final.png` |
36
- | Compare the rebuild with a recording | `replay tests/recordings/rooms --checkpoint main_loop --state room --state lives --pin random_ptr:2 --rebuild build/clean.prg --symbols build/symbols/clean.json --out .c64-re-tools/local/results/rooms` |
36
+ | Compare the rebuild with a recording | `replay tests/recordings/rooms --checkpoint main_loop --state room --state lives --pin random_ptr:2 --rebuild build/clean.prg --out .c64-re-tools/local/results/rooms` |
37
+ | Replay each recording on the default build | `replay tests/recordings/rooms tests/recordings/fight --rebuild build/clean.prg` |
37
38
  | Find what changed between two snapshot files | `diff .c64-re-tools/local/runs/rooms/before.vsf .c64-re-tools/local/runs/rooms/after.vsf` |
38
39
  | Find what changed between two observations of runs | `diff .c64-re-tools/local/runs/rooms/results.json:room0 .c64-re-tools/local/runs/rooms/results.json:room3` |
39
40
  | Find what changed between two memory files of runs | `diff .c64-re-tools/local/runs/a/all.bin .c64-re-tools/local/runs/b/all.bin --gap 4` |
@@ -45,7 +46,8 @@ To get the command list, run the script with no arguments.
45
46
  - The reference program and the rebuild are PRG files in the project. The script refuses a disk, tape or cartridge image. Extract the program file from the image first.
46
47
  - The reference gets its names from the project knowledge. Give `"symbols": "knowledge"` for the reference.
47
48
  - The rebuild gets its names from the symbol file of its build. Build the rebuild with a symbol file that has all symbols, also the constants that the source does not use.
48
- - The loader program of a generated source can show a start screen that waits for a key. If the symbols of the program have the labels of that start screen, `test`, `run` and `replay` start the program after the start screen. Do not add a step for the start screen.
49
+ - The loader program of a generated source can show a start screen that waits for a key. If the symbols of the program have the labels of that start screen, `test`, `run` and `replay` start the program after the start screen. Do not add a step that goes past the start screen.
50
+ - To test the start screen itself, put the label `loader_start_screen_wait` (the wait for a key) or `loader_start_screen_continue` (the code after the wait) into a step. The name or the address of the label applies. Then `test` and `run` do not go past the start screen. In `test`, this applies only to the side of the step. For example, make the first step a `runUntil` step to `loader_start_screen_wait`.
49
51
  - You write the scenario file, the run file and the record file. Their formats are in the files of the section "Reference".
50
52
  - A file in `tests/` is a scenario or a run file with expected values. Give a scenario to `test` and a run file to `run`. `test` refuses a run file.
51
53
  - `<recording>` is the `--out` folder of `record`.
@@ -90,7 +92,7 @@ Each flag applies only to the commands in the table. On another command, the scr
90
92
  | `--state <item>` | `replay` | A memory item to compare at each checkpoint. Give it again for each item. |
91
93
  | `--pin <item>` | `replay` | Random state in RAM. At each checkpoint, the rebuild gets the values of the reference there. Give it again for each item. |
92
94
  | `--rebuild <prg>` | `replay` | The rebuild to compare with the reference. Without it, the script replays only on the reference. |
93
- | `--symbols <file>` | `replay` | The symbol file of the rebuild. The default is the symbols of the recording. |
95
+ | `--symbols <file>` | `replay` | The symbol file of the rebuild. The default is the symbol file of its build. When its build has no symbol file, the default is the names of the recording. |
94
96
  | `--out <dir>` | `replay` | With a FAIL, write the RAM of each side at the first different checkpoint into this folder. |
95
97
  | `--screen <png>` | `replay` | Write the screen of the reference at the end of the session into this PNG file. |
96
98
  | `--gap <n>` | `diff` | Join changed ranges across at most n equal bytes. The default is 0. |
@@ -201,7 +203,7 @@ A recording keeps a session of the reference program, for example a play through
201
203
  - Ask the user to play first. Tell the user which parts of the program the recordings must have, for example each room, a fight and a lost life.
202
204
  - Record a session from steps only for a part that the sessions of the user do not have, or when the user cannot play.
203
205
  - Replay each recording on the default build. Do not replay a release build or a build with a switch that is not at its default.
204
- - When the generated source has a loader, the default build is `build/clean_loader.prg`. Give `--symbols build/symbols/clean_loader.json` with it. Else the default build is `build/clean.prg`, with `--symbols build/symbols/clean.json`.
206
+ - When the generated source has a loader, the default build is `build/clean_loader.prg`. Else the default build is `build/clean.prg`.
205
207
  - Commit the recording folder with the scenarios. Do not put a recording into the project knowledge. Do not put test results, screenshots or playtest results into it.
206
208
  - A finding that a recording shows can go into the project knowledge. Give `evidence` of `show` as its test evidence.
207
209
  - The C64 of a recording has no disk drive. For a program that loads more files from a disk, use a scenario with `test`.
@@ -261,10 +263,12 @@ The script tells what a recording holds. It does not replay the recording. Use i
261
263
  - `coverage`: the number of RAM addresses in the coverage map that the session `executed`, `read` and `written`.
262
264
  - `evidence`: the test evidence for a finding that the recording shows.
263
265
 
264
- ### `replay <recording>`
266
+ ### `replay <recording>...`
265
267
 
266
268
  The script first replays the recording on the reference. The reference must end the session with the recorded state. With `--rebuild`, the script then replays the recording on the rebuild and compares the state at each checkpoint. Without `--rebuild`, it replays only on the reference.
267
269
 
270
+ Give all recordings to one `replay` command. The script replays them one after the other. Do not run replays at the same time: a replay that waits for the processor can stop before its end. With more than one recording, `--checkpoint`, `--state` and `--pin` apply to each recording, `--out` gets a folder for each recording, and the script refuses `--screen`.
271
+
268
272
  `--checkpoint` and `--state` go together. `--pin` needs both of them. `--symbols` needs `--rebuild`. Give at most 16 `--state` and `--pin` items. Without `--checkpoint`, the script uses the comparison of the record file.
269
273
  A `$` address is an address of the reference. On the rebuild, it moves with the name before it. Give each state item a name when you can.
270
274
  `--screen` writes the screen of the reference at the end of the session into a PNG file. The screen is the same on each replay. The script writes it only when the reference ends the session with the recorded state.
@@ -277,18 +281,21 @@ A `$` address is an address of the reference. On the rebuild, it moves with the
277
281
  - `checkpoints` and `compared`: the checkpoints of the reference, and the checkpoints of the rebuild that were the same.
278
282
  - `firstDifference`: with a FAIL, the checkpoint (1 is the first), the cycle on each side, and each state item that is different. An item has `address`, and the `reference` and `rebuild` values as hex.
279
283
  - `reason`: why the result is FAIL or INCONCLUSIVE.
284
+ - `symbols`: the names of the rebuild, a symbol file or `knowledge`.
280
285
  - `movedSites`: the number of input sites at a different address in the rebuild.
281
286
  - `startScreen`: `skipped` when the rebuild started after its start screen.
282
287
  - `idleReads`: the number of input reads of the rebuild that the recording had no value for.
283
288
  - `files`: with `--out` and a FAIL, the RAM of each side at the first different checkpoint.
284
289
  - `screen`: with `--screen`, the PNG file of the screen of the reference at the end of the session.
285
290
 
291
+ With more than one recording, `body` holds `result`, the counts `passed`, `failed` and `inconclusive`, and `recordings` with the fields above for each recording. `result` is `FAIL` when a recording failed, else `INCONCLUSIVE` when a recording was inconclusive, else `PASS`. When a recording did not pass, `nextAction` replays it alone. Run `nextAction`, and do the step for its result.
292
+
286
293
  Do this for each result:
287
294
 
288
295
  - `PASS`: each checkpoint of the rebuild has the state of the reference. Without `--rebuild`, the recording replays on the reference.
289
296
  - `FAIL` with `--out`: `files` has the RAM of each side at the first different checkpoint. `nextAction` compares the two files with `diff`. Then examine the first different state item in the emulator.
290
297
  - `FAIL` without `--out`: `hint` tells you to give `--out`. A FAIL where an enemy or an event is different, but the input is the same, often shows that a `--pin` is missing.
291
- - `FAIL` with no `firstDifference`: the rebuild did not get to all checkpoints. `reason` gives the number. Examine the rebuild in the emulator after its last checkpoint.
298
+ - `FAIL` with no `firstDifference`: the rebuild did not get to all checkpoints. `reason` gives the number. When the rebuild has the names of the recording, `hint` tells you to give `--symbols`. Else examine the rebuild in the emulator after its last checkpoint.
292
299
  - `INCONCLUSIVE`: `reason` gives the cause:
293
300
  - "does not reproduce": the reference does not end the session with the recorded state. Record the session again.
294
301
  - "never came to the checkpoint": the reference did not execute the checkpoint routine in the session. Give another routine.
@@ -299,7 +306,6 @@ Traps:
299
306
 
300
307
  - A run does not have the timing of a recording. The same steps in a run can give a different session, for example a lost fight. To show the screen of a recorded session, use `replay --screen`. Do not do the steps again in a run.
301
308
  - On the reference, an input read with no recorded value makes the result INCONCLUSIVE. The rebuild can read input where the reference does not, for example in its loader before the start screen. `idleReads` counts these reads. They do not change a PASS of the rebuild.
302
- - The script refuses a recording of an older version in an old form with `invalid-input`. Record the session again.
303
309
 
304
310
  ---
305
311
 
@@ -4,11 +4,10 @@
4
4
  // that the runs use: VICE reads its own snapshot format. Two memory files of a
5
5
  // run, or two observations of runs (also two of one run), compare as they are.
6
6
 
7
- import { formatC64Address, parseC64Address } from "#src/c64.ts";
7
+ import { formatC64Address, formatC64RangeFields, parseC64Address } from "#src/c64.ts";
8
8
  import { Refusal } from "#src/errors.ts";
9
- import { isObject } from "#src/host-client/steps.ts";
10
- import { WireFailure } from "#src/host-client/tools.ts";
11
- import { readProjectFile, writeReported } from "#src/host-client/transfer.ts";
9
+ import { isObject } from "#src/host-client/tools.ts";
10
+ import { readProjectFile, readProjectJson, writeReported } from "#src/host-client/transfer.ts";
12
11
  import { readMemoryInParts, ViceSessionClient } from "#src/host-client/vice-session.ts";
13
12
  import { checkSnapshotFile } from "#src/media.ts";
14
13
  import { listed, UsageError } from "#src/script.ts";
@@ -27,13 +26,7 @@ function kindOf(path: string): Kind {
27
26
  /** The state of one observation of a results.json: its memory items and its registers. */
28
27
  function observation(path: string): MachineState {
29
28
  const [file, name] = [path.slice(0, path.lastIndexOf(":")), path.slice(path.lastIndexOf(":") + 1)];
30
- let results: { observations?: Record<string, { memory?: Record<string, unknown>; registers?: Record<string, unknown> }> };
31
- try {
32
- results = JSON.parse(readProjectFile(file).bytes.toString("utf8")) as typeof results;
33
- } catch (error) {
34
- if (error instanceof WireFailure) throw error;
35
- throw new Refusal("invalid-input", `${file} is not JSON: ${(error as Error).message}`);
36
- }
29
+ const results = readProjectJson(file) as { observations?: Record<string, { memory?: Record<string, unknown>; registers?: Record<string, unknown> }> };
37
30
  const seen = results.observations?.[name];
38
31
  if (seen === undefined) throw new Refusal("not-found", `${file} has no observation ${name}. It has ${Object.keys(results.observations ?? {}).join(", ") || "none"}.`);
39
32
  const observed: Record<string, string> = {};
@@ -115,7 +108,7 @@ async function snapshotState(client: ViceSessionClient, path: string, ntsc: bool
115
108
  return { memory: { base: 0, bytes: memory }, colorRam, values };
116
109
  }
117
110
 
118
- const show = (range: ChangedRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end), ...(range.a === undefined ? {} : { a: range.a, b: range.b }) });
111
+ const show = (range: ChangedRange) => ({ ...formatC64RangeFields(range), ...(range.a === undefined ? {} : { a: range.a, b: range.b }) });
119
112
  /** A changed value as a person reads it: the pc as "$xxxx". */
120
113
  const showValue = (item: { name: string; a: number | boolean; b: number | boolean }) => (item.name === "cpu.pc" && typeof item.a === "number" && typeof item.b === "number" ? { name: item.name, a: formatC64Address(item.a), b: formatC64Address(item.b) } : item);
121
114
 
@@ -124,7 +117,7 @@ const showValue = (item: { name: string; a: number | boolean; b: number | boolea
124
117
  * diff compared. With none, the reason names what each side has, so that a
125
118
  * count of 0 does not read as "equal".
126
119
  */
127
- export function comparedItems(what: string, a: readonly string[], b: readonly string[], first: string, second: string): { compared: number; reason?: string } {
120
+ function comparedItems(what: string, a: readonly string[], b: readonly string[], first: string, second: string): { compared: number; reason?: string } {
128
121
  const compared = a.filter((name) => b.includes(name)).length;
129
122
  if (compared > 0) return { compared };
130
123
  const has = (names: readonly string[]) => (names.length === 0 ? "none" : names.join(", "));
@@ -8,23 +8,24 @@
8
8
  // replays the same session. A recording needs no names: the checkpoint and the
9
9
  // state can be chosen at replay time, with the names that the knowledge has then.
10
10
 
11
- import { createHash } from "node:crypto";
12
11
  import { readFileSync, writeFileSync } from "node:fs";
13
12
 
14
- import { isRefusal, Refusal } from "#src/errors.ts";
15
- import { c64AddressOf, COVERAGE, formatC64Address, parseC64Address } from "#src/c64.ts";
13
+ import { Refusal } from "#src/errors.ts";
14
+ import { c64AddressOf, COVERAGE, formatC64Address, hexWord, parseC64Address } from "#src/c64.ts";
16
15
  import { keyTaps, type KeyTap } from "#src/c64-keys.ts";
17
16
  import { READY_FRAMES } from "#src/host-client/entry-state.ts";
18
- import { ACTION_STEP_KINDS, checkActionStep, isInteger, isObject, keyboardBytes, renamedField, stepKind, type ActionStep, type Location } from "#src/host-client/steps.ts";
19
- import { readProjectFile, type Written } from "#src/host-client/transfer.ts";
17
+ import { ACTION_STEP_KINDS, checkActionStep, keyboardBytes, stepKind, type ActionStep, type Location } from "#src/host-client/steps.ts";
18
+ import { isInteger, isObject } from "#src/host-client/tools.ts";
19
+ import { readProjectFile, readProjectJson, type Written } from "#src/host-client/transfer.ts";
20
20
  import { RECORDING_FILES } from "#src/knowledge/recording-files.ts";
21
21
  import { LOADER_JUMP, startScreenLabels } from "#src/knowledge/start-screen.ts";
22
+ import { sha256 } from "#src/knowledge/text.ts";
22
23
  import { PAL_FRAME_CYCLES, type C64RunSession, type CoreStatus } from "#src/native/c64run.ts";
23
24
  import type { Workspace } from "#src/native/staging.ts";
24
25
  import { listed } from "#src/script.ts";
25
26
  import { namesOf, type Outcome } from "./scenario.ts";
26
27
 
27
- export const RECORDING_FORMAT = 1;
28
+ const RECORDING_FORMAT = 1;
28
29
  /**
29
30
  * CIA 1 ports A and B (joystick 2, joystick 1 and the keyboard matrix); the
30
31
  * four SID registers that a program can read: the paddles ($D419, $D41A) and
@@ -32,10 +33,10 @@ export const RECORDING_FORMAT = 1;
32
33
  * random seeds; and I/O 1 and I/O 2 ($DE00-$DFFF), where a C64 without a
33
34
  * cartridge gives the last byte on the bus.
34
35
  */
35
- export const DEFAULT_INPUTS = ["$dc00", "$dc01", "$d419", "$d41a", "$d41b", "$d41c", "$de00-$dfff"];
36
+ const DEFAULT_INPUTS = ["$dc00", "$dc01", "$d419", "$d41a", "$d41b", "$d41c", "$de00-$dfff"];
36
37
 
37
38
  /** The inputs argument of the replay core: hex addresses and ranges without $. */
38
- export function inputsArgument(inputs: string[]): string {
39
+ function inputsArgument(inputs: string[]): string {
39
40
  return inputs.map((input) => input.replace(/\$/g, "")).join(",");
40
41
  }
41
42
  /** Frames that a pressed key is held, and then released. */
@@ -61,7 +62,7 @@ export interface RecordFile {
61
62
  /** "knowledge", "none", or a project JSON file (the symbol file of a build or a name → "$xxxx" map). */
62
63
  symbols: string;
63
64
  /** true: load the program with the CPU at READY and no RUN; a registers step starts it. */
64
- load?: boolean;
65
+ load: boolean;
65
66
  /** The comparison that a replay uses when it gets none: the checkpoint routine and the state. */
66
67
  compare?: Comparison;
67
68
  inputs: string[];
@@ -136,8 +137,6 @@ export interface Recording {
136
137
  hash: string;
137
138
  }
138
139
 
139
- export { RECORDING_FILES };
140
-
141
140
  /** Steps that are input or time: the replay gives the program the reads that they caused, and does not do them again. */
142
141
  const INPUT_KINDS = new Set(["joystick", "press", "frames"]);
143
142
  /** The KERNAL keyboard queue: $0277, its length in $c6, at most 10 keys. */
@@ -145,8 +144,6 @@ const QUEUE = 0x0277;
145
144
  const QUEUE_LENGTH = 0x00c6;
146
145
  const QUEUE_SIZE = 10;
147
146
 
148
- const hex = (address: number) => address.toString(16).padStart(4, "0");
149
-
150
147
  /** The key code of the replay core for a matrix place: 80 + the place. RESTORE is ff. */
151
148
  const coreKey = (place: number) => (0x80 + place).toString(16);
152
149
 
@@ -165,15 +162,12 @@ export function parseStateItem(text: string, option = "--state"): StateItem {
165
162
  }
166
163
 
167
164
  /** Checks the memory items of state or pin (`what`): names, $ addresses, or { address, size }. */
168
- export function checkState(value: unknown, fail: (message: string) => never, what = "state"): StateItem[] {
165
+ function checkState(value: unknown, fail: (message: string) => never, what = "state"): StateItem[] {
169
166
  if (!Array.isArray(value) || value.length === 0 || value.length > MAX_STATE_ITEMS) fail(`${what} must be a list of 1 to ${MAX_STATE_ITEMS} memory items`);
170
167
  return (value as unknown[]).map((item, index) => {
171
168
  const spec = typeof item === "string" ? { address: item } : item;
172
169
  if (isObject(spec)) {
173
- for (const key of Object.keys(spec)) {
174
- const renamed = renamedField(key, ["address", "size"]);
175
- if (key !== "address" && key !== "size") fail(`${what} item ${index + 1} has the field ${key}. ${renamed ?? "A memory item has address and size, and nothing else"}`);
176
- }
170
+ for (const key of Object.keys(spec)) if (key !== "address" && key !== "size") fail(`${what} item ${index + 1} has the field ${key}. A memory item has address and size, and nothing else`);
177
171
  }
178
172
  if (!isObject(spec) || typeof spec.address !== "string") fail(`${what} item ${index + 1} must be a name, a $ address, or { address, size }`);
179
173
  const size = (spec as { size?: unknown }).size ?? 1;
@@ -196,13 +190,7 @@ export function readRecordFile(path: string): RecordFile {
196
190
  const fail = (message: string): never => {
197
191
  throw new Refusal("invalid-input", `record file ${path}: ${message}`);
198
192
  };
199
- let value: unknown;
200
- try {
201
- value = JSON.parse(readProjectFile(path).bytes.toString("utf8"));
202
- } catch (error) {
203
- if (isRefusal(error)) throw error;
204
- return fail((error as Error).message);
205
- }
193
+ const value = readProjectJson(path, (message) => `record file ${path}: ${message}`);
206
194
  if (!isObject(value)) return fail("it must be a JSON object");
207
195
  const known = ["name", "program", "symbols", "load", "checkpoint", "state", "pin", "inputs", "coverage", "steps"];
208
196
  for (const key of Object.keys(value)) if (!known.includes(key)) fail(`it has the key ${key}; a record file has ${known.join(", ")}`);
@@ -247,7 +235,7 @@ function addressTarget(step: ActionStep | RestoreAction): Location[] {
247
235
  /** Starts the counts of the replay core at the addresses. */
248
236
  async function countAt(core: C64RunSession, addresses: number[]): Promise<void> {
249
237
  const unique = [...new Set(addresses)];
250
- if (unique.length > 0) await core.command(`count-pc ${unique.map(hex).join(",")}`);
238
+ if (unique.length > 0) await core.command(`count-pc ${unique.map(hexWord).join(",")}`);
251
239
  }
252
240
 
253
241
  /** 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. */
@@ -268,13 +256,7 @@ function checkCoreStep(step: ActionStep, at: string, fail: (message: string) =>
268
256
  /** Reads and checks recording.json of a recording folder. */
269
257
  export function readRecording(folder: string): Recording {
270
258
  const path = `${folder}/${RECORDING_FILES.recording}`;
271
- let value: unknown;
272
- try {
273
- value = JSON.parse(readProjectFile(path).bytes.toString("utf8"));
274
- } catch (error) {
275
- if (isRefusal(error)) throw error;
276
- throw new Refusal("invalid-input", `recording ${path}: ${(error as Error).message}`);
277
- }
259
+ const value = readProjectJson(path, (message) => `recording ${path}: ${message}`);
278
260
  const fail = (message: string): never => {
279
261
  throw new Refusal("invalid-input", `recording ${path}: ${message}`);
280
262
  };
@@ -282,8 +264,8 @@ export function readRecording(folder: string): Recording {
282
264
  for (const key of ["name", "program", "sha256", "symbols", "hash"]) if (typeof value[key] !== "string") fail(`${key} is missing`);
283
265
  for (const key of ["inputs", "events", "sites"]) if (!Array.isArray(value[key])) fail(`${key} is missing`);
284
266
  if (!isInteger(value.ticks, 1, Number.MAX_SAFE_INTEGER)) fail("ticks is missing");
285
- // A recording of an older version can have the step forms of the 2.0 files: refused with the form to write, never replayed wrong.
286
- const remedy = "Record the session again with record, or write the 2.1 form in recording.json";
267
+ // A recording that does not check is refused, never replayed wrong.
268
+ const remedy = "Record the session again with record";
287
269
  if (value.compare !== undefined) {
288
270
  const compare = isObject(value.compare) ? value.compare : fail("compare must be an object with checkpoint, state and pin");
289
271
  const where = (message: string): never => fail(`compare: ${message}. ${remedy}`);
@@ -300,10 +282,6 @@ export function readRecording(folder: string): Recording {
300
282
  // The action with the defaults filled in, as the record file gave it.
301
283
  const action = checkActionStep(stepKind(event.action, ACTION_STEP_KINDS, named, where), event.action, named, where);
302
284
  event.action = action;
303
- // Before 2.6.0-rc.16, a runUntil to an address had the point of another event: a replay cannot find its target again.
304
- if ("runUntil" in action && action.runUntil.target.kind === "address" && !("pc" in event.key)) {
305
- fail(`${named}: a runUntil step to an address has a point of an older version, which a replay cannot find. Record the session again with record`);
306
- }
307
285
  });
308
286
  return value as unknown as Recording;
309
287
  }
@@ -385,9 +363,9 @@ export interface EntryPoint {
385
363
  async function passStartScreen(core: C64RunSession, own: Map<string, number>, limit: number): Promise<number | string | undefined> {
386
364
  const labels = startScreenLabels(own);
387
365
  if (labels === undefined) return undefined;
388
- const reached = await core.status(`run-pc ${hex(labels.wait)} ${limit}`);
366
+ const reached = await core.status(`run-pc ${hexWord(labels.wait)} ${limit}`);
389
367
  if (reached.word !== "reached") return `the rebuild did not come to the wait of its start screen at ${formatC64Address(labels.wait)}`;
390
- await core.status(`goto ${hex(labels.continue)}`);
368
+ await core.status(`goto ${hexWord(labels.continue)}`);
391
369
  return reached.tick;
392
370
  }
393
371
 
@@ -395,15 +373,15 @@ async function passStartScreen(core: C64RunSession, own: Map<string, number>, li
395
373
  * The entry that the generated loader of a rebuild jumps to: the operand of its jump, from a short run of the
396
374
  * rebuild. Gives a problem when the rebuild does not come to the jump.
397
375
  */
398
- export async function loaderEntry(core: C64RunSession, recording: Recording, subject: ReplaySubject): Promise<number | string> {
399
- const own = namesOf(subject.symbols);
376
+ export async function loaderEntry(core: C64RunSession, recording: Recording, subject: ReplaySubject, names: typeof namesOf): Promise<number | string> {
377
+ const own = names(subject.symbols);
400
378
  const jump = own.get(LOADER_JUMP)!;
401
379
  const limit = recording.ticks * REBUILD_TIME_FACTOR;
402
380
  await core.init();
403
381
  await startProgram(core, readProjectFile(subject.program).bytes, false);
404
382
  const screen = await passStartScreen(core, own, limit);
405
383
  if (typeof screen === "string") return screen;
406
- if ((await core.status(`run-pc ${hex(jump)} ${limit}`)).word !== "reached") return `the rebuild did not come to the jump of its loader at ${formatC64Address(jump)}`;
384
+ if ((await core.status(`run-pc ${hexWord(jump)} ${limit}`)).word !== "reached") return `the rebuild did not come to the jump of its loader at ${formatC64Address(jump)}`;
407
385
  const operand = await core.peek((jump + 1) & 0xffff, 2);
408
386
  return operand[0]! | (operand[1]! << 8);
409
387
  }
@@ -444,7 +422,7 @@ function busiestSite(answer: string): { site: number; addr: number; count: numbe
444
422
  async function runToKey(core: C64RunSession, key: RecordedEvent["key"], until: number, map: Map<number, number>, skipped: number, at: SideAddresses): Promise<"reached" | "not-reached" | "halted"> {
445
423
  if ("previous" in key) return (await core.status("status")).word === "halted" ? "halted" : "reached";
446
424
  if ("pc" in key) {
447
- const status = await core.status(`run-pc ${hex(at.code(key.pc))} ${until} ${key.count}`);
425
+ const status = await core.status(`run-pc ${hexWord(at.code(key.pc))} ${until} ${key.count}`);
448
426
  return status.word === "halted" ? "halted" : status.word === "reached" ? "reached" : "not-reached";
449
427
  }
450
428
  if ("tick" in key) {
@@ -452,11 +430,10 @@ async function runToKey(core: C64RunSession, key: RecordedEvent["key"], until: n
452
430
  return status.word === "halted" ? "halted" : "reached";
453
431
  }
454
432
  const site = parseC64Address(key.site);
455
- const status = await core.status(`run-reads ${hex(map.get(site) ?? site)} ${hex(parseC64Address(key.addr))} ${key.count} ${until}`);
433
+ const status = await core.status(`run-reads ${hexWord(map.get(site) ?? site)} ${hexWord(parseC64Address(key.addr))} ${key.count} ${until}`);
456
434
  return status.word === "halted" ? "halted" : status.word === "reached" ? "reached" : "not-reached";
457
435
  }
458
436
 
459
- /** Does a step that is not input. Gives a reason when a runUntil does not reach its target. */
460
437
  /** The status flags in the order of the P register, bit 7 to bit 0; bit 5 is always 1. */
461
438
  const FLAG_BITS: Record<string, number> = { n: 0x80, v: 0x40, b: 0x10, d: 0x08, i: 0x04, z: 0x02, c: 0x01 };
462
439
 
@@ -470,6 +447,7 @@ const COMPARE: Record<string, (value: number, wanted: number) => boolean> = {
470
447
  gte: (value, wanted) => value >= wanted,
471
448
  };
472
449
 
450
+ /** Does a step that is not input. Gives a reason when a runUntil does not reach its target. */
473
451
  async function doAction(core: C64RunSession, step: ActionStep | RestoreAction, at: SideAddresses): Promise<string | undefined> {
474
452
  if ("restore" in step) {
475
453
  // The NMI line is low while RESTORE is down: hold it as a press step holds a key.
@@ -493,7 +471,7 @@ async function doAction(core: C64RunSession, step: ActionStep | RestoreAction, a
493
471
  for (const [name, set] of Object.entries(flags ?? {})) if (set !== undefined) p = set ? p | FLAG_BITS[name]! : p & ~FLAG_BITS[name]!;
494
472
  const values = [step.registers.a ?? now.a, step.registers.x ?? now.x, step.registers.y ?? now.y, step.registers.sp ?? now.s, p].map((n) => n.toString(16));
495
473
  await core.status(`regs ${values.join(" ")}`);
496
- if (pc !== undefined) await core.status(`goto ${hex(at.code(pc))}`);
474
+ if (pc !== undefined) await core.status(`goto ${hexWord(at.code(pc))}`);
497
475
  } else if ("runUntil" in step) {
498
476
  const { target, timeoutFrames } = step.runUntil;
499
477
  const start = (await core.status("status")).tick;
@@ -506,14 +484,14 @@ async function doAction(core: C64RunSession, step: ActionStep | RestoreAction, a
506
484
  }
507
485
  }
508
486
  if (target.kind !== "address") return "a recording has no raster target";
509
- const reached = await core.status(`run-pc ${hex(at.code(target.address))} ${until}`);
487
+ const reached = await core.status(`run-pc ${hexWord(at.code(target.address))} ${until}`);
510
488
  if (reached.word !== "reached") return `the program did not reach ${target.address} within ${timeoutFrames} frames`;
511
489
  }
512
490
  return undefined;
513
491
  }
514
492
 
515
493
  function rangesArgument(state: StateItem[], at: SideAddresses): string {
516
- return state.map((item) => `${hex(at.data(item.address))}:${item.size}`).join(",");
494
+ return state.map((item) => `${hexWord(at.data(item.address))}:${item.size}`).join(",");
517
495
  }
518
496
 
519
497
  export interface RecordOutcome {
@@ -554,9 +532,9 @@ export async function record(
554
532
  await core.command(`inputs ${inputsArgument(file.inputs)}`);
555
533
  await core.command(`record ${reads}`);
556
534
  await countAt(core, targets);
557
- await startProgram(core, prg, file.load ?? false);
535
+ await startProgram(core, prg, file.load);
558
536
  // From READY on: the start of the C64 itself is never in the map.
559
- await core.command(COVERAGE_COMMANDS.get(file.coverage) ?? `coverage on-pc ${hex(parseC64Address(file.coverage))}`);
537
+ await core.command(COVERAGE_COMMANDS.get(file.coverage) ?? `coverage on-pc ${hexWord(parseC64Address(file.coverage))}`);
560
538
  const events: RecordedEvent[] = [];
561
539
  const masks = [0, 0];
562
540
  let reason: string | undefined;
@@ -568,7 +546,7 @@ export async function record(
568
546
  if ("runUntil" in action && action.runUntil.target.kind === "address") {
569
547
  // The next opcode fetch at the target: its count from the start is the point, on each replay.
570
548
  const { address } = action.runUntil.target;
571
- const pc = hex(at.code(address));
549
+ const pc = hexWord(at.code(address));
572
550
  const count = Number(/count=(\d+)/.exec(await core.command(`hits ${pc}`))![1]) + 1;
573
551
  const reached = await core.status(`run-pc ${pc} ${tick + action.runUntil.timeoutFrames * PAL_FRAME_CYCLES} ${count}`);
574
552
  if (reached.word !== "reached") return `the program did not reach ${address} within ${action.runUntil.timeoutFrames} frames`;
@@ -642,9 +620,9 @@ export async function record(
642
620
  format: RECORDING_FORMAT,
643
621
  name: file.name,
644
622
  program: file.program,
645
- sha256: createHash("sha256").update(prg).digest("hex"),
623
+ sha256: sha256(prg),
646
624
  symbols: file.symbols,
647
- load: file.load ?? false,
625
+ load: file.load,
648
626
  ...(file.compare === undefined ? {} : { compare: file.compare }),
649
627
  inputs: file.inputs,
650
628
  events,
@@ -699,25 +677,26 @@ export async function replaySide(
699
677
  folder: string,
700
678
  subject: ReplaySubject,
701
679
  workspace: Workspace,
680
+ names: typeof namesOf,
702
681
  options: { compare?: Comparison; stop?: number; dump?: number; pins?: string[]; entry?: number; handover?: { entry: number; reference: EntryPoint } } = {},
703
682
  ): Promise<SideRun & { ram?: Uint8Array }> {
704
683
  const prg = readProjectFile(subject.program).bytes;
705
684
  const reference = subject.side === "reference";
706
685
  // The names of the reference: a recording without names takes those of the knowledge.
707
- const names = recording.symbols === "none" ? "knowledge" : recording.symbols;
686
+ const referenceSymbols = recording.symbols === "none" ? "knowledge" : recording.symbols;
708
687
  const same = (address: number) => address;
709
688
  const move = reference
710
689
  ? { code: same, data: same }
711
- : { code: mover(namesOf(names, "code"), namesOf(subject.symbols, "code")), data: mover(namesOf(names), namesOf(subject.symbols)) };
712
- const own = namesOf(subject.symbols);
690
+ : { code: mover(names(referenceSymbols, "code"), names(subject.symbols, "code")), data: mover(names(referenceSymbols), names(subject.symbols)) };
691
+ const own = names(subject.symbols);
713
692
  const at = sideAddresses(own, subject.side, move);
714
- const moved = reference ? [] : siteMap(recording.sites, namesOf(names, "code"), namesOf(subject.symbols, "code"));
693
+ const moved = reference ? [] : siteMap(recording.sites, names(referenceSymbols, "code"), names(subject.symbols, "code"));
715
694
  const map = new Map(moved);
716
695
  const reads = workspace.path(`${subject.side}-${RECORDING_FILES.reads}`);
717
696
  writeFileSync(reads, readProjectFile(`${folder}/${RECORDING_FILES.reads}`).bytes);
718
697
  const samples = workspace.path(`${subject.side}-checkpoints.txt`);
719
698
  const mapFile = workspace.path(`${subject.side}-sites.map`);
720
- writeFileSync(mapFile, moved.map(([from, to]) => `${hex(from)} ${hex(to)}\n`).join(""));
699
+ writeFileSync(mapFile, moved.map(([from, to]) => `${hexWord(from)} ${hexWord(to)}\n`).join(""));
721
700
  await core.init();
722
701
  await core.command(`inputs ${inputsArgument(recording.inputs)}`);
723
702
  await core.command(`site-map ${mapFile}`);
@@ -733,14 +712,14 @@ export async function replaySide(
733
712
  await core.command(`pin ${pinFile} ${rangesArgument(pinned, at)}`);
734
713
  }
735
714
  // The samples hold the state, then the pinned items.
736
- await core.command(`sample ${hex(at.code(compare.checkpoint))} ${samples} ${rangesArgument([...compare.state, ...pinned], at)}${stop > 0 ? ` ${stop}` : ""}`);
715
+ await core.command(`sample ${hexWord(at.code(compare.checkpoint))} ${samples} ${rangesArgument([...compare.state, ...pinned], at)}${stop > 0 ? ` ${stop}` : ""}`);
737
716
  sampling = true;
738
717
  };
739
718
  // A rebuild with a loader takes its checkpoints from its entry on, as the reference leaves out those before its own.
740
719
  if (options.compare !== undefined && options.handover === undefined) await startSampling(options.compare);
741
720
  const targets = recording.events.flatMap((event) => ("pc" in event.key ? [at.code(event.key.pc)] : []));
742
721
  await countAt(core, targets);
743
- if (options.entry !== undefined) await core.command(`mark ${hex(options.entry)}`);
722
+ if (options.entry !== undefined) await core.command(`mark ${hexWord(options.entry)}`);
744
723
  await startProgram(core, prg, recording.load);
745
724
  const base = reference ? recording.ticks : recording.ticks * REBUILD_TIME_FACTOR;
746
725
  let limit = base;
@@ -763,10 +742,10 @@ export async function replaySide(
763
742
  const { handover } = options;
764
743
  if (problem === undefined && handover !== undefined) {
765
744
  const jump = own.get(LOADER_JUMP)!;
766
- if ((await core.status(`run-pc ${hex(jump)} ${limit}`)).word !== "reached") problem = `the rebuild did not come to the jump of its loader at ${formatC64Address(jump)}`;
745
+ if ((await core.status(`run-pc ${hexWord(jump)} ${limit}`)).word !== "reached") problem = `the rebuild did not come to the jump of its loader at ${formatC64Address(jump)}`;
767
746
  else {
768
747
  await countAt(core, targets);
769
- const reached = await core.status(`run-pc ${hex(handover.entry)} ${limit}`);
748
+ const reached = await core.status(`run-pc ${hexWord(handover.entry)} ${limit}`);
770
749
  if (reached.word !== "reached") problem = `the rebuild did not come to its entry at ${formatC64Address(handover.entry)}`;
771
750
  else {
772
751
  // The loader sets the entry state of the capture, but the phase of the frame and of the CIA timers at the entry
@@ -830,7 +809,7 @@ export async function replaySide(
830
809
  const counts = new Map<string, number>();
831
810
  for (const event of recording.events) {
832
811
  if (!("pc" in event.key) || counts.has(event.key.pc)) continue;
833
- const before = /marked=(\d+)/.exec(await core.command(`hits ${hex(at.code(event.key.pc))}`));
812
+ const before = /marked=(\d+)/.exec(await core.command(`hits ${hexWord(at.code(event.key.pc))}`));
834
813
  if (before !== null) counts.set(event.key.pc, Number(before[1]));
835
814
  }
836
815
  // A checkpoint at the first fetch at the entry has the tick of the mark. The rebuild starts its checkpoints after that fetch.
@@ -891,6 +870,8 @@ export interface ReplayResult {
891
870
  compared: number;
892
871
  reason?: string;
893
872
  firstDifference?: CheckpointDifference;
873
+ /** The names of the rebuild: a symbol file, or knowledge. */
874
+ symbols?: string;
894
875
  movedSites?: number;
895
876
  /** Input reads of the rebuild that the recording had no value for: they got the idle value. */
896
877
  idleReads?: number;
@@ -942,7 +923,7 @@ export function showRecording(folder: string, max: number): RecordingSummary {
942
923
  changes.set(key, (changes.get(key) ?? 0) + 1);
943
924
  }
944
925
  const sites = recording.sites
945
- .map((site): InputSite => ({ site: site.site, address: site.addr, reads: site.reads, changes: changes.get(`${hex(parseC64Address(site.site))} ${hex(parseC64Address(site.addr))}`) ?? 0 }))
926
+ .map((site): InputSite => ({ site: site.site, address: site.addr, reads: site.reads, changes: changes.get(`${hexWord(parseC64Address(site.site))} ${hexWord(parseC64Address(site.addr))}`) ?? 0 }))
946
927
  .sort((a, b) => parseC64Address(a.site) - parseC64Address(b.site) || parseC64Address(a.address) - parseC64Address(b.address));
947
928
  const map = readProjectFile(`${folder}/${RECORDING_FILES.coverage}`).bytes;
948
929
  const count = (bit: number) => map.reduce((total, byte) => total + ((byte & bit) === 0 ? 0 : 1), 0);
@@ -4,20 +4,23 @@
4
4
  // each checkpoint with the reference's. --checkpoint and --state choose the
5
5
  // comparison, else the record file gave it.
6
6
 
7
- import { createHash } from "node:crypto";
7
+ import { existsSync } from "node:fs";
8
8
 
9
+ import { symbolsPath } from "#src/build-name.ts";
9
10
  import { isRefusal, Refusal } from "#src/errors.ts";
10
11
  import { readPrg } from "#src/host-client/image.ts";
11
12
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
12
13
  import { formatC64Address } from "#src/c64.ts";
13
14
  import { encodePng } from "#src/graphics.ts";
14
15
  import { LOADER_JUMP } from "#src/knowledge/start-screen.ts";
16
+ import { sha256 } from "#src/knowledge/text.ts";
15
17
  import { C64RunSession } from "#src/native/c64run.ts";
16
18
  import { localToolContext } from "#src/native/local.ts";
17
19
  import { Workspace } from "#src/native/staging.ts";
20
+ import { resolveProjectPath } from "#src/project.ts";
18
21
  import { UsageError } from "#src/script.ts";
19
22
  import { firstDifference, loaderEntry, mover, parseStateItem, pinLines, readRecording, replaySide, siteMap, type Comparison, type ReplayResult, type ReplaySubject } from "./recording.ts";
20
- import { namesOf } from "./scenario.ts";
23
+ import { cachedNames } from "./scenario.ts";
21
24
 
22
25
  const MAX_STATE_ITEMS = 16;
23
26
 
@@ -33,6 +36,46 @@ export interface ReplayOptions {
33
36
  screen?: string;
34
37
  }
35
38
 
39
+ /**
40
+ * The names of the rebuild: the given symbol file, else the symbol file of its build when the build wrote one,
41
+ * else the names of the reference. The labels of a loader and of a start screen are only in the build's own file.
42
+ */
43
+ export function rebuildNames(rebuild: string, symbols: string | undefined, reference: string): string {
44
+ if (symbols !== undefined) return symbols;
45
+ const own = symbolsPath(rebuild);
46
+ return existsSync(resolveProjectPath(own)) ? own : reference;
47
+ }
48
+
49
+ /** The replay of several recordings: FAIL when one failed, else INCONCLUSIVE when one could not compare, else PASS. */
50
+ export interface ReplayAll {
51
+ result: ReplayResult["result"];
52
+ passed: number;
53
+ failed: number;
54
+ inconclusive: number;
55
+ recordings: ReplayResult[];
56
+ }
57
+
58
+ /**
59
+ * Replays each recording in turn with the same options: replays at the same time share the processor and can go past the
60
+ * time limit of the core. --out gets a folder for each recording, by the name of its folder. A recording that the script
61
+ * refuses is INCONCLUSIVE with the refusal as its reason; a missing tool stops all.
62
+ */
63
+ export async function replayAll(folders: readonly string[], values: Omit<ReplayOptions, "folder" | "screen">, one: (values: ReplayOptions) => Promise<ReplayResult> = replay): Promise<ReplayAll> {
64
+ const recordings: ReplayResult[] = [];
65
+ for (const folder of folders) {
66
+ const name = folder.replace(/\/+$/, "").split("/").at(-1)!;
67
+ try {
68
+ recordings.push(await one({ ...values, folder, ...(values.out === undefined ? {} : { out: `${values.out}/${name}` }) }));
69
+ } catch (error) {
70
+ if (!isRefusal(error) || error.code === "installation-incomplete") throw error;
71
+ recordings.push({ result: "INCONCLUSIVE", recording: folder, side: values.rebuild === undefined ? "reference" : "rebuild", checkpoints: 0, compared: 0, reason: error.message });
72
+ }
73
+ }
74
+ const count = (outcome: ReplayResult["result"]) => recordings.filter((item) => item.result === outcome).length;
75
+ const [passed, failed, inconclusive] = [count("PASS"), count("FAIL"), count("INCONCLUSIVE")];
76
+ return { result: failed > 0 ? "FAIL" : inconclusive > 0 ? "INCONCLUSIVE" : "PASS", passed, failed, inconclusive, recordings };
77
+ }
78
+
36
79
  /** Replays the recording on the reference, and with `rebuild` on the rebuild: PASS, FAIL or INCONCLUSIVE. */
37
80
  export async function replay(values: ReplayOptions): Promise<ReplayResult> {
38
81
  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.");
@@ -41,6 +84,7 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
41
84
  if (values.pin.length > 0 && values.checkpoint === undefined) throw new UsageError("--pin needs --checkpoint and --state. Give them too, or leave out --pin.");
42
85
  const folder = values.folder.replace(/\/+$/, "").replace(/\/recording\.json$/, "");
43
86
  const recording = readRecording(folder);
87
+ const namesOf = cachedNames();
44
88
  const given: Comparison | undefined =
45
89
  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")) }) };
46
90
  const compare = given ?? recording.compare;
@@ -65,8 +109,7 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
65
109
  throw error;
66
110
  }
67
111
  }
68
- const sha256 = createHash("sha256").update(readProjectFile(recording.program).bytes).digest("hex");
69
- if (sha256 !== recording.sha256) return result("INCONCLUSIVE", "reference", { reason: `${recording.program} is not the program of the recording (its SHA-256 changed); record the session again` });
112
+ if (sha256(readProjectFile(recording.program).bytes) !== recording.sha256) return result("INCONCLUSIVE", "reference", { reason: `${recording.program} is not the program of the recording (its SHA-256 changed); record the session again` });
70
113
 
71
114
  const context = localToolContext();
72
115
  const core = await C64RunSession.open(context);
@@ -75,8 +118,9 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
75
118
  // A recording made without names takes the names that the knowledge has now.
76
119
  const referenceSymbols = recording.symbols === "none" ? "knowledge" : recording.symbols;
77
120
  const reference: ReplaySubject = { side: "reference", program: recording.program, symbols: referenceSymbols };
78
- const side = (subject: ReplaySubject, options: Parameters<typeof replaySide>[5]) => replaySide(core, recording, folder, subject, workspace, options);
79
- const rebuildSymbols = values.symbols ?? referenceSymbols;
121
+ const side = (subject: ReplaySubject, options: Parameters<typeof replaySide>[6]) => replaySide(core, recording, folder, subject, workspace, namesOf, options);
122
+ const rebuildSymbols = values.rebuild === undefined ? referenceSymbols : rebuildNames(values.rebuild, values.symbols, referenceSymbols);
123
+ const named = { symbols: rebuildSymbols };
80
124
  // A rebuild with a generated loader starts the program where its loader jumps to. The reference comes to that entry by the same name.
81
125
  // The checkpoints of both sides count from that entry, and at the entry the rebuild gets the raster position, the CIA timers and
82
126
  // the interrupt state of the reference, which the loader cannot set as the reference has them. A runUntil to an address counts
@@ -84,8 +128,8 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
84
128
  // the rebuild, and the result is INCONCLUSIVE.
85
129
  let loader: { entry: number; reference: number } | undefined;
86
130
  if (values.rebuild !== undefined && !recording.load && namesOf(rebuildSymbols).has(LOADER_JUMP)) {
87
- const entry = await loaderEntry(core, recording, { side: "rebuild", program: values.rebuild, symbols: rebuildSymbols });
88
- if (typeof entry === "string") return result("FAIL", "rebuild", { reason: entry });
131
+ const entry = await loaderEntry(core, recording, { side: "rebuild", program: values.rebuild, symbols: rebuildSymbols }, namesOf);
132
+ if (typeof entry === "string") return result("FAIL", "rebuild", { ...named, reason: entry });
89
133
  loader = { entry, reference: mover(namesOf(rebuildSymbols, "code"), namesOf(referenceSymbols, "code"))(entry) };
90
134
  }
91
135
  // The self-check: the reference ends the session with the recorded state, to the cycle.
@@ -130,7 +174,7 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
130
174
  const replayed = await side(rebuild, { compare: compare!, stop: expected.length, pins, ...(handover === undefined ? {} : { handover }) });
131
175
  const difference = firstDifference(expected, replayed.samples, compare!.state);
132
176
  // A read that the recording has no value for gets the idle value: it is in the result, never silent.
133
- const base = { checkpoints: expected.length, movedSites, ...(replayed.startScreenSkipped === true ? { startScreen: "skipped" } : {}), ...(replayed.unknown > 0 ? { idleReads: replayed.unknown } : {}) };
177
+ const base = { checkpoints: expected.length, ...named, movedSites, ...(replayed.startScreenSkipped === true ? { startScreen: "skipped" } : {}), ...(replayed.unknown > 0 ? { idleReads: replayed.unknown } : {}) };
134
178
  if (difference === undefined && replayed.samples.length >= expected.length) return result("PASS", "rebuild", { ...base, compared: expected.length });
135
179
  const reason =
136
180
  difference !== undefined