@henols/c64-re-tools 2.6.0-rc.9 → 2.7.0-rc.1

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 (79) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +7 -7
  3. package/skills/c64-assembler/scripts/assembler.ts +4 -3
  4. package/skills/c64-basic/SKILL.md +1 -1
  5. package/skills/c64-development/SKILL.md +7 -7
  6. package/skills/c64-disk/SKILL.md +13 -13
  7. package/skills/c64-docs/SKILL.md +25 -10
  8. package/skills/c64-docs/references/page-types.md +11 -11
  9. package/skills/c64-docs/references/style.md +21 -0
  10. package/skills/c64-docs/scripts/docs.ts +78 -18
  11. package/skills/c64-docs/scripts/lib/links.ts +1 -1
  12. package/skills/c64-docs/scripts/lib/reference.ts +117 -31
  13. package/skills/c64-docs/scripts/lib/source-map.ts +14 -0
  14. package/skills/c64-knowledge/SKILL.md +15 -14
  15. package/skills/c64-knowledge/scripts/knowledge.ts +17 -10
  16. package/skills/c64-memory-map/SKILL.md +1 -1
  17. package/skills/c64-packer/SKILL.md +1 -1
  18. package/skills/c64-provenance/SKILL.md +5 -4
  19. package/skills/c64-provenance/scripts/lib/compare.ts +1 -1
  20. package/skills/c64-reverse-engineering/SKILL.md +26 -11
  21. package/skills/c64-source/SKILL.md +18 -15
  22. package/skills/c64-source/scripts/lib/export.ts +20 -8
  23. package/skills/c64-source/scripts/lib/loader.ts +51 -28
  24. package/skills/c64-source/scripts/lib/source.ts +27 -20
  25. package/skills/c64-source/scripts/source.ts +68 -53
  26. package/skills/c64-static-analysis/SKILL.md +24 -22
  27. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  28. package/skills/c64-static-analysis/scripts/lib/instructions.ts +4 -4
  29. package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
  30. package/skills/c64-static-analysis/scripts/static-analysis.ts +36 -27
  31. package/skills/c64-testing/SKILL.md +32 -24
  32. package/skills/c64-testing/references/recording-format.md +15 -9
  33. package/skills/c64-testing/references/scenario-format.md +9 -7
  34. package/skills/c64-testing/scripts/lib/recording.ts +214 -49
  35. package/skills/c64-testing/scripts/lib/replay.ts +45 -19
  36. package/skills/c64-testing/scripts/lib/runs.ts +7 -2
  37. package/skills/c64-testing/scripts/lib/scenario.ts +31 -31
  38. package/skills/c64-testing/scripts/testing.ts +37 -16
  39. package/skills/c64-unpacker/SKILL.md +16 -14
  40. package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
  41. package/skills/c64-unpacker/scripts/unpacker.ts +38 -6
  42. package/src/build-name.ts +9 -4
  43. package/src/c64.ts +1 -1
  44. package/src/host/main.ts +2 -2
  45. package/src/host/server.ts +3 -1
  46. package/src/host/tools/index.ts +1 -1
  47. package/src/host/vice/process.ts +34 -17
  48. package/src/host/vice/session.ts +55 -27
  49. package/src/host-client/steps.ts +4 -1
  50. package/src/host-client/tools.ts +1 -1
  51. package/src/knowledge/evidence.ts +66 -0
  52. package/src/knowledge/history.ts +5 -5
  53. package/src/knowledge/import.ts +12 -5
  54. package/src/knowledge/program.ts +81 -33
  55. package/src/knowledge/read.ts +3 -3
  56. package/src/knowledge/schema.ts +7 -7
  57. package/src/knowledge/separate.ts +2 -2
  58. package/src/knowledge/start-screen.ts +2 -0
  59. package/src/knowledge/text.ts +28 -3
  60. package/src/knowledge/write.ts +7 -7
  61. package/src/mcp/tools/debug.ts +23 -21
  62. package/src/mcp/tools/memory.ts +12 -9
  63. package/src/native/c64run.ts +7 -4
  64. package/src/native/{ghidra → decompiler}/analyze.ts +17 -17
  65. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  66. package/src/native/{ghidra → decompiler}/walk.ts +6 -6
  67. package/src/native/types.ts +25 -25
  68. package/src/opcodes.ts +1 -1
  69. package/src/project.ts +1 -1
  70. package/src/reference-pages.ts +64 -0
  71. package/src/script.ts +2 -2
  72. package/tools/c64run.c +151 -5
  73. /package/src/native/{ghidra → decompiler}/c64rt-wasm.ts +0 -0
  74. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  75. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  76. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
  77. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.sla +0 -0
  78. /package/src/native/{ghidra → decompiler}/pcode.ts +0 -0
  79. /package/src/native/{ghidra → decompiler}/wasm.ts +0 -0
@@ -2,9 +2,9 @@
2
2
  // values that its input reads got (the joystick ports, the keyboard matrix,
3
3
  // the SID noise) and the state hash at its end. A replay gives the same values
4
4
  // to the same reads, keyed by the site (the reading instruction) and the read
5
- // index. On the original it must end with the same hash. On a rebuild it
5
+ // index. On the reference it must end with the same hash. On a rebuild it
6
6
  // compares the state at each entry of one routine (the checkpoints) with the
7
- // original's. Timing does not key anything, so a rebuild with other timing
7
+ // reference's. Timing does not key anything, so a rebuild with other timing
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
 
@@ -17,7 +17,7 @@ import { keyTaps, type KeyTap } from "#src/c64-keys.ts";
17
17
  import { READY_FRAMES } from "#src/host-client/entry-state.ts";
18
18
  import { ACTION_STEP_KINDS, checkActionStep, isInteger, isObject, keyboardBytes, renamedField, stepKind, type ActionStep, type Location } from "#src/host-client/steps.ts";
19
19
  import { readProjectFile, type Written } from "#src/host-client/transfer.ts";
20
- 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";
21
21
  import { PAL_FRAME_CYCLES, type C64RunSession, type CoreStatus } from "#src/native/c64run.ts";
22
22
  import type { Workspace } from "#src/native/staging.ts";
23
23
  import { namesOf, type Outcome } from "./scenario.ts";
@@ -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;
@@ -78,7 +82,7 @@ const COVERAGE_COMMANDS = new Map([
78
82
  /**
79
83
  * What a replay compares: the state at each entry of a routine, for example the
80
84
  * main loop of a game. `pin` is random state in RAM (a seed, a pointer into a
81
- * random table): at each checkpoint the rebuild gets the original's values there.
85
+ * random table): at each checkpoint the rebuild gets the reference's values there.
82
86
  */
83
87
  export interface Comparison {
84
88
  checkpoint: Location;
@@ -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 {
@@ -231,6 +237,17 @@ export function readRecordFile(path: string): RecordFile {
231
237
  };
232
238
  }
233
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
+
234
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. */
235
252
  function checkCoreStep(step: ActionStep, at: string, fail: (message: string) => never): void {
236
253
  if ("write" in step && step.write.space !== "c64") fail(`${at}: a recording has the C64 alone, not ${step.write.space}`);
@@ -279,14 +296,19 @@ export function readRecording(folder: string): Recording {
279
296
  const named = typeof event.step === "number" ? `${at} (step ${event.step})` : at;
280
297
  if (event.action.restore === true && Object.keys(event.action).length === 1) return;
281
298
  // The action with the defaults filled in, as the record file gave it.
282
- event.action = checkActionStep(stepKind(event.action, ACTION_STEP_KINDS, named, where), event.action, named, where);
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
+ }
283
305
  });
284
306
  return value as unknown as Recording;
285
307
  }
286
308
 
287
309
  /**
288
310
  * The addresses of one side. A name comes from the symbols of the side. A $
289
- * address is an address of the original: on the rebuild it moves with the
311
+ * address is an address of the reference: on the rebuild it moves with the
290
312
  * name before it (code with a code label, data with any symbol).
291
313
  */
292
314
  export interface SideAddresses {
@@ -308,8 +330,8 @@ function sideAddresses(symbols: Map<string, number>, side: string, move: { code:
308
330
  const MAX_LABEL_DISTANCE = 4096;
309
331
 
310
332
  /**
311
- * Moves an address of the original to the rebuild: the name before it in the
312
- * original, plus the same offset from that name in the rebuild. An address
333
+ * Moves an address of the reference to the rebuild: the name before it in the
334
+ * reference, plus the same offset from that name in the rebuild. An address
313
335
  * without a name before it (within MAX_LABEL_DISTANCE) stays where it is.
314
336
  */
315
337
  export function mover(from: Map<string, number>, to: Map<string, number>): (address: number) => number {
@@ -336,6 +358,55 @@ export function siteMap(sites: RecordedSite[], from: Map<string, number>, to: Ma
336
358
  return moved;
337
359
  }
338
360
 
361
+ /** Where the reference 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 reference 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
+
339
410
  /** Power-on and READY, then the program in memory as a LOAD leaves it, and RUN in the keyboard queue. */
340
411
  async function startProgram(core: C64RunSession, prg: Uint8Array, load: boolean): Promise<CoreStatus> {
341
412
  if (prg.length < 3) throw new Refusal("invalid-input", "the program is not a PRG file");
@@ -369,8 +440,12 @@ function busiestSite(answer: string): { site: number; addr: number; count: numbe
369
440
  * Runs to the point of an event. `map` moves a site to the rebuild. "halted"
370
441
  * when a sample stop came first, "not-reached" when the point did not come before `until`.
371
442
  */
372
- 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"> {
373
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
+ }
374
449
  if ("tick" in key) {
375
450
  const status = await core.status(`run ${key.tick + skipped}`);
376
451
  return status.word === "halted" ? "halted" : "reached";
@@ -463,17 +538,21 @@ export async function record(
463
538
  ): Promise<RecordOutcome> {
464
539
  const prg = readProjectFile(file.program).bytes;
465
540
  const same = (address: number) => address;
466
- const at = sideAddresses(namesOf(file.symbols), "original", { code: same, data: same });
541
+ const at = sideAddresses(namesOf(file.symbols), "reference", { code: same, data: same });
467
542
  // A checkpoint and state of the record file must resolve now, so that a replay can use them.
468
543
  if (file.compare !== undefined) {
469
544
  at.code(file.compare.checkpoint);
470
545
  for (const item of file.compare.state) at.data(item.address);
471
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`);
472
550
  const reads = workspace.path(RECORDING_FILES.reads);
473
551
  const coverage = workspace.path(RECORDING_FILES.coverage);
474
552
  await core.init();
475
553
  await core.command(`inputs ${inputsArgument(file.inputs)}`);
476
554
  await core.command(`record ${reads}`);
555
+ await countAt(core, targets);
477
556
  await startProgram(core, prg, file.load ?? false);
478
557
  // From READY on: the start of the C64 itself is never in the map.
479
558
  await core.command(COVERAGE_COMMANDS.get(file.coverage) ?? `coverage on-pc ${hex(parseC64Address(file.coverage))}`);
@@ -485,13 +564,25 @@ export async function record(
485
564
  // replay. An event right after another event runs where that one ended.
486
565
  const runEvent = async (action: ActionStep | RestoreAction, step?: number): Promise<string | undefined> => {
487
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
+ }
488
577
  const busiest = afterEvent ? undefined : busiestSite(await core.command("sites"));
489
578
  const key: RecordedEvent["key"] = afterEvent
490
579
  ? { previous: true }
491
580
  : busiest === undefined
492
581
  ? { tick: tick + 1 }
493
582
  : { site: formatC64Address(busiest.site), addr: formatC64Address(busiest.addr), count: busiest.count + 1 };
494
- 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
+ }
495
586
  events.push({ ...(step === undefined ? {} : { step }), action, key });
496
587
  return doAction(core, action, at);
497
588
  };
@@ -571,7 +662,7 @@ export async function record(
571
662
 
572
663
  /** One side of a replay. */
573
664
  export interface ReplaySubject {
574
- side: "original" | "rebuild";
665
+ side: "reference" | "rebuild";
575
666
  program: string;
576
667
  symbols: string;
577
668
  }
@@ -585,6 +676,8 @@ export interface SideRun {
585
676
  problem?: string;
586
677
  /** True when the rebuild went on after the wait of its start screen. */
587
678
  startScreenSkipped?: boolean;
679
+ /** The reference with an `entry`: where it came to that entry, when it came to it. */
680
+ entryPoint?: EntryPoint;
588
681
  /**
589
682
  * Input reads that the recording has no value for, which got the fixed idle value:
590
683
  * at sites that it does not have, and after its end at a site.
@@ -594,7 +687,7 @@ export interface SideRun {
594
687
  }
595
688
 
596
689
  /**
597
- * Replays a recording on one side. The original runs to the end of the
690
+ * Replays a recording on one side. The reference runs to the end of the
598
691
  * session; a rebuild runs until `stop` checkpoints (or REBUILD_TIME_FACTOR
599
692
  * times the cycles). With `dump`, it stops at that checkpoint (1 = the first)
600
693
  * and gives the RAM there.
@@ -605,19 +698,19 @@ export async function replaySide(
605
698
  folder: string,
606
699
  subject: ReplaySubject,
607
700
  workspace: Workspace,
608
- options: { compare?: Comparison; stop?: number; dump?: number; pins?: string[] } = {},
701
+ options: { compare?: Comparison; stop?: number; dump?: number; pins?: string[]; entry?: number; handover?: { entry: number; reference: EntryPoint } } = {},
609
702
  ): Promise<SideRun & { ram?: Uint8Array }> {
610
703
  const prg = readProjectFile(subject.program).bytes;
611
- const original = subject.side === "original";
612
- // The names of the original: a recording without names takes those of the knowledge.
704
+ const reference = subject.side === "reference";
705
+ // The names of the reference: a recording without names takes those of the knowledge.
613
706
  const names = recording.symbols === "none" ? "knowledge" : recording.symbols;
614
707
  const same = (address: number) => address;
615
- const move = original
708
+ const move = reference
616
709
  ? { code: same, data: same }
617
710
  : { code: mover(namesOf(names, "code"), namesOf(subject.symbols, "code")), data: mover(namesOf(names), namesOf(subject.symbols)) };
618
711
  const own = namesOf(subject.symbols);
619
712
  const at = sideAddresses(own, subject.side, move);
620
- const moved = original ? [] : siteMap(recording.sites, namesOf(names, "code"), namesOf(subject.symbols, "code"));
713
+ const moved = reference ? [] : siteMap(recording.sites, namesOf(names, "code"), namesOf(subject.symbols, "code"));
621
714
  const map = new Map(moved);
622
715
  const reads = workspace.path(`${subject.side}-${RECORDING_FILES.reads}`);
623
716
  writeFileSync(reads, readProjectFile(`${folder}/${RECORDING_FILES.reads}`).bytes);
@@ -628,43 +721,92 @@ export async function replaySide(
628
721
  await core.command(`inputs ${inputsArgument(recording.inputs)}`);
629
722
  await core.command(`site-map ${mapFile}`);
630
723
  await core.command(`replay ${reads}`);
631
- if (options.compare !== undefined) {
724
+ let sampling = false;
725
+ const startSampling = async (compare: Comparison) => {
632
726
  const stop = options.dump ?? options.stop ?? 0;
633
- const pinned = options.compare.pin ?? [];
727
+ const pinned = compare.pin ?? [];
634
728
  if (options.pins !== undefined && pinned.length > 0) {
635
- // The rebuild: each checkpoint first gets the original's values of the random state.
729
+ // The rebuild: each checkpoint first gets the reference's values of the random state.
636
730
  const pinFile = workspace.path(`${subject.side}-pins.txt`);
637
731
  writeFileSync(pinFile, options.pins.map((line) => `${line}\n`).join(""));
638
732
  await core.command(`pin ${pinFile} ${rangesArgument(pinned, at)}`);
639
733
  }
640
734
  // The samples hold the state, then the pinned items.
641
- await core.command(`sample ${hex(at.code(options.compare.checkpoint))} ${samples} ${rangesArgument([...options.compare.state, ...pinned], at)}${stop > 0 ? ` ${stop}` : ""}`);
642
- }
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 reference 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)}`);
643
743
  await startProgram(core, prg, recording.load);
644
- let limit = original ? recording.ticks : recording.ticks * REBUILD_TIME_FACTOR;
744
+ const base = reference ? recording.ticks : recording.ticks * REBUILD_TIME_FACTOR;
745
+ let limit = base;
645
746
  let problem: string | undefined;
646
- // A loader with a start screen that RUN starts waits for a key or a fire button that the recording does not have:
647
- // the rebuild goes on after the wait, as the check of the loader does. The cycles to the wait do not count.
648
- const wait = own.get(START_SCREEN_WAIT);
649
- const resume = own.get(START_SCREEN_CONTINUE);
747
+ // A tick key of the rebuild comes this many cycles later than in the reference.
650
748
  let skipped = 0;
651
- if (!original && !recording.load && wait !== undefined && resume !== undefined) {
652
- const reached = await core.status(`run-pc ${hex(wait)} ${limit}`);
653
- if (reached.word === "reached") {
654
- skipped = reached.tick;
655
- limit += skipped;
656
- await core.status(`goto ${hex(resume)}`);
657
- } else problem = `the rebuild did not come to the wait of its start screen at ${formatC64Address(wait)}`;
749
+ let screenSkipped = false;
750
+ if (!reference && !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
+ }
658
759
  }
659
- for (const event of problem === undefined ? recording.events : []) {
760
+ // A pc key counts the opcode fetches from the start, also those of the code before the entry: the unpacker of
761
+ // the reference, or the loader of the rebuild. The rebuild counts again from the jump of its loader, without those of the reference.
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 reference started: the rebuild waits at its entry for the beam position of the reference, 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.reference.phase}`);
775
+ // After the entry, a tick key is as far from the entry as in the reference.
776
+ skipped = entered.tick - handover.reference.tick;
777
+ limit = base + Math.max(0, skipped);
778
+ if (options.compare !== undefined) await startSampling(options.compare);
779
+ }
780
+ }
781
+ }
782
+ // The reference 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()) {
660
791
  const what = event.step === undefined ? "the RESTORE of the play" : "step " + event.step;
661
- const point = await runToKey(core, event.key, limit, map, skipped);
792
+ let key = event.key;
793
+ if (handover !== undefined) {
794
+ // The reference 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.reference.eventsBefore) continue;
796
+ if ("pc" in key) key = { ...key, count: key.count - (handover.reference.counts.get(key.pc) ?? 0) };
797
+ }
798
+ const point = await runToKey(core, key, limit, map, skipped, at);
662
799
  if (point === "halted") break;
663
800
  if (point === "not-reached") {
664
801
  problem = "the program did not come to the point of " + what;
665
802
  break;
666
803
  }
667
- 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);
668
810
  if (problem !== undefined) {
669
811
  problem = what + ": " + problem;
670
812
  break;
@@ -676,19 +818,42 @@ export async function replaySide(
676
818
  const misses = sites.split(" ").slice(2).reduce((sum, entry) => sum + Number(entry.split(":")[4] ?? 0), 0);
677
819
  const ram = options.dump === undefined ? undefined : await core.peek(0, 0x10000);
678
820
  let lines: string[] = [];
679
- if (options.compare !== undefined) {
821
+ if (sampling) {
680
822
  await core.command("pin off");
681
823
  await core.command("sample off");
682
824
  lines = readFileSync(samples, "utf8").split("\n").filter((line) => line !== "");
683
825
  }
684
- 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
+ };
685
850
  }
686
851
 
687
852
  export interface CheckpointDifference {
688
853
  /** 1 = the first checkpoint. */
689
854
  checkpoint: number;
690
- tick: { original: number; rebuild: number };
691
- items: Array<{ address: Location; original: string; rebuild: string }>;
855
+ tick: { reference: number; rebuild: number };
856
+ items: Array<{ address: Location; reference: string; rebuild: string }>;
692
857
  }
693
858
 
694
859
  /** The pinned values of each sample line: the fields after the state items. */
@@ -707,8 +872,8 @@ export function firstDifference(expected: string[], got: string[], state: StateI
707
872
  const a = allA.slice(0, state.length);
708
873
  const b = allB.slice(0, state.length);
709
874
  if (a.join(" ") === b.join(" ")) continue;
710
- const items = state.flatMap((item, at) => (a[at] === b[at] ? [] : [{ address: item.address, original: a[at] ?? "", rebuild: b[at] ?? "" }]));
711
- return { checkpoint: index + 1, tick: { original: Number(tickA), rebuild: Number(tickB) }, items };
875
+ const items = state.flatMap((item, at) => (a[at] === b[at] ? [] : [{ address: item.address, reference: a[at] ?? "", rebuild: b[at] ?? "" }]));
876
+ return { checkpoint: index + 1, tick: { reference: Number(tickA), rebuild: Number(tickB) }, items };
712
877
  }
713
878
  return undefined;
714
879
  }
@@ -716,9 +881,9 @@ export function firstDifference(expected: string[], got: string[], state: StateI
716
881
  export interface ReplayResult {
717
882
  result: Outcome;
718
883
  recording: string;
719
- /** The side that the result is about: the original (the self-check) or the rebuild. */
720
- side: "original" | "rebuild";
721
- /** The routine of the checkpoints, and the checkpoints of the original. */
884
+ /** The side that the result is about: the reference (the self-check) or the rebuild. */
885
+ side: "reference" | "rebuild";
886
+ /** The routine of the checkpoints, and the checkpoints of the reference. */
722
887
  checkpoint?: Location;
723
888
  checkpoints: number;
724
889
  /** The checkpoints of the rebuild that were equal. */
@@ -1,7 +1,7 @@
1
1
  // The replay of c64-testing: replays a recording in the replay core
2
- // (c64run). First on the original program, which must end with the recorded
2
+ // (c64run). First on the reference program, which must end with the recorded
3
3
  // state hash. Then, with --rebuild, on the rebuild: it compares the state at
4
- // each checkpoint with the original's. --checkpoint and --state choose the
4
+ // each checkpoint with the reference's. --checkpoint and --state choose the
5
5
  // comparison, else the record file gave it.
6
6
 
7
7
  import { createHash } from "node:crypto";
@@ -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;
@@ -28,7 +30,7 @@ export interface ReplayOptions {
28
30
  out?: string;
29
31
  }
30
32
 
31
- /** Replays the recording on the original, and with `rebuild` on the rebuild: PASS, FAIL or INCONCLUSIVE. */
33
+ /** Replays the recording on the reference, and with `rebuild` on the rebuild: PASS, FAIL or INCONCLUSIVE. */
32
34
  export async function replay(values: ReplayOptions): Promise<ReplayResult> {
33
35
  if (values.symbols !== undefined && values.rebuild === undefined) throw new UsageError("--symbols gives the names of the rebuild, and --rebuild is missing. Give --rebuild too, or leave out --symbols.");
34
36
  if ((values.checkpoint === undefined) !== (values.state.length === 0)) throw new UsageError("--checkpoint and --state go together. Give both of them, or neither.");
@@ -59,38 +61,59 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
59
61
  }
60
62
  }
61
63
  const sha256 = createHash("sha256").update(readProjectFile(recording.program).bytes).digest("hex");
62
- if (sha256 !== recording.sha256) return result("INCONCLUSIVE", "original", { reason: `${recording.program} is not the program of the recording (its SHA-256 changed); record the session again` });
64
+ 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` });
63
65
 
64
66
  const context = localToolContext();
65
67
  const core = await C64RunSession.open(context);
66
68
  const workspace = Workspace.create(context.supervisor, "c64-re-tools-replay-");
67
69
  try {
68
70
  // A recording made without names takes the names that the knowledge has now.
69
- const originalSymbols = recording.symbols === "none" ? "knowledge" : recording.symbols;
70
- const original: ReplaySubject = { side: "original", program: recording.program, symbols: originalSymbols };
71
+ const referenceSymbols = recording.symbols === "none" ? "knowledge" : recording.symbols;
72
+ const reference: ReplaySubject = { side: "reference", program: recording.program, symbols: referenceSymbols };
71
73
  const side = (subject: ReplaySubject, options: Parameters<typeof replaySide>[5]) => replaySide(core, recording, folder, subject, workspace, options);
72
- // The self-check: the original ends the session with the recorded state, to the cycle.
73
- const self = await side(original, { ...(compare === undefined ? {} : { compare }) });
74
- if (self.problem !== undefined) return result("INCONCLUSIVE", "original", { reason: `the recording does not reproduce on the original: ${self.problem}` });
74
+ const rebuildSymbols = values.symbols ?? referenceSymbols;
75
+ // A rebuild with a generated loader starts the program where its loader jumps to. The reference comes to that entry by the same name.
76
+ let loader: { entry: number; reference: 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, reference: mover(namesOf(rebuildSymbols, "code"), namesOf(referenceSymbols, "code"))(entry) };
81
+ }
82
+ // The self-check: the reference ends the session with the recorded state, to the cycle.
83
+ const self = await side(reference, { ...(compare === undefined ? {} : { compare }), ...(loader === undefined ? {} : { entry: loader.reference }) });
84
+ if (self.problem !== undefined) return result("INCONCLUSIVE", "reference", { reason: `the recording does not reproduce on the reference: ${self.problem}` });
75
85
  if (self.unknown > 0 || self.misses > 0) {
76
- return result("INCONCLUSIVE", "original", { reason: `the recording does not reproduce on the original: ${self.unknown + self.misses} input reads had no recorded value; record the session again with this version of the toolkit` });
86
+ return result("INCONCLUSIVE", "reference", { reason: `the recording does not reproduce on the reference: ${self.unknown + self.misses} input reads had no recorded value; record the session again with this version of the toolkit` });
77
87
  }
78
88
  if (self.end.tick !== recording.ticks || self.end.hash !== recording.hash) {
79
- return result("INCONCLUSIVE", "original", { reason: "the recording does not reproduce on the original: the state at its end is different; record the session again with this version of the toolkit" });
89
+ return result("INCONCLUSIVE", "reference", { reason: "the recording does not reproduce on the reference: the state at its end is different; record the session again with this version of the toolkit" });
80
90
  }
81
91
  const expected = self.samples;
82
- if (compare !== undefined && expected.length === 0) return result("INCONCLUSIVE", "original", { reason: `the original never came to the checkpoint ${compare.checkpoint} in the session` });
83
- if (values.rebuild === undefined) return result("PASS", "original", { checkpoints: expected.length });
92
+ if (compare !== undefined && expected.length === 0) return result("INCONCLUSIVE", "reference", { reason: `the reference never came to the checkpoint ${compare.checkpoint} in the session` });
93
+ if (values.rebuild === undefined) return result("PASS", "reference", { checkpoints: expected.length });
94
+ let handover: { entry: number; reference: NonNullable<typeof self.entryPoint> } | undefined;
95
+ if (loader !== undefined) {
96
+ const entered = self.entryPoint;
97
+ const at = formatC64Address(loader.reference);
98
+ if (entered === undefined) return result("INCONCLUSIVE", "reference", { reason: `the reference 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", "reference", { 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, reference: 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
- movedSites = siteMap(recording.sites, namesOf(originalSymbols, "code"), namesOf(rebuild.symbols, "code")).length;
111
+ movedSites = siteMap(recording.sites, namesOf(referenceSymbols, "code"), namesOf(rebuild.symbols, "code")).length;
89
112
  } catch (error) {
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 } : {}) };
@@ -102,8 +125,10 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
102
125
  const failed = result("FAIL", "rebuild", { ...base, compared: (difference?.checkpoint ?? replayed.samples.length + 1) - 1, reason, ...(difference === undefined ? {} : { firstDifference: difference }) });
103
126
  if (values.out !== undefined && difference !== undefined) {
104
127
  const files: Written[] = [];
105
- for (const subject of [original, rebuild]) {
106
- const dumped = await side(subject, { compare: compare!, dump: difference.checkpoint, ...(subject.side === "rebuild" ? { pins } : {}) });
128
+ for (const subject of [reference, rebuild]) {
129
+ // The reference also stops at the checkpoints before its entry, which its samples leave out.
130
+ const dump = difference.checkpoint + (subject.side === "reference" ? (handover?.reference.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, 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. */
@@ -135,7 +140,7 @@ function readRun(path: string): Run {
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);