@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
@@ -263,7 +263,7 @@ class Connection {
263
263
  const record = (outcome: Record<string, unknown>) => {
264
264
  const ms = elapsedMs(started);
265
265
  trace().event("request", { connection: this.#id, op: request.op, id: request.id, params: request.params, attachments: attachments.length, ms, ...outcome });
266
- // A call from a skill script (c1541, petcat, status) is always logged; the many calls of a VICE session only in the trace.
266
+ // A call from a skill script (c1541, petcat) is always logged; the many calls of a VICE session only in the trace.
267
267
  if (this.#isTool) {
268
268
  const what = outcome.ok === true ? "ok" : `${String(outcome.code)}: ${String(outcome.message)}`;
269
269
  this.#log(`${request.op} ${JSON.stringify(summarize(request.params) ?? {})}: ${what} (${ms} ms)`);
@@ -387,6 +387,8 @@ export async function startHostServer(options: HostServerOptions): Promise<HostS
387
387
  server.once("error", failed);
388
388
  server.listen({ host: address, port, exclusive: true }, () => {
389
389
  server.off("error", failed);
390
+ // A failed accept (for example EMFILE) fails only that connection; the listener goes on.
391
+ server.on("error", (error) => log(`listener on ${address} port ${port}: ${error.message}`));
390
392
  const bound = server.address();
391
393
  if (bound === null || typeof bound === "string") reject(new Error("listener has no TCP address"));
392
394
  else resolve(bound.port);
@@ -1,6 +1,6 @@
1
1
  // The typed tool dispatcher of the Host Runtime. The host runs only
2
2
  // VICE and the tools that come with it (c1541, petcat); skill scripts run
3
- // ACME, DXA and Ghidra themselves. One entry per operation, never a
3
+ // ACME, DXA and the decompiler themselves. One entry per operation, never a
4
4
  // generic executable route.
5
5
 
6
6
  import type { ProcessSupervisor } from "../../native/processes.ts";
@@ -25,7 +25,7 @@
25
25
  // A headless VICE plays no sound: `-sounddev dummy` keeps the SID emulated.
26
26
 
27
27
  import { mkdtempSync, readFileSync, rmSync } from "node:fs";
28
- import { createServer } from "node:net";
28
+ import { createServer, type Server } from "node:net";
29
29
  import { tmpdir } from "node:os";
30
30
  import { join } from "node:path";
31
31
  import { setTimeout as sleep } from "node:timers/promises";
@@ -49,18 +49,33 @@ export function findVice(env: NodeJS.ProcessEnv = process.env): string {
49
49
  }
50
50
 
51
51
  /** Asks the OS for a free loopback port. Another process can still take it before VICE binds. */
52
- export function freePort(): Promise<number> {
53
- return new Promise((resolve, reject) => {
54
- const server = createServer();
55
- server.once("error", reject);
56
- server.listen(0, "127.0.0.1", () => {
57
- const address = server.address();
58
- server.close(() => {
59
- if (address === null || typeof address === "string") reject(new Error("no TCP address"));
60
- else resolve(address.port);
61
- });
62
- });
63
- });
52
+ export async function freePort(): Promise<number> {
53
+ return (await freePorts(1))[0]!;
54
+ }
55
+
56
+ /** Asks the OS for `count` different free loopback ports: each probe stays bound until all are known. */
57
+ export async function freePorts(count: number): Promise<number[]> {
58
+ const servers: Server[] = [];
59
+ try {
60
+ const ports: number[] = [];
61
+ for (let index = 0; index < count; index++) {
62
+ const server = createServer();
63
+ servers.push(server);
64
+ ports.push(
65
+ await new Promise<number>((resolve, reject) => {
66
+ server.once("error", reject);
67
+ server.listen(0, "127.0.0.1", () => {
68
+ const address = server.address();
69
+ if (address === null || typeof address === "string") reject(new Error("no TCP address"));
70
+ else resolve(address.port);
71
+ });
72
+ }),
73
+ );
74
+ }
75
+ return ports;
76
+ } finally {
77
+ await Promise.all(servers.map((server) => new Promise<void>((resolve) => server.close(() => resolve()))));
78
+ }
64
79
  }
65
80
 
66
81
  /** A VICE with no window (the default) or one with a window the user can use. */
@@ -254,8 +269,7 @@ async function launchOnce(options: LaunchOptions): Promise<ViceProcess> {
254
269
  const env = options.env ?? process.env;
255
270
  const log = options.log ?? (() => {});
256
271
  const binary = findVice(env);
257
- const port = await freePort();
258
- const textPort = await freePort();
272
+ const [port, textPort] = (await freePorts(2)) as [number, number];
259
273
  const scratch = mkdtempSync(join(tmpdir(), "c64-re-tools-vice-"));
260
274
  // Owned by the supervisor: its exit guard and the watchdog remove it if this process dies.
261
275
  const releaseScratch = options.supervisor.ownPath(scratch);
@@ -384,9 +398,12 @@ async function checkSameMachine(monitor: BinaryMonitor, text: TextMonitor): Prom
384
398
  if (seen === null || Number.parseInt(seen[1]!, 16) !== marker) {
385
399
  throw new WireFailure("machine-unavailable", "The emulator's two monitor connections reached different machines.");
386
400
  }
387
- } finally {
388
- await write(original);
401
+ } catch (error) {
402
+ // The first failure tells why the launch failed; a failed restore after it would hide it.
403
+ await write(original).catch(() => {});
404
+ throw error;
389
405
  }
406
+ await write(original);
390
407
  }
391
408
 
392
409
  /** Connects the binary monitor and proves it answers a ping, until `deadline`. */
@@ -82,7 +82,6 @@ const WINDOW_CLOSED =
82
82
  "Breakpoints and watchpoints are kept. Check the machine state before you continue.";
83
83
 
84
84
  /** Emulator state that a move to another VICE cannot carry. */
85
- /** The first bytes of every VICE snapshot file. */
86
85
  const NOT_CARRIED = ["cpu history", "memory map", "profile", "keyboard input not yet typed"];
87
86
 
88
87
  /** Starts another VICE for this session; `log` also gets that launch's lines. */
@@ -141,7 +140,8 @@ const BROKEN_MESSAGES: Record<ViceFeature, string> = {
141
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.",
142
141
  };
143
142
 
144
- 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[]>;
145
145
 
146
146
  /**
147
147
  * Where VICE keeps a staged file: an autostarted disk stays in drive 8, a tape
@@ -170,6 +170,8 @@ export class ViceSession implements ViceSessionHandle {
170
170
  readonly #stepLimitMs: number;
171
171
  readonly #launch: ViceLauncher | undefined;
172
172
  readonly #directory: DiskDirectory | undefined;
173
+ /** Stops the host tool runs of this session when it closes. */
174
+ readonly #abort = new AbortController();
173
175
  /** Session files that outlive one VICE: snapshots, staged media, handovers. */
174
176
  readonly #workDir: string;
175
177
  readonly #releaseWorkDir: () => void;
@@ -373,6 +375,7 @@ export class ViceSession implements ViceSessionHandle {
373
375
 
374
376
  async close(): Promise<void> {
375
377
  this.#closed = true;
378
+ this.#abort.abort();
376
379
  try {
377
380
  await this.#vice.stop();
378
381
  } finally {
@@ -436,7 +439,7 @@ export class ViceSession implements ViceSessionHandle {
436
439
  if (type === "tap") this.#refuseBroken("tape", "c64_autostart of a tape image");
437
440
  const bytes = onlyAttachment(attachments);
438
441
  checkMedia(type, bytes);
439
- 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);
440
443
  const file = this.#stage(bytes, type);
441
444
  // VICE keeps a cartridge through every reset and autostart, as a real C64 does.
442
445
  if (type !== "crt" && this.#cartridge) {
@@ -475,7 +478,7 @@ export class ViceSession implements ViceSessionHandle {
475
478
  return this.#reset(params as ViceOperations["reset"]["params"]);
476
479
  case "keyboard": {
477
480
  const bytes = Buffer.from((params as ViceOperations["keyboard"]["params"]).data, "hex");
478
- await this.#refuseWhileAutostartLoads("type");
481
+ await this.#refuseWhileAutostartLoads("a key now stops it before RUN", "type");
479
482
  await this.#observe(() => this.#machine.feedKeyboard(bytes));
480
483
  return { queuedBytes: bytes.length };
481
484
  }
@@ -718,12 +721,16 @@ export class ViceSession implements ViceSessionHandle {
718
721
  // running, and only a stop caused by this breakpoint counts.
719
722
  const vector = await this.#machine.resetVector();
720
723
  const checkpoint = await this.#machine.addCheckpoint({ start: vector, end: vector, operation: 0x04, space: "c64" });
721
- await this.#resume();
722
- const stopped = this.#nextStop(RESET_STOP_LIMIT_MS, checkpoint);
723
- await this.#resumingCommand(() => this.#machine.reset(params.mode));
724
- const reached = (await stopped) !== undefined;
725
- if (!reached) await this.#stop();
726
- 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
+ }
727
734
  if (!reached) throw new WireFailure("operation-failed", "The C64 did not reach its reset vector after the reset.");
728
735
  this.#atResetStop = true;
729
736
  return { state: "stopped", pc: vector };
@@ -847,6 +854,9 @@ export class ViceSession implements ViceSessionHandle {
847
854
  hits.push(await this.#traceHit(index, params.points[index]!.kind, frames));
848
855
  if (hits.length >= params.maxHits) return { hits, frames, end: "hits", pc: stop.pc };
849
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 };
850
860
  if (stop.hits.includes(clock)) {
851
861
  if (stop.pc === clockPc && (await this.#jamAt(stop.pc))) return { hits, frames, end: "jam", pc: stop.pc };
852
862
  clockPc = stop.pc;
@@ -860,8 +870,6 @@ export class ViceSession implements ViceSessionHandle {
860
870
  continue;
861
871
  }
862
872
  if (traced.length > 0) continue;
863
- const point = this.#userPoint(stop.hits);
864
- if (point !== undefined) return { hits, frames, end: point.stopReason, pc: stop.pc };
865
873
  if (await this.#jamAt(stop.pc)) return { hits, frames, end: "jam", pc: stop.pc };
866
874
  if (this.#pendingStep) {
867
875
  this.#pendingStep = false;
@@ -1184,16 +1192,29 @@ export class ViceSession implements ViceSessionHandle {
1184
1192
  return publicView(point);
1185
1193
  }
1186
1194
 
1187
- /** VICE turns warp on for an autostart and off when it types RUN. A key in between ends the autostart with no message. */
1188
- async #refuseWhileAutostartLoads(verb: string): Promise<void> {
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> {
1189
1200
  if (this.#autostarting && !this.#userWarp && (await this.#observe(() => this.#machine.warp()))) {
1190
1201
  throw new WireFailure(
1191
1202
  "operation-failed",
1192
- `The autostart still loads the program, and a key now stops it before RUN. Run frames with c64_execution advance-frames, then ${verb} again.`,
1203
+ `The autostart still loads the program, and ${effect}. Run frames with c64_execution advance-frames, then ${verb} again.`,
1193
1204
  );
1194
1205
  }
1195
1206
  }
1196
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
+
1197
1218
  /**
1198
1219
  * Presses keys of the keyboard matrix and RESTORE. VICE has no command for
1199
1220
  * that: a snapshot gets the keys in its keyboard module, and RESTORE as a
@@ -1204,7 +1225,7 @@ export class ViceSession implements ViceSessionHandle {
1204
1225
  */
1205
1226
  async #press(params: ViceOperations["press"]["params"]): Promise<PressResult> {
1206
1227
  this.#refuseBroken("keyboard", "c64_press");
1207
- await this.#refuseWhileAutostartLoads("press the keys");
1228
+ await this.#refuseWhileAutostartLoads("a key now stops it before RUN", "press the keys");
1208
1229
  if (this.#atResetStop) {
1209
1230
  throw new WireFailure(
1210
1231
  "operation-failed",
@@ -1411,13 +1432,7 @@ export class ViceSession implements ViceSessionHandle {
1411
1432
  if (params.action === "list") return { snapshots: [...this.#snapshots.keys()] };
1412
1433
  const existing = this.#snapshots.get(params.name);
1413
1434
  if (params.action === "save") {
1414
- if (this.#atResetStop) {
1415
- throw new WireFailure(
1416
- "operation-failed",
1417
- "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. " +
1418
- "Step one instruction with c64_execution, then save the snapshot.",
1419
- );
1420
- }
1435
+ this.#refuseAtResetStop("save the snapshot");
1421
1436
  if (existing === undefined && this.#snapshots.size >= MAX_SNAPSHOTS) {
1422
1437
  throw new WireFailure("limit-exceeded", `A session keeps at most ${MAX_SNAPSHOTS} snapshots. Remove one first with action remove.`);
1423
1438
  }
@@ -1443,6 +1458,8 @@ export class ViceSession implements ViceSessionHandle {
1443
1458
  if (this.#autostarting) await this.#reset({ mode: "soft", run: false });
1444
1459
  await this.#machine.restoreSnapshot(file);
1445
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;
1446
1463
  // A restore starts a jammed CPU again, but VICE still records no CPU history.
1447
1464
  this.#jammed = undefined;
1448
1465
  if (this.#historyStopped) this.#historyOld = true;
@@ -1466,12 +1483,19 @@ export class ViceSession implements ViceSessionHandle {
1466
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.");
1467
1484
  const file = this.#stage(bytes, "vsf");
1468
1485
  // VICE resets the machine after a snapshot file that it cannot read: a backup keeps the state before the restore.
1469
- 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");
1470
1488
  await this.#stop();
1471
- await this.#machine.saveSnapshot(backup);
1489
+ if (backup !== undefined) await this.#machine.saveSnapshot(backup);
1472
1490
  try {
1473
1491
  return await this.#restoreFrom(file);
1474
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
+ }
1475
1499
  const kept = await this.#restoreFrom(backup).then(
1476
1500
  () => true,
1477
1501
  () => false,
@@ -1489,7 +1513,7 @@ export class ViceSession implements ViceSessionHandle {
1489
1513
  );
1490
1514
  } finally {
1491
1515
  rmSync(file, { force: true });
1492
- rmSync(backup, { force: true });
1516
+ if (backup !== undefined) rmSync(backup, { force: true });
1493
1517
  }
1494
1518
  }
1495
1519
 
@@ -1506,13 +1530,17 @@ export class ViceSession implements ViceSessionHandle {
1506
1530
  if (this.#mode === mode) return { window: mode === "window", state: this.#state, notCarried: [] };
1507
1531
  if (this.#held !== undefined) throw new WireFailure("machine-unavailable", this.#heldWhy);
1508
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);
1509
1536
  const running = this.#state === "running";
1510
1537
  this.#log(mode === "window" ? "moving the machine to a VICE with a window" : "moving the machine back to a headless VICE");
1511
1538
  await this.#stop();
1512
1539
  const handover: Handover = {
1513
1540
  file: join(this.#workDir, mode === "window" ? "window-open.vsf" : "window-close.vsf"),
1514
1541
  running,
1515
- warp: await this.#machine.warp(),
1542
+ // VICE's own warp can be the one of a loading autostart.
1543
+ warp: this.#userWarp,
1516
1544
  elapsed: (await this.#machine.clock()) - this.#timingStart,
1517
1545
  };
1518
1546
  await this.#machine.saveSnapshot(handover.file);
@@ -344,6 +344,9 @@ export function newStepForm(kind: string, step: Record<string, unknown>): { fiel
344
344
  }
345
345
  }
346
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
+
347
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. */
348
351
  export function refuseOldStep(kind: string, step: Record<string, unknown>, at: string, fail: (message: string) => never): void {
349
352
  const found = newStepForm(kind, step);
@@ -359,7 +362,7 @@ export function refuseOldStep(kind: string, step: Record<string, unknown>, at: s
359
362
  */
360
363
  export function checkActionStep(kind: ActionStepKind, step: Record<string, unknown>, at: string, fail: (message: string) => never): ActionStep {
361
364
  refuseOldStep(kind, step, at, fail);
362
- for (const key of Object.keys(step)) if (key !== kind) fail(`${at} has the key ${key}, which a ${kind} step does not have`);
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
 
@@ -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";
@@ -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);