@henols/c64-re-tools 2.6.0-rc.8 → 2.6.0

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 (82) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-assembler/SKILL.md +3 -3
  3. package/skills/c64-assembler/scripts/assembler.ts +4 -3
  4. package/skills/c64-development/SKILL.md +3 -3
  5. package/skills/c64-docs/SKILL.md +6 -4
  6. package/skills/c64-docs/scripts/docs.ts +23 -10
  7. package/skills/c64-docs/scripts/lib/reference.ts +117 -31
  8. package/skills/c64-docs/scripts/lib/source-map.ts +14 -0
  9. package/skills/c64-knowledge/SKILL.md +10 -9
  10. package/skills/c64-knowledge/scripts/knowledge.ts +16 -9
  11. package/skills/c64-reverse-engineering/SKILL.md +9 -3
  12. package/skills/c64-source/SKILL.md +13 -10
  13. package/skills/c64-source/scripts/lib/export.ts +13 -2
  14. package/skills/c64-source/scripts/lib/loader.ts +51 -28
  15. package/skills/c64-source/scripts/lib/source.ts +24 -7
  16. package/skills/c64-source/scripts/source.ts +65 -47
  17. package/skills/c64-static-analysis/SKILL.md +26 -22
  18. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  19. package/skills/c64-static-analysis/scripts/lib/instructions.ts +4 -4
  20. package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
  21. package/skills/c64-static-analysis/scripts/static-analysis.ts +51 -35
  22. package/skills/c64-testing/SKILL.md +11 -4
  23. package/skills/c64-testing/references/recording-format.md +19 -7
  24. package/skills/c64-testing/references/scenario-format.md +6 -5
  25. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  26. package/skills/c64-testing/scripts/lib/play.ts +39 -37
  27. package/skills/c64-testing/scripts/lib/recording.ts +213 -65
  28. package/skills/c64-testing/scripts/lib/replay.ts +31 -5
  29. package/skills/c64-testing/scripts/lib/runs.ts +8 -3
  30. package/skills/c64-testing/scripts/lib/scenario.ts +4 -6
  31. package/skills/c64-testing/scripts/testing.ts +23 -2
  32. package/skills/c64-unpacker/SKILL.md +6 -3
  33. package/skills/c64-unpacker/scripts/lib/loads.ts +2 -2
  34. package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
  35. package/skills/c64-unpacker/scripts/unpacker.ts +38 -6
  36. package/skills/emulator/SKILL.md +2 -5
  37. package/src/build-name.ts +9 -4
  38. package/src/c64-keys.ts +98 -0
  39. package/src/c64.ts +1 -1
  40. package/src/host/main.ts +2 -2
  41. package/src/host/server.ts +3 -1
  42. package/src/host/tools/index.ts +1 -1
  43. package/src/host/vice/process.ts +34 -17
  44. package/src/host/vice/session.ts +132 -30
  45. package/src/host-client/steps.ts +21 -18
  46. package/src/host-client/tools.ts +1 -1
  47. package/src/host-client/vice-session.ts +7 -1
  48. package/src/knowledge/evidence.ts +66 -0
  49. package/src/knowledge/history.ts +5 -5
  50. package/src/knowledge/import.ts +12 -5
  51. package/src/knowledge/program.ts +81 -33
  52. package/src/knowledge/read.ts +12 -3
  53. package/src/knowledge/schema.ts +7 -7
  54. package/src/knowledge/start-screen.ts +2 -0
  55. package/src/knowledge/text.ts +28 -3
  56. package/src/knowledge/write.ts +6 -6
  57. package/src/mcp/inputs.ts +12 -0
  58. package/src/mcp/server.ts +1 -0
  59. package/src/mcp/tools/debug.ts +23 -21
  60. package/src/mcp/tools/input.ts +38 -5
  61. package/src/mcp/tools/memory.ts +12 -9
  62. package/src/native/c64run.ts +7 -4
  63. package/src/native/{ghidra → decompiler}/analyze.ts +17 -17
  64. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  65. package/src/native/{ghidra → decompiler}/walk.ts +6 -6
  66. package/src/native/discover.ts +3 -3
  67. package/src/native/processes.ts +3 -3
  68. package/src/native/types.ts +25 -25
  69. package/src/opcodes.ts +1 -1
  70. package/src/protocol/vice.ts +47 -0
  71. package/src/reference-pages.ts +64 -0
  72. package/src/script.ts +1 -1
  73. package/src/vsf.ts +98 -0
  74. package/tools/c64run.c +158 -15
  75. package/skills/c64-testing/scripts/lib/keys.ts +0 -36
  76. /package/src/native/{ghidra → decompiler}/c64rt-wasm.ts +0 -0
  77. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  78. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  79. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
  80. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.sla +0 -0
  81. /package/src/native/{ghidra → decompiler}/pcode.ts +0 -0
  82. /package/src/native/{ghidra → decompiler}/wasm.ts +0 -0
@@ -13,13 +13,13 @@ import { readFileSync, writeFileSync } from "node:fs";
13
13
 
14
14
  import { isRefusal, Refusal } from "#src/errors.ts";
15
15
  import { c64AddressOf, formatC64Address, parseC64Address } from "#src/c64.ts";
16
+ import { keyTaps, type KeyTap } from "#src/c64-keys.ts";
16
17
  import { READY_FRAMES } from "#src/host-client/entry-state.ts";
17
18
  import { ACTION_STEP_KINDS, checkActionStep, isInteger, isObject, keyboardBytes, renamedField, stepKind, type ActionStep, type Location } from "#src/host-client/steps.ts";
18
19
  import { readProjectFile, type Written } from "#src/host-client/transfer.ts";
19
- import { START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
20
+ import { LOADER_JUMP, START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
20
21
  import { PAL_FRAME_CYCLES, type C64RunSession, type CoreStatus } from "#src/native/c64run.ts";
21
22
  import type { Workspace } from "#src/native/staging.ts";
22
- import { NAMED_KEYS } from "./keys.ts";
23
23
  import { namesOf, type Outcome } from "./scenario.ts";
24
24
 
25
25
  export const RECORDING_FORMAT = 1;
@@ -39,6 +39,10 @@ export function inputsArgument(inputs: string[]): string {
39
39
  /** Frames that a pressed key is held, and then released. */
40
40
  const KEY_FRAMES = 3;
41
41
  const MAX_STATE_ITEMS = 16;
42
+ /** The replay core counts the opcode fetches at this many addresses at most: the targets of the runUntil steps to an address. */
43
+ const MAX_COUNTED_TARGETS = 64;
44
+ /** An event other than a runUntil to an address waits this long for the next input read. */
45
+ const READ_WAIT_FRAMES = 600;
42
46
  const MAX_STATE_BYTES = 4096;
43
47
  /** A replay of a rebuild may take this many times the cycles of the recording before it stops. */
44
48
  const REBUILD_TIME_FACTOR = 2;
@@ -99,9 +103,11 @@ export interface RecordedEvent {
99
103
  /**
100
104
  * The point: the n-th read at the busiest program site, or a tick when no
101
105
  * program site has read yet. An event that follows another event directly
102
- * has { previous: true }: it runs where that one ended.
106
+ * has { previous: true }: it runs where that one ended. A runUntil to an
107
+ * address has { pc, count }: the count-th opcode fetch at its target from the
108
+ * start, which needs no read; the event is done when the point is reached.
103
109
  */
104
- key: { site: Location; addr: Location; count: number } | { tick: number } | { previous: true };
110
+ key: { site: Location; addr: Location; count: number } | { tick: number } | { previous: true } | { pc: Location; count: number };
105
111
  }
106
112
 
107
113
  export interface RecordedSite {
@@ -139,28 +145,8 @@ const QUEUE_SIZE = 10;
139
145
 
140
146
  const hex = (address: number) => address.toString(16).padStart(4, "0");
141
147
 
142
- /** The keys of the replay core for the characters that a press step can have. */
143
- const KEY_CODES = new Map<string, number>([
144
- ...[..."ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 +-.:@,*;=/!\"#$%&'()[]<>?"].map((character) => [character, character.charCodeAt(0)] as [string, number]),
145
- ["\n", 0x0d],
146
- ]);
147
-
148
- /**
149
- * The key codes of a text; a-z type as A-Z, as the C64 shows them after
150
- * power-on. A key without a character has its name in braces, for example {F1}.
151
- */
152
- export function keyCodes(text: string): number[] {
153
- return (text.replace(/\r\n?/g, "\n").match(/\{[^{}]*\}|[^]/g) ?? []).map((part) => {
154
- if (part.length > 1) {
155
- const named = NAMED_KEYS[part.slice(1, -1).toUpperCase()];
156
- if (named === undefined) throw new Refusal("invalid-input", `press has no key ${part}. The keys in braces are ${Object.keys(NAMED_KEYS).map((name) => `{${name}}`).join(", ")}`);
157
- return named;
158
- }
159
- const code = KEY_CODES.get(part.toUpperCase());
160
- if (code === undefined) throw new Refusal("invalid-input", `press cannot press ${JSON.stringify(part)} on the C64 keyboard`);
161
- return code;
162
- });
163
- }
148
+ /** The key code of the replay core for a matrix place: 80 + the place. RESTORE is ff. */
149
+ const coreKey = (place: number) => (0x80 + place).toString(16);
164
150
 
165
151
  /** The joystick mask of the replay core: 1 up, 2 down, 4 left, 8 right, $10 fire. */
166
152
  export function joystickMask(direction: Extract<ActionStep, { joystick: unknown }>["joystick"]["direction"], fire: boolean): number {
@@ -235,7 +221,7 @@ export function readRecordFile(path: string): RecordFile {
235
221
  if (!Array.isArray(value.steps) || value.steps.length === 0) fail("steps must be a list with at least one step");
236
222
  const steps = (value.steps as unknown[]).map((raw, index) => {
237
223
  const at = `step ${index + 1}`;
238
- const step = checkActionStep(stepKind(raw, ACTION_STEP_KINDS, at, fail), raw as Record<string, unknown>, at, fail, { press: true });
224
+ const step = checkActionStep(stepKind(raw, ACTION_STEP_KINDS, at, fail), raw as Record<string, unknown>, at, fail);
239
225
  checkCoreStep(step, at, fail);
240
226
  return step;
241
227
  });
@@ -251,17 +237,20 @@ export function readRecordFile(path: string): RecordFile {
251
237
  };
252
238
  }
253
239
 
240
+ /** The target of a runUntil step to an address, as a list of none or one. */
241
+ function addressTarget(step: ActionStep | RestoreAction): Location[] {
242
+ return "runUntil" in step && step.runUntil.target.kind === "address" ? [step.runUntil.target.address] : [];
243
+ }
244
+
245
+ /** Starts the counts of the replay core at the addresses. */
246
+ async function countAt(core: C64RunSession, addresses: number[]): Promise<void> {
247
+ const unique = [...new Set(addresses)];
248
+ if (unique.length > 0) await core.command(`count-pc ${unique.map(hex).join(",")}`);
249
+ }
250
+
254
251
  /** 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. */
255
252
  function checkCoreStep(step: ActionStep, at: string, fail: (message: string) => never): void {
256
253
  if ("write" in step && step.write.space !== "c64") fail(`${at}: a recording has the C64 alone, not ${step.write.space}`);
257
- if ("press" in step) {
258
- try {
259
- keyCodes(step.press);
260
- } catch (error) {
261
- if (isRefusal(error)) fail(`${at}: ${error.message}`);
262
- throw error;
263
- }
264
- }
265
254
  if ("type" in step) {
266
255
  const keys = keyboardBytes(step.type);
267
256
  if (typeof keys !== "string" && keys.length > QUEUE_SIZE) fail(`${at}: the KERNAL keyboard queue holds ${QUEUE_SIZE} keys; give more type steps, or press for keys of the keyboard matrix`);
@@ -307,7 +296,12 @@ export function readRecording(folder: string): Recording {
307
296
  const named = typeof event.step === "number" ? `${at} (step ${event.step})` : at;
308
297
  if (event.action.restore === true && Object.keys(event.action).length === 1) return;
309
298
  // The action with the defaults filled in, as the record file gave it.
310
- event.action = checkActionStep(stepKind(event.action, ACTION_STEP_KINDS, named, where), event.action, named, where, { press: true });
299
+ const action = checkActionStep(stepKind(event.action, ACTION_STEP_KINDS, named, where), event.action, named, where);
300
+ event.action = action;
301
+ // Before 2.6.0-rc.16, a runUntil to an address had the point of another event: a replay cannot find its target again.
302
+ if ("runUntil" in action && action.runUntil.target.kind === "address" && !("pc" in event.key)) {
303
+ 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`);
304
+ }
311
305
  });
312
306
  return value as unknown as Recording;
313
307
  }
@@ -364,6 +358,55 @@ export function siteMap(sites: RecordedSite[], from: Map<string, number>, to: Ma
364
358
  return moved;
365
359
  }
366
360
 
361
+ /** Where the original came to the entry that the loader of a rebuild jumps to. */
362
+ export interface EntryPoint {
363
+ /** The tick of the first opcode fetch at the entry. */
364
+ tick: number;
365
+ /**
366
+ * The phase of the machine at that fetch, as the replay core gives it: the beam position, the CIA timers and
367
+ * the interrupt state. It depends on how the program started, so the rebuild gets it at its own entry.
368
+ */
369
+ phase: string;
370
+ /** The count of each pc key, by its target, before that fetch. */
371
+ counts: Map<string, number>;
372
+ /** The number of events of the recording before the entry: always the first ones. */
373
+ eventsBefore: number;
374
+ /** The number of checkpoints before the entry, which the samples of the original leave out. */
375
+ samplesBefore: number;
376
+ }
377
+
378
+ /**
379
+ * A loader with a start screen that RUN starts waits for a key or a fire button that the recording does not have:
380
+ * the rebuild goes on after the wait, as the check of the loader does. Gives the tick of the wait, a problem, or
381
+ * undefined when the rebuild has no start screen.
382
+ */
383
+ async function passStartScreen(core: C64RunSession, own: Map<string, number>, limit: number): Promise<number | string | undefined> {
384
+ const wait = own.get(START_SCREEN_WAIT);
385
+ const resume = own.get(START_SCREEN_CONTINUE);
386
+ if (wait === undefined || resume === undefined) return undefined;
387
+ const reached = await core.status(`run-pc ${hex(wait)} ${limit}`);
388
+ if (reached.word !== "reached") return `the rebuild did not come to the wait of its start screen at ${formatC64Address(wait)}`;
389
+ await core.status(`goto ${hex(resume)}`);
390
+ return reached.tick;
391
+ }
392
+
393
+ /**
394
+ * The entry that the generated loader of a rebuild jumps to: the operand of its jump, from a short run of the
395
+ * rebuild. Gives a problem when the rebuild does not come to the jump.
396
+ */
397
+ export async function loaderEntry(core: C64RunSession, recording: Recording, subject: ReplaySubject): Promise<number | string> {
398
+ const own = namesOf(subject.symbols);
399
+ const jump = own.get(LOADER_JUMP)!;
400
+ const limit = recording.ticks * REBUILD_TIME_FACTOR;
401
+ await core.init();
402
+ await startProgram(core, readProjectFile(subject.program).bytes, false);
403
+ const screen = await passStartScreen(core, own, limit);
404
+ if (typeof screen === "string") return screen;
405
+ 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)}`;
406
+ const operand = await core.peek((jump + 1) & 0xffff, 2);
407
+ return operand[0]! | (operand[1]! << 8);
408
+ }
409
+
367
410
  /** Power-on and READY, then the program in memory as a LOAD leaves it, and RUN in the keyboard queue. */
368
411
  async function startProgram(core: C64RunSession, prg: Uint8Array, load: boolean): Promise<CoreStatus> {
369
412
  if (prg.length < 3) throw new Refusal("invalid-input", "the program is not a PRG file");
@@ -397,8 +440,12 @@ function busiestSite(answer: string): { site: number; addr: number; count: numbe
397
440
  * Runs to the point of an event. `map` moves a site to the rebuild. "halted"
398
441
  * when a sample stop came first, "not-reached" when the point did not come before `until`.
399
442
  */
400
- async function runToKey(core: C64RunSession, key: RecordedEvent["key"], until: number, map: Map<number, number>, skipped: number): Promise<"reached" | "not-reached" | "halted"> {
443
+ async function runToKey(core: C64RunSession, key: RecordedEvent["key"], until: number, map: Map<number, number>, skipped: number, at: SideAddresses): Promise<"reached" | "not-reached" | "halted"> {
401
444
  if ("previous" in key) return (await core.status("status")).word === "halted" ? "halted" : "reached";
445
+ if ("pc" in key) {
446
+ const status = await core.status(`run-pc ${hex(at.code(key.pc))} ${until} ${key.count}`);
447
+ return status.word === "halted" ? "halted" : status.word === "reached" ? "reached" : "not-reached";
448
+ }
402
449
  if ("tick" in key) {
403
450
  const status = await core.status(`run ${key.tick + skipped}`);
404
451
  return status.word === "halted" ? "halted" : "reached";
@@ -497,11 +544,15 @@ export async function record(
497
544
  at.code(file.compare.checkpoint);
498
545
  for (const item of file.compare.state) at.data(item.address);
499
546
  }
547
+ // Two names can give one address: the replay core counts each address once.
548
+ const targets = [...new Set(file.steps.flatMap(addressTarget).map(at.code))];
549
+ if (targets.length > MAX_COUNTED_TARGETS) throw new Refusal("invalid-input", `record file of ${file.name}: the runUntil steps go to more than ${MAX_COUNTED_TARGETS} addresses`);
500
550
  const reads = workspace.path(RECORDING_FILES.reads);
501
551
  const coverage = workspace.path(RECORDING_FILES.coverage);
502
552
  await core.init();
503
553
  await core.command(`inputs ${inputsArgument(file.inputs)}`);
504
554
  await core.command(`record ${reads}`);
555
+ await countAt(core, targets);
505
556
  await startProgram(core, prg, file.load ?? false);
506
557
  // From READY on: the start of the C64 itself is never in the map.
507
558
  await core.command(COVERAGE_COMMANDS.get(file.coverage) ?? `coverage on-pc ${hex(parseC64Address(file.coverage))}`);
@@ -513,13 +564,25 @@ export async function record(
513
564
  // replay. An event right after another event runs where that one ended.
514
565
  const runEvent = async (action: ActionStep | RestoreAction, step?: number): Promise<string | undefined> => {
515
566
  const tick = (await core.status("status")).tick;
567
+ if ("runUntil" in action && action.runUntil.target.kind === "address") {
568
+ // The next opcode fetch at the target: its count from the start is the point, on each replay.
569
+ const { address } = action.runUntil.target;
570
+ const pc = hex(at.code(address));
571
+ const count = Number(/count=(\d+)/.exec(await core.command(`hits ${pc}`))![1]) + 1;
572
+ const reached = await core.status(`run-pc ${pc} ${tick + action.runUntil.timeoutFrames * PAL_FRAME_CYCLES} ${count}`);
573
+ if (reached.word !== "reached") return `the program did not reach ${address} within ${action.runUntil.timeoutFrames} frames`;
574
+ events.push({ ...(step === undefined ? {} : { step }), action, key: { pc: address, count } });
575
+ return undefined;
576
+ }
516
577
  const busiest = afterEvent ? undefined : busiestSite(await core.command("sites"));
517
578
  const key: RecordedEvent["key"] = afterEvent
518
579
  ? { previous: true }
519
580
  : busiest === undefined
520
581
  ? { tick: tick + 1 }
521
582
  : { site: formatC64Address(busiest.site), addr: formatC64Address(busiest.addr), count: busiest.count + 1 };
522
- if ((await runToKey(core, key, tick + 600 * PAL_FRAME_CYCLES, new Map(), 0)) !== "reached") return "the program did not read its input again within 600 frames";
583
+ if ((await runToKey(core, key, tick + READ_WAIT_FRAMES * PAL_FRAME_CYCLES, new Map(), 0, at)) !== "reached") {
584
+ return `the program did not read its input again within ${READ_WAIT_FRAMES} frames. This step runs at the next input read. Put a runUntil step to an address before it: that step needs no input read`;
585
+ }
523
586
  events.push({ ...(step === undefined ? {} : { step }), action, key });
524
587
  return doAction(core, action, at);
525
588
  };
@@ -532,11 +595,22 @@ export async function record(
532
595
  masks[step.joystick.port - 1] = joystickMask(step.joystick.direction, step.joystick.fire ?? false);
533
596
  await core.command(`joy ${masks[0]!.toString(16)} ${masks[1]!.toString(16)}`);
534
597
  } else if ("press" in step) {
535
- for (const code of keyCodes(step.press)) {
536
- await core.command(`key ${code.toString(16)} down`);
537
- await core.status(`run ${(tick += KEY_FRAMES * PAL_FRAME_CYCLES)}`);
538
- await core.command(`key ${code.toString(16)} up`);
539
- await core.status(`run ${(tick += KEY_FRAMES * PAL_FRAME_CYCLES)}`);
598
+ const hold = step.press.frames * PAL_FRAME_CYCLES;
599
+ for (const tap of keyTaps(step.press.keys) as KeyTap[]) {
600
+ for (const place of tap.keys) await core.command(`key ${coreKey(place)} down`);
601
+ // RESTORE is no read: an event at the next read of the program, with the keys of the tap down.
602
+ if (tap.restore) reason = await runEvent({ restore: true }, index + 1);
603
+ if (reason !== undefined) break;
604
+ tick = (await core.status("status")).tick;
605
+ await core.status(`run ${(tick += hold)}`);
606
+ for (const place of tap.keys) await core.command(`key ${coreKey(place)} up`);
607
+ await core.status(`run ${(tick += hold)}`);
608
+ // Frames ran: the next RESTORE is no event right after an event.
609
+ afterEvent = false;
610
+ }
611
+ if (reason !== undefined) {
612
+ reason = `step ${index + 1}: RESTORE: ${reason}`;
613
+ break;
540
614
  }
541
615
  } else {
542
616
  reason = await runEvent(step, index + 1);
@@ -602,6 +676,8 @@ export interface SideRun {
602
676
  problem?: string;
603
677
  /** True when the rebuild went on after the wait of its start screen. */
604
678
  startScreenSkipped?: boolean;
679
+ /** The original with an `entry`: where it came to that entry, when it came to it. */
680
+ entryPoint?: EntryPoint;
605
681
  /**
606
682
  * Input reads that the recording has no value for, which got the fixed idle value:
607
683
  * at sites that it does not have, and after its end at a site.
@@ -622,7 +698,7 @@ export async function replaySide(
622
698
  folder: string,
623
699
  subject: ReplaySubject,
624
700
  workspace: Workspace,
625
- options: { compare?: Comparison; stop?: number; dump?: number; pins?: string[] } = {},
701
+ options: { compare?: Comparison; stop?: number; dump?: number; pins?: string[]; entry?: number; handover?: { entry: number; original: EntryPoint } } = {},
626
702
  ): Promise<SideRun & { ram?: Uint8Array }> {
627
703
  const prg = readProjectFile(subject.program).bytes;
628
704
  const original = subject.side === "original";
@@ -645,9 +721,10 @@ export async function replaySide(
645
721
  await core.command(`inputs ${inputsArgument(recording.inputs)}`);
646
722
  await core.command(`site-map ${mapFile}`);
647
723
  await core.command(`replay ${reads}`);
648
- if (options.compare !== undefined) {
724
+ let sampling = false;
725
+ const startSampling = async (compare: Comparison) => {
649
726
  const stop = options.dump ?? options.stop ?? 0;
650
- const pinned = options.compare.pin ?? [];
727
+ const pinned = compare.pin ?? [];
651
728
  if (options.pins !== undefined && pinned.length > 0) {
652
729
  // The rebuild: each checkpoint first gets the original's values of the random state.
653
730
  const pinFile = workspace.path(`${subject.side}-pins.txt`);
@@ -655,33 +732,81 @@ export async function replaySide(
655
732
  await core.command(`pin ${pinFile} ${rangesArgument(pinned, at)}`);
656
733
  }
657
734
  // The samples hold the state, then the pinned items.
658
- await core.command(`sample ${hex(at.code(options.compare.checkpoint))} ${samples} ${rangesArgument([...options.compare.state, ...pinned], at)}${stop > 0 ? ` ${stop}` : ""}`);
659
- }
735
+ await core.command(`sample ${hex(at.code(compare.checkpoint))} ${samples} ${rangesArgument([...compare.state, ...pinned], at)}${stop > 0 ? ` ${stop}` : ""}`);
736
+ sampling = true;
737
+ };
738
+ // A rebuild with a loader takes its checkpoints from its entry on, as the original leaves out those before its own.
739
+ if (options.compare !== undefined && options.handover === undefined) await startSampling(options.compare);
740
+ const targets = recording.events.flatMap((event) => ("pc" in event.key ? [at.code(event.key.pc)] : []));
741
+ await countAt(core, targets);
742
+ if (options.entry !== undefined) await core.command(`mark ${hex(options.entry)}`);
660
743
  await startProgram(core, prg, recording.load);
661
- let limit = original ? recording.ticks : recording.ticks * REBUILD_TIME_FACTOR;
744
+ const base = original ? recording.ticks : recording.ticks * REBUILD_TIME_FACTOR;
745
+ let limit = base;
662
746
  let problem: string | undefined;
663
- // A loader with a start screen that RUN starts waits for a key or a fire button that the recording does not have:
664
- // the rebuild goes on after the wait, as the check of the loader does. The cycles to the wait do not count.
665
- const wait = own.get(START_SCREEN_WAIT);
666
- const resume = own.get(START_SCREEN_CONTINUE);
747
+ // A tick key of the rebuild comes this many cycles later than in the original.
667
748
  let skipped = 0;
668
- if (!original && !recording.load && wait !== undefined && resume !== undefined) {
669
- const reached = await core.status(`run-pc ${hex(wait)} ${limit}`);
670
- if (reached.word === "reached") {
671
- skipped = reached.tick;
672
- limit += skipped;
673
- await core.status(`goto ${hex(resume)}`);
674
- } else problem = `the rebuild did not come to the wait of its start screen at ${formatC64Address(wait)}`;
749
+ let screenSkipped = false;
750
+ if (!original && !recording.load) {
751
+ // The cycles to the wait of a start screen do not count.
752
+ const screen = await passStartScreen(core, own, limit);
753
+ if (typeof screen === "string") problem = screen;
754
+ else if (screen !== undefined) {
755
+ skipped = screen;
756
+ limit = base + skipped;
757
+ screenSkipped = true;
758
+ }
759
+ }
760
+ // A pc key counts the opcode fetches from the start, also those of the code before the entry: the unpacker of
761
+ // the original, or the loader of the rebuild. The rebuild counts again from the jump of its loader, without those of the original.
762
+ const { handover } = options;
763
+ if (problem === undefined && handover !== undefined) {
764
+ const jump = own.get(LOADER_JUMP)!;
765
+ 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)}`;
766
+ else {
767
+ await countAt(core, targets);
768
+ const reached = await core.status(`run-pc ${hex(handover.entry)} ${limit}`);
769
+ if (reached.word !== "reached") problem = `the rebuild did not come to its entry at ${formatC64Address(handover.entry)}`;
770
+ else {
771
+ // The loader sets the entry state of the capture, but the phase of the frame and of the CIA timers at the entry
772
+ // depends on how the original started: the rebuild waits at its entry for the beam position of the original, and
773
+ // gets its CIA timers and interrupt state there. A program that starts its timers without a load keeps that phase.
774
+ const entered = await core.status(`align ${handover.original.phase}`);
775
+ // After the entry, a tick key is as far from the entry as in the original.
776
+ skipped = entered.tick - handover.original.tick;
777
+ limit = base + Math.max(0, skipped);
778
+ if (options.compare !== undefined) await startSampling(options.compare);
779
+ }
780
+ }
675
781
  }
676
- for (const event of problem === undefined ? recording.events : []) {
782
+ // The original with an entry: the events before the mark at the entry came.
783
+ let eventsBefore = 0;
784
+ let entryTick: number | undefined;
785
+ let entryPhase = "";
786
+ const marked = async () => {
787
+ const answer = /tick=(\d+) phase=([0-9a-f]+)/.exec(await core.command("marked"));
788
+ if (answer !== null) [entryTick, entryPhase] = [Number(answer[1]), answer[2]!];
789
+ };
790
+ for (const [index, event] of (problem === undefined ? recording.events : []).entries()) {
677
791
  const what = event.step === undefined ? "the RESTORE of the play" : "step " + event.step;
678
- const point = await runToKey(core, event.key, limit, map, skipped);
792
+ let key = event.key;
793
+ if (handover !== undefined) {
794
+ // The original came to this point before its entry, where the rebuild runs its loader. Each such event is a pc key: replay checks it.
795
+ if (index < handover.original.eventsBefore) continue;
796
+ if ("pc" in key) key = { ...key, count: key.count - (handover.original.counts.get(key.pc) ?? 0) };
797
+ }
798
+ const point = await runToKey(core, key, limit, map, skipped, at);
679
799
  if (point === "halted") break;
680
800
  if (point === "not-reached") {
681
801
  problem = "the program did not come to the point of " + what;
682
802
  break;
683
803
  }
684
- problem = await doAction(core, event.action, at);
804
+ if (options.entry !== undefined && entryTick === undefined) {
805
+ await marked();
806
+ if (entryTick === undefined) eventsBefore = index + 1;
807
+ }
808
+ // At the point of a runUntil to an address, its target is reached.
809
+ if (!("pc" in event.key)) problem = await doAction(core, event.action, at);
685
810
  if (problem !== undefined) {
686
811
  problem = what + ": " + problem;
687
812
  break;
@@ -693,12 +818,35 @@ export async function replaySide(
693
818
  const misses = sites.split(" ").slice(2).reduce((sum, entry) => sum + Number(entry.split(":")[4] ?? 0), 0);
694
819
  const ram = options.dump === undefined ? undefined : await core.peek(0, 0x10000);
695
820
  let lines: string[] = [];
696
- if (options.compare !== undefined) {
821
+ if (sampling) {
697
822
  await core.command("pin off");
698
823
  await core.command("sample off");
699
824
  lines = readFileSync(samples, "utf8").split("\n").filter((line) => line !== "");
700
825
  }
701
- return { samples: lines, end, unknown, misses, ...(problem === undefined ? {} : { problem }), ...(skipped > 0 ? { startScreenSkipped: true } : {}), ...(ram === undefined ? {} : { ram }) };
826
+ let entryPoint: EntryPoint | undefined;
827
+ if (options.entry !== undefined && entryTick === undefined) await marked();
828
+ if (entryTick !== undefined) {
829
+ const counts = new Map<string, number>();
830
+ for (const event of recording.events) {
831
+ if (!("pc" in event.key) || counts.has(event.key.pc)) continue;
832
+ const before = /marked=(\d+)/.exec(await core.command(`hits ${hex(at.code(event.key.pc))}`));
833
+ if (before !== null) counts.set(event.key.pc, Number(before[1]));
834
+ }
835
+ // A checkpoint at the first fetch at the entry has the tick of the mark. The rebuild starts its checkpoints after that fetch.
836
+ const after = lines.filter((line) => Number(line.split(" ")[0]) > entryTick!);
837
+ entryPoint = { tick: entryTick, phase: entryPhase, counts, eventsBefore, samplesBefore: lines.length - after.length };
838
+ lines = after;
839
+ }
840
+ return {
841
+ samples: lines,
842
+ end,
843
+ unknown,
844
+ misses,
845
+ ...(problem === undefined ? {} : { problem }),
846
+ ...(screenSkipped ? { startScreenSkipped: true } : {}),
847
+ ...(entryPoint === undefined ? {} : { entryPoint }),
848
+ ...(ram === undefined ? {} : { ram }),
849
+ };
702
850
  }
703
851
 
704
852
  export interface CheckpointDifference {
@@ -9,11 +9,13 @@ import { createHash } from "node:crypto";
9
9
  import { isRefusal, Refusal } from "#src/errors.ts";
10
10
  import { readPrg } from "#src/host-client/image.ts";
11
11
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
12
+ import { formatC64Address } from "#src/c64.ts";
13
+ import { LOADER_JUMP } from "#src/knowledge/start-screen.ts";
12
14
  import { C64RunSession } from "#src/native/c64run.ts";
13
15
  import { localToolContext } from "#src/native/local.ts";
14
16
  import { Workspace } from "#src/native/staging.ts";
15
17
  import { UsageError } from "#src/script.ts";
16
- import { firstDifference, parseStateItem, pinLines, readRecording, replaySide, siteMap, type Comparison, type ReplayResult, type ReplaySubject } from "./recording.ts";
18
+ import { firstDifference, loaderEntry, mover, parseStateItem, pinLines, readRecording, replaySide, siteMap, type Comparison, type ReplayResult, type ReplaySubject } from "./recording.ts";
17
19
  import { namesOf } from "./scenario.ts";
18
20
 
19
21
  const MAX_STATE_ITEMS = 16;
@@ -69,8 +71,16 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
69
71
  const originalSymbols = recording.symbols === "none" ? "knowledge" : recording.symbols;
70
72
  const original: ReplaySubject = { side: "original", program: recording.program, symbols: originalSymbols };
71
73
  const side = (subject: ReplaySubject, options: Parameters<typeof replaySide>[5]) => replaySide(core, recording, folder, subject, workspace, options);
74
+ const rebuildSymbols = values.symbols ?? originalSymbols;
75
+ // A rebuild with a generated loader starts the program where its loader jumps to. The original comes to that entry by the same name.
76
+ let loader: { entry: number; original: number } | undefined;
77
+ if (values.rebuild !== undefined && !recording.load && namesOf(rebuildSymbols).has(LOADER_JUMP)) {
78
+ const entry = await loaderEntry(core, recording, { side: "rebuild", program: values.rebuild, symbols: rebuildSymbols });
79
+ if (typeof entry === "string") return result("FAIL", "rebuild", { reason: entry });
80
+ loader = { entry, original: mover(namesOf(rebuildSymbols, "code"), namesOf(originalSymbols, "code"))(entry) };
81
+ }
72
82
  // The self-check: the original ends the session with the recorded state, to the cycle.
73
- const self = await side(original, { ...(compare === undefined ? {} : { compare }) });
83
+ const self = await side(original, { ...(compare === undefined ? {} : { compare }), ...(loader === undefined ? {} : { entry: loader.original }) });
74
84
  if (self.problem !== undefined) return result("INCONCLUSIVE", "original", { reason: `the recording does not reproduce on the original: ${self.problem}` });
75
85
  if (self.unknown > 0 || self.misses > 0) {
76
86
  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` });
@@ -81,8 +91,21 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
81
91
  const expected = self.samples;
82
92
  if (compare !== undefined && expected.length === 0) return result("INCONCLUSIVE", "original", { reason: `the original never came to the checkpoint ${compare.checkpoint} in the session` });
83
93
  if (values.rebuild === undefined) return result("PASS", "original", { checkpoints: expected.length });
94
+ let handover: { entry: number; original: NonNullable<typeof self.entryPoint> } | undefined;
95
+ if (loader !== undefined) {
96
+ const entered = self.entryPoint;
97
+ const at = formatC64Address(loader.original);
98
+ if (entered === undefined) return result("INCONCLUSIVE", "original", { reason: `the original never came to ${at}, where the loader of the rebuild jumps` });
99
+ // An event before the entry has no point in a rebuild with a loader. A runUntil to an address there does nothing, and the rebuild leaves it out.
100
+ const early = recording.events.slice(0, entered.eventsBefore).find((event) => !("pc" in event.key));
101
+ if (early !== undefined) {
102
+ const what = early.step === undefined ? "the RESTORE of the play" : `step ${early.step}`;
103
+ return result("INCONCLUSIVE", "original", { reason: `${what} ran before the program came to its entry ${at}. A rebuild with a loader has no point for it. Make the steps of the record file start after the entry` });
104
+ }
105
+ handover = { entry: loader.entry, original: entered };
106
+ }
84
107
 
85
- const rebuild: ReplaySubject = { side: "rebuild", program: values.rebuild, symbols: values.symbols ?? originalSymbols };
108
+ const rebuild: ReplaySubject = { side: "rebuild", program: values.rebuild, symbols: rebuildSymbols };
86
109
  let movedSites: number;
87
110
  try {
88
111
  movedSites = siteMap(recording.sites, namesOf(originalSymbols, "code"), namesOf(rebuild.symbols, "code")).length;
@@ -90,7 +113,7 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
90
113
  throw new UsageError(`--symbols ${rebuild.symbols}: ${(error as Error).message}`);
91
114
  }
92
115
  const pins = pinLines(expected, compare!.state);
93
- const replayed = await side(rebuild, { compare: compare!, stop: expected.length, pins });
116
+ const replayed = await side(rebuild, { compare: compare!, stop: expected.length, pins, ...(handover === undefined ? {} : { handover }) });
94
117
  const difference = firstDifference(expected, replayed.samples, compare!.state);
95
118
  // A read that the recording has no value for gets the idle value: it is in the result, never silent.
96
119
  const base = { checkpoints: expected.length, movedSites, ...(replayed.startScreenSkipped === true ? { startScreen: "skipped" } : {}), ...(replayed.unknown > 0 ? { idleReads: replayed.unknown } : {}) };
@@ -103,7 +126,9 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
103
126
  if (values.out !== undefined && difference !== undefined) {
104
127
  const files: Written[] = [];
105
128
  for (const subject of [original, rebuild]) {
106
- const dumped = await side(subject, { compare: compare!, dump: difference.checkpoint, ...(subject.side === "rebuild" ? { pins } : {}) });
129
+ // The original also stops at the checkpoints before its entry, which its samples leave out.
130
+ const dump = difference.checkpoint + (subject.side === "original" ? (handover?.original.samplesBefore ?? 0) : 0);
131
+ const dumped = await side(subject, { compare: compare!, dump, ...(subject.side === "rebuild" ? { pins, ...(handover === undefined ? {} : { handover }) } : {}) });
107
132
  files.push(writeReported(`${values.out}/${subject.side}-${difference.checkpoint}.bin`, dumped.ram!, { what: "--out" }));
108
133
  }
109
134
  failed.files = files;
@@ -114,3 +139,4 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
114
139
  workspace.remove();
115
140
  }
116
141
  }
142
+
@@ -9,7 +9,7 @@ import { screenText } from "#src/graphics.ts";
9
9
  import { runProgram } from "#src/host-client/autostart.ts";
10
10
  import { isRefusal, Refusal } from "#src/errors.ts";
11
11
  import { readCoverage } from "#src/host-client/coverage.ts";
12
- import { ACTION_STEP_KINDS, checkActionStep, checkLocation, checkStepNames, isInteger, isObject, refuseOldStep, renamedField, runActionStep, VICE_STEP_KINDS, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
12
+ import { ACTION_STEP_KINDS, aStep, checkActionStep, checkLocation, checkStepNames, isInteger, isObject, refuseOldStep, renamedField, runActionStep, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
13
13
  import { readPrg } from "#src/host-client/image.ts";
14
14
  import { MAX_MEMORY_READ, MAX_TRACE_FRAMES, MAX_TRACE_HITS, MAX_TRACE_POINTS, TRACE_KINDS, WireFailure, type TraceHit, type TraceKind } from "#src/host-client/tools.ts";
15
15
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
@@ -61,6 +61,11 @@ const RUN_FIELDS = "A run file has name, start and steps, and optionally symbols
61
61
  const START_FORMS = '{ "program": "<file.prg>" }, { "program": "<file.prg>", "load": true } or { "snapshot": "<file.vsf>" }';
62
62
  const TRACE_KEYS = ["trace", "points", "frames", "maxHits"];
63
63
  const OBSERVE_KEYS = ["observe", "memory", "registers", "vicii", "sprites"];
64
+ /** The fix for a key that the same step of a scenario has, or none. */
65
+ function scenarioKeyFix(key: string, step: Record<string, unknown>): string {
66
+ if (key === "screen" && "observe" in step) return `. A run writes the screen with its own step: {"screen": "${typeof step.observe === "string" ? step.observe : "<name>"}"}`;
67
+ return key === "side" ? ". A run has one program. Remove side" : "";
68
+ }
64
69
  const EXPECT_KEYS = ["expect", "memory", "registers"];
65
70
  const EXPECTED_MEMORY_KEYS = ["address", "data", "text", "mask", "view"];
66
71
  /** The characters that screenText gives for the screen codes 0 to 63; a graphics code gives a dot. */
@@ -131,11 +136,11 @@ function readRun(path: string): Run {
131
136
  if (!isObject(step)) return fail(`${at} must be an object`);
132
137
  const kinds = "observe" in step ? ["observe"] : "expect" in step ? ["expect"] : "trace" in step ? ["trace"] : Object.keys(step).filter((key) => (ACTION_STEP_KINDS as readonly string[]).includes(key) || (OWN_KINDS as readonly string[]).includes(key));
133
138
  if (kinds.length > 1) return fail(`${at} has ${kinds.length} step kinds: ${kinds.join(", ")}. Give each one its own step`);
134
- if (kinds.length !== 1) return fail(`${at} must have exactly one of ${[...VICE_STEP_KINDS, ...OWN_KINDS].join(", ")}`);
139
+ if (kinds.length !== 1) return fail(`${at} must have exactly one of ${[...ACTION_STEP_KINDS, ...OWN_KINDS].join(", ")}`);
135
140
  const kind = kinds[0]!;
136
141
  refuseOldStep(kind, step, at, fail);
137
142
  const allowed = kind === "observe" ? OBSERVE_KEYS : kind === "expect" ? EXPECT_KEYS : kind === "trace" ? TRACE_KEYS : [kind];
138
- for (const key of Object.keys(step)) if (!allowed.includes(key)) fail(`${at} has the key ${key}, which a ${kind} step does not have`);
143
+ for (const key of Object.keys(step)) if (!allowed.includes(key)) fail(`${at} has the key ${key}, which ${aStep(kind)} of a run does not have${scenarioKeyFix(key, step)}`);
139
144
  if ((ACTION_STEP_KINDS as readonly string[]).includes(kind)) {
140
145
  // The step with its defaults filled in, as the shared schema of the action steps gives it.
141
146
  (value.steps as unknown[])[index] = checkActionStep(kind as ActionStepKind, step, at, fail);
@@ -7,7 +7,7 @@ import { isRefusal, Refusal } from "#src/errors.ts";
7
7
  import { c64AddressOf, formatC64Address, formatSprite, formatVicii, parseC64Address } from "#src/c64.ts";
8
8
  import { MAX_BASELINES, MAX_MASK_RECTANGLES, maskCoversFrame, WireFailure } from "#src/host-client/tools.ts";
9
9
  import { LOAD_LIMIT_FRAMES, RUN_LIMIT_FRAMES, runProgram } from "#src/host-client/autostart.ts";
10
- import { ACTION_STEP_KINDS, checkActionStep, checkLocation, isInteger, isObject, refuseOldStep, renamedField, runActionStep, VICE_STEP_KINDS, type ActionStep, type ActionStepKind, type Location } from "#src/host-client/steps.ts";
10
+ import { ACTION_STEP_KINDS, aStep, checkActionStep, checkLocation, isInteger, isObject, refuseOldStep, renamedField, runActionStep, type ActionStep, type ActionStepKind, type Location } from "#src/host-client/steps.ts";
11
11
  import { applyEntryState, parseEntryState } from "#src/host-client/entry-state.ts";
12
12
  import { readPrg } from "#src/host-client/image.ts";
13
13
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
@@ -52,7 +52,7 @@ type StepBody =
52
52
  | { autostart: true }
53
53
  | { snapshot: string }
54
54
  | { normalize: true }
55
- | Exclude<ActionStep, { press: string }>
55
+ | ActionStep
56
56
  | { observe: string; memory?: Array<Location | MemoryObservation>; registers?: ObservedRegister[]; screen?: ScreenPolicy; vicii?: boolean; sprites?: number[] };
57
57
 
58
58
  /** A step; with side, only that side does it. An observe step has no side: it compares both. */
@@ -108,8 +108,6 @@ export interface ScenarioResult {
108
108
  }
109
109
 
110
110
  const STEP_KINDS = ["reset", "load", "autostart", "snapshot", "normalize", ...ACTION_STEP_KINDS, "observe"];
111
- /** The step kinds that a scenario runs: press is for the replay core only. */
112
- const SHOWN_KINDS = ["reset", "load", "autostart", "snapshot", "normalize", ...VICE_STEP_KINDS, "observe"];
113
111
 
114
112
  /** The keys of a scenario file: all but videoStandard are required. */
115
113
  const SCENARIO_KEYS = ["name", "original", "rebuild", "steps", "videoStandard"];
@@ -156,11 +154,11 @@ export function readScenario(path: string): Scenario {
156
154
  // An observe step names what it observes with "memory" and "registers" too.
157
155
  const kinds = "observe" in step ? ["observe"] : Object.keys(step).filter((key) => STEP_KINDS.includes(key));
158
156
  if (kinds.length > 1) return fail(`${at} has ${kinds.length} step kinds: ${kinds.join(", ")}. Give each one its own step`);
159
- if (kinds.length !== 1) return fail(`${at} must have exactly one of ${SHOWN_KINDS.join(", ")}`);
157
+ if (kinds.length !== 1) return fail(`${at} must have exactly one of ${STEP_KINDS.join(", ")}${typeof step.screen === "string" ? `. A scenario compares the screen in an observe step: {"observe": "${step.screen}", "screen": {}}` : ""}`);
160
158
  const kind = kinds[0]!;
161
159
  refuseOldStep(kind, step, at, fail);
162
160
  const allowed = [...(STEP_KEYS[kind] ?? [kind]), ...(kind === "observe" ? [] : ["side"])];
163
- for (const key of Object.keys(step)) if (!allowed.includes(key)) fail(`${at} has the key ${key}, which a ${kind} step does not have`);
161
+ for (const key of Object.keys(step)) if (!allowed.includes(key)) fail(`${at} has the key ${key}, which ${aStep(kind)} does not have`);
164
162
  if (step.side !== undefined && !(SIDES as unknown[]).includes(step.side)) fail(`${at}: side must be original or rebuild`);
165
163
  if ((ACTION_STEP_KINDS as readonly string[]).includes(kind)) {
166
164
  // The step with its defaults filled in, as the shared schema of the action steps gives it.