@henols/c64-re-tools 2.8.0-rc.4 → 2.8.0-rc.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +1 -1
  3. package/skills/c64-assembler/scripts/assembler.ts +78 -24
  4. package/skills/c64-docs/scripts/docs.ts +31 -10
  5. package/skills/c64-knowledge/SKILL.md +11 -7
  6. package/skills/c64-knowledge/references/batches.md +2 -1
  7. package/skills/c64-knowledge/references/source-knowledge.md +1 -1
  8. package/skills/c64-knowledge/scripts/knowledge.ts +46 -29
  9. package/skills/c64-packer/scripts/packer.ts +9 -2
  10. package/skills/c64-provenance/SKILL.md +2 -2
  11. package/skills/c64-provenance/scripts/lib/runtime.ts +45 -10
  12. package/skills/c64-provenance/scripts/provenance.ts +10 -3
  13. package/skills/c64-source/references/loader.md +8 -7
  14. package/skills/c64-source/scripts/lib/loader.ts +4 -111
  15. package/skills/c64-source/scripts/lib/source.ts +3 -1
  16. package/skills/c64-source/scripts/source.ts +49 -78
  17. package/skills/c64-static-analysis/SKILL.md +2 -2
  18. package/skills/c64-static-analysis/scripts/lib/coverage.ts +56 -4
  19. package/skills/c64-static-analysis/scripts/lib/idioms.ts +92 -42
  20. package/skills/c64-static-analysis/scripts/static-analysis.ts +32 -21
  21. package/skills/c64-testing/SKILL.md +7 -0
  22. package/skills/c64-testing/scripts/lib/play.ts +8 -7
  23. package/skills/c64-testing/scripts/lib/recording.ts +278 -27
  24. package/skills/c64-testing/scripts/lib/replay.ts +9 -8
  25. package/skills/c64-testing/scripts/lib/runs.ts +5 -1
  26. package/skills/c64-testing/scripts/lib/scenario.ts +4 -0
  27. package/skills/c64-testing/scripts/testing.ts +30 -11
  28. package/skills/c64-unpacker/SKILL.md +13 -11
  29. package/skills/c64-unpacker/scripts/lib/loads.ts +10 -5
  30. package/skills/c64-unpacker/scripts/lib/machine.ts +163 -3
  31. package/skills/c64-unpacker/scripts/lib/stages.ts +13 -6
  32. package/skills/c64-unpacker/scripts/unpacker.ts +34 -15
  33. package/skills/emulator/SKILL.md +2 -2
  34. package/src/c64.ts +21 -0
  35. package/src/host/vice/adapter.ts +2 -1
  36. package/src/host/vice/chips.ts +6 -9
  37. package/src/host/vice/session.ts +2 -2
  38. package/src/host-client/image.ts +40 -4
  39. package/src/host-client/tools.ts +1 -1
  40. package/src/host-client/transfer.ts +48 -26
  41. package/src/host-client/vice-session.ts +15 -0
  42. package/src/knowledge/database.ts +72 -19
  43. package/src/knowledge/import.ts +32 -7
  44. package/src/knowledge/join.ts +50 -2
  45. package/src/knowledge/names.ts +2 -2
  46. package/src/knowledge/program.ts +103 -24
  47. package/src/knowledge/schema.ts +6 -0
  48. package/src/knowledge/start-screen.ts +57 -7
  49. package/src/knowledge/write.ts +20 -13
  50. package/src/loader.ts +101 -33
  51. package/src/mcp/output.ts +13 -12
  52. package/src/mcp/server.ts +33 -22
  53. package/src/mcp/tools/debug.ts +21 -24
  54. package/src/mcp/tools/media.ts +27 -27
  55. package/src/mcp/tools/memory.ts +13 -17
  56. package/src/mcp/tools/video.ts +10 -12
  57. package/src/native/c64run.ts +39 -1
  58. package/src/native/decompiler/analyze.ts +1 -1
  59. package/src/native/dxa.ts +2 -2
  60. package/src/native/types.ts +26 -7
  61. package/src/opcodes.ts +5 -0
  62. package/src/program-code.ts +4 -2
  63. package/src/project.ts +224 -71
  64. package/src/protocol/vice.ts +5 -3
  65. package/src/script.ts +60 -15
  66. package/{skills/c64-source/scripts/lib → src}/stage.ts +142 -11
  67. package/tools/c64run.c +18 -5
@@ -9,16 +9,19 @@
9
9
  // state can be chosen at replay time, with the names that the knowledge has then.
10
10
 
11
11
  import { readFileSync, writeFileSync } from "node:fs";
12
+ import type { DatabaseSync } from "node:sqlite";
12
13
 
13
14
  import { Refusal } from "#src/errors.ts";
14
- import { c64AddressOf, COVERAGE, formatC64Address, hexWord, parseC64Address } from "#src/c64.ts";
15
+ import { type AddressRange, c64AddressOf, COVERAGE, formatC64Address, formatC64RangeFields, hexWord, inRanges, parseC64Address, rangesWhere } from "#src/c64.ts";
15
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, keyboardBytes, stepKind, type ActionStep, type Location } from "#src/host-client/steps.ts";
18
19
  import { isInteger, isObject } from "#src/host-client/tools.ts";
19
20
  import { readProjectFile, readProjectJson, type Written } from "#src/host-client/transfer.ts";
21
+ import { entryMemory, programImage } from "#src/knowledge/program.ts";
20
22
  import { RECORDING_FILES } from "#src/knowledge/recording-files.ts";
21
23
  import { LOADER_JUMP, startScreenLabels } from "#src/knowledge/start-screen.ts";
24
+ import { refuseAbsoluteInFile } from "#src/project.ts";
22
25
  import { sha256 } from "#src/knowledge/text.ts";
23
26
  import { PAL_FRAME_CYCLES, type C64RunSession, type CoreStatus } from "#src/native/c64run.ts";
24
27
  import type { Workspace } from "#src/native/staging.ts";
@@ -135,6 +138,18 @@ export interface Recording {
135
138
  /** The cycles of the session, and the state hash at its end (RAM from $0002 and colour RAM). */
136
139
  ticks: number;
137
140
  hash: string;
141
+ /**
142
+ * The cycles of the input (see trackInput): keys down, a joystick that is not centered, typed keys in the queue,
143
+ * and each press step to the end of its frames. None without input.
144
+ */
145
+ input?: TickSpan[];
146
+ }
147
+
148
+ /** The cycles from `from` up to `to`. `typed`: the keys of a type step, which are input only while the KERNAL queue holds keys. */
149
+ export interface TickSpan {
150
+ from: number;
151
+ to: number;
152
+ typed?: true;
138
153
  }
139
154
 
140
155
  /** Steps that are input or time: the replay gives the program the reads that they caused, and does not do them again. */
@@ -144,8 +159,10 @@ const QUEUE = 0x0277;
144
159
  const QUEUE_LENGTH = 0x00c6;
145
160
  const QUEUE_SIZE = 10;
146
161
 
147
- /** The key code of the replay core for a matrix place: 80 + the place. RESTORE is ff. */
148
- const coreKey = (place: number) => (0x80 + place).toString(16);
162
+ /** The key code of the replay core for a matrix place: 80 + the place. */
163
+ const coreKey = (place: number) => 0x80 + place;
164
+ /** The key code of RESTORE in the replay core. */
165
+ const RESTORE_KEY = 0xff;
149
166
 
150
167
  /** The joystick mask of the replay core: 1 up, 2 down, 4 left, 8 right, $10 fire. */
151
168
  export function joystickMask(direction: Extract<ActionStep, { joystick: unknown }>["joystick"]["direction"], fire: boolean): number {
@@ -197,6 +214,8 @@ export function readRecordFile(path: string): RecordFile {
197
214
  if (typeof value.name !== "string" || value.name === "") fail("name must be a short text");
198
215
  if (typeof value.program !== "string" || value.program === "") fail("program must be a PRG file in the project");
199
216
  if (value.symbols !== undefined && typeof value.symbols !== "string") fail('symbols must be "knowledge", "none" or a JSON file');
217
+ refuseAbsoluteInFile(value.program, "program", fail);
218
+ refuseAbsoluteInFile(value.symbols, "symbols", fail);
200
219
  if (value.load !== undefined && typeof value.load !== "boolean") fail("load must be true or false");
201
220
  if ((value.checkpoint === undefined) !== (value.state === undefined)) fail("give checkpoint and state together, or neither: a replay can give them");
202
221
  if (value.checkpoint !== undefined && (typeof value.checkpoint !== "string" || value.checkpoint === "")) fail("checkpoint must be the name or $ address of a routine");
@@ -263,6 +282,8 @@ export function readRecording(folder: string): Recording {
263
282
  if (!isObject(value) || value.format !== RECORDING_FORMAT) return fail(`it is not a recording of format ${RECORDING_FORMAT}`);
264
283
  for (const key of ["name", "program", "sha256", "symbols", "hash"]) if (typeof value[key] !== "string") fail(`${key} is missing`);
265
284
  for (const key of ["inputs", "events", "sites"]) if (!Array.isArray(value[key])) fail(`${key} is missing`);
285
+ refuseAbsoluteInFile(value.program, "program", fail);
286
+ refuseAbsoluteInFile(value.symbols, "symbols", fail);
266
287
  if (!isInteger(value.ticks, 1, Number.MAX_SAFE_INTEGER)) fail("ticks is missing");
267
288
  // A recording that does not check is refused, never replayed wrong.
268
289
  const remedy = "Record the session again with record";
@@ -273,6 +294,9 @@ export function readRecording(folder: string): Recording {
273
294
  checkState(compare.state, where);
274
295
  if (compare.pin !== undefined) checkState(compare.pin, where, "pin");
275
296
  }
297
+ if (value.input !== undefined && (!Array.isArray(value.input) || !value.input.every((span) => isObject(span) && isInteger(span.from, 0, Number.MAX_SAFE_INTEGER) && isInteger(span.to, 0, Number.MAX_SAFE_INTEGER) && (span.typed === undefined || span.typed === true)))) {
298
+ fail(`input must be a list of { from, to } cycles. ${remedy}`);
299
+ }
276
300
  (value.events as unknown[]).forEach((event, index) => {
277
301
  const at = `event ${index + 1}`;
278
302
  const where = (message: string): never => fail(`${message}. ${remedy}`);
@@ -338,8 +362,15 @@ export function siteMap(sites: RecordedSite[], from: Map<string, number>, to: Ma
338
362
  return moved;
339
363
  }
340
364
 
365
+ /** Pages 0-3 of RAM and the stack pointer of a program at its entry. */
366
+ export interface EntryRam {
367
+ sp: number;
368
+ /** $0000-$03ff. */
369
+ ram: Uint8Array;
370
+ }
371
+
341
372
  /** Where the reference came to the entry that the loader of a rebuild jumps to. */
342
- export interface EntryPoint {
373
+ export interface EntryPoint extends EntryRam {
343
374
  /** The tick of the first opcode fetch at the entry. */
344
375
  tick: number;
345
376
  /**
@@ -355,6 +386,181 @@ export interface EntryPoint {
355
386
  samplesBefore: number;
356
387
  }
357
388
 
389
+ /**
390
+ * The mark of the replay core at the first opcode fetch at an entry. Give it after count-pc, which clears it. `after`
391
+ * comes after the point of each event, before its action: the events before the mark came are the first ones.
392
+ */
393
+ async function markEntry(core: C64RunSession, entry: number) {
394
+ await core.command(`mark ${hexWord(entry)}`);
395
+ const marked = async () => {
396
+ const answer = /tick=(\d+) phase=([0-9a-f]+)/.exec(await core.command("marked"));
397
+ return answer === null ? undefined : { tick: Number(answer[1]), phase: answer[2]! };
398
+ };
399
+ /** Pages 0-3 and the stack pointer at the mark, which came. */
400
+ const memory = async (): Promise<EntryRam> => {
401
+ const answer = /s=([0-9a-f]{2}) ram=([0-9a-f]{2048})/.exec(await core.command("marked-ram"));
402
+ if (answer === null) throw new Refusal("operation-failed", "c64run marked-ram gave no memory at the mark");
403
+ return { sp: Number.parseInt(answer[1]!, 16), ram: Uint8Array.from(Buffer.from(answer[2]!, "hex")) };
404
+ };
405
+ let came: { tick: number; phase: string } | undefined;
406
+ let eventsBefore = 0;
407
+ return {
408
+ /** After the point of event `index` (0 is the first). */
409
+ async after(index: number): Promise<void> {
410
+ if (came !== undefined) return;
411
+ came = await marked();
412
+ if (came === undefined) eventsBefore = index + 1;
413
+ },
414
+ /** Where the program came to the entry, with its memory there, or undefined when it did not come to it. */
415
+ async end(): Promise<({ tick: number; phase: string; eventsBefore: number } & EntryRam) | undefined> {
416
+ came ??= await marked();
417
+ return came === undefined ? undefined : { ...came, eventsBefore, ...(await memory()) };
418
+ },
419
+ };
420
+ }
421
+
422
+ /**
423
+ * Why a rebuild with a loader cannot replay the events: the first of the events before the entry that is no runUntil
424
+ * to an address. A rebuild with a loader runs its loader there, so the event has no point in it.
425
+ */
426
+ export function eventBeforeEntry(events: readonly RecordedEvent[], eventsBefore: number, entry: number): string | undefined {
427
+ const early = events.slice(0, eventsBefore).find((event) => !("pc" in event.key));
428
+ if (early === undefined) return undefined;
429
+ const what = early.step === undefined ? "the RESTORE of the play" : `step ${early.step}`;
430
+ return `${what} ran before the program came to its entry ${formatC64Address(entry)}. A rebuild with a loader has no point for it. Make the steps of the record file start after the entry`;
431
+ }
432
+
433
+ /** The memory that the loader of a rebuild writes at an entry: $0002-$03ff of the program of the knowledge at its entry, and its stack pointer. */
434
+ export interface LoaderEntryState {
435
+ sp: number;
436
+ /** The parts of $0002-$03ff that the loader writes. */
437
+ written: AddressRange[];
438
+ byteAt: (address: number) => number;
439
+ }
440
+
441
+ /** Pages 0-3 without the CPU port: the memory of the entry state check. */
442
+ const LOW_PAGES: AddressRange = { start: 0x0002, end: 0x03ff };
443
+
444
+ /**
445
+ * The entry state of the knowledge at `entry`, as the loader of a rebuild writes it ($0002-$03ff: the segments there,
446
+ * and the pages that the entry state has). Undefined when the knowledge has no entry state, one at another entry, one
447
+ * without a stack pointer, or when the loader writes nothing of $0002-$03ff.
448
+ */
449
+ export function loaderEntryState(db: DatabaseSync | undefined, entry: number): LoaderEntryState | undefined {
450
+ const image = programImage(db);
451
+ if (image?.state === undefined || image.entry !== entry) return undefined;
452
+ const sp = isObject(image.state.registers) ? image.state.registers.sp : undefined;
453
+ if (!isInteger(sp, 0, 0xff)) return undefined;
454
+ const memory = entryMemory(image);
455
+ const written = memory.segments.flatMap((segment) => (segment.end < LOW_PAGES.start || segment.start > LOW_PAGES.end ? [] : [{ start: Math.max(segment.start, LOW_PAGES.start), end: Math.min(segment.end, LOW_PAGES.end) }]));
456
+ return written.length === 0 ? undefined : { sp, written, byteAt: memory.byteAt };
457
+ }
458
+
459
+ /**
460
+ * The bytes that the entry state check does not compare: the bytes of the KERNAL that its interrupt and its screen
461
+ * editor change by time alone, and the bytes that the start of the program sets in another way in the emulator of a
462
+ * capture than in the replay core. These bytes differ also with the same input, and no new capture makes them the
463
+ * same. The bytes of the keyboard scan ($91, $c5, $cb, $f5/$f6, $028b/$028c) change with the input, and the check
464
+ * compares them.
465
+ */
466
+ const UNCOMPARED_BYTES: readonly AddressRange[] = [
467
+ // The jiffy clock: each interrupt counts it up.
468
+ { start: 0x00a0, end: 0x00a2 },
469
+ // The load of the emulator sets them to the start of the BASIC text; the start of the replay core puts the program into RAM without them.
470
+ { start: 0x00ac, end: 0x00ad },
471
+ // $cd: the interrupts to the next blink of the cursor. $ce: the character under the cursor at the last blink.
472
+ // $cf: the blink phase. A key that the editor takes ends the blink at the phase that the time gave.
473
+ { start: 0x00cd, end: 0x00cf },
474
+ // The colour under the cursor at the last blink.
475
+ { start: 0x0287, end: 0x0287 },
476
+ ];
477
+
478
+ /**
479
+ * Where a program at its entry differs from the entry state that the loader of a rebuild writes: the ranges of $0002-$03ff
480
+ * with other bytes. The free part of the stack page, from $0100 up to the stack pointer of either state, holds no state,
481
+ * and the bytes of UNCOMPARED_BYTES are not compared.
482
+ */
483
+ export function entryStateDiffers(program: EntryRam, loader: LoaderEntryState): AddressRange[] {
484
+ const free = 0x0100 + Math.max(program.sp, loader.sp);
485
+ const compared = (address: number) => inRanges(loader.written, address) && (address < 0x0100 || address > free) && !inRanges(UNCOMPARED_BYTES, address);
486
+ return rangesWhere((address) => compared(address) && program.ram[address] !== loader.byteAt(address));
487
+ }
488
+
489
+ /**
490
+ * The spans of the input of a session: from the input that starts while no input is held to the end of the last one.
491
+ * Input is a key down (a press step, the play, RESTORE) and a joystick that is not centered (a joystick step, the
492
+ * play): the key() and joy() of the core report each one with its tick. `typed` starts a typed span for the keys of a
493
+ * type step, and `settle` ends it when the KERNAL queue is empty; it can end late, so the queue at the entry decides
494
+ * (entryStateCheck). `cover` makes the key spans from `from` on one span up to `to`, for the frames of a step. `spans`
495
+ * closes a span that is still open at `end`, and ends the tracking.
496
+ */
497
+ export function trackInput(core: Pick<C64RunSession, "onInput" | "peek" | "status">): {
498
+ typed: (tick: number) => void;
499
+ settle: () => Promise<void>;
500
+ cover: (from: number, to: number) => void;
501
+ spans: (end: number) => TickSpan[];
502
+ } {
503
+ const down = new Set<number>();
504
+ let joystick = false;
505
+ const spans: TickSpan[] = [];
506
+ const typedSpans: TickSpan[] = [];
507
+ let typedFrom: number | undefined;
508
+ let since: number | undefined;
509
+ const held = () => down.size > 0 || joystick;
510
+ const change = (tick: number, update: () => void) => {
511
+ const before = held();
512
+ update();
513
+ if (!before && held()) since = tick;
514
+ else if (before && !held()) {
515
+ spans.push({ from: since!, to: tick });
516
+ since = undefined;
517
+ }
518
+ };
519
+ core.onInput((input, tick) =>
520
+ change(tick, () => {
521
+ if (input.kind === "joy") joystick = input.masks.some((mask) => mask !== 0);
522
+ else if (input.down) down.add(input.code);
523
+ else down.delete(input.code);
524
+ }),
525
+ );
526
+ const settle = async () => {
527
+ if (typedFrom === undefined || (await core.peek(QUEUE_LENGTH, 1))[0] !== 0) return;
528
+ typedSpans.push({ from: typedFrom, to: (await core.status("status")).tick, typed: true });
529
+ typedFrom = undefined;
530
+ };
531
+ const cover = (from: number, to: number) => {
532
+ const later = spans.filter((span) => span.from >= from);
533
+ const earlier = spans.filter((span) => span.from < from);
534
+ // An input that is still held (a joystick) carries the step: its open span starts at the step.
535
+ if (since !== undefined) since = Math.min(since, from);
536
+ else if (later.length > 0) earlier.push({ from, to: Math.max(to, ...later.map((span) => span.to)) });
537
+ else return;
538
+ spans.splice(0, spans.length, ...earlier);
539
+ };
540
+ const end = (at: number) => {
541
+ core.onInput(undefined);
542
+ const open = [...(since === undefined ? [] : [{ from: since, to: at }]), ...(typedFrom === undefined ? [] : [{ from: typedFrom, to: at, typed: true as const }])];
543
+ return [...spans, ...typedSpans, ...open].sort((a, b) => a.from - b.from);
544
+ };
545
+ return { typed: (tick) => (typedFrom ??= tick), settle, cover, spans: end };
546
+ }
547
+
548
+ /** The note in place of the entry state check when the program came to its entry during the input. */
549
+ export const ENTRY_DURING_INPUT = "not compared: the program came to its entry during the input of the session";
550
+
551
+ /**
552
+ * The entry state check of a program at its entry (`tick`) against the entry state that the loader writes: the
553
+ * differing ranges, or nothing when all bytes are the same. A capture stops at the first arrival after its steps, so
554
+ * at an entry during the input (`input`) it holds a later state, which no new capture changes: then only the note.
555
+ * A typed span counts only when the KERNAL queue at the entry still holds keys.
556
+ */
557
+ export function entryStateCheck(program: EntryRam & { tick: number }, input: readonly TickSpan[], loader: LoaderEntryState): { entryStateDiffers?: Array<{ start: string; end: string }>; entryState?: string } {
558
+ const during = (span: TickSpan) => program.tick >= span.from && program.tick < span.to && (span.typed !== true || program.ram[QUEUE_LENGTH] !== 0);
559
+ if (input.some(during)) return { entryState: ENTRY_DURING_INPUT };
560
+ const differs = entryStateDiffers(program, loader);
561
+ return differs.length === 0 ? {} : { entryStateDiffers: differs.map(formatC64RangeFields) };
562
+ }
563
+
358
564
  /**
359
565
  * A loader with a start screen that RUN starts waits for a key or a fire button that the recording does not have:
360
566
  * the rebuild goes on after the wait, as the check of the loader does. Gives the tick of the wait, a problem, or
@@ -452,9 +658,9 @@ async function doAction(core: C64RunSession, step: ActionStep | RestoreAction, a
452
658
  if ("restore" in step) {
453
659
  // The NMI line is low while RESTORE is down: hold it as a press step holds a key.
454
660
  const tick = (await core.status("status")).tick;
455
- await core.command("key ff down");
661
+ await core.key(RESTORE_KEY, true);
456
662
  await core.status("run " + (tick + KEY_FRAMES * PAL_FRAME_CYCLES));
457
- await core.command("key ff up");
663
+ await core.key(RESTORE_KEY, false);
458
664
  } else if ("write" in step) {
459
665
  await core.write(at.data(step.write.address), Buffer.from(step.write.data, "hex"));
460
666
  } else if ("type" in step) {
@@ -502,19 +708,44 @@ export interface RecordOutcome {
502
708
  coverageFrom?: { tick: number; pc: number };
503
709
  /** Why the session did not complete (a runUntil that did not reach its target). */
504
710
  reason?: string;
711
+ /** With an entry: why a rebuild with a loader cannot replay the recording, as replay finds it on the reference. */
712
+ loaderProblem?: string;
713
+ /** With an entry that the program came to: its pages 0-3 and its stack pointer there, and the cycle of its arrival. */
714
+ entryRam?: EntryRam & { tick: number };
505
715
  }
506
716
 
507
717
  /**
508
718
  * Plays the steps of a record file in the replay core and records the session.
509
719
  * `input` runs after the steps, with `restore` for a RESTORE press of the play;
510
- * a reason that it gives means no recording.
720
+ * a reason that it gives means no recording. With `entry`, the entry of the
721
+ * program where the loader of a rebuild jumps to, the outcome tells when the
722
+ * program did not come to it, or which event ran before it came to it, as
723
+ * replay finds it on the reference.
511
724
  */
512
725
  export async function record(
513
726
  core: C64RunSession,
514
727
  file: RecordFile,
515
728
  workspace: Workspace,
516
729
  input?: (core: C64RunSession, restore: () => Promise<string | undefined>) => Promise<string | undefined>,
730
+ entry?: number,
517
731
  ): Promise<RecordOutcome> {
732
+ try {
733
+ return await recordSession(core, file, workspace, input, entry);
734
+ } finally {
735
+ // The input listener of the session ends with the record, also when the record fails.
736
+ core.onInput(undefined);
737
+ }
738
+ }
739
+
740
+ async function recordSession(
741
+ core: C64RunSession,
742
+ file: RecordFile,
743
+ workspace: Workspace,
744
+ input: Parameters<typeof record>[3],
745
+ entry: number | undefined,
746
+ ): Promise<RecordOutcome> {
747
+ // Every key and joystick goes through key() and joy() of the core: the steps, the play and a RESTORE.
748
+ const tracked = trackInput(core);
518
749
  const prg = readProjectFile(file.program).bytes;
519
750
  const same = (address: number) => address;
520
751
  const at = sideAddresses(namesOf(file.symbols), "reference", { code: same, data: same });
@@ -532,6 +763,7 @@ export async function record(
532
763
  await core.command(`inputs ${inputsArgument(file.inputs)}`);
533
764
  await core.command(`record ${reads}`);
534
765
  await countAt(core, targets);
766
+ const mark = entry === undefined ? undefined : await markEntry(core, entry);
535
767
  await startProgram(core, prg, file.load);
536
768
  // From READY on: the start of the C64 itself is never in the map.
537
769
  await core.command(COVERAGE_COMMANDS.get(file.coverage) ?? `coverage on-pc ${hexWord(parseC64Address(file.coverage))}`);
@@ -551,6 +783,7 @@ export async function record(
551
783
  const reached = await core.status(`run-pc ${pc} ${tick + action.runUntil.timeoutFrames * PAL_FRAME_CYCLES} ${count}`);
552
784
  if (reached.word !== "reached") return `the program did not reach ${address} within ${action.runUntil.timeoutFrames} frames`;
553
785
  events.push({ ...(step === undefined ? {} : { step }), action, key: { pc: address, count } });
786
+ await mark?.after(events.length - 1);
554
787
  return undefined;
555
788
  }
556
789
  const busiest = afterEvent ? undefined : busiestSite(await core.command("sites"));
@@ -563,6 +796,7 @@ export async function record(
563
796
  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`;
564
797
  }
565
798
  events.push({ ...(step === undefined ? {} : { step }), action, key });
799
+ await mark?.after(events.length - 1);
566
800
  return doAction(core, action, at);
567
801
  };
568
802
  for (const [index, step] of file.steps.entries()) {
@@ -572,32 +806,38 @@ export async function record(
572
806
  await core.status(`run ${tick + step.frames * PAL_FRAME_CYCLES}`);
573
807
  } else if ("joystick" in step) {
574
808
  masks[step.joystick.port - 1] = joystickMask(step.joystick.direction, step.joystick.fire ?? false);
575
- await core.command(`joy ${masks[0]!.toString(16)} ${masks[1]!.toString(16)}`);
809
+ await core.joy(masks[0]!, masks[1]!);
576
810
  } else if ("press" in step) {
577
811
  const hold = step.press.frames * PAL_FRAME_CYCLES;
812
+ const start = tick;
578
813
  for (const tap of keyTaps(step.press.keys) as KeyTap[]) {
579
- for (const place of tap.keys) await core.command(`key ${coreKey(place)} down`);
814
+ for (const place of tap.keys) await core.key(coreKey(place), true);
580
815
  // RESTORE is no read: an event at the next read of the program, with the keys of the tap down.
581
816
  if (tap.restore) reason = await runEvent({ restore: true }, index + 1);
582
817
  if (reason !== undefined) break;
583
818
  tick = (await core.status("status")).tick;
584
819
  await core.status(`run ${(tick += hold)}`);
585
- for (const place of tap.keys) await core.command(`key ${coreKey(place)} up`);
820
+ for (const place of tap.keys) await core.key(coreKey(place), false);
586
821
  await core.status(`run ${(tick += hold)}`);
587
822
  // Frames ran: the next RESTORE is no event right after an event.
588
823
  afterEvent = false;
589
824
  }
825
+ // A press step is key input to the end of its frames, as the steps of a capture end there.
826
+ tracked.cover(start, (await core.status("status")).tick);
590
827
  if (reason !== undefined) {
591
828
  reason = `step ${index + 1}: RESTORE: ${reason}`;
592
829
  break;
593
830
  }
594
831
  } else {
595
832
  reason = await runEvent(step, index + 1);
833
+ // The keys of a type step are input from the start of the step until the KERNAL took them from its queue.
834
+ if ("type" in step && reason === undefined) tracked.typed(tick);
596
835
  if (reason !== undefined) {
597
836
  reason = `step ${index + 1}: ${reason}`;
598
837
  break;
599
838
  }
600
839
  }
840
+ await tracked.settle();
601
841
  afterEvent = event;
602
842
  }
603
843
  // The play runs frames before each RESTORE: a RESTORE never runs where an event of the steps ended.
@@ -607,7 +847,16 @@ export async function record(
607
847
  return failed === undefined ? undefined : "RESTORE: " + failed;
608
848
  };
609
849
  if (input !== undefined && reason === undefined) reason = await input(core, restore);
850
+ const came = await mark?.end();
851
+ const loaderProblem =
852
+ entry === undefined
853
+ ? undefined
854
+ : came === undefined
855
+ ? `the program did not come to its entry ${formatC64Address(entry)} in the session, where the loader of a rebuild jumps. Make the session go on until the program runs from its entry`
856
+ : eventBeforeEntry(events, came.eventsBefore, entry);
610
857
  const end = await core.status("status");
858
+ await tracked.settle();
859
+ const spans = tracked.spans(end.tick);
611
860
  const sites = (await core.command("sites")).split(" ").slice(2).map((entry): RecordedSite => {
612
861
  const [where, reads, kind] = entry.split(":");
613
862
  const [site, addr] = where!.split("/");
@@ -629,6 +878,7 @@ export async function record(
629
878
  sites,
630
879
  ticks: end.tick,
631
880
  hash: end.hash,
881
+ ...(spans.length === 0 ? {} : { input: spans }),
632
882
  };
633
883
  return {
634
884
  recording,
@@ -636,6 +886,8 @@ export async function record(
636
886
  coverage: readFileSync(coverage),
637
887
  ...(from === null ? {} : { coverageFrom: { tick: Number(from[1]), pc: Number.parseInt(from[2]!, 16) } }),
638
888
  ...(reason === undefined ? {} : { reason }),
889
+ ...(loaderProblem === undefined ? {} : { loaderProblem }),
890
+ ...(came === undefined ? {} : { entryRam: { sp: came.sp, ram: came.ram, tick: came.tick } }),
639
891
  };
640
892
  }
641
893
 
@@ -655,6 +907,8 @@ export interface SideRun {
655
907
  problem?: string;
656
908
  /** True when the rebuild went on after the wait of its start screen. */
657
909
  startScreenSkipped?: boolean;
910
+ /** The rebuild with a `handover`: its pages 0-3 and its stack pointer at its entry, as its loader left them. */
911
+ entryRam?: EntryRam;
658
912
  /** The reference with an `entry`: where it came to that entry, when it came to it. */
659
913
  entryPoint?: EntryPoint;
660
914
  /**
@@ -719,7 +973,7 @@ export async function replaySide(
719
973
  if (options.compare !== undefined && options.handover === undefined) await startSampling(options.compare);
720
974
  const targets = recording.events.flatMap((event) => ("pc" in event.key ? [at.code(event.key.pc)] : []));
721
975
  await countAt(core, targets);
722
- if (options.entry !== undefined) await core.command(`mark ${hexWord(options.entry)}`);
976
+ const mark = options.entry === undefined ? undefined : await markEntry(core, options.entry);
723
977
  await startProgram(core, prg, recording.load);
724
978
  const base = reference ? recording.ticks : recording.ticks * REBUILD_TIME_FACTOR;
725
979
  let limit = base;
@@ -740,6 +994,7 @@ export async function replaySide(
740
994
  // A pc key counts the opcode fetches from the start, also those of the code before the entry: the unpacker of
741
995
  // the reference, or the loader of the rebuild. The rebuild counts again from the jump of its loader, without those of the reference.
742
996
  const { handover } = options;
997
+ let entryRam: EntryRam | undefined;
743
998
  if (problem === undefined && handover !== undefined) {
744
999
  const jump = own.get(LOADER_JUMP)!;
745
1000
  if ((await core.status(`run-pc ${hexWord(jump)} ${limit}`)).word !== "reached") problem = `the rebuild did not come to the jump of its loader at ${formatC64Address(jump)}`;
@@ -748,6 +1003,7 @@ export async function replaySide(
748
1003
  const reached = await core.status(`run-pc ${hexWord(handover.entry)} ${limit}`);
749
1004
  if (reached.word !== "reached") problem = `the rebuild did not come to its entry at ${formatC64Address(handover.entry)}`;
750
1005
  else {
1006
+ entryRam = { sp: reached.s, ram: await core.peek(0, 0x400) };
751
1007
  // The loader sets the entry state of the capture, but the phase of the frame and of the CIA timers at the entry
752
1008
  // depends on how the reference started: the rebuild waits at its entry for the beam position of the reference, and
753
1009
  // gets its CIA timers and interrupt state there. A program that starts its timers without a load keeps that phase.
@@ -759,14 +1015,6 @@ export async function replaySide(
759
1015
  }
760
1016
  }
761
1017
  }
762
- // The reference with an entry: the events before the mark at the entry came.
763
- let eventsBefore = 0;
764
- let entryTick: number | undefined;
765
- let entryPhase = "";
766
- const marked = async () => {
767
- const answer = /tick=(\d+) phase=([0-9a-f]+)/.exec(await core.command("marked"));
768
- if (answer !== null) [entryTick, entryPhase] = [Number(answer[1]), answer[2]!];
769
- };
770
1018
  for (const [index, event] of (problem === undefined ? recording.events : []).entries()) {
771
1019
  const what = event.step === undefined ? "the RESTORE of the play" : "step " + event.step;
772
1020
  let key = event.key;
@@ -781,10 +1029,8 @@ export async function replaySide(
781
1029
  problem = "the program did not come to the point of " + what;
782
1030
  break;
783
1031
  }
784
- if (options.entry !== undefined && entryTick === undefined) {
785
- await marked();
786
- if (entryTick === undefined) eventsBefore = index + 1;
787
- }
1032
+ // The reference with an entry: the events before the mark at the entry came.
1033
+ await mark?.after(index);
788
1034
  // At the point of a runUntil to an address, its target is reached.
789
1035
  if (!("pc" in event.key)) problem = await doAction(core, event.action, at);
790
1036
  if (problem !== undefined) {
@@ -804,8 +1050,8 @@ export async function replaySide(
804
1050
  lines = readFileSync(samples, "utf8").split("\n").filter((line) => line !== "");
805
1051
  }
806
1052
  let entryPoint: EntryPoint | undefined;
807
- if (options.entry !== undefined && entryTick === undefined) await marked();
808
- if (entryTick !== undefined) {
1053
+ const came = await mark?.end();
1054
+ if (came !== undefined) {
809
1055
  const counts = new Map<string, number>();
810
1056
  for (const event of recording.events) {
811
1057
  if (!("pc" in event.key) || counts.has(event.key.pc)) continue;
@@ -813,8 +1059,8 @@ export async function replaySide(
813
1059
  if (before !== null) counts.set(event.key.pc, Number(before[1]));
814
1060
  }
815
1061
  // A checkpoint at the first fetch at the entry has the tick of the mark. The rebuild starts its checkpoints after that fetch.
816
- const after = lines.filter((line) => Number(line.split(" ")[0]) > entryTick!);
817
- entryPoint = { tick: entryTick, phase: entryPhase, counts, eventsBefore, samplesBefore: lines.length - after.length };
1062
+ const after = lines.filter((line) => Number(line.split(" ")[0]) > came.tick);
1063
+ entryPoint = { ...came, counts, samplesBefore: lines.length - after.length };
818
1064
  lines = after;
819
1065
  }
820
1066
  return {
@@ -825,6 +1071,7 @@ export async function replaySide(
825
1071
  ...(problem === undefined ? {} : { problem }),
826
1072
  ...(screenSkipped ? { startScreenSkipped: true } : {}),
827
1073
  ...(entryPoint === undefined ? {} : { entryPoint }),
1074
+ ...(entryRam === undefined ? {} : { entryRam }),
828
1075
  ...(ram === undefined ? {} : { ram }),
829
1076
  };
830
1077
  }
@@ -875,6 +1122,10 @@ export interface ReplayResult {
875
1122
  movedSites?: number;
876
1123
  /** Input reads of the rebuild that the recording had no value for: they got the idle value. */
877
1124
  idleReads?: number;
1125
+ /** A rebuild with a loader: where the reference at its entry differs from the entry state that the loader writes. */
1126
+ entryStateDiffers?: Array<{ start: string; end: string }>;
1127
+ /** A rebuild with a loader: why the entry state is not compared. */
1128
+ entryState?: string;
878
1129
  files?: Written[];
879
1130
  /** The screen of the reference at the end of the session (--screen). */
880
1131
  screen?: Written;
@@ -5,6 +5,7 @@
5
5
  // comparison, else the record file gave it.
6
6
 
7
7
  import { existsSync } from "node:fs";
8
+ import { basename } from "node:path";
8
9
 
9
10
  import { symbolsPath } from "#src/build-name.ts";
10
11
  import { isRefusal, Refusal } from "#src/errors.ts";
@@ -19,7 +20,7 @@ import { localToolContext } from "#src/native/local.ts";
19
20
  import { Workspace } from "#src/native/staging.ts";
20
21
  import { resolveProjectPath } from "#src/project.ts";
21
22
  import { UsageError } from "#src/script.ts";
22
- import { firstDifference, loaderEntry, mover, parseStateItem, pinLines, readRecording, replaySide, siteMap, type Comparison, type ReplayResult, type ReplaySubject } from "./recording.ts";
23
+ import { entryStateCheck, eventBeforeEntry, firstDifference, loaderEntry, mover, parseStateItem, pinLines, readRecording, replaySide, siteMap, type Comparison, type ReplayResult, type ReplaySubject } from "./recording.ts";
23
24
  import { cachedNames } from "./scenario.ts";
24
25
 
25
26
  const MAX_STATE_ITEMS = 16;
@@ -63,7 +64,7 @@ export interface ReplayAll {
63
64
  export async function replayAll(folders: readonly string[], values: Omit<ReplayOptions, "folder" | "screen">, one: (values: ReplayOptions) => Promise<ReplayResult> = replay): Promise<ReplayAll> {
64
65
  const recordings: ReplayResult[] = [];
65
66
  for (const folder of folders) {
66
- const name = folder.replace(/\/+$/, "").split("/").at(-1)!;
67
+ const name = basename(folder);
67
68
  try {
68
69
  recordings.push(await one({ ...values, folder, ...(values.out === undefined ? {} : { out: `${values.out}/${name}` }) }));
69
70
  } catch (error) {
@@ -155,11 +156,8 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
155
156
  const at = formatC64Address(loader.reference);
156
157
  if (entered === undefined) return result("INCONCLUSIVE", "reference", { reason: `the reference never came to ${at}, where the loader of the rebuild jumps` });
157
158
  // 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.
158
- const early = recording.events.slice(0, entered.eventsBefore).find((event) => !("pc" in event.key));
159
- if (early !== undefined) {
160
- const what = early.step === undefined ? "the RESTORE of the play" : `step ${early.step}`;
161
- 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` });
162
- }
159
+ const early = eventBeforeEntry(recording.events, entered.eventsBefore, loader.reference);
160
+ if (early !== undefined) return result("INCONCLUSIVE", "reference", { reason: early });
163
161
  handover = { entry: loader.entry, reference: entered };
164
162
  }
165
163
 
@@ -173,8 +171,11 @@ export async function replay(values: ReplayOptions): Promise<ReplayResult> {
173
171
  const pins = pinLines(expected, compare!.state);
174
172
  const replayed = await side(rebuild, { compare: compare!, stop: expected.length, pins, ...(handover === undefined ? {} : { handover }) });
175
173
  const difference = firstDifference(expected, replayed.samples, compare!.state);
174
+ // The loader of the rebuild writes the entry state of the capture it was made from: the rebuild at its entry has it.
175
+ const { entryRam } = replayed;
176
+ const entryState = handover === undefined || entryRam === undefined ? {} : entryStateCheck(handover.reference, recording.input ?? [], { sp: entryRam.sp, written: [{ start: 0x0002, end: 0x03ff }], byteAt: (address) => entryRam.ram[address]! });
176
177
  // A read that the recording has no value for gets the idle value: it is in the result, never silent.
177
- const base = { checkpoints: expected.length, ...named, movedSites, ...(replayed.startScreenSkipped === true ? { startScreen: "skipped" } : {}), ...(replayed.unknown > 0 ? { idleReads: replayed.unknown } : {}) };
178
+ const base = { checkpoints: expected.length, ...named, movedSites, ...(replayed.startScreenSkipped === true ? { startScreen: "skipped" } : {}), ...(replayed.unknown > 0 ? { idleReads: replayed.unknown } : {}), ...entryState };
178
179
  if (difference === undefined && replayed.samples.length >= expected.length) return result("PASS", "rebuild", { ...base, compared: expected.length });
179
180
  const reason =
180
181
  difference !== undefined
@@ -18,7 +18,7 @@ import { isInteger, isObject, MAX_MEMORY_READ, MAX_TRACE_FRAMES, MAX_TRACE_HITS,
18
18
  import { readProjectFile, readProjectJson, writeReported, type Written } from "#src/host-client/transfer.ts";
19
19
  import { readMemoryInParts, ViceSessionClient } from "#src/host-client/vice-session.ts";
20
20
  import { checkSnapshotFile } from "#src/media.ts";
21
- import { checkOutputPath, LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRelative, resolveProjectPath } from "#src/project.ts";
21
+ import { checkOutputPath, LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRelative, refuseAbsoluteInFile, resolveProjectPath } from "#src/project.ts";
22
22
  import { namesOf } from "./scenario.ts";
23
23
  import { namesStartScreen, passStartScreen } from "./start-screen.ts";
24
24
 
@@ -128,6 +128,9 @@ function readRun(path: string): Run {
128
128
  for (const key of Object.keys(start)) if (!(typeof start.program === "string" ? ["program", "load"] : ["snapshot"]).includes(key)) fail(`start has the key ${key}. start must be ${START_FORMS}`);
129
129
  if (start.load !== undefined && typeof start.load !== "boolean") fail("start.load must be true or false");
130
130
  if (value.symbols !== undefined && typeof value.symbols !== "string") fail('symbols must be "knowledge", "none" or a JSON file');
131
+ refuseAbsoluteInFile(start.program, "start.program", fail);
132
+ refuseAbsoluteInFile(start.snapshot, "start.snapshot", fail);
133
+ refuseAbsoluteInFile(value.symbols, "symbols", fail);
131
134
  if (!Array.isArray(value.steps) || value.steps.length === 0) fail("steps must be a list with at least one step");
132
135
  const labels = new Set<string>();
133
136
  (value.steps as unknown[]).forEach((step, index) => {
@@ -147,6 +150,7 @@ function readRun(path: string): Run {
147
150
  const name = step[kind];
148
151
  if (kind === "snapshot") {
149
152
  if (typeof name !== "string" || name === "") fail(`${at}: snapshot needs a project file`);
153
+ refuseAbsoluteInFile(name, `${at}: snapshot`, fail);
150
154
  return;
151
155
  }
152
156
  if (typeof name !== "string" || !NAME.test(name)) fail(`${at}: ${kind} needs a name of 1 to 64 letters, digits, dots, underscores or hyphens`);
@@ -17,6 +17,7 @@ import { openForRead } from "#src/knowledge/database.ts";
17
17
  import { nameTable } from "#src/knowledge/names.ts";
18
18
  import { DEFAULT_SPACE } from "#src/knowledge/schema.ts";
19
19
  import { programImage } from "#src/knowledge/program.ts";
20
+ import { refuseAbsoluteInFile } from "#src/project.ts";
20
21
  import { listed } from "#src/script.ts";
21
22
  import { namesStartScreen, passStartScreen } from "./start-screen.ts";
22
23
 
@@ -139,6 +140,8 @@ export function readScenario(path: string): Scenario {
139
140
  const form = `${side} must be { "program": "<file.prg>", "symbols": "knowledge" }. symbols can also be "none" or a JSON file`;
140
141
  if (!isObject(subject) || typeof subject.program !== "string" || typeof subject.symbols !== "string") return fail(form);
141
142
  for (const key of Object.keys(subject)) if (key !== "program" && key !== "symbols") fail(`${side} has the key ${key}. ${form}`);
143
+ refuseAbsoluteInFile(subject.program, `${side}.program`, fail);
144
+ refuseAbsoluteInFile(subject.symbols, `${side}.symbols`, fail);
142
145
  }
143
146
  if (!Array.isArray(scenario.steps) || scenario.steps.length === 0) fail("steps must be a list with at least one step");
144
147
  const labels = new Set<string>();
@@ -183,6 +186,7 @@ function checkStep(kind: string, step: Record<string, unknown>, at: string, fail
183
186
  return;
184
187
  case "snapshot":
185
188
  if (typeof step.snapshot !== "string" || step.snapshot === "") fail(`${at}: snapshot needs a .vsf file in the project`);
189
+ refuseAbsoluteInFile(step.snapshot, `${at}: snapshot`, fail);
186
190
  return;
187
191
  case "normalize":
188
192
  if (step.normalize !== true) fail(`${at}: normalize is true: it writes the entry state of the knowledge`);