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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-assembler/SKILL.md +3 -3
  3. package/skills/c64-assembler/scripts/assembler.ts +4 -3
  4. package/skills/c64-development/SKILL.md +3 -3
  5. package/skills/c64-docs/SKILL.md +6 -4
  6. package/skills/c64-docs/scripts/docs.ts +23 -10
  7. package/skills/c64-docs/scripts/lib/reference.ts +117 -31
  8. package/skills/c64-docs/scripts/lib/source-map.ts +14 -0
  9. package/skills/c64-knowledge/SKILL.md +10 -9
  10. package/skills/c64-knowledge/scripts/knowledge.ts +16 -9
  11. package/skills/c64-reverse-engineering/SKILL.md +9 -3
  12. package/skills/c64-source/SKILL.md +13 -10
  13. package/skills/c64-source/scripts/lib/export.ts +13 -2
  14. package/skills/c64-source/scripts/lib/loader.ts +51 -28
  15. package/skills/c64-source/scripts/lib/source.ts +24 -7
  16. package/skills/c64-source/scripts/source.ts +65 -47
  17. package/skills/c64-static-analysis/SKILL.md +26 -22
  18. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  19. package/skills/c64-static-analysis/scripts/lib/instructions.ts +4 -4
  20. package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
  21. package/skills/c64-static-analysis/scripts/static-analysis.ts +51 -35
  22. package/skills/c64-testing/SKILL.md +11 -4
  23. package/skills/c64-testing/references/recording-format.md +19 -7
  24. package/skills/c64-testing/references/scenario-format.md +6 -5
  25. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  26. package/skills/c64-testing/scripts/lib/play.ts +39 -37
  27. package/skills/c64-testing/scripts/lib/recording.ts +213 -65
  28. package/skills/c64-testing/scripts/lib/replay.ts +31 -5
  29. package/skills/c64-testing/scripts/lib/runs.ts +8 -3
  30. package/skills/c64-testing/scripts/lib/scenario.ts +4 -6
  31. package/skills/c64-testing/scripts/testing.ts +23 -2
  32. package/skills/c64-unpacker/SKILL.md +6 -3
  33. package/skills/c64-unpacker/scripts/lib/loads.ts +2 -2
  34. package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
  35. package/skills/c64-unpacker/scripts/unpacker.ts +38 -6
  36. package/skills/emulator/SKILL.md +2 -5
  37. package/src/build-name.ts +9 -4
  38. package/src/c64-keys.ts +98 -0
  39. package/src/c64.ts +1 -1
  40. package/src/host/main.ts +2 -2
  41. package/src/host/server.ts +3 -1
  42. package/src/host/tools/index.ts +1 -1
  43. package/src/host/vice/process.ts +34 -17
  44. package/src/host/vice/session.ts +132 -30
  45. package/src/host-client/steps.ts +21 -18
  46. package/src/host-client/tools.ts +1 -1
  47. package/src/host-client/vice-session.ts +7 -1
  48. package/src/knowledge/evidence.ts +66 -0
  49. package/src/knowledge/history.ts +5 -5
  50. package/src/knowledge/import.ts +12 -5
  51. package/src/knowledge/program.ts +81 -33
  52. package/src/knowledge/read.ts +12 -3
  53. package/src/knowledge/schema.ts +7 -7
  54. package/src/knowledge/start-screen.ts +2 -0
  55. package/src/knowledge/text.ts +28 -3
  56. package/src/knowledge/write.ts +6 -6
  57. package/src/mcp/inputs.ts +12 -0
  58. package/src/mcp/server.ts +1 -0
  59. package/src/mcp/tools/debug.ts +23 -21
  60. package/src/mcp/tools/input.ts +38 -5
  61. package/src/mcp/tools/memory.ts +12 -9
  62. package/src/native/c64run.ts +7 -4
  63. package/src/native/{ghidra → decompiler}/analyze.ts +17 -17
  64. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  65. package/src/native/{ghidra → decompiler}/walk.ts +6 -6
  66. package/src/native/discover.ts +3 -3
  67. package/src/native/processes.ts +3 -3
  68. package/src/native/types.ts +25 -25
  69. package/src/opcodes.ts +1 -1
  70. package/src/protocol/vice.ts +47 -0
  71. package/src/reference-pages.ts +64 -0
  72. package/src/script.ts +1 -1
  73. package/src/vsf.ts +98 -0
  74. package/tools/c64run.c +158 -15
  75. package/skills/c64-testing/scripts/lib/keys.ts +0 -36
  76. /package/src/native/{ghidra → decompiler}/c64rt-wasm.ts +0 -0
  77. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  78. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  79. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
  80. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.sla +0 -0
  81. /package/src/native/{ghidra → decompiler}/pcode.ts +0 -0
  82. /package/src/native/{ghidra → decompiler}/wasm.ts +0 -0
@@ -5,13 +5,14 @@
5
5
 
6
6
  import { isOneOf, WireFailure, type VideoStandard } from "../../protocol/messages.ts";
7
7
  import { DISK_IMAGE_TYPES, type DiskFile, type DiskImageType } from "../../protocol/tools.ts";
8
- import { MAX_BASELINES, MAX_SNAPSHOTS, MAX_COMPARE_DIFFERENCES, RASTER, type Breakpoint, type BreakpointParams, type PointRemoved, type Condition, type ExecutionParams, type HistoryEntry, type RunTarget, type RunUntilResult, type ScreenComparison, type CiaSelection, type CiaState, type ObserveParams, type ObserveResult, type SidState, type SpriteState, type ViciiState, type JoystickState, type Watchpoint, type WatchpointParams, type ExecutionResult, type MachineStatus, type TraceHit, type TraceKind, type TraceResult, type PointStopReason, type RunState, type ViceOperation, type ViceOperations, type WindowResult } from "../../protocol/vice.ts";
8
+ import { MAX_BASELINES, MAX_SNAPSHOTS, MAX_COMPARE_DIFFERENCES, RASTER, type Breakpoint, type BreakpointParams, type PointRemoved, type Condition, type ExecutionParams, type HistoryEntry, type RunTarget, type RunUntilResult, type ScreenComparison, type CiaSelection, type CiaState, type ObserveParams, type ObserveResult, type SidState, type SpriteState, type ViciiState, type JoystickState, type Watchpoint, type WatchpointParams, type ExecutionResult, type MachineStatus, type TraceHit, type TraceKind, type TraceResult, type PointStopReason, type PressResult, type RunState, type ViceOperation, type ViceOperations, type WindowResult } from "../../protocol/vice.ts";
9
9
  import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
10
10
  import { tmpdir } from "node:os";
11
11
  import { join } from "node:path";
12
12
  import { setTimeout as sleep } from "node:timers/promises";
13
13
 
14
14
  import { formatC64Address, instructionLength } from "../../c64.ts";
15
+ import { matrixRows } from "../../c64-keys.ts";
15
16
  import { encodePng, type IndexedFrame } from "../../graphics.ts";
16
17
  import { accessedValue, instructionText, operandAddress } from "../../opcodes.ts";
17
18
  import type { ProcessSupervisor } from "../../native/processes.ts";
@@ -33,6 +34,7 @@ import { compareFrames, differenceImage } from "./screen.ts";
33
34
  import { isRefusal } from "../../errors.ts";
34
35
  import type { ViceFeature, ViceFlaw } from "../../native/discover.ts";
35
36
  import { checkMedia, hasSignature } from "../../media.ts";
37
+ import { pressSnapshotRestore, setSnapshotMatrix } from "../../vsf.ts";
36
38
  import { launchVice, startErrorLines, type ViceMode, type ViceProcess } from "./process.ts";
37
39
  import { TextMonitorError, TextMonitorTimeoutError } from "./text-monitor.ts";
38
40
 
@@ -80,7 +82,6 @@ const WINDOW_CLOSED =
80
82
  "Breakpoints and watchpoints are kept. Check the machine state before you continue.";
81
83
 
82
84
  /** Emulator state that a move to another VICE cannot carry. */
83
- /** The first bytes of every VICE snapshot file. */
84
85
  const NOT_CARRIED = ["cpu history", "memory map", "profile", "keyboard input not yet typed"];
85
86
 
86
87
  /** Starts another VICE for this session; `log` also gets that launch's lines. */
@@ -136,9 +137,11 @@ export interface SessionOptions {
136
137
  const BROKEN_MESSAGES: Record<ViceFeature, string> = {
137
138
  joystick: "Joystick input is not implemented in this setup. Do not use the joystick in this task. Give this message to the user.",
138
139
  tape: "The load of a tape image is not implemented in this setup. Do not load tape images in this task. Give this message to the user.",
140
+ keyboard: "Keys of the keyboard matrix are not implemented in this setup. Do not press keys in this task. Give this message to the user.",
139
141
  };
140
142
 
141
- export type DiskDirectory = (type: DiskImageType, image: Buffer) => Promise<DiskFile[]>;
143
+ /** `signal` aborts when the session closes. */
144
+ export type DiskDirectory = (type: DiskImageType, image: Buffer, signal: AbortSignal) => Promise<DiskFile[]>;
142
145
 
143
146
  /**
144
147
  * Where VICE keeps a staged file: an autostarted disk stays in drive 8, a tape
@@ -167,6 +170,8 @@ export class ViceSession implements ViceSessionHandle {
167
170
  readonly #stepLimitMs: number;
168
171
  readonly #launch: ViceLauncher | undefined;
169
172
  readonly #directory: DiskDirectory | undefined;
173
+ /** Stops the host tool runs of this session when it closes. */
174
+ readonly #abort = new AbortController();
170
175
  /** Session files that outlive one VICE: snapshots, staged media, handovers. */
171
176
  readonly #workDir: string;
172
177
  readonly #releaseWorkDir: () => void;
@@ -370,6 +375,7 @@ export class ViceSession implements ViceSessionHandle {
370
375
 
371
376
  async close(): Promise<void> {
372
377
  this.#closed = true;
378
+ this.#abort.abort();
373
379
  try {
374
380
  await this.#vice.stop();
375
381
  } finally {
@@ -433,7 +439,7 @@ export class ViceSession implements ViceSessionHandle {
433
439
  if (type === "tap") this.#refuseBroken("tape", "c64_autostart of a tape image");
434
440
  const bytes = onlyAttachment(attachments);
435
441
  checkMedia(type, bytes);
436
- if (index > 0 && this.#directory !== undefined && isOneOf(DISK_IMAGE_TYPES, type)) checkDirectoryEntry(await this.#directory(type, bytes), index);
442
+ if (index > 0 && this.#directory !== undefined && isOneOf(DISK_IMAGE_TYPES, type)) checkDirectoryEntry(await this.#directory(type, bytes, this.#abort.signal), index);
437
443
  const file = this.#stage(bytes, type);
438
444
  // VICE keeps a cartridge through every reset and autostart, as a real C64 does.
439
445
  if (type !== "crt" && this.#cartridge) {
@@ -472,16 +478,12 @@ export class ViceSession implements ViceSessionHandle {
472
478
  return this.#reset(params as ViceOperations["reset"]["params"]);
473
479
  case "keyboard": {
474
480
  const bytes = Buffer.from((params as ViceOperations["keyboard"]["params"]).data, "hex");
475
- // VICE turns warp on for an autostart and off when it types RUN. A key in between ends the autostart with no message.
476
- if (this.#autostarting && !this.#userWarp && (await this.#observe(() => this.#machine.warp()))) {
477
- throw new WireFailure(
478
- "operation-failed",
479
- "The autostart still loads the program, and a key now stops it before RUN. Run frames with c64_execution advance-frames, then type again.",
480
- );
481
- }
481
+ await this.#refuseWhileAutostartLoads("a key now stops it before RUN", "type");
482
482
  await this.#observe(() => this.#machine.feedKeyboard(bytes));
483
483
  return { queuedBytes: bytes.length };
484
484
  }
485
+ case "press":
486
+ return this.#press(params as ViceOperations["press"]["params"]);
485
487
  case "breakpoint":
486
488
  return this.#breakpoint(params as BreakpointParams);
487
489
  case "watchpoint":
@@ -719,12 +721,16 @@ export class ViceSession implements ViceSessionHandle {
719
721
  // running, and only a stop caused by this breakpoint counts.
720
722
  const vector = await this.#machine.resetVector();
721
723
  const checkpoint = await this.#machine.addCheckpoint({ start: vector, end: vector, operation: 0x04, space: "c64" });
722
- await this.#resume();
723
- const stopped = this.#nextStop(RESET_STOP_LIMIT_MS, checkpoint);
724
- await this.#resumingCommand(() => this.#machine.reset(params.mode));
725
- const reached = (await stopped) !== undefined;
726
- if (!reached) await this.#stop();
727
- await this.#machine.deleteCheckpoint(checkpoint);
724
+ let reached: boolean;
725
+ try {
726
+ await this.#resume();
727
+ const stopped = this.#nextStop(RESET_STOP_LIMIT_MS, checkpoint);
728
+ await this.#resumingCommand(() => this.#machine.reset(params.mode));
729
+ reached = (await stopped) !== undefined;
730
+ if (!reached) await this.#stop();
731
+ } finally {
732
+ await this.#machine.deleteCheckpoint(checkpoint);
733
+ }
728
734
  if (!reached) throw new WireFailure("operation-failed", "The C64 did not reach its reset vector after the reset.");
729
735
  this.#atResetStop = true;
730
736
  return { state: "stopped", pc: vector };
@@ -848,6 +854,9 @@ export class ViceSession implements ViceSessionHandle {
848
854
  hits.push(await this.#traceHit(index, params.points[index]!.kind, frames));
849
855
  if (hits.length >= params.maxHits) return { hits, frames, end: "hits", pc: stop.pc };
850
856
  }
857
+ // A user point ends the trace, also when a trace point or the clock hit in the same stop.
858
+ const point = this.#userPoint(stop.hits);
859
+ if (point !== undefined) return { hits, frames, end: point.stopReason, pc: stop.pc };
851
860
  if (stop.hits.includes(clock)) {
852
861
  if (stop.pc === clockPc && (await this.#jamAt(stop.pc))) return { hits, frames, end: "jam", pc: stop.pc };
853
862
  clockPc = stop.pc;
@@ -861,8 +870,6 @@ export class ViceSession implements ViceSessionHandle {
861
870
  continue;
862
871
  }
863
872
  if (traced.length > 0) continue;
864
- const point = this.#userPoint(stop.hits);
865
- if (point !== undefined) return { hits, frames, end: point.stopReason, pc: stop.pc };
866
873
  if (await this.#jamAt(stop.pc)) return { hits, frames, end: "jam", pc: stop.pc };
867
874
  if (this.#pendingStep) {
868
875
  this.#pendingStep = false;
@@ -1185,6 +1192,94 @@ export class ViceSession implements ViceSessionHandle {
1185
1192
  return publicView(point);
1186
1193
  }
1187
1194
 
1195
+ /**
1196
+ * VICE turns warp on for an autostart and off when it types RUN. A key in
1197
+ * between ends the autostart with no message, and another VICE does not go on with it.
1198
+ */
1199
+ async #refuseWhileAutostartLoads(effect: string, verb: string): Promise<void> {
1200
+ if (this.#autostarting && !this.#userWarp && (await this.#observe(() => this.#machine.warp()))) {
1201
+ throw new WireFailure(
1202
+ "operation-failed",
1203
+ `The autostart still loads the program, and ${effect}. Run frames with c64_execution advance-frames, then ${verb} again.`,
1204
+ );
1205
+ }
1206
+ }
1207
+
1208
+ /** VICE (3.9, 3.10) stops answering at the restore of a snapshot saved at the reset stop while the disk drive was busy. */
1209
+ #refuseAtResetStop(verb: string): void {
1210
+ if (!this.#atResetStop) return;
1211
+ throw new WireFailure(
1212
+ "operation-failed",
1213
+ "The CPU stands at the reset stop of c64_reset with run false. The emulator stops answering at the restore of a snapshot saved here when the disk drive was busy. " +
1214
+ `Step one instruction with c64_execution, then ${verb}.`,
1215
+ );
1216
+ }
1217
+
1218
+ /**
1219
+ * Presses keys of the keyboard matrix and RESTORE. VICE has no command for
1220
+ * that: a snapshot gets the keys in its keyboard module, and RESTORE as a
1221
+ * pending NMI, and is restored at the same cycle. Each tap holds its keys
1222
+ * for `frames` frames, then waits `frames` frames with all keys up. A
1223
+ * breakpoint, watchpoint or JAM ends the taps early, and the machine stays
1224
+ * stopped; else it runs again when it ran before. All keys are up at the end.
1225
+ */
1226
+ async #press(params: ViceOperations["press"]["params"]): Promise<PressResult> {
1227
+ this.#refuseBroken("keyboard", "c64_press");
1228
+ await this.#refuseWhileAutostartLoads("a key now stops it before RUN", "press the keys");
1229
+ if (this.#atResetStop) {
1230
+ throw new WireFailure(
1231
+ "operation-failed",
1232
+ "The CPU stands at the reset stop of c64_reset with run false. The emulator stops answering when keys are pressed here while the disk drive is busy. " +
1233
+ "Step one instruction with c64_execution, then press the keys.",
1234
+ );
1235
+ }
1236
+ const running = this.#state === "running";
1237
+ await this.#stop();
1238
+ await this.#refuseJammed("press");
1239
+ let taps = 0;
1240
+ for (const tap of params.taps) {
1241
+ await this.#setKeys(matrixRows(tap.keys), tap.restore);
1242
+ const held = await this.#runFrames(params.frames);
1243
+ await this.#setKeys(matrixRows([]), false);
1244
+ const end = held.end === "frames" ? await this.#runFrames(params.frames) : held;
1245
+ if (end.end !== "frames") {
1246
+ this.#stopSpace = end.space;
1247
+ return {
1248
+ taps,
1249
+ state: "stopped",
1250
+ stopReason: end.end as PointStopReason,
1251
+ pc: end.space === "drive8" ? (await this.#machine.readRegisters("drive8")).pc : end.pc,
1252
+ space: end.space,
1253
+ ...(end.pointId === undefined ? {} : { pointId: end.pointId }),
1254
+ };
1255
+ }
1256
+ taps++;
1257
+ }
1258
+ if (running) await this.#resume();
1259
+ return { taps, state: this.#state };
1260
+ }
1261
+
1262
+ /** Sets the keyboard matrix (`rows`, bit n of row r for column n), and presses RESTORE, in a snapshot restored at the same cycle. */
1263
+ async #setKeys(rows: number[], restore: boolean): Promise<void> {
1264
+ const file = join(this.#workDir, "press.vsf");
1265
+ try {
1266
+ await this.#machine.saveSnapshot(file);
1267
+ const bytes = readFileSync(file);
1268
+ const why = setSnapshotMatrix(bytes, rows) ?? (restore ? pressSnapshotRestore(bytes) : undefined);
1269
+ if (why !== undefined) {
1270
+ this.#log(`c64_press was used, and this VICE writes snapshots that c64-re-tools does not know: ${why}.`);
1271
+ throw new WireFailure("not-implemented", BROKEN_MESSAGES.keyboard);
1272
+ }
1273
+ writeFileSync(file, bytes);
1274
+ await this.#machine.restoreSnapshot(file);
1275
+ } finally {
1276
+ rmSync(file, { force: true });
1277
+ }
1278
+ // A restore starts the CPU history of VICE again.
1279
+ this.#historySince = await this.#machine.clock();
1280
+ if (this.#historyStopped) this.#historyOld = true;
1281
+ }
1282
+
1188
1283
  /**
1189
1284
  * Refuses a tool that a known flaw of this VICE breaks: not-implemented for
1190
1285
  * the caller, without the VICE version, and the flaw on the host console.
@@ -1337,13 +1432,7 @@ export class ViceSession implements ViceSessionHandle {
1337
1432
  if (params.action === "list") return { snapshots: [...this.#snapshots.keys()] };
1338
1433
  const existing = this.#snapshots.get(params.name);
1339
1434
  if (params.action === "save") {
1340
- if (this.#atResetStop) {
1341
- throw new WireFailure(
1342
- "operation-failed",
1343
- "The CPU stands at the reset stop of c64_reset with run false. The emulator stops answering at the restore of a snapshot saved here when the disk drive was busy. " +
1344
- "Step one instruction with c64_execution, then save the snapshot.",
1345
- );
1346
- }
1435
+ this.#refuseAtResetStop("save the snapshot");
1347
1436
  if (existing === undefined && this.#snapshots.size >= MAX_SNAPSHOTS) {
1348
1437
  throw new WireFailure("limit-exceeded", `A session keeps at most ${MAX_SNAPSHOTS} snapshots. Remove one first with action remove.`);
1349
1438
  }
@@ -1369,6 +1458,8 @@ export class ViceSession implements ViceSessionHandle {
1369
1458
  if (this.#autostarting) await this.#reset({ mode: "soft", run: false });
1370
1459
  await this.#machine.restoreSnapshot(file);
1371
1460
  this.#historySince = await this.#machine.clock();
1461
+ // A save at the reset stop is refused, so no restored machine stands there.
1462
+ this.#atResetStop = false;
1372
1463
  // A restore starts a jammed CPU again, but VICE still records no CPU history.
1373
1464
  this.#jammed = undefined;
1374
1465
  if (this.#historyStopped) this.#historyOld = true;
@@ -1392,12 +1483,19 @@ export class ViceSession implements ViceSessionHandle {
1392
1483
  if (!hasSignature("vsf", bytes)) throw new WireFailure("invalid-input", "The file is not a VICE snapshot file (.vsf). Give a file that c64_snapshot save wrote.");
1393
1484
  const file = this.#stage(bytes, "vsf");
1394
1485
  // VICE resets the machine after a snapshot file that it cannot read: a backup keeps the state before the restore.
1395
- const backup = join(this.#workDir, "before-restore.vsf");
1486
+ // At the reset stop there is none: VICE can stop answering at the restore of a snapshot saved there (#atResetStop).
1487
+ const backup = this.#atResetStop ? undefined : join(this.#workDir, "before-restore.vsf");
1396
1488
  await this.#stop();
1397
- await this.#machine.saveSnapshot(backup);
1489
+ if (backup !== undefined) await this.#machine.saveSnapshot(backup);
1398
1490
  try {
1399
1491
  return await this.#restoreFrom(file);
1400
1492
  } catch (error) {
1493
+ if (backup === undefined) {
1494
+ throw new WireFailure(
1495
+ "machine-state-lost",
1496
+ "The emulator did not restore this snapshot file, and it reset the machine. A snapshot file restores only in the emulator version and with the machine settings that saved it. Use c64_reset with run false to stop at the reset again.",
1497
+ );
1498
+ }
1401
1499
  const kept = await this.#restoreFrom(backup).then(
1402
1500
  () => true,
1403
1501
  () => false,
@@ -1415,7 +1513,7 @@ export class ViceSession implements ViceSessionHandle {
1415
1513
  );
1416
1514
  } finally {
1417
1515
  rmSync(file, { force: true });
1418
- rmSync(backup, { force: true });
1516
+ if (backup !== undefined) rmSync(backup, { force: true });
1419
1517
  }
1420
1518
  }
1421
1519
 
@@ -1432,13 +1530,17 @@ export class ViceSession implements ViceSessionHandle {
1432
1530
  if (this.#mode === mode) return { window: mode === "window", state: this.#state, notCarried: [] };
1433
1531
  if (this.#held !== undefined) throw new WireFailure("machine-unavailable", this.#heldWhy);
1434
1532
  if (this.#launch === undefined) throw new WireFailure("operation-failed", "This session cannot start another emulator.");
1533
+ const verb = mode === "window" ? "open the window" : "close the window";
1534
+ this.#refuseAtResetStop(verb);
1535
+ await this.#refuseWhileAutostartLoads("a move to another emulator now stops it before RUN", verb);
1435
1536
  const running = this.#state === "running";
1436
1537
  this.#log(mode === "window" ? "moving the machine to a VICE with a window" : "moving the machine back to a headless VICE");
1437
1538
  await this.#stop();
1438
1539
  const handover: Handover = {
1439
1540
  file: join(this.#workDir, mode === "window" ? "window-open.vsf" : "window-close.vsf"),
1440
1541
  running,
1441
- warp: await this.#machine.warp(),
1542
+ // VICE's own warp can be the one of a loading autostart.
1543
+ warp: this.#userWarp,
1442
1544
  elapsed: (await this.#machine.clock()) - this.#timingStart,
1443
1545
  };
1444
1546
  await this.#machine.saveSnapshot(handover.file);
@@ -7,13 +7,14 @@
7
7
  // type c64_keyboard { mode: "text", text } or { mode: "petscii", bytes }: the KERNAL keyboard queue
8
8
  // frames c64_execution the count of advance-frames
9
9
  // runUntil c64_run_until { target, timeoutFrames? }
10
- // press (no tool) keys of the keyboard matrix; only the replay core of c64-testing record and replay has them
10
+ // press c64_press { keys, frames? }: keys of the keyboard matrix and RESTORE
11
11
  //
12
12
  // An address in a step is $ and 1 to 4 hex digits, or a name that the script resolves.
13
13
  // The scripts install without packages, so this checker has no zod: the MCP
14
14
  // tools keep their zod schemas, and a test checks that both take the same inputs.
15
15
 
16
16
  import { c64AddressOf, SYMBOL_NAME, textToPetscii } from "../c64.ts";
17
+ import { keyTaps, MAX_PRESS_FRAMES, PRESS_FRAMES, type KeyTap } from "../c64-keys.ts";
17
18
  import { isRefusal, Refusal } from "../errors.ts";
18
19
  import {
19
20
  COMPARISONS,
@@ -57,14 +58,12 @@ export type ActionStep =
57
58
  | { registers: { pc?: Location; a?: number; x?: number; y?: number; sp?: number; flags?: Flags } }
58
59
  | { joystick: { port: 1 | 2; direction: (typeof JOYSTICK_DIRECTIONS)[number]; fire: boolean } }
59
60
  | { type: KeyboardInput }
60
- | { press: string }
61
+ | { press: { keys: string; frames: number } }
61
62
  | { frames: number }
62
63
  | { runUntil: { target: StepTarget; timeoutFrames: number } };
63
64
 
64
65
  export const ACTION_STEP_KINDS = ["write", "registers", "joystick", "type", "press", "frames", "runUntil"] as const;
65
66
  export type ActionStepKind = (typeof ACTION_STEP_KINDS)[number];
66
- /** The step kinds that VICE runs: all but press, which only the replay core has. */
67
- export const VICE_STEP_KINDS = ACTION_STEP_KINDS.filter((kind) => kind !== "press");
68
67
 
69
68
  /** The fields of each object of the steps: the same as the inputs of the MCP tools. */
70
69
  export const STEP_FIELDS = {
@@ -72,6 +71,7 @@ export const STEP_FIELDS = {
72
71
  registers: ["pc", "a", "x", "y", "sp", "flags"],
73
72
  joystick: ["port", "direction", "fire"],
74
73
  type: ["mode", "text", "bytes"],
74
+ press: ["keys", "frames"],
75
75
  runUntil: ["target", "timeoutFrames"],
76
76
  addressTarget: ["kind", "address", "space", "condition"],
77
77
  memoryTarget: ["kind", "address", "operator", "value", "space", "view"],
@@ -228,9 +228,6 @@ function checkTarget(value: unknown, where: string, fail: (message: string) => n
228
228
  return fail(`${where}.kind must be one of address, memory, raster`);
229
229
  }
230
230
 
231
- /** What a step of a script without the replay core gets for press: the scripts that read these steps run without a window. */
232
- const PRESS_REMEDY = "press pushes keys of the keyboard matrix, and only the replay of a record file has them. Use type for the KERNAL keyboard queue, or put the press step in a record file and play the record file";
233
-
234
231
  /** Checks the input of one step kind and returns it with the defaults of its MCP tool. */
235
232
  function checkInput(kind: ActionStepKind, value: unknown, at: string, fail: (message: string) => never): ActionStep {
236
233
  const where = `${at}: ${kind}`;
@@ -275,9 +272,14 @@ function checkInput(kind: ActionStepKind, value: unknown, at: string, fail: (mes
275
272
  else if (keys.length > MAX_KEYBOARD_BYTES) fail(`${where}: the keyboard queue takes at most ${MAX_KEYBOARD_BYTES} keys at once. This input has ${keys.length} keys`);
276
273
  return { type: input };
277
274
  }
278
- case "press":
279
- if (typeof value !== "string" || value === "") fail(`${where} needs the keys to press as text`);
280
- return { press: value as string };
275
+ case "press": {
276
+ const fields = new Fields(value, where, STEP_FIELDS.press, fail);
277
+ const keys = fields.get("keys");
278
+ if (typeof keys !== "string") fields.fail("keys", "must be the keys as text, for example {F1} or {LSHIFT+CBM}");
279
+ const taps = keyTaps(keys as string);
280
+ if (typeof taps === "string") fail(`${where}.keys: ${taps}`);
281
+ return { press: { keys: keys as string, frames: fields.integer("frames", 1, MAX_PRESS_FRAMES, PRESS_FRAMES) } };
282
+ }
281
283
  case "frames":
282
284
  if (!isInteger(value, 1, MAX_TIMEOUT_FRAMES)) fail(`${where} must be a frame count from 1 to ${MAX_TIMEOUT_FRAMES}`);
283
285
  return { frames: value as number };
@@ -342,6 +344,9 @@ export function newStepForm(kind: string, step: Record<string, unknown>): { fiel
342
344
  }
343
345
  }
344
346
 
347
+ /** "a write step", "an observe step": the step kind with its article, for a refusal. */
348
+ export const aStep = (kind: string): string => `${/^[aeiou]/.test(kind) ? "an" : "a"} ${kind} step`;
349
+
345
350
  /** Refuses a step in a form of the 2.0 files: the message names its 2.0 fields and gives the step to write. */
346
351
  export function refuseOldStep(kind: string, step: Record<string, unknown>, at: string, fail: (message: string) => never): void {
347
352
  const found = newStepForm(kind, step);
@@ -352,14 +357,12 @@ export function refuseOldStep(kind: string, step: Record<string, unknown>, at: s
352
357
 
353
358
  /**
354
359
  * Checks one action step of the given kind and returns it with the defaults
355
- * filled in. The step has no other key. `press` is refused unless the caller
356
- * runs the steps on the replay core. A step in a form of the 2.0 files is
360
+ * filled in. The step has no other key. A step in a form of the 2.0 files is
357
361
  * refused with the step to write.
358
362
  */
359
- export function checkActionStep(kind: ActionStepKind, step: Record<string, unknown>, at: string, fail: (message: string) => never, options: { press?: boolean } = {}): ActionStep {
363
+ export function checkActionStep(kind: ActionStepKind, step: Record<string, unknown>, at: string, fail: (message: string) => never): ActionStep {
360
364
  refuseOldStep(kind, step, at, fail);
361
- for (const key of Object.keys(step)) if (key !== kind) fail(`${at} has the key ${key}, which a ${kind} step does not have`);
362
- if (kind === "press" && options.press !== true) fail(`${at}: ${PRESS_REMEDY}`);
365
+ for (const key of Object.keys(step)) if (key !== kind) fail(`${at} has the key ${key}, which ${aStep(kind)} does not have`);
363
366
  return checkInput(kind, step[kind], at, fail);
364
367
  }
365
368
 
@@ -376,11 +379,11 @@ export function stepKind<K extends string>(step: unknown, kinds: readonly K[], a
376
379
  }
377
380
 
378
381
  /** Checks a list of action steps and returns them with the defaults filled in. */
379
- export function checkActionSteps(value: unknown, fail: (message: string) => never, options: { press?: boolean } = {}): ActionStep[] {
382
+ export function checkActionSteps(value: unknown, fail: (message: string) => never): ActionStep[] {
380
383
  if (!Array.isArray(value) || value.length === 0) return fail("the steps are a JSON list with at least one step");
381
384
  return value.map((step: unknown, index) => {
382
385
  const at = `step ${index + 1}`;
383
- return checkActionStep(stepKind(step, ACTION_STEP_KINDS, at, fail, options.press === true ? ACTION_STEP_KINDS : VICE_STEP_KINDS), step as Record<string, unknown>, at, fail, options);
386
+ return checkActionStep(stepKind(step, ACTION_STEP_KINDS, at, fail), step as Record<string, unknown>, at, fail);
384
387
  });
385
388
  }
386
389
 
@@ -471,7 +474,7 @@ export async function runActionStep(client: ViceSessionClient, step: ActionStep,
471
474
  } else if ("type" in step) {
472
475
  await client.keyboard(keyboardBytes(step.type) as Uint8Array);
473
476
  } else if ("press" in step) {
474
- throw new Refusal("invalid-input", PRESS_REMEDY);
477
+ await client.press(keyTaps(step.press.keys) as KeyTap[], step.press.frames);
475
478
  } else if ("frames" in step) {
476
479
  await stop(client);
477
480
  // One advance-frames runs at most MAX_EXECUTION_COUNT frames. Each part ends at the raster position
@@ -1,7 +1,7 @@
1
1
  // Short-lived typed requests to the Host Runtime for skill scripts:
2
2
  // VICE's own tools (c1541, petcat) and the host tool status. Each request
3
3
  // opens its own "tool" connection, sends bytes, and closes. Skill scripts run
4
- // ACME, DXA and Ghidra themselves through src/native (Ghidra in process).
4
+ // ACME, DXA and the decompiler themselves through src/native (the decompiler in process).
5
5
 
6
6
  import { ProtocolError, WireFailure } from "../protocol/messages.ts";
7
7
  import { DISK_IMAGE_TYPES, validateToolResult, type C1541Result, type DiskAction, type DiskImageType, type DiskSector, type PetcatResult, type ToolOperation, type ToolOperations } from "../protocol/tools.ts";
@@ -2,7 +2,8 @@
2
2
  // one VICE. Exposes C64-domain operations only.
3
3
 
4
4
  import { ProtocolError, WireFailure, type VideoStandard } from "../protocol/messages.ts";
5
- import { MAX_MEMORY_READ, traceHitsFromAttachment, validateViceResult, type TraceResult, type Breakpoint, type BreakpointParams, type PointRemoved, type Watchpoint, type WatchpointParams, type ExecutionParams, type ExecutionResult, type JoystickState, type MachineStatus, type MemmapRange, type MemoryWriteParams, type ProfileEntry, type RegisterValues, type ResetMode, type RunState, type RunTarget, type RunUntilResult, type MemoryReadParams, type MemoryReadResult, type Registers, type Space, type ViceOperation, type ViceOperations } from "../protocol/vice.ts";
5
+ import { MAX_MEMORY_READ, traceHitsFromAttachment, validateViceResult, type TraceResult, type Breakpoint, type BreakpointParams, type PointRemoved, type Watchpoint, type WatchpointParams, type ExecutionParams, type ExecutionResult, type JoystickState, type MachineStatus, type PressResult, type MemmapRange, type MemoryWriteParams, type ProfileEntry, type RegisterValues, type ResetMode, type RunState, type RunTarget, type RunUntilResult, type MemoryReadParams, type MemoryReadResult, type Registers, type Space, type ViceOperation, type ViceOperations } from "../protocol/vice.ts";
6
+ import type { KeyTap } from "../c64-keys.ts";
6
7
  import { HostConnection } from "./connect.ts";
7
8
  import { readProjectFile } from "./transfer.ts";
8
9
 
@@ -158,6 +159,11 @@ export class ViceSessionClient {
158
159
  return this.#request("joystick", state);
159
160
  }
160
161
 
162
+ /** Presses keys of the keyboard matrix and RESTORE: each tap holds its keys `frames` frames, then waits `frames` frames with all keys up. */
163
+ press(taps: KeyTap[], frames: number): Promise<PressResult> {
164
+ return this.#request("press", { taps, frames });
165
+ }
166
+
161
167
  /** Action list gives all breakpoints, remove gives `{removed, id}`; add, enable and disable give the one breakpoint. */
162
168
  breakpoint(params: Extract<BreakpointParams, { action: "list" }>): Promise<{ breakpoints: Breakpoint[] }>;
163
169
  breakpoint(params: Extract<BreakpointParams, { action: "remove" }>): Promise<PointRemoved>;
@@ -0,0 +1,66 @@
1
+ // The files that the knowledge gives as evidence, against the project as it
2
+ // is now. A revision keeps the SHA-256 of each file that it rests on, so a
3
+ // file that is gone or that changed since then shows here.
4
+
5
+ import { createHash } from "node:crypto";
6
+ import { readFileSync } from "node:fs";
7
+ import type { DatabaseSync } from "node:sqlite";
8
+
9
+ import { LOCAL_DIRECTORY, PROJECT_DIRECTORY, resolveProjectFile } from "../project.ts";
10
+ import { coverageRuns } from "./read.ts";
11
+
12
+ /** A file of the evidence that is not as the knowledge gives it: missing, or with other bytes. */
13
+ export interface EvidenceChange {
14
+ /** The project path of the file. */
15
+ file: string;
16
+ state: "missing" | "changed";
17
+ /** The revisions that give the file with the SHA-256 that the file no longer has, oldest first. */
18
+ revisions: string[];
19
+ }
20
+
21
+ /** The SHA-256 of a project file, or undefined when it is not there. */
22
+ function fileHash(root: string, path: string): string | undefined {
23
+ try {
24
+ return createHash("sha256").update(readFileSync(resolveProjectFile(path, root))).digest("hex");
25
+ } catch {
26
+ return undefined;
27
+ }
28
+ }
29
+
30
+ /**
31
+ * The evidence files that are missing or changed. A file counts with its
32
+ * latest SHA-256 in the knowledge: for a coverage map, its latest import
33
+ * into each space; for another file, the latest revision that gives it. An
34
+ * earlier SHA-256 of the same file is history. A file in
35
+ * .c64-re-tools/local/ does not count: git does not keep it, and the
36
+ * knowledge keeps what it needs of it. `only` limits the check to some files.
37
+ */
38
+ export function changedEvidence(db: DatabaseSync | undefined, root: string, only?: (file: string) => boolean): EvidenceChange[] {
39
+ if (db === undefined) return [];
40
+ const rows = db.prepare("SELECT revision, kind, ref, sha256 FROM evidence WHERE sha256 IS NOT NULL ORDER BY revision, id").all() as Array<{ revision: string; kind: string; ref: string; sha256: string }>;
41
+ const local = `${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/`;
42
+ const wanted = (file: string) => !file.startsWith(local) && (only === undefined || only(file));
43
+ // The SHA-256 values that each file must have now.
44
+ const expected = new Map<string, Set<string>>();
45
+ const expect = (file: string, sha256: string) => {
46
+ if (!wanted(file)) return;
47
+ if (!expected.has(file)) expected.set(file, new Set());
48
+ expected.get(file)!.add(sha256);
49
+ };
50
+ const latest = new Map<string, string>();
51
+ for (const row of rows) if (row.kind !== "coverage") latest.set(row.ref, row.sha256);
52
+ for (const [file, sha256] of latest) expect(file, sha256);
53
+ // The runs of a name are oldest first: the last run in each space is the map that the knowledge has.
54
+ const maps = new Map(coverageRuns(db).map((run) => [`${run.space}\n${run.name}`, run]));
55
+ for (const run of maps.values()) expect(run.name, run.sha256);
56
+ const changes: EvidenceChange[] = [];
57
+ for (const [file, hashes] of [...expected].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
58
+ const now = fileHash(root, file);
59
+ for (const sha256 of hashes) {
60
+ if (now === sha256) continue;
61
+ const revisions = [...new Set(rows.filter((row) => row.ref === file && row.sha256 === sha256).map((row) => row.revision))];
62
+ changes.push({ file, state: now === undefined ? "missing" : "changed", revisions });
63
+ }
64
+ }
65
+ return changes;
66
+ }
@@ -86,12 +86,12 @@ export interface EntryRow {
86
86
  revision: string;
87
87
  }
88
88
 
89
- /** A coverage range of one kind. */
89
+ /** The ranges of one kind of the coverage map at a project path: their number. */
90
90
  export interface CoverageRow {
91
91
  space: Space;
92
+ map: string;
92
93
  kind: CoverageKind;
93
- start: number;
94
- end: number;
94
+ ranges: number;
95
95
  origin: Origin;
96
96
  revision: string;
97
97
  }
@@ -285,8 +285,8 @@ export function revision(db: DatabaseSync | undefined, text: string): RevisionCh
285
285
  [
286
286
  "coverage",
287
287
  "coverage",
288
- "space, kind, start_address, end_address, origin, valid_from_revision",
289
- (row: Raw): CoverageRow => ({ space: row.space as Space, kind: row.kind as CoverageKind, start: row.start_address as number, end: row.end_address as number, origin: row.origin as Origin, revision: row.valid_from_revision as string }),
288
+ "space, map, kind, length(ranges) - length(replace(ranges, ' ', '')) + 1 AS ranges, origin, valid_from_revision",
289
+ (row: Raw): CoverageRow => ({ space: row.space as Space, map: row.map as string, kind: row.kind as CoverageKind, ranges: row.ranges as number, origin: row.origin as Origin, revision: row.valid_from_revision as string }),
290
290
  ],
291
291
  ] as const;
292
292
  const added: HistoryEntry[] = [];
@@ -69,6 +69,13 @@ export function runProvenance(image: Uint8Array, toolVersion: string | undefined
69
69
  return toolVersion === undefined ? { inputHash } : { inputHash, toolVersion };
70
70
  }
71
71
 
72
+ /** The version of the analyzer in its last revision of these image bytes: undefined when it has none, or when that revision does not tell it. */
73
+ export function lastToolVersion(db: DatabaseSync, analyzer: Analyzer, image: Uint8Array): string | undefined {
74
+ const { inputHash } = runProvenance(image, undefined);
75
+ const row = db.prepare("SELECT tool_version FROM revisions WHERE origin = ? AND input_hash = ? ORDER BY id DESC LIMIT 1").get(analyzer, inputHash!) as { tool_version: string | null } | undefined;
76
+ return row?.tool_version ?? undefined;
77
+ }
78
+
72
79
  export type ImportConflict =
73
80
  | {
74
81
  category: "symbol";
@@ -261,10 +268,10 @@ function importNames(db: DatabaseSync, change: Change, findings: NormalizedFindi
261
268
  }
262
269
  }
263
270
 
264
- /** Analyzers whose regions a heuristic finding replaces where it lies: user/LLM > heuristic > DXA/Ghidra. */
265
- const YIELDS_TO_HEURISTIC = new Set<Origin>(["dxa", "ghidra"]);
271
+ /** Analyzers whose regions a heuristic finding replaces where it lies: user/LLM > heuristic > DXA/decompiler. */
272
+ const YIELDS_TO_HEURISTIC = new Set<Origin>(["dxa", "decompiler"]);
266
273
  /** Analyzers whose data gives way to a code finding over an executed instruction start. */
267
- const YIELDS_TO_EXECUTED_CODE = new Set<Origin>(["dxa", "ghidra"]);
274
+ const YIELDS_TO_EXECUTED_CODE = new Set<Origin>(["dxa", "decompiler"]);
268
275
 
269
276
  /** The first address in the range that is an executed instruction start, or undefined. */
270
277
  function firstExecuted(findings: NormalizedFindings, start: number, end: number): number | undefined {
@@ -279,7 +286,7 @@ function holdsExecuted(findings: NormalizedFindings, start: number, end: number)
279
286
  }
280
287
 
281
288
  /**
282
- * The data findings of DXA or Ghidra that code evidence contradicts: an
289
+ * The data findings of DXA or the decompiler that code evidence contradicts: an
283
290
  * executed instruction start, or a code name (label or routine) of the user or
284
291
  * the LLM, in the range. Evidence wins over an analyzer guess: such a finding
285
292
  * is not imported, and the analyzer's own code there stays.
@@ -314,7 +321,7 @@ function importRegions(db: DatabaseSync, change: Change, given: NormalizedFindin
314
321
  result.conflicts.push(...contradicted);
315
322
  const findings = { ...given, regions: given.regions.filter((region) => !contradicted.some((item) => item.start === region.start && item.end === region.end)) };
316
323
  if (analyzer === "heuristic") {
317
- // An idiom is specific evidence about its bytes: the DXA or Ghidra region there gives way, its parts outside stay.
324
+ // An idiom is specific evidence about its bytes: the DXA or decompiler region there gives way, its parts outside stay.
318
325
  for (const region of findings.regions) {
319
326
  for (const row of regionsOverlapping(db, region.start, region.end, space).filter((candidate) => YIELDS_TO_HEURISTIC.has(candidate.origin))) {
320
327
  change.close("regions", "space = ? AND start_address = ? AND end_address = ? AND origin = ?", space, row.start, row.end, row.origin);