@henols/c64-re-tools 2.6.0-rc.2 → 2.6.0-rc.20

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 (107) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-assembler/SKILL.md +28 -14
  3. package/skills/c64-assembler/scripts/assembler.ts +28 -15
  4. package/skills/c64-development/SKILL.md +4 -4
  5. package/skills/c64-docs/SKILL.md +9 -7
  6. package/skills/c64-docs/scripts/docs.ts +24 -11
  7. package/skills/c64-docs/scripts/lib/reference.ts +119 -33
  8. package/skills/c64-docs/scripts/lib/source-map.ts +23 -4
  9. package/skills/c64-knowledge/SKILL.md +67 -42
  10. package/skills/c64-knowledge/scripts/knowledge.ts +90 -67
  11. package/skills/c64-knowledge/scripts/lib/listing.ts +18 -3
  12. package/skills/c64-packer/SKILL.md +1 -1
  13. package/skills/c64-provenance/SKILL.md +11 -10
  14. package/skills/c64-provenance/scripts/lib/library.ts +16 -16
  15. package/skills/c64-provenance/scripts/provenance.ts +33 -23
  16. package/skills/c64-reverse-engineering/SKILL.md +17 -11
  17. package/skills/c64-source/SKILL.md +71 -47
  18. package/skills/c64-source/scripts/lib/export.ts +89 -34
  19. package/skills/c64-source/scripts/lib/loader.ts +79 -36
  20. package/skills/c64-source/scripts/lib/source.ts +38 -32
  21. package/skills/c64-source/scripts/lib/stage.ts +11 -5
  22. package/skills/c64-source/scripts/lib/start-screen.asm +4 -2
  23. package/skills/c64-source/scripts/source.ts +278 -145
  24. package/skills/c64-static-analysis/SKILL.md +29 -25
  25. package/skills/c64-static-analysis/scripts/lib/coverage.ts +2 -25
  26. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  27. package/skills/c64-static-analysis/scripts/lib/instructions.ts +26 -24
  28. package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
  29. package/skills/c64-static-analysis/scripts/static-analysis.ts +69 -67
  30. package/skills/c64-testing/SKILL.md +15 -5
  31. package/skills/c64-testing/references/recording-format.md +26 -5
  32. package/skills/c64-testing/references/scenario-format.md +11 -8
  33. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  34. package/skills/c64-testing/scripts/lib/play.ts +39 -41
  35. package/skills/c64-testing/scripts/lib/recording.ts +220 -46
  36. package/skills/c64-testing/scripts/lib/replay.ts +32 -6
  37. package/skills/c64-testing/scripts/lib/runs.ts +8 -3
  38. package/skills/c64-testing/scripts/lib/scenario.ts +18 -11
  39. package/skills/c64-testing/scripts/testing.ts +23 -2
  40. package/skills/c64-unpacker/SKILL.md +10 -5
  41. package/skills/c64-unpacker/scripts/lib/loads.ts +34 -13
  42. package/skills/c64-unpacker/scripts/lib/machine.ts +7 -3
  43. package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
  44. package/skills/c64-unpacker/scripts/unpacker.ts +43 -9
  45. package/skills/emulator/SKILL.md +7 -12
  46. package/src/build-name.ts +55 -0
  47. package/src/c64-keys.ts +98 -0
  48. package/src/c64.ts +22 -2
  49. package/src/cli/main.ts +3 -29
  50. package/src/host/main.ts +3 -3
  51. package/src/host/server.ts +3 -1
  52. package/src/host/tools/index.ts +2 -7
  53. package/src/host/vice/process.ts +34 -17
  54. package/src/host/vice/session.ts +138 -31
  55. package/src/host-client/steps.ts +21 -18
  56. package/src/host-client/tools.ts +2 -7
  57. package/src/host-client/vice-session.ts +7 -1
  58. package/src/knowledge/evidence.ts +66 -0
  59. package/src/knowledge/history.ts +5 -5
  60. package/src/knowledge/import.ts +12 -5
  61. package/src/knowledge/program.ts +123 -32
  62. package/src/knowledge/read.ts +36 -13
  63. package/src/knowledge/schema.ts +43 -17
  64. package/src/knowledge/start-screen.ts +70 -0
  65. package/src/knowledge/text.ts +33 -5
  66. package/src/knowledge/write.ts +75 -36
  67. package/src/mcp/inputs.ts +12 -0
  68. package/src/mcp/server.ts +1 -1
  69. package/src/mcp/tools/debug.ts +23 -21
  70. package/src/mcp/tools/input.ts +38 -5
  71. package/src/mcp/tools/machine.ts +3 -42
  72. package/src/mcp/tools/media.ts +1 -1
  73. package/src/mcp/tools/memory.ts +12 -9
  74. package/src/native/acme.ts +1 -1
  75. package/src/native/c64run.ts +7 -4
  76. package/src/native/decompiler/analyze.ts +98 -0
  77. package/src/native/decompiler/c64rt-wasm.ts +4 -0
  78. package/src/native/decompiler/language/c64rt_6510.sla +0 -0
  79. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  80. package/src/native/decompiler/pcode.ts +222 -0
  81. package/src/native/decompiler/walk.ts +205 -0
  82. package/src/native/decompiler/wasm.ts +98 -0
  83. package/src/native/discover.ts +3 -3
  84. package/src/native/dxa.ts +12 -1
  85. package/src/native/processes.ts +4 -4
  86. package/src/native/types.ts +27 -27
  87. package/src/opcodes.ts +1 -1
  88. package/src/platform.ts +30 -1
  89. package/src/project.ts +17 -4
  90. package/src/protocol/tools.ts +1 -45
  91. package/src/protocol/vice.ts +47 -0
  92. package/src/reference-pages.ts +64 -0
  93. package/src/script.ts +4 -4
  94. package/src/vsf.ts +98 -0
  95. package/tools/c64run.c +158 -15
  96. package/tools/install-container.sh +1 -2
  97. package/src/cli/status.ts +0 -127
  98. package/src/host/tools/status.ts +0 -47
  99. package/src/native/ghidra/analyze.ts +0 -87
  100. package/src/native/ghidra/index.ts +0 -170
  101. package/src/native/ghidra/scripts/C64Export.java +0 -274
  102. package/src/native/ghidra/scripts/C64Prepare.java +0 -66
  103. package/src/native/status.ts +0 -135
  104. package/tools/install-ghidra.sh +0 -40
  105. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  106. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  107. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
@@ -15,6 +15,7 @@ import { readPrg } from "#src/host-client/image.ts";
15
15
  import { writeReported, type Written } from "#src/host-client/transfer.ts";
16
16
  import { ViceSessionClient } from "#src/host-client/vice-session.ts";
17
17
  import { knowledgeAt, knowledgeNames } from "#src/knowledge/names.ts";
18
+ import { PAL_FRAME_CYCLES } from "#src/native/c64run.ts";
18
19
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec, type OptionSpec } from "#src/script.ts";
19
20
  import { basicStart, inspect, readMemoryMap, underRom, writtenThenExecuted } from "./lib/evidence.ts";
20
21
  import { loads, readLoadSteps } from "./lib/loads.ts";
@@ -197,6 +198,8 @@ interface Followed {
197
198
  failed?: string;
198
199
  /** What stopped the CPU before the frames ran: a JAM or a point of the program. */
199
200
  halted?: { stopReason: string; pc: number };
201
+ /** The first step (1 = the first) in which the CPU executed `until`, before the run waited for it. */
202
+ untilRan?: number;
200
203
  }
201
204
 
202
205
  type RunUntilStep = Extract<ActionStep, { runUntil: unknown }>;
@@ -250,9 +253,16 @@ async function follow(
250
253
  const atTarget = (pc: number) => stopAt !== undefined && pc === stopAt;
251
254
  // The current stage: its memory map since it started, chunk by chunk, its own code, and the written code it calls.
252
255
  let stage = { map: new Uint8Array(0x10000), own: new Set<number>(), called: [] as AddressRange[] };
256
+ // A step that runs frames can pass until: the run then waits for it in vain.
257
+ let running = 0;
258
+ let untilRan: number | undefined;
259
+ const noteUntil = (map: Uint8Array) => {
260
+ if (options.until !== undefined && running > 0 && untilRan === undefined && (map[options.until]! & EXECUTE) !== 0) untilRan = running;
261
+ };
253
262
  const startStage = async (next: number, last: Uint8Array) => {
254
263
  mergeMaps(stage.map, last);
255
264
  await markIoRam(stage.map);
265
+ noteUntil(stage.map);
256
266
  found.push({ entry, firstFrame, frames: total - firstFrame, wrote: stageWrote(stage.map), next });
257
267
  entry = next;
258
268
  firstFrame = total;
@@ -426,8 +436,11 @@ async function follow(
426
436
  stopAt = undefined;
427
437
  }
428
438
  };
439
+ // Stage 0 starts at the program, whatever the first step is: RUN and the BASIC line before it are no part of it.
440
+ await client.memmap({ action: "clear" });
429
441
  // The steps run first and in the tracked time: a frames step and a runUntil step to an address. The others act between two chunks.
430
442
  for (const [index, step] of options.steps.entries()) {
443
+ running = index + 1;
431
444
  if ("frames" in step) await track(step.frames);
432
445
  else if (trackedRunUntil(step)) {
433
446
  if (!(await trackTo(knowledgeAt()(step.runUntil.target.address), step.runUntil.timeoutFrames))) {
@@ -435,8 +448,21 @@ async function follow(
435
448
  const why = halted === undefined ? "" : ` ${stoppedEarly(halted.stopReason, halted.pc, total, step.runUntil.timeoutFrames)}`;
436
449
  return { stages: found, frames: total, reached: false, failed: `Step ${index + 1} did not reach its target in ${step.runUntil.timeoutFrames} frames. It is at ${formatC64Address(pc)}.${why}` };
437
450
  }
438
- } else await runActionStep(client, step, knowledgeAt());
451
+ } else {
452
+ // A press or a runUntil to memory or the raster runs frames outside the chunks. The stopwatch of the session gives them,
453
+ // also for a run that a point stops early. What the step wrote and ran is in the stage before the next chunk clears the memory map.
454
+ await client.timing("start");
455
+ const notReached = await runActionStep(client, step, knowledgeAt());
456
+ const timed = await client.timing("read");
457
+ total += Math.round(Number("cycles" in timed ? timed.cycles : 0) / PAL_FRAME_CYCLES);
458
+ mergeMaps(stage.map, await readCoverage(client));
459
+ if (notReached !== undefined && "runUntil" in step) {
460
+ return { stages: found, frames: total, reached: false, failed: `Step ${index + 1} did not reach its target in ${step.runUntil.timeoutFrames} frames. It stopped by ${notReached.stopReason} at ${formatC64Address(notReached.pc)}.` };
461
+ }
462
+ }
463
+ noteUntil(stage.map);
439
464
  }
465
+ running = 0;
440
466
  const left = Math.max(0, options.frames - total);
441
467
  let reached = false;
442
468
  if (options.until === undefined) await track(left);
@@ -445,7 +471,7 @@ async function follow(
445
471
  mergeMaps(stage.map, await readCoverage(client));
446
472
  await markIoRam(stage.map);
447
473
  found.push({ entry, firstFrame, frames: total - firstFrame, wrote: stageWrote(stage.map) });
448
- return { stages: found, frames: total, reached, ...(halted === undefined ? {} : { halted }) };
474
+ return { stages: found, frames: total, reached, ...(halted === undefined ? {} : { halted }), ...(untilRan === undefined ? {} : { untilRan }) };
449
475
  }
450
476
 
451
477
  const showRange = (range: { start: number; end: number }) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
@@ -490,6 +516,11 @@ async function stages(program: string, options: { frames: number; entry?: number
490
516
  }
491
517
  }
492
518
 
519
+ /** Why a capture can wait for --until in vain: a step ran over it. */
520
+ function passedInStep(until: number, step: number): string {
521
+ return `The CPU executed ${formatC64Address(until)} in step ${step}, before the wait for --until started. A press step runs frames. Make the steps stop before the program gets to that address, or give an --until address that the program gets to later.`;
522
+ }
523
+
493
524
  async function capture(
494
525
  program: string,
495
526
  options: { until: number; out: string; range?: AddressRange; exclude: AddressRange[]; timeoutFrames: number; entry?: number; steps: ActionStep[]; minStage: number },
@@ -504,7 +535,7 @@ async function capture(
504
535
  return {
505
536
  output: {
506
537
  captured: false,
507
- reason: `The program did not get to ${formatC64Address(options.until)} in ${options.timeoutFrames} frames. It is at ${formatC64Address(registers.pc)}.${followed.halted === undefined ? "" : ` ${stoppedEarly(followed.halted.stopReason, followed.halted.pc, followed.frames, options.timeoutFrames)}`}`,
538
+ reason: `The program did not get to ${formatC64Address(options.until)} in ${options.timeoutFrames} frames. It is at ${formatC64Address(registers.pc)}.${followed.halted === undefined ? "" : ` ${stoppedEarly(followed.halted.stopReason, followed.halted.pc, followed.frames, options.timeoutFrames)}`}${followed.untilRan === undefined ? "" : ` ${passedInStep(options.until, followed.untilRan)}`}`,
508
539
  ...(followed.halted === undefined ? {} : { stopReason: followed.halted.stopReason }),
509
540
  stages: showStages(followed.stages),
510
541
  },
@@ -515,7 +546,8 @@ async function capture(
515
546
  const memory = await readRam(client, 0x0000, 0x10000);
516
547
  const state = await machineState(client);
517
548
  // The segments: what the stages wrote, without loader leftovers, with no overlap.
518
- const found = options.range !== undefined ? [options.range] : captureSegments(followed.stages, registers.pc);
549
+ const load = bytes[0]! | (bytes[1]! << 8);
550
+ const found = options.range !== undefined ? [options.range] : captureSegments(followed.stages, registers.pc, { start: load, end: Math.min(0xffff, load + bytes.length - 3) });
519
551
  const segments = withoutRanges(found, options.exclude);
520
552
  const file = (path: string) => `${options.out}/${path}`;
521
553
  const written: Written[] = [];
@@ -533,7 +565,7 @@ async function capture(
533
565
  `${JSON.stringify(
534
566
  {
535
567
  entry: formatC64Address(registers.pc),
536
- segments: segments.map((segment, index) => ({ ...showRange(segment), ...("writtenBy" in segment ? { writtenBy: segment.writtenBy } : {}), file: files[index] })),
568
+ segments: segments.map((segment, index) => ({ ...showRange(segment), ...("writtenBy" in segment ? { writtenBy: segment.writtenBy } : {}), ...("loaded" in segment ? { loaded: true } : {}), file: files[index] })),
537
569
  ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(showRange) }),
538
570
  vectors,
539
571
  stages: showStages(followed.stages),
@@ -556,7 +588,7 @@ async function capture(
556
588
  out: options.out,
557
589
  files: written,
558
590
  ...(removed.length === 0 ? {} : { removed }),
559
- segments: segments.map(showRange),
591
+ segments: segments.map((segment) => ({ ...showRange(segment), ...("loaded" in segment ? { loaded: true } : {}) })),
560
592
  ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(showRange) }),
561
593
  stages: followed.stages.length,
562
594
  differsFromReset: entry.differsFromReset,
@@ -642,7 +674,9 @@ function loaded(call: Call, { output, failed }: { output: Record<string, unknown
642
674
  if (failed) return result;
643
675
  const out = call.string("out")!;
644
676
  const drive = call.flag("drive") ? ` Put the drive RAM ${out}/<name>/drive8.prg into the project knowledge in the space drive8.` : "";
645
- return reply(result, { hint: `Put the capture ${out}/<name>/image.json of the part that you work on into the project knowledge.${drive}` });
677
+ const captures = (output.captures as unknown[]).length === 0 ? "" : `Put the capture ${out}/<name>/image.json of the part that you work on into the project knowledge.${drive}`;
678
+ const saved = output.saved === undefined ? "" : `A run of the program can start from a snapshot file ${out}/<name>.vsf.`;
679
+ return reply(result, { hint: [captures, saved].filter((text) => text !== "").join(" ") });
646
680
  }
647
681
 
648
682
  const COMMANDS: CommandSpec[] = [
@@ -702,10 +736,10 @@ const COMMANDS: CommandSpec[] = [
702
736
  },
703
737
  {
704
738
  name: "loads",
705
- summary: "Runs a multi-load program with the steps file. Each capture step {\"capture\": \"<name>\"} writes <dir>/<name>/ with image.bin, image.json, entry_state.json and a PRG for each block that the C64 side changed since the previous capture.",
739
+ summary: "Runs a multi-load program with the steps file. Each capture step {\"capture\": \"<name>\"} writes <dir>/<name>/ with image.bin, image.json, entry_state.json and a PRG for each block that the C64 side changed since the previous capture. Each save step {\"save\": \"<name>\"} writes the machine state to <dir>/<name>.vsf.",
706
740
  subjects: [{ name: "<program>", help: "a PRG, or a disk, tape or cartridge image, relative to the project folder" }],
707
741
  options: {
708
- steps: { ...STEPS, required: true, help: "action steps and capture steps (JSON)" },
742
+ steps: { ...STEPS, required: true, help: "action steps, capture steps and save steps (JSON)" },
709
743
  out: { ...OPTIONS.out, output: "folder", value: "<dir>", required: true, help: "the folder for the captures, relative to the project folder" },
710
744
  drive: { kind: "flag", help: "also write the 2 KiB drive RAM as drive8.prg, for knowledge space drive8" },
711
745
  "min-block": { kind: "count", value: "<bytes>", min: 1, max: 0x10000, default: 64, help: "write a changed block of at least this many bytes (default 64)" },
@@ -27,7 +27,6 @@ Use only the MCP tools. Each MCP session has its own machine. Nothing else can c
27
27
 
28
28
  | Need | C64 tool |
29
29
  |---|---|
30
- | Run state, warp mode, window | `c64_status` |
31
30
  | Reset, power cycle | `c64_reset` |
32
31
  | Fast emulation | `c64_warp` |
33
32
  | Show the machine to the user in a window, hide it again | `c64_window` |
@@ -44,7 +43,7 @@ Use only the MCP tools. Each MCP session has its own machine. Nothing else can c
44
43
  | Chips of the machine | `c64_vicii`, `c64_sprite`, `c64_cia`, `c64_sid` |
45
44
  | Screen image, screen compare | `c64_screen` |
46
45
  | Several of these from one moment | `c64_observe` |
47
- | Keyboard, joystick | `c64_keyboard`, `c64_joystick` |
46
+ | Keyboard, joystick | `c64_keyboard`, `c64_press`, `c64_joystick` |
48
47
  | Program and disk media | `c64_autostart`, `c64_program_load`, `c64_disk_attach` |
49
48
  | Machine state to go back to, also in a later session | `c64_snapshot` |
50
49
 
@@ -64,21 +63,17 @@ To keep a coverage run:
64
63
  ## Workflow
65
64
 
66
65
  1. Read the project knowledge for the addresses in the question.
67
- 2. Get the machine state with `c64_status`.
68
- 3. Load the subject if it is not loaded. Use `c64_autostart` to start it as a user does. Use `c64_program_load` to put a program in memory with no start.
69
- 4. Set the stop condition. Use a breakpoint, a watchpoint or a `c64_run_until` target. Add a condition when the stop must occur only in one state.
70
- 5. Run, step or give input. Prefer `c64_run_until` and `advance-frames` to waits. They stop at the same emulated time on every run.
71
- 6. Read only the state that answers the question. To read several things from one moment, use `c64_observe`.
72
- 7. Interpret the evidence. Keep the observed facts apart from your conclusions.
66
+ 2. Load the subject if it is not loaded. Use `c64_autostart` to start it as a user does. Use `c64_program_load` to put a program in memory with no start.
67
+ 3. Set the stop condition. Use a breakpoint, a watchpoint or a `c64_run_until` target. Add a condition when the stop must occur only in one state.
68
+ 4. Run, step or give input. Prefer `c64_run_until` and `advance-frames` to waits. They stop at the same emulated time on every run.
69
+ 5. Read only the state that answers the question. To read several things from one moment, use `c64_observe`.
70
+ 6. Interpret the evidence. Keep the observed facts apart from your conclusions.
73
71
 
74
72
  Before a risky experiment, save the state with `c64_snapshot`. Restore it to try again from the same point.
75
73
 
76
74
  ### Input that the tools cannot give
77
75
 
78
- Some programs read input in a way that the input tools cannot give. The tool description tells when. Then use one of these ways:
79
-
80
- - Open the window and ask the user to give the input.
81
- - Record a test session with a `press` step.
76
+ Some programs read input in a way that the input tools cannot give. The tool description tells when. Then open the window and ask the user to give the input.
82
77
 
83
78
  Do not change the program to make it accept the input.
84
79
 
@@ -0,0 +1,55 @@
1
+ // The name of a build: the file name tells what kind of build a program is.
2
+ // A release build is release_<label>. A build of config.asm is clean when each
3
+ // switch has its default, else custom_ with each switch that differs: its
4
+ // name when it is on, no_<name> when it is off. A build of an entry other
5
+ // than main.asm adds the entry, for example clean_loader. The loader of the
6
+ // packed form alone is only its copier, so its build is clean_copier: the loader
7
+ // program, which generate packs, keeps clean_loader. A source without
8
+ // config.asm and without a release keeps the name of its entry. The symbols
9
+ // of a build go into symbols/ next to the program, so the program folder
10
+ // holds only programs.
11
+
12
+ import { basename, dirname, extname, join } from "node:path";
13
+
14
+ /** The folder of the builds, relative to the project folder. Git does not keep it. */
15
+ export const BUILD_DIRECTORY = "build";
16
+
17
+ /** The file with the value of each switch. The user edits it, and generate keeps the values. */
18
+ export const CONFIG_FILE = "config.asm";
19
+
20
+ /** A value line of config.asm: NAME = 0 or NAME = 1. */
21
+ const CONFIG_VALUE = /^\s*([A-Z][A-Z0-9_]*)\s*=\s*([01])\s*(?:;.*)?$/;
22
+
23
+ /** The values of the switches in a config.asm text, by name. Lines that are not a value line are not read. */
24
+ export function configValues(text: string): Map<string, 0 | 1> {
25
+ const values = new Map<string, 0 | 1>();
26
+ for (const line of text.split(/\r?\n/)) {
27
+ const match = CONFIG_VALUE.exec(line);
28
+ if (match !== null) values.set(match[1]!, match[2] === "1" ? 1 : 0);
29
+ }
30
+ return values;
31
+ }
32
+
33
+ /** What a build is made of: a release, or the values of config.asm with the default of each switch (0 when the defaults do not have it). */
34
+ export type BuildKind = { release: string } | { values: ReadonlyMap<string, number>; defaults: ReadonlyMap<string, number> };
35
+
36
+ /** The line of a generated loader.asm of the packed form. Its build alone is only the copier, not the loader program. */
37
+ export const COPIER_LINE = "; A build of this file alone is only the copier: its build name has copier in place of loader.";
38
+
39
+ /** The name of a build of `entry`, without an extension. `source` is the text of the entry: COPIER_LINE in it gives the name copier. */
40
+ export function buildName(entry: string, kind: BuildKind | undefined, source?: string): string {
41
+ const base = source?.split(/\r?\n/).includes(COPIER_LINE) ? "copier" : basename(entry, extname(entry));
42
+ if (kind === undefined) return base;
43
+ let type: string;
44
+ if ("release" in kind) type = `release_${kind.release}`;
45
+ else {
46
+ const changed = [...kind.values].filter(([name, value]) => value !== (kind.defaults.get(name) ?? 0)).map(([name, value]) => (value === 0 ? `no_${name}` : name).toLowerCase());
47
+ type = changed.length === 0 ? "clean" : `custom_${changed.join("_")}`;
48
+ }
49
+ return base === "main" ? type : `${type}_${base}`;
50
+ }
51
+
52
+ /** The symbols file of a program: symbols/<name>.json in the folder of the program. */
53
+ export function symbolsPath(program: string): string {
54
+ return join(dirname(program), "symbols", `${basename(program, extname(program))}.json`).split("\\").join("/");
55
+ }
@@ -0,0 +1,98 @@
1
+ // The keys of the C64 keyboard matrix and RESTORE. A key is its place in the
2
+ // matrix: row * 8 + column, where the row is the line of CIA 1 port A that
3
+ // the scan drives low and the column the bit of port B that reads low. The
4
+ // press of VICE and of the replay core, and the play page, use these numbers.
5
+
6
+ /** A press of keys that go down together and up together. `keys` are matrix places, without repeats, in rising order. */
7
+ export interface KeyTap {
8
+ keys: number[];
9
+ restore: boolean;
10
+ }
11
+
12
+ /** The keys that a tap holds at most, RESTORE included: the replay core has no more. */
13
+ export const MAX_TAP_KEYS = 4;
14
+ /** The taps of one press at most. */
15
+ export const MAX_PRESS_TAPS = 64;
16
+ /** The frames that a tap holds its keys, and then waits with all keys up, when the press gives no frames. */
17
+ export const PRESS_FRAMES = 3;
18
+ /** The frames of a tap at most: one minute of PAL frames. */
19
+ export const MAX_PRESS_FRAMES = 3000;
20
+
21
+ /** The matrix, row by row (port A line 0 to 7), column 0 to 7 in each row. A name has more than one character. */
22
+ const MATRIX = [
23
+ ["DEL", "RETURN", "RIGHT", "F7", "F1", "F3", "F5", "DOWN"],
24
+ ["3", "W", "A", "4", "Z", "S", "E", "LSHIFT"],
25
+ ["5", "R", "D", "6", "C", "F", "T", "X"],
26
+ ["7", "Y", "G", "8", "B", "H", "U", "V"],
27
+ ["9", "I", "J", "0", "M", "K", "O", "N"],
28
+ ["+", "P", "L", "-", ".", ":", "@", ","],
29
+ ["POUND", "*", ";", "HOME", "RSHIFT", "=", "UPARROW", "/"],
30
+ ["1", "LEFTARROW", "CTRL", "2", "SPACE", "CBM", "Q", "STOP"],
31
+ ];
32
+
33
+ /** The matrix place of each key. */
34
+ export const MATRIX_KEYS: Readonly<Record<string, number>> = Object.fromEntries(MATRIX.flatMap((row, line) => row.map((key, column) => [key, line * 8 + column])));
35
+
36
+ const LSHIFT = MATRIX_KEYS.LSHIFT!;
37
+
38
+ /** The names that press a key with the left SHIFT: the second function of the key. */
39
+ const SHIFTED_NAMES: Readonly<Record<string, string>> = { F2: "F1", F4: "F3", F6: "F5", F8: "F7", UP: "DOWN", LEFT: "RIGHT", INST: "DEL", CLR: "HOME", RUN: "STOP" };
40
+ /** The characters that a key gives with SHIFT. */
41
+ const SHIFTED_CHARACTERS: Readonly<Record<string, string>> = { "!": "1", '"': "2", "#": "3", $: "4", "%": "5", "&": "6", "'": "7", "(": "8", ")": "9", "[": ":", "]": ";", "<": ",", ">": ".", "?": "/" };
42
+
43
+ /** The names in braces, in the order that a refusal lists them. */
44
+ export const KEY_NAMES = [
45
+ ...["F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8"],
46
+ ...["RETURN", "SPACE", "DEL", "INST", "HOME", "CLR", "STOP", "RUN", "RESTORE", "CTRL", "CBM", "LSHIFT", "RSHIFT"],
47
+ ...["UP", "DOWN", "LEFT", "RIGHT", "POUND", "UPARROW", "LEFTARROW"],
48
+ ];
49
+
50
+ /** The matrix places of one key: a name, or one character. Undefined when the C64 has no such key. RESTORE has no place: it gives []. */
51
+ function placesOf(key: string): number[] | undefined {
52
+ const upper = key.toUpperCase();
53
+ if (upper === "RESTORE") return [];
54
+ if (key === "\n") return [MATRIX_KEYS.RETURN!];
55
+ if (key === " ") return [MATRIX_KEYS.SPACE!];
56
+ const shifted = SHIFTED_NAMES[upper] ?? SHIFTED_CHARACTERS[key];
57
+ if (shifted !== undefined) return [LSHIFT, MATRIX_KEYS[shifted]!];
58
+ // A character is its own key; a name has more than one character.
59
+ const place = key.length === 1 || KEY_NAMES.includes(upper) ? MATRIX_KEYS[upper] : undefined;
60
+ return place === undefined ? undefined : [place];
61
+ }
62
+
63
+ /**
64
+ * The taps of a text, or why it has no taps. Each character is one tap, and
65
+ * a-z press the same keys as A-Z. A key without a character has its name in
66
+ * braces, for example {F1}. Names joined with + in braces are one tap that
67
+ * holds the keys together, for example {LSHIFT+CBM} or {STOP+RESTORE}.
68
+ */
69
+ export function keyTaps(text: string): KeyTap[] | string {
70
+ const taps: KeyTap[] = [];
71
+ for (const part of text.replace(/\r\n?/g, "\n").match(/\{[^{}]*\}|[^]/g) ?? []) {
72
+ const keys = part.length > 1 ? part.slice(1, -1).split("+") : [part];
73
+ const places = new Set<number>();
74
+ let restore = false;
75
+ for (const key of keys) {
76
+ const found = key === "" ? undefined : placesOf(key);
77
+ if (found === undefined) {
78
+ if (part.length === 1) return `the C64 keyboard has no key ${JSON.stringify(part)}`;
79
+ return `there is no key ${key === "" ? part : `{${key}}`}. The keys in braces are ${KEY_NAMES.map((name) => `{${name}}`).join(", ")}, and each character key, for example {CTRL+3}. + joins the keys of one tap, for example {LSHIFT+CBM}`;
80
+ }
81
+ if (key.toUpperCase() === "RESTORE") restore = true;
82
+ for (const place of found) places.add(place);
83
+ }
84
+ const count = places.size + (restore ? 1 : 0);
85
+ if (count > MAX_TAP_KEYS) return `${part} holds ${count} keys, and one tap holds at most ${MAX_TAP_KEYS} keys, RESTORE included`;
86
+ taps.push({ keys: [...places].sort((a, b) => a - b), restore });
87
+ }
88
+ if (taps.length === 0) return "give at least one key";
89
+ if (taps.length > MAX_PRESS_TAPS) return `one press has at most ${MAX_PRESS_TAPS} taps. This text has ${taps.length}`;
90
+ return taps;
91
+ }
92
+
93
+ /** The 8 rows of the matrix with `keys` down: bit n of row r is the key at column n. */
94
+ export function matrixRows(keys: readonly number[]): number[] {
95
+ const rows = [0, 0, 0, 0, 0, 0, 0, 0];
96
+ for (const key of keys) rows[key >> 3]! |= 1 << (key & 7);
97
+ return rows;
98
+ }
package/src/c64.ts CHANGED
@@ -33,7 +33,7 @@ export interface AddressRange {
33
33
  }
34
34
 
35
35
  /** The knowledge spaces: the C64, the 1541 drive in unit 8, and cartridge banks 0 to 255. */
36
- export const SPACE_PATTERN = /^(c64|drive8|bank(0|[1-9][0-9]?|1[0-9]{2}|2[0-4][0-9]|25[0-5]))$/;
36
+ export const SPACE_PATTERN = /^(c64|drive8|loading|bank(0|[1-9][0-9]?|1[0-9]{2}|2[0-4][0-9]|25[0-5]))$/;
37
37
 
38
38
  /** VIC-II state with its addresses as $xxxx; the other values stay numbers. */
39
39
  export function formatVicii<T extends { screenAddress: number; graphicsAddress: number }>(state: T): Omit<T, "screenAddress" | "graphicsAddress"> & { screenAddress: string; graphicsAddress: string } {
@@ -478,6 +478,26 @@ export function coverageEntries(map: Uint8Array, image: (address: number) => num
478
478
  return entries;
479
479
  }
480
480
 
481
+ const ROM_ACCESS = COVERAGE.romRead | COVERAGE.romExecute;
482
+ const RAM_USE = COVERAGE.ramRead | COVERAGE.ramExecute;
483
+
484
+ /**
485
+ * The image bytes under ROM that the runs never used: the CPU read or ran the
486
+ * ROM there, and never read or ran the RAM. A JSR $FFE4 or an IRQ
487
+ * vector at $FFFE then leads into ROM, not into the leftover RAM bytes of a
488
+ * flat image, so the ranges are data for an analysis run.
489
+ */
490
+ export function romOnlyRanges(map: Uint8Array, image: (address: number) => number | undefined): AddressRange[] {
491
+ const ranges: AddressRange[] = [];
492
+ for (let address = 0; address < 0x10000; address++) {
493
+ if ((map[address]! & ROM_ACCESS) === 0 || (map[address]! & RAM_USE) !== 0 || image(address) === undefined) continue;
494
+ const last = ranges.at(-1);
495
+ if (last !== undefined && last.end === address - 1) last.end = address;
496
+ else ranges.push({ start: address, end: address });
497
+ }
498
+ return ranges;
499
+ }
500
+
481
501
  /** Every executed instruction start in RAM inside the image: VICE marks the opcode byte of an instruction as executed, not its operand. */
482
502
  export function executedStarts(map: Uint8Array, image: (address: number) => number | undefined): number[] {
483
503
  const starts: number[] = [];
@@ -491,7 +511,7 @@ const BRANCHES = new Set([0x10, 0x30, 0x50, 0x70, 0x90, 0xb0, 0xd0, 0xf0]);
491
511
  const NO_FALL = new Set([0x00, 0x40, 0x4c, 0x60, 0x6c]);
492
512
 
493
513
  /**
494
- * The coverage flow starts split for Ghidra. A start is a code start, a
514
+ * The coverage flow starts split for the decompiler. A start is a code start, a
495
515
  * place in a routine, when it follows an executed JSR, or when an executed
496
516
  * branch or JMP from outside its own flow reaches it (the loop of a routine
497
517
  * that jumps back to its own start does not count). Any other start, for
package/src/cli/main.ts CHANGED
@@ -1,20 +1,16 @@
1
1
  #!/usr/bin/env tsx
2
2
  // The human CLI: installs the skills and the VICE MCP
3
- // declaration into agent harnesses through AP SDK, and reports status. It is
4
- // thin: AP SDK does the harness-specific work.
3
+ // declaration into agent harnesses through AP SDK. It is thin: AP SDK does
4
+ // the harness-specific work.
5
5
 
6
- import { dirname, join } from "node:path";
7
- import { fileURLToPath } from "node:url";
8
6
  import { parseArgs } from "node:util";
9
7
 
10
8
  import { oldNodeRefusal, PACKAGE } from "../package.ts";
11
9
  import { localToolContext } from "../native/local.ts";
12
- import { localToolStatus } from "../native/status.ts";
13
10
  import { isRefusal } from "../errors.ts";
14
11
  import { startTrace } from "../trace.ts";
15
12
  import { runApSdk } from "./ap-sdk.ts";
16
13
  import { installedItems, parseTargets, removeDroppedItems, tidyAfterUninstall, type Scope, undoWindsurfProjectMcp, windsurfBefore, withoutWindsurfMcp } from "./cleanup.ts";
17
- import { hostStatusLines, installedLines, toolLines } from "./status.ts";
18
14
 
19
15
  const HELP = `c64-re-tools: Commodore 64 reverse engineering and development
20
16
 
@@ -22,7 +18,6 @@ Usage:
22
18
  c64-re-tools install [--target <harnesses>] [--global] install the skills and the VICE MCP
23
19
  c64-re-tools update [--target <harnesses>] [--global] install this version over an earlier one
24
20
  c64-re-tools uninstall [--target <harnesses>] [--global] remove them
25
- c64-re-tools status version, package, tools and the Host Runtime
26
21
  c64-re-tools --help
27
22
 
28
23
  Harnesses: claude, codex, pi, opencode, gemini, copilot, cursor, windsurf
@@ -36,9 +31,8 @@ project folder below the root uses that install; a project is a folder with
36
31
  through npx. The Host Runtime runs on the machine with VICE: start it there
37
32
  with npx -y --package=${PACKAGE.name}@${PACKAGE.tag} c64-re-tools-host.
38
33
  It runs VICE and the tools that come with it (c1541, petcat). The skill
39
- scripts run ACME, DXA, Exomizer, Ghidra and c64run in the dev container.`;
34
+ scripts run ACME, DXA, Exomizer and c64run in the dev container.`;
40
35
 
41
- const here = dirname(fileURLToPath(import.meta.url));
42
36
 
43
37
  /** Runs the AP SDK CLI. Writes its error output to stderr and returns its exit status and its report. */
44
38
  async function apSdk(command: "install" | "uninstall", flags: readonly string[]): Promise<{ code: number; output: string }> {
@@ -48,20 +42,6 @@ async function apSdk(command: "install" | "uninstall", flags: readonly string[])
48
42
  return { code: run.code, output: run.stdout };
49
43
  }
50
44
 
51
- async function status(): Promise<number> {
52
- console.log(`c64-re-tools ${PACKAGE.version}`);
53
- console.log(`Package: ${join(here, "..", "..")}`);
54
- console.log(`Node: ${process.version} (${process.execPath})`);
55
- for (const line of installedLines()) console.log(line);
56
- // The skill scripts run these tools here, on this machine.
57
- const local = await localToolStatus(localToolContext());
58
- for (const line of toolLines("Tools here:", local)) console.log(line);
59
- const host = await hostStatusLines();
60
- for (const line of host.lines) console.log(line);
61
- // A script or a CI check can tell a ready setup from a broken one.
62
- return host.ready && local.every((tool) => tool.runs) ? 0 : 1;
63
- }
64
-
65
45
  async function main(argv: string[]): Promise<number> {
66
46
  startTrace("cli", { warn: (line) => console.error(line) });
67
47
  const { values, positionals } = parseArgs({
@@ -106,12 +86,6 @@ async function main(argv: string[]): Promise<number> {
106
86
  if (code === 0) tidyAfterUninstall(items, scope);
107
87
  return code;
108
88
  }
109
- case "status":
110
- if (flags.length > 0) {
111
- console.error(`status takes no --target or --global.\n\n${HELP}`);
112
- return 2;
113
- }
114
- return status();
115
89
  default:
116
90
  console.error(`Unknown command ${command}.\n\n${HELP}`);
117
91
  return 2;
package/src/host/main.ts CHANGED
@@ -121,12 +121,12 @@ async function main(): Promise<number> {
121
121
  log,
122
122
  flaws,
123
123
  // c1541 lists the disk, so an autostart index selects a program.
124
- directory: async (imageType, image) => {
125
- const { result } = await inspect({ action: "directory", imageType }, image, { supervisor, signal: new AbortController().signal, log });
124
+ directory: async (imageType, image, signal) => {
125
+ const { result } = await inspect({ action: "directory", imageType }, image, { supervisor, signal, log });
126
126
  return result.action === "directory" ? result.entries : [];
127
127
  },
128
128
  }),
129
- tools: createToolDispatcher({ supervisor, log, vice }),
129
+ tools: createToolDispatcher({ supervisor, log }),
130
130
  });
131
131
  } catch (error) {
132
132
  if (error instanceof ListenError && error.code === "EADDRINUSE") {
@@ -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,16 +1,14 @@
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
- import type { ViceVersion } from "../../native/discover.ts";
7
6
  import type { ProcessSupervisor } from "../../native/processes.ts";
8
7
  import type { ToolContext } from "../../native/run.ts";
9
8
  import type { ToolOperation, ToolOperations } from "../../protocol/tools.ts";
10
9
  import type { ToolDispatcher } from "../server.ts";
11
10
  import { inspect } from "./c1541.ts";
12
11
  import { decode } from "./petcat.ts";
13
- import { hostStatus } from "./status.ts";
14
12
 
15
13
  /** Runs one operation with its validated parameters and attachments. */
16
14
  type Adapter<O extends ToolOperation> = (
@@ -20,16 +18,13 @@ type Adapter<O extends ToolOperation> = (
20
18
  ) => Promise<{ result: ToolOperations[O]["result"]; attachments?: Buffer[] }>;
21
19
 
22
20
  const ADAPTERS: { [O in ToolOperation]: Adapter<O> } = {
23
- "host.status": (_params, _attachments, context) => hostStatus(context),
24
21
  "c1541.inspect": (params, attachments, context) => inspect(params, attachments[0]!, context),
25
22
  "petcat.decode": (_params, attachments, context) => decode(attachments[0]!, context),
26
23
  };
27
24
 
28
- /** `vice`: the version that the host read from the emulator at start, for host.status. */
29
- export function createToolDispatcher(options: { supervisor: ProcessSupervisor; env?: NodeJS.ProcessEnv; log?: (line: string) => void; vice?: ViceVersion }): ToolDispatcher {
25
+ export function createToolDispatcher(options: { supervisor: ProcessSupervisor; env?: NodeJS.ProcessEnv; log?: (line: string) => void }): ToolDispatcher {
30
26
  return (op, params, attachments, signal) => {
31
27
  const context = { supervisor: options.supervisor, signal, env: options.env, log: options.log };
32
- if (op === "host.status") return hostStatus(context, options.vice) as ReturnType<ToolDispatcher>;
33
28
  return ADAPTERS[op](params, attachments, context);
34
29
  };
35
30
  }
@@ -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`. */