@henols/c64-re-tools 2.1.2 → 2.1.4

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 (50) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +1 -1
  3. package/skills/c64-assembler/scripts/assembler.ts +2 -2
  4. package/skills/c64-disk/scripts/lib/containers.ts +2 -1
  5. package/skills/c64-docs/SKILL.md +1 -1
  6. package/skills/c64-docs/scripts/docs.ts +5 -3
  7. package/skills/c64-emulator/SKILL.md +4 -0
  8. package/skills/c64-knowledge/SKILL.md +7 -2
  9. package/skills/c64-knowledge/scripts/knowledge.ts +6 -12
  10. package/skills/c64-knowledge/scripts/lib/listing.ts +8 -1
  11. package/skills/c64-memory-map/SKILL.md +3 -1
  12. package/skills/c64-memory-map/scripts/memory-map.ts +26 -5
  13. package/skills/c64-provenance/SKILL.md +5 -4
  14. package/skills/c64-provenance/scripts/lib/compare.ts +12 -0
  15. package/skills/c64-provenance/scripts/lib/library.ts +33 -5
  16. package/skills/c64-provenance/scripts/lib/separate.ts +34 -6
  17. package/skills/c64-provenance/scripts/provenance.ts +26 -11
  18. package/skills/c64-source/SKILL.md +3 -2
  19. package/skills/c64-source/scripts/lib/source.ts +18 -4
  20. package/skills/c64-source/scripts/source.ts +40 -28
  21. package/skills/c64-static-analysis/SKILL.md +4 -3
  22. package/skills/c64-static-analysis/scripts/lib/findings.ts +47 -10
  23. package/skills/c64-static-analysis/scripts/lib/pointers.ts +38 -25
  24. package/skills/c64-static-analysis/scripts/static-analysis.ts +17 -14
  25. package/skills/c64-testing/SKILL.md +6 -3
  26. package/skills/c64-testing/references/scenario-format.md +7 -3
  27. package/skills/c64-testing/scripts/lib/diff-files.ts +27 -8
  28. package/skills/c64-testing/scripts/lib/runs.ts +24 -8
  29. package/skills/c64-testing/scripts/lib/scenario.ts +133 -83
  30. package/skills/c64-testing/scripts/testing.ts +6 -3
  31. package/skills/c64-unpacker/SKILL.md +5 -4
  32. package/skills/c64-unpacker/scripts/lib/loads.ts +9 -3
  33. package/skills/c64-unpacker/scripts/lib/machine.ts +31 -0
  34. package/skills/c64-unpacker/scripts/unpacker.ts +4 -1
  35. package/src/host/vice/session.ts +118 -11
  36. package/src/host-client/image.ts +22 -8
  37. package/src/host-client/steps.ts +2 -2
  38. package/src/host-client/tools.ts +4 -3
  39. package/src/host-client/transfer.ts +8 -3
  40. package/src/host-client/vice-session.ts +3 -3
  41. package/src/knowledge/write.ts +110 -29
  42. package/src/mcp/output.ts +1 -1
  43. package/src/mcp/server.ts +7 -0
  44. package/src/mcp/tools/debug.ts +2 -1
  45. package/src/mcp/tools/media.ts +8 -5
  46. package/src/media.ts +18 -0
  47. package/src/opcodes.ts +31 -1
  48. package/src/platform.ts +14 -1
  49. package/src/project.ts +14 -3
  50. package/src/script.ts +71 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henols/c64-re-tools",
3
- "version": "2.1.2",
3
+ "version": "2.1.4",
4
4
  "description": "Agent-friendly Commodore 64 engineering toolkit for reverse engineering, debugging, development and testing.",
5
5
  "license": "MIT",
6
6
  "author": "Henrik Olsson",
@@ -35,7 +35,7 @@ node <skill>/scripts/assembler.ts build src main.a --out build/game.prg
35
35
  | `--plain` | Write only the bytes of the program, without the 2-byte load address of a PRG. `loadRange` still tells where the bytes go. |
36
36
  | `--all-symbols` | List all symbols. Without it, the list does not include the constants that the source does not use. `unusedConstants` gives their count. |
37
37
  | `--max-listed 200` | Show at most 200 symbols in the result. The default is 50. `symbols.count` gives the count of all symbols. |
38
- | `--out-symbols build/game.json` | Write all symbols to this file as `{"symbols": [...]}`. Give this file to the c64-testing skill as the symbols of the rebuild. |
38
+ | `--out-symbols build/game.json` | Write the symbols to this file as `{"symbols": [...]}`. Without `--all-symbols`, the file does not have the constants that the source does not use. Give this file to the c64-testing skill as the symbols of the rebuild. |
39
39
 
40
40
  The script copies the full source root. Put all files that the program includes under it. Version control directories stay out.
41
41
 
@@ -54,7 +54,7 @@ await runScript({
54
54
  plain: { kind: "flag", help: "write the bytes only, without the 2-byte load address of a PRG" },
55
55
  "all-symbols": { kind: "flag", help: "list also the constants that the source does not use" },
56
56
  "max-listed": { ...OPTIONS["max-listed"], help: "list at most n symbols (default 50). The count is always given" },
57
- "out-symbols": { kind: "path", output: "file", value: "<file.json>", help: "write all symbols to this project file as {\"symbols\": [...]}: the names of the rebuild for c64-testing" },
57
+ "out-symbols": { kind: "path", output: "file", value: "<file.json>", help: "write the listed symbols to this project file as {\"symbols\": [...]}: the names of the rebuild for c64-testing. Without --all-symbols, the file does not have the constants that the source does not use" },
58
58
  },
59
59
  notes: "Symbol values are $ and at least four hex digits. Put the program into the knowledge with knowledge.ts image of the c64-knowledge skill before --compare.",
60
60
  run: async (call) => {
@@ -101,7 +101,7 @@ await runScript({
101
101
  ...written,
102
102
  ...(plain ? { plain: true } : {}),
103
103
  loadRange: { start: formatC64Address(range.start), end: formatC64Address(range.end), bytes: range.bytes },
104
- symbols: listedItems(shown, call.count("max-listed")!, showSymbol, "a larger --max-listed, or --out-symbols <file.json> for all symbols"),
104
+ symbols: listedItems(shown, call.count("max-listed")!, showSymbol, "a larger --max-listed, or --out-symbols <file.json> for the whole list"),
105
105
  ...(symbolsPath === undefined ? {} : { symbolsFile: writeReported(symbolsPath, `${JSON.stringify({ symbols: shown.map(showSymbol) }, null, 1)}\n`, { what: "--out-symbols" }) }),
106
106
  ...(all ? {} : { unusedConstants: result.symbols!.length - shown.length }),
107
107
  diagnostics: result.diagnostics,
@@ -33,7 +33,8 @@ export interface Crt {
33
33
 
34
34
  export function parseCrt(bytes: Uint8Array): Crt {
35
35
  const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
36
- if (buffer.length < 0x40 || !hasSignature("crt", buffer)) throw new Refusal("media-error", "the file is not a CRT: it does not start with C64 CARTRIDGE");
36
+ if (!hasSignature("crt", buffer)) throw new Refusal("media-error", "the file is not a CRT: it does not start with C64 CARTRIDGE");
37
+ if (buffer.length < 0x40) throw new Refusal("media-error", `the CRT header is shorter than 64 bytes: the file has only ${buffer.length} bytes`);
37
38
  const headerLength = buffer.readUInt32BE(0x10);
38
39
  const type = buffer.readUInt16BE(0x16);
39
40
  const exrom = buffer[0x18]!;
@@ -38,7 +38,7 @@ node <skill>/scripts/docs.ts link README.md docs --source src --check
38
38
  | `--source src` | `docs.ts link`: the source directory of c64-source. The command reads `src/source-map.json`. |
39
39
  | `--out docs/reference` | The directory of the reference. `docs.ts generate` writes only there. It refuses to start when the directory holds a page that it did not write. |
40
40
  | `README.md docs` | The pages of the documentation: `.md` files and directories. `docs.ts link` reads each file and every `.md` file below each directory. It changes only the pages that you wrote. It checks the pages of the reference. |
41
- | `--reference <dir>` | The directory of the reference for `docs.ts link`. The default is the `reference` directory of the first directory that has one, for example `docs/reference`. |
41
+ | `--reference <dir>` | The directory of the reference for `docs.ts link`. The default is the first `reference` directory in a given directory or beside a given page, for example `docs/reference`. |
42
42
  | `--check` | `docs.ts link` writes nothing. `result` is `FAIL` when a link is not up to date or a page has a problem. |
43
43
  | `--max-listed 20` | List at most this number of items in each list. The default is 50. |
44
44
 
@@ -169,7 +169,9 @@ function link(call: Call): Record<string, unknown> {
169
169
  const directories = given.filter((path) => !path.endsWith(".md") || isDirectory(path));
170
170
  const map = readSourceMap(call.string("source")!);
171
171
  const givenReference = call.string("reference");
172
- const reference = givenReference === undefined ? directories.map((path) => posix.join(path, "reference")).find((path) => isDirectory(path)) : posix.normalize(givenReference);
172
+ // The default reference: the reference/ folder in a given folder, or beside a given page.
173
+ const besides = given.map((path) => (directories.includes(path) ? path : posix.dirname(path)));
174
+ const reference = givenReference === undefined ? besides.map((path) => posix.join(path, "reference")).find((path) => isDirectory(path)) : posix.normalize(givenReference);
173
175
  const problems: Problem[] = [];
174
176
  const db = openForRead();
175
177
  let symbols;
@@ -279,7 +281,7 @@ function link(call: Call): Record<string, unknown> {
279
281
  for (const problem of problems) byKind[problem.kind] = (byKind[problem.kind] ?? 0) + 1;
280
282
  const output: Record<string, unknown> = {
281
283
  pages: pages.length,
282
- ...(reference === undefined ? { reference: "none: run docs.ts generate for links to the entries" } : { reference }),
284
+ ...(reference === undefined ? { reference: "none: no reference/ folder is in or beside the given pages. Give --reference <dir>, or run docs.ts generate for links to the entries" } : { reference }),
283
285
  ...(check ? { notUpToDate: { links, pages: changedPages } } : { linked: { links, pages: changedPages } }),
284
286
  problems: { byKind, ...listed(problems, call.count("max-listed")!, (problem) => ({ at: `${problem.page}:${problem.line}`, kind: problem.kind, message: problem.message })) },
285
287
  };
@@ -312,7 +314,7 @@ await runScript({
312
314
  subjects: [{ name: "<page>", help: ".md files and folders of the documentation, relative to the project folder, for example README.md docs. link reads each file and every .md file below each folder", list: true }],
313
315
  options: {
314
316
  source: { ...SOURCE, required: true },
315
- reference: { kind: "path", value: "<dir>", help: "the reference pages of docs.ts generate. The default is the reference/ folder of the first folder that has one" },
317
+ reference: { kind: "path", value: "<dir>", help: "the reference pages of docs.ts generate. The default is the first reference/ folder in a given folder or beside a given page" },
316
318
  check: { kind: "flag", help: "write nothing. FAIL when a link is not up to date or a page has a problem" },
317
319
  "max-listed": OPTIONS["max-listed"],
318
320
  },
@@ -81,6 +81,8 @@ Write operations need a stopped CPU. Stop the CPU with `c64_execution` action `p
81
81
 
82
82
  A cartridge from `c64_autostart` stays in the C64 through every reset, as on a real C64. `c64_status` gives `cartridge: true` while the C64 has it, and `cartridge: false` when it does not. `c64_autostart` of a file that is not a cartridge removes the cartridge first. `c64_autostart` also sets both joysticks to the center first. `joysticksCentred` gives the ports that it changed.
83
83
 
84
+ `c64_autostart` returns while the load continues. The emulator turns warp on until it types RUN. A key in that time stops the autostart, so `c64_keyboard` refuses it. Run frames with `advance-frames` until `c64_status` gives `warp: false`. Then type.
85
+
84
86
  Step, next and until-return work only in space `c64`. The emulator cannot stop the disk drive CPU after one instruction. To find when the drive executes an address, use `c64_run_until` with an address target in space `drive8`, or a breakpoint in space `drive8`. The drive can execute a few more instructions before it stops. The computer completes its current instruction. The `pc` in the result is the drive address where it stopped. `space` in the result is `drive8`. A breakpoint or a watchpoint in space `drive8` that stops `advance-frames` gives the same `pc` and `space`. `c64_status` also gives them. A memory target or a memory condition tests only space `c64`.
85
87
 
86
88
  `c64_keyboard` puts keys in the keyboard queue of the KERNAL. A program that reads the keyboard matrix directly does not see them. Many games do this. No MCP tool presses a key of the keyboard matrix. For such a program:
@@ -135,6 +137,8 @@ An error is `{"error": {"code": "...", "message": "..."}}`. The message tells wh
135
137
  - `machine-unavailable` and the message says that the VICE window closed: the session starts the emulator again. Wait a few seconds. Then do the operation again.
136
138
  - `machine-state-lost` with a different message: the connection to the host runtime was lost, and the machine state is gone. Do not continue with results from before. The next call starts a new machine when the host runtime runs. Load the program again, and set the breakpoints and the watchpoints again. If the next call gives `machine-unavailable` with a message that the host runtime does not run, obey the rule for that message.
137
139
  - `machine-unavailable` and the message names a pause or a dialog in the emulator window: this occurs only while the window is open. Do not send more operations. Tell the user to resume the emulator (Pause, Alt+P) or to close the dialog in the VICE window. Then do the operation again. The machine state does not change.
140
+ - `machine-unavailable` and the message says that the emulator does not take commands now, with no window open: wait a few seconds. Then do the operation again one time. If you get the same error again, stop the task. Tell the user to restart the c64-re-tools MCP server, and wait for the user.
141
+ - `media-error`: the file is not of the type that its extension names. Give a file of that type.
138
142
  - `machine-running`: stop the CPU first, then try again.
139
143
  - `installation-incomplete`, or `machine-unavailable` with a message that the host runtime does not run: stop the task. Give the message to the user and wait for the user. The message gives the remedy. Do not make a replacement for the tool or the host runtime, for example your own disk parser, disassembler or emulator script. Do not try to repair the installation.
140
144
  - `c64_run_until` with `stopReason` `timeout`: the target did not occur in the frame limit. This is evidence too. Report it.
@@ -129,12 +129,16 @@ Write:
129
129
 
130
130
  Each write is one revision. A classification inside a region splits that region, so regions never overlap.
131
131
 
132
+ A write can give the same fact that an analyzer gave. Then the fact gets the origin of the write, and `previous` in the result shows the row of the analyzer. The next analysis does not remove the fact. This is true for a symbol, a region, a comment and a reference. A `--by user` write over the same fact of `llm` also changes the origin to `user`. A `--by llm` write over the same fact of `user` changes nothing.
133
+
134
+ A comment and a module are at the start of an instruction. In a code region, the script refuses an address that is an operand byte of an instruction. The error gives the start of that instruction. In data, each address is correct.
135
+
132
136
  ## The program and the coverage
133
137
 
134
138
  The knowledge holds the program, so a project needs no image or coverage files. The other skills read them from the knowledge and take no path to them.
135
139
 
136
140
  1. Capture a packed program with the c64-unpacker skill into `.c64-re-tools/local/`. Then put it in with `image .c64-re-tools/local/capture/image.json`. The script reads `image.bin`, `entry_state.json` and the stages next to it.
137
- 2. For a program without a packer, drive code or a cartridge bank, put the PRG in with `image <file.prg>`. Give `--space drive8` or `--space bank0` for drive code or a bank.
141
+ 2. For a program without a packer, drive code or a cartridge bank, put the PRG in with `image <file.prg>`. Give `--space drive8` or `--space bank0` for drive code or a bank. A PRG has the extension `.prg` or no extension. The script refuses a file with another extension.
138
142
  3. Write each coverage map of a run into `.c64-re-tools/local/`. Then add it with `coverage <map.bin> ...`.
139
143
  4. Read what the knowledge holds with `program`: the segments, the entry, and the coverage maps that it has.
140
144
 
@@ -233,9 +237,10 @@ A patch is ACME code that replaces a range of the program when the build defines
233
237
  - A switch name is upper case, for example `CRACK` or `TRAINER`. It cannot be the name of a symbol or a platform name.
234
238
  - Many patches can have the same switch. The c64-source skill builds each switch on its own. It does not build two switches together.
235
239
  - The code must fit in the range. NOP ($EA) fills the bytes after the code. `--nop` gives a range of NOP only.
240
+ - `patch` refuses code that is longer than the range when each line is a 6510 instruction, `!byte`, `!word`, `!fill` or a comment. `patch` does not check the length of other code, for example code with a label or a macro. It does not assemble the code. `generate` of the c64-source skill builds each switch and does these checks. `switches[].result` is `overflow` for code that is longer than its range, and `does not assemble` for code that ACME refuses.
236
241
  - `--code` gives the code as text. `--code-file` reads the code from a project file. The code can use the labels and the macros of the source, and local labels with a dot, for example `.skip`.
237
242
  - The braces in the code must be pairs, because the source puts the code inside `{ }`.
238
- - A patch cannot overlap another patch or a macro use.
243
+ - A patch cannot overlap another patch or a macro use. A patch with the same start and the same switch replaces the patch. A patch of another switch at the same start gives the error `conflict`.
239
244
  - Each byte of the range must be in the program of the knowledge.
240
245
  - A `patch` write without `--comment` keeps the comment that the patch has.
241
246
 
@@ -328,6 +328,9 @@ function shownPrevious(row: NonNullable<BatchStep["previous"]>) {
328
328
  if ("switch" in row) return patch(row);
329
329
  if ("body" in row) return macro(row);
330
330
  if ("macro" in row) return macroUse(row);
331
+ if ("placement" in row) return comment(row);
332
+ if ("from" in row) return reference(row);
333
+ if ("file" in row) return module(row);
331
334
  return symbol(row);
332
335
  }
333
336
 
@@ -659,10 +662,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
659
662
  (call) => {
660
663
  const context = contextOf(call);
661
664
  const request = { space: call.space, address: call.parseAddress(call.subject(0), "<address>"), placement: oneOf(COMMENT_PLACEMENTS, call.subject(1), "<placement>"), text: call.rest(2).join(" ") };
662
- return (db) => {
663
- const result = setComment(db, context, request);
664
- return { revision: result.revision, comment: comment(result.current) };
665
- };
665
+ return (db) => shown(setComment(db, context, request), "comment", comment);
666
666
  },
667
667
  ),
668
668
  writeCommand({ name: "uncomment", summary: "Removes a comment.", subjects: [ADDRESS, { name: "<placement>", help: `one of ${COMMENT_PLACEMENTS.join(", ")}` }] }, (call) => {
@@ -681,10 +681,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
681
681
  const context = contextOf(call);
682
682
  const request = { space: call.space, from: call.parseAddress(call.subject(0), "<from>"), to: call.parseAddress(call.subject(1), "<to>"), kind: oneOf(REFERENCE_KINDS, call.subject(2), "<kind>") };
683
683
  return name === "reference"
684
- ? (db) => {
685
- const result = addReference(db, context, request);
686
- return { revision: result.revision, reference: reference(result.current) };
687
- }
684
+ ? (db) => shown(addReference(db, context, request), "reference", reference)
688
685
  : (db) => ({ revision: removeReference(db, context, request).revision });
689
686
  },
690
687
  ),
@@ -695,10 +692,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
695
692
  const context = contextOf(call);
696
693
  const title = call.string("title");
697
694
  const request = { space: call.space, start: call.parseAddress(call.subject(0), "<start>"), file: call.subject(1), ...(title === undefined ? {} : { title }) };
698
- return (db) => {
699
- const result = setModule(db, context, request);
700
- return { revision: result.revision, module: module(result.current) };
701
- };
695
+ return (db) => shown(setModule(db, context, request), "module", module);
702
696
  },
703
697
  ),
704
698
  writeCommand({ name: "unmodule", summary: "Removes the module that starts at an address.", subjects: [START] }, (call) => {
@@ -68,7 +68,14 @@ export function listing(source: ListingSource, start: number, end: number): List
68
68
  const bytes = Array.from({ length }, (_, offset) => source.byteAt(address + offset)!.toString(16).padStart(2, "0")).join(" ");
69
69
  const label = source.nameOf(address);
70
70
  const second = source.secondNames(address).filter((name) => name !== label);
71
- const { line: lineComments, side } = source.comments(address);
71
+ const { line: lineComments, side: own } = source.comments(address);
72
+ // A comment inside the line (knowledge of an older version) shows with its address, as in the source of c64-source.
73
+ const inner: string[] = [];
74
+ for (let offset = 1; offset < length; offset++) {
75
+ const found = source.comments(address + offset);
76
+ for (const text of [...found.line, ...(found.side === undefined ? [] : [found.side])]) inner.push(`${formatC64Address(address + offset)}: ${text}`);
77
+ }
78
+ const side = own === undefined && inner.length === 0 ? undefined : [...(own === undefined ? [] : [own]), ...inner].join(" ");
72
79
  const references = source.references(address);
73
80
  const access = accessOf(source.coverage, address, length);
74
81
  return {
@@ -30,12 +30,14 @@ node <skill>/scripts/memory-map.ts export --out src/hw.asm
30
30
  | Command | Result |
31
31
  |---|---|
32
32
  | `at <address> ...` | For each address: `kind` (`platform` or `application`), the area, the name and the meaning. |
33
- | `decode <register> <value>` | The meaning of the value. Use `--bank` with the value of `$DD00` to get the addresses for `$D018`. The decoders are for `$01`, `$D010`, `$D011`, `$D015` to `$D01F`, `$D016`, `$D018`, `$DC0D`, `$DD00` and `$DD0D`. |
33
+ | `decode <register> <value>` | The meaning of the value. Use `--bank` with the value of `$DD00` to get the addresses for `$D018`. The other registers refuse `--bank`. The decoders are for `$01`, `$D010`, `$D011`, `$D015` to `$D01F`, `$D016`, `$D018`, `$DC0D`, `$DD00` and `$DD0D`. |
34
34
  | `list <vic\|sid\|cia1\|cia2\|kernal\|system>` | The entries of that group as a list: `count` and `listed`. `--max-listed` limits `listed`. The default is 50. |
35
35
  | `export --out <file>` | Writes all platform names to a project file as an ACME include: one line for each name, with its meaning as a comment. A zero-page name is `NAME = $xx`. Other names are `NAME = $xxxx`. |
36
36
 
37
37
  Write a value for `decode` and `--bank` as `$` and hex digits, as a decimal number, or as `%` and binary digits. Put a `$` value in single quotes in a shell.
38
38
 
39
+ `at` and `decode` also take a platform name, for example `SCROLY` or `CHROUT`, in upper or lower case. A platform name comes before a name of the knowledge. `list` and `export` show the platform names.
40
+
39
41
  ### Calling the script
40
42
 
41
43
  - Call a script as `node <skill>/scripts/<script>.ts <command> [subjects] [options]`. The command comes first.
@@ -3,6 +3,7 @@
3
3
  // writes the platform names to a project file as an ACME include.
4
4
 
5
5
  import { formatC64Address, formatC64Byte } from "#src/c64.ts";
6
+ import { isRefusal, Refusal } from "#src/errors.ts";
6
7
  import { writeReported } from "#src/host-client/transfer.ts";
7
8
  import { knowledgeNames } from "#src/knowledge/names.ts";
8
9
  import { decode, IO, lookup, platformNames, ROM, SYSTEM, type Entry } from "#src/platform.ts";
@@ -10,6 +11,24 @@ import { listed, OPTIONS, runScript, UsageError } from "#src/script.ts";
10
11
 
11
12
  const show = (entry: Entry) => ({ start: formatC64Address(entry.start), ...(entry.end !== entry.start ? { end: formatC64Address(entry.end) } : {}), name: entry.name, meaning: entry.meaning });
12
13
 
14
+ /** The platform names by name in upper case: memory-map knows them also outside a project. */
15
+ const PLATFORM = new Map(platformNames().map((entry) => [entry.name.toUpperCase(), entry.address]));
16
+
17
+ /**
18
+ * The address of a name: a platform name (a register, a KERNAL or BASIC entry,
19
+ * a system variable) in any letter case first, else a name of the knowledge.
20
+ */
21
+ function names(name: string, space: string): number {
22
+ const platform = PLATFORM.get(name.toUpperCase());
23
+ if (platform !== undefined) return platform;
24
+ try {
25
+ return knowledgeNames(name, space);
26
+ } catch (error) {
27
+ if (!isRefusal(error) || error.code !== "not-found") throw error;
28
+ throw new Refusal("not-found", `${name} is not a C64 platform name and not a name in the knowledge. Give a $ address, a platform name that memory-map.ts list or export shows (for example SCROLY or CHROUT), or a name that knowledge.ts symbols lists.`);
29
+ }
30
+ }
31
+
13
32
  const LISTS: Record<string, () => Entry[]> = {
14
33
  vic: () => IO[0]!.registers,
15
34
  sid: () => IO[1]!.registers,
@@ -22,12 +41,12 @@ const LISTS: Record<string, () => Entry[]> = {
22
41
  await runScript({
23
42
  name: "memory-map",
24
43
  summary: "The platform meaning of C64 addresses and of values in platform registers.",
25
- names: knowledgeNames,
44
+ names,
26
45
  commands: [
27
46
  {
28
47
  name: "at",
29
48
  summary: "The platform meaning of each address: its name, area and meaning.",
30
- subjects: [{ name: "<address>", help: "an address or a name of the knowledge", list: true }],
49
+ subjects: [{ name: "<address>", help: "an address, a platform name such as SCROLY, or a name of the knowledge", list: true }],
31
50
  run: (call) => ({
32
51
  addresses: call.subjects.map((text) => {
33
52
  const found = lookup(call.parseAddress(text, "<address>"));
@@ -47,14 +66,16 @@ await runScript({
47
66
  name: "decode",
48
67
  summary: "The meaning of a value in a platform register.",
49
68
  subjects: [
50
- { name: "<register>", help: "the register: $0001, $d011, $d016, $d018, $d010, $d015-$d01f, $dc0d, $dd00 or $dd0d" },
69
+ { name: "<register>", help: "the register, as an address or a platform name: $0001, $d011 (SCROLY), $d016, $d018, $d010, $d015-$d01f, $dc0d, $dd00 or $dd0d" },
51
70
  { name: "<value>", help: "the value of the register: $ and hex, decimal, or % and binary, 0 to 255" },
52
71
  ],
53
- options: { bank: { kind: "number", value: "<value>", help: "the value of $dd00, for the VIC-II bank of a $d018 value", max: 0xff } },
72
+ options: { bank: { kind: "number", value: "<value>", help: "the value of $dd00, for the VIC-II bank of a $d018 value. Only for $d018", max: 0xff } },
54
73
  run: (call) => {
55
74
  const register = call.parseAddress(call.subject(0), "<register>");
56
75
  const value = call.parseNumber(call.subject(1), "<value>", 0, 0xff);
57
- return { register: formatC64Address(register), value: formatC64Byte(value), name: lookup(register).name, ...decode(register, value, call.count("bank")) };
76
+ const bank = call.count("bank");
77
+ if (bank !== undefined && register !== 0xd018) throw new UsageError(`--bank works only with $d018 (VMCSB), not with ${formatC64Address(register)}. Remove --bank`);
78
+ return { register: formatC64Address(register), value: formatC64Byte(value), name: lookup(register).name, ...decode(register, value, bank) };
58
79
  },
59
80
  },
60
81
  {
@@ -97,7 +97,8 @@ Use `separate` when you have only one release. It reads the program, its stages
97
97
  - `ranges`: the program in ranges with the same stage and access. `stage` is the last unpack stage that wrote the range. The last stage is the program. An earlier stage is a depacker, an intro or a loader. Only a capture of c64-unpacker `capture` has stages. For a program from `loads` or a PRG, `noStages` tells this.
98
98
  - `access`: from the coverage of the knowledge: `executed`, `read`, `written`, `read-written` or `untouched`. `untouched` bytes did not take part in the runs. A `read` byte right after executed code, or at a return address, can be a dummy read of the 6502 that the program does not use.
99
99
  - `codeRegions.total`: the number of code regions in the knowledge.
100
- - `codeRegions.unreachable`: code regions of the knowledge that no chain of call and jump references reaches from the entry. A region also reaches the code after it when its last instruction is not RTS, RTI, JMP, BRK or JAM: the CPU continues there. Run c64-static-analysis first, so that the knowledge has the code regions and the references.
100
+ - `roots`: the addresses where the reachability starts. They are the entry, and the NMI, RESET and IRQ vectors at `$FFFA`-`$FFFF` when the image holds them. An interrupt handler starts from its vector, because no call or jump goes to it. `from` tells the source of each root.
101
+ - `codeRegions.unreachable`: code regions of the knowledge that no chain of call and jump references reaches from a root. A region also reaches the code after it when its last instruction is not RTS, RTI, JMP, BRK or JAM: the CPU continues there. Run c64-static-analysis first, so that the knowledge has the code regions and the references.
101
102
  - `outside`: RAM outside the program that the program `read` or `executed` but did not write, and code it `generated`. A loader or an earlier stage put the bytes that the program did not write. A `generated` range can have gaps of two bytes or less: these are operand bytes.
102
103
 
103
104
  Each list has `count` and `listed`. `listed` has the first ranges, at most `--max-listed` (default 50). `--out` writes all of them and the result shows the file as `{out, bytes, sha256}`. Run more coverage runs for parts that are `untouched`, and add them with `coverage` of the c64-knowledge skill, before you decide.
@@ -113,7 +114,7 @@ Use `leftovers` to find what the program holds in addition to its working code.
113
114
  | `fill` | One byte that repeats, at least 16 times, or a pattern of two to four bytes that repeats, at least 32 bytes in total. `pattern` is the repeated bytes. |
114
115
  | `residue` | Bytes that no run touched and that are no text, BASIC, fill or code region. `bytes` shows the first 16 bytes. |
115
116
  | `copies` | Bytes that are the same as earlier bytes of the program, at least 32 bytes. `copyOf` is the address of the earlier bytes. |
116
- | `deadCode` | Code regions of the knowledge that the entry does not reach, as in `codeRegions.unreachable` of `separate`, and that no run executed. |
117
+ | `deadCode` | Code regions of the knowledge that no root reaches, as in `codeRegions.unreachable` of `separate`, and that no run executed. |
117
118
 
118
119
  Text from another computer can show the tools of the developer:
119
120
 
@@ -192,9 +193,9 @@ Record a confirmed conclusion as a normal comment, region or symbol with the c64
192
193
 
193
194
  ## Result
194
195
 
195
- The differing ranges with the bytes of each release and the groups that agree, and the share of identical bytes. `common` gives the ranges where all releases have bytes. `releases` gives the segments and the `shift` of each release. With `--frames`, each difference also has `runtime`, and `run` tells if each release started, or why not.
196
+ The differing ranges with the bytes of each release and the groups that agree, and the share of identical bytes. `identicalShare` has 3 decimals. It is 1 only when no byte differs. `identicalBytes` and `differingBytes` give the counts. `common` gives the ranges where all releases have bytes. `releases` gives the segments and the `shift` of each release. With `--frames`, each difference also has `runtime`, and `run` tells if each release started, or why not.
196
197
 
197
- For `leftovers`: the lists of findings, with `entry` and the number of `stages`. `noEntry`, `noStages` and `noCoverage` tell which knowledge is missing.
198
+ For `leftovers`: the lists of findings, with `entry`, `roots` and the number of `stages`. `noStages` and `noCoverage` tell which knowledge is missing. Without a root, `roots` tells why `deadCode` is empty.
198
199
 
199
200
  The runtime evidence and the leftovers are evidence only. The script does not decide which bytes are original.
200
201
 
@@ -39,6 +39,18 @@ const JOIN_GAP = 4;
39
39
 
40
40
  export const covers = (release: Release, address: number) => release.segments.some((segment) => address >= segment.start && address <= segment.end);
41
41
 
42
+ /**
43
+ * The share of identical bytes with 3 decimals. It is 1 only when no byte
44
+ * differs, and 0 only when no byte is identical: a rounded share must not hide
45
+ * one differing or one identical byte.
46
+ */
47
+ export function identicalShare(identical: number, differing: number): number {
48
+ const compared = identical + differing;
49
+ if (compared === 0 || identical === 0) return 0;
50
+ if (differing === 0) return 1;
51
+ return Math.min(0.999, Math.max(0.001, Number((identical / compared).toFixed(3))));
52
+ }
53
+
42
54
  /** The ranges where every release has bytes, inside from..to. */
43
55
  export function commonRanges(releases: Release[], from = 0x0000, to = 0xffff): AddressRange[] {
44
56
  const ranges: AddressRange[] = [];
@@ -5,8 +5,8 @@
5
5
  // suggests its names there as an apply batch. Nothing here writes knowledge.
6
6
 
7
7
  import { createHash } from "node:crypto";
8
- import { mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
9
- import { join, relative, resolve, sep } from "node:path";
8
+ import { mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
9
+ import { dirname, join, relative, resolve, sep } from "node:path";
10
10
 
11
11
  import { Refusal } from "#src/errors.ts";
12
12
  import { writeRefusal, type Written } from "#src/host-client/transfer.ts";
@@ -14,7 +14,7 @@ import { formatC64Address, instructionLength } from "#src/c64.ts";
14
14
  import { evaluate, identifiers, operandText } from "#src/knowledge/expression.ts";
15
15
  import type { CommentRow, OperandRow, ReferenceRow, RegionRow, SymbolRow } from "#src/knowledge/read.ts";
16
16
  import { COMMENT_PLACEMENTS, type CommentPlacement, isSemantic, OPERAND_SELECTS, type OperandSelect, REFERENCE_KINDS, type ReferenceKind, REGION_TYPES, type RegionType, SYMBOL_KINDS, type SymbolKind } from "#src/knowledge/schema.ts";
17
- import { PROJECT_DIRECTORY } from "#src/project.ts";
17
+ import { checkOutputPath, isInside, knowledgePart, PROJECT_DIRECTORY } from "#src/project.ts";
18
18
 
19
19
  /** A routine shorter than this is not saved and not searched: its bytes occur by chance. */
20
20
  export const MIN_ROUTINE = 16;
@@ -291,14 +291,42 @@ export function parseRoutine(text: string, file: string): Routine {
291
291
  };
292
292
  }
293
293
 
294
+ /**
295
+ * Refuses a library folder to write that is inside the project `root`, also
296
+ * through a symbolic link, when the output check of every script refuses it
297
+ * (checkOutputPath): for example a folder in the knowledge. A folder outside
298
+ * the project gets no check.
299
+ */
300
+ function checkLibraryOutput(path: string, root: string): void {
301
+ let existing = path;
302
+ while (statSync(existing, { throwIfNoEntry: false }) === undefined && dirname(existing) !== existing) existing = dirname(existing);
303
+ const real = join(realpathSync(existing), relative(existing, path));
304
+ const realRoot = realpathSync(root);
305
+ for (const [base, target] of [[root, path], [realRoot, real]] as const) {
306
+ if (isInside(base, target)) {
307
+ // A project path shows with "/" on every system, as the messages give it.
308
+ const shown = relative(base, target).split(sep).join("/") || ".";
309
+ const part = knowledgePart(shown);
310
+ if (part !== undefined) {
311
+ throw new Refusal("invalid-input", `--library: ${shown} is in ${part}, the knowledge of the project. Only the c64-knowledge skill writes it: a write there destroys the knowledge. Give a library folder beside the projects, for example ../library.`);
312
+ }
313
+ checkOutputPath(shown, "folder", { root: base, what: "--library" });
314
+ return;
315
+ }
316
+ }
317
+ }
318
+
294
319
  /**
295
320
  * The library folder that --library names, relative to the working directory
296
321
  * like --project (D71). A library is a plain folder, never a project. With
297
- * `create`, a missing folder is made.
322
+ * `create`, a missing folder is made; a folder inside the project must pass
323
+ * the output check of every script, which refuses the knowledge.
298
324
  */
299
325
  export function libraryFolder(folder: string, options: { create: boolean; cwd?: string }): string {
300
326
  if (folder.length === 0) throw new Refusal("invalid-input", "The library folder must not be empty.");
301
- const path = resolve(options.cwd ?? process.cwd(), folder);
327
+ const root = options.cwd ?? process.cwd();
328
+ const path = resolve(root, folder);
329
+ if (options.create) checkLibraryOutput(path, root);
302
330
  const stat = statSync(path, { throwIfNoEntry: false });
303
331
  if (stat === undefined) {
304
332
  if (!options.create) throw new Refusal("not-found", `There is no library folder ${folder}. Save a routine to it first with routine.`);
@@ -1,7 +1,8 @@
1
1
  // Evidence from one release: for each range of the image, the unpack
2
2
  // stage that wrote it and the access class from coverage; for each code
3
3
  // region of knowledge, whether call and jump references or the run on from
4
- // its last instruction reach it from the entry; and what the program reads
4
+ // its last instruction reach it from a root (the entry, and the NMI, RESET
5
+ // and IRQ vectors at $fffa-$ffff when the image holds them); and what the program reads
5
6
  // or executes outside the image. Evidence only: nothing here decides what is
6
7
  // original.
7
8
 
@@ -30,13 +31,21 @@ export interface EvidenceRange extends AddressRange {
30
31
 
31
32
  export interface CodeRegionEvidence extends AddressRange {
32
33
  type: string;
33
- /** Absent when the image has no entry. */
34
+ /** Absent when the image has no root: no entry and no hardware vector. */
34
35
  reachable?: boolean;
35
36
  /** Absent without coverage. */
36
37
  executed?: boolean;
37
38
  }
38
39
 
40
+ /** An address where the reachability starts, and why: the entry, or a hardware vector in the image. */
41
+ export interface Root {
42
+ address: number;
43
+ from: "entry" | "NMI vector $fffa" | "RESET vector $fffc" | "IRQ vector $fffe";
44
+ }
45
+
39
46
  export interface Separation {
47
+ /** The roots of the reachability, in the order entry, NMI, RESET, IRQ. */
48
+ roots: Root[];
40
49
  ranges: EvidenceRange[];
41
50
  codeRegions: CodeRegionEvidence[];
42
51
  /**
@@ -50,6 +59,24 @@ export interface Separation {
50
59
 
51
60
  const SYSTEM_PAGES_END = 0x03ff;
52
61
 
62
+ /** The hardware vectors of the 6510: the CPU reads them from $fffa-$ffff, the RAM when the KERNAL is banked out. */
63
+ const HARDWARE_VECTORS = [
64
+ { at: 0xfffa, from: "NMI vector $fffa" },
65
+ { at: 0xfffc, from: "RESET vector $fffc" },
66
+ { at: 0xfffe, from: "IRQ vector $fffe" },
67
+ ] as const;
68
+
69
+ /**
70
+ * The roots of the reachability: the entry, and each hardware vector whose
71
+ * two bytes are in the image. An interrupt handler runs by its vector, and
72
+ * no call or jump reference reaches it.
73
+ */
74
+ export function reachabilityRoots(segments: readonly AddressRange[], memory: Uint8Array, entry?: number): Root[] {
75
+ const inImage = (address: number) => segments.some((segment) => address >= segment.start && address <= segment.end);
76
+ const vectors = HARDWARE_VECTORS.filter((vector) => inImage(vector.at) && inImage(vector.at + 1)).map((vector): Root => ({ address: memory[vector.at]! | (memory[vector.at + 1]! << 8), from: vector.from }));
77
+ return [...(entry === undefined ? [] : [{ address: entry, from: "entry" as const }]), ...vectors];
78
+ }
79
+
53
80
  /** BRK, JMP, RTI, RTS, JMP (indirect) and the JAM opcodes: the CPU does not run on to the next instruction after them. */
54
81
  const NO_FALL_THROUGH = new Set([0x00, 0x4c, 0x40, 0x60, 0x6c, 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72, 0x92, 0xb2, 0xd2, 0xf2]);
55
82
 
@@ -114,12 +141,13 @@ export function separate(input: SeparationInput): Separation {
114
141
  }
115
142
  }
116
143
 
117
- // Reachability: from the region that holds the entry, through call and jump references and the run on
144
+ // Reachability: from the regions that hold a root, through call and jump references and the run on
118
145
  // from the last instruction of a region into the next address, to a fixed point.
119
146
  const regions = input.codeRegions.filter((region) => input.segments.some((segment) => region.start <= segment.end && segment.start <= region.end));
120
147
  const holding = (address: number) => regions.findIndex((region) => address >= region.start && address <= region.end);
148
+ const roots = reachabilityRoots(input.segments, input.memory, input.entry);
121
149
  const reached = new Set<number>();
122
- if (input.entry !== undefined && holding(input.entry) >= 0) reached.add(holding(input.entry));
150
+ for (const root of roots) if (holding(root.address) >= 0) reached.add(holding(root.address));
123
151
  // The CPU runs the bytes after the region as instructions: through bytes of no code region (a dual-use
124
152
  // instruction, for example) into the next code region, unless one of them does not run on.
125
153
  const runOn = (from: number): number | undefined => {
@@ -154,7 +182,7 @@ export function separate(input: SeparationInput): Separation {
154
182
  ran = false;
155
183
  for (let address = region.start; address <= region.end && !ran; address++) ran = executed[address] === 1;
156
184
  }
157
- return { start: region.start, end: region.end, type: region.type, ...(input.entry === undefined ? {} : { reachable: reached.has(index) }), ...(ran === undefined ? {} : { executed: ran }) };
185
+ return { start: region.start, end: region.end, type: region.type, ...(roots.length === 0 ? {} : { reachable: reached.has(index) }), ...(ran === undefined ? {} : { executed: ran }) };
158
186
  });
159
187
 
160
188
  const read: number[] = [];
@@ -174,5 +202,5 @@ export function separate(input: SeparationInput): Separation {
174
202
  for (let address = from + 1; address < to; address++) if (inImage(address)) return false;
175
203
  return true;
176
204
  };
177
- return { ranges, codeRegions, outside: { read: merge(read), executed: merge(ranOutside), generated: merge(generated, 2, outsideImage) } };
205
+ return { roots, ranges, codeRegions, outside: { read: merge(read), executed: merge(ranOutside), generated: merge(generated, 2, outsideImage) } };
178
206
  }
@@ -43,11 +43,11 @@ import { platformNames } from "#src/platform.ts";
43
43
  import { projectRoot } from "#src/project.ts";
44
44
  import { knowledgeAt, knowledgeNames } from "#src/knowledge/names.ts";
45
45
  import { listed, OPTIONS, runScript, UsageError, type Call, type CommandSpec } from "#src/script.ts";
46
- import { compareReleases, shiftSuggestion, suggestShifts, type Release } from "./lib/compare.ts";
46
+ import { compareReleases, identicalShare, shiftSuggestion, suggestShifts, type Release } from "./lib/compare.ts";
47
47
  import { findRoutine, libraryFolder, readLibrary, routineFrom, saveRoutine, suggest } from "./lib/library.ts";
48
48
  import { watchRelease, type Start } from "./lib/runtime.ts";
49
49
  import { findLeftovers } from "./lib/leftovers.ts";
50
- import { separate } from "./lib/separate.ts";
50
+ import { separate, type Root } from "./lib/separate.ts";
51
51
 
52
52
  const hexBytes = (bytes: number[]) => Buffer.from(bytes).toString("hex").replace(/(..)(?!$)/g, "$1 ");
53
53
 
@@ -107,7 +107,7 @@ async function compare(call: Call): Promise<unknown> {
107
107
  const shifts = new Map<number, number>();
108
108
  for (const text of call.strings("shift")) {
109
109
  const match = /^(\d+):([+-]?\d+)$/.exec(text);
110
- if (match === null) throw new UsageError(`--shift must be <release number>:<bytes>, for example 2:-256, not ${text}`);
110
+ if (match === null) throw new UsageError(`--shift must be <release>:<bytes>, for example 2:-256, not ${text}`);
111
111
  if (Number(match[1]) < 1 || Number(match[1]) > positionals.length) {
112
112
  throw new UsageError(`--shift ${text}: there is no release ${match[1]}. This compare has ${positionals.length} releases: give a release number from 1 to ${positionals.length}`);
113
113
  }
@@ -122,13 +122,12 @@ async function compare(call: Call): Promise<unknown> {
122
122
  const releases = loaded.map((item) => item.release);
123
123
  const range = call.range("range");
124
124
  const comparison = compareReleases(releases, range === undefined ? {} : { from: range.start, to: range.end });
125
- const compared = comparison.identicalBytes + comparison.differingBytes;
126
- const identicalShare = compared === 0 ? 0 : comparison.identicalBytes / compared;
125
+ const share = identicalShare(comparison.identicalBytes, comparison.differingBytes);
127
126
  // A poor match at the load addresses can mean that the releases are placed differently.
128
127
  // Each release gets its best shifts: data that stayed can outvote code that moved, so one is not enough.
129
128
  const applied = loaded.map((item) => item.shift);
130
129
  const suggestions =
131
- identicalShare < 0.5
130
+ share < 0.5
132
131
  ? releases.slice(1).flatMap((release, index) =>
133
132
  suggestShifts(releases[0]!, release).map((found) => {
134
133
  const suggestion = shiftSuggestion(releases, applied, index + 1, found);
@@ -170,7 +169,7 @@ async function compare(call: Call): Promise<unknown> {
170
169
  common: comparison.common.map((range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) })),
171
170
  identicalBytes: comparison.identicalBytes,
172
171
  differingBytes: comparison.differingBytes,
173
- identicalShare: Number(identicalShare.toFixed(3)),
172
+ identicalShare: share,
174
173
  differences: comparison.differences.map((difference, index) => ({
175
174
  start: formatC64Address(difference.start),
176
175
  end: formatC64Address(difference.end),
@@ -239,6 +238,11 @@ function programEvidence() {
239
238
  return { program, stages, coverage, found };
240
239
  }
241
240
 
241
+ /** The roots of the reachability as a person reads them. */
242
+ const showRoots = (roots: readonly Root[]) => roots.map((root) => ({ address: formatC64Address(root.address), from: root.from }));
243
+
244
+ const NO_ROOTS = "none: the program in the knowledge has no entry, and the image does not hold the hardware vectors at $fffa-$ffff, so no code region is reachable or unreachable.";
245
+
242
246
  const NO_STAGES = "The program in the knowledge has no stage log. Only a capture of c64-unpacker gives one. A capture of loads holds one part of a program and has none.";
243
247
 
244
248
  /** separate: evidence from the program in the knowledge, with all ranges in --out and the first ones in the result. */
@@ -251,7 +255,8 @@ function separateCommand(call: Call): unknown {
251
255
  const ranges = found.ranges.map((range) => ({ ...show(range), ...(range.stage === undefined ? {} : { stage: range.stage }), ...(range.access === undefined ? {} : { access: range.access }) }));
252
256
  const codeRegions = found.codeRegions.map((region) => ({ ...show(region), type: region.type, ...(region.reachable === undefined ? {} : { reachable: region.reachable }), ...(region.executed === undefined ? {} : { executed: region.executed }) }));
253
257
  const outside = { read: found.outside.read.map(show), executed: found.outside.executed.map(show), generated: found.outside.generated.map(show) };
254
- const written = out === undefined ? undefined : writeReported(out, `${JSON.stringify({ ranges, codeRegions, outside }, null, 1)}\n`, { what: "--out" });
258
+ const roots = showRoots(found.roots);
259
+ const written = out === undefined ? undefined : writeReported(out, `${JSON.stringify({ roots, ranges, codeRegions, outside }, null, 1)}\n`, { what: "--out" });
255
260
  const rest = out === undefined ? undefined : out;
256
261
  const list = <T>(items: T[]) => listed(items, max, undefined, rest);
257
262
  const bytes = (filter: (range: (typeof found.ranges)[number]) => boolean) => found.ranges.filter(filter).reduce((sum, range) => sum + range.end - range.start + 1, 0);
@@ -266,10 +271,12 @@ function separateCommand(call: Call): unknown {
266
271
  }),
267
272
  ...(coverage === undefined ? {} : { bytesByAccess: Object.fromEntries((["executed", "read", "written", "read-written", "untouched"] as const).map((access) => [access, bytes((range) => range.access === access)])) }),
268
273
  ranges: list(ranges),
274
+ // The roots of the reachability: the entry and the hardware vectors in the image.
275
+ roots: roots.length === 0 ? NO_ROOTS : roots,
269
276
  // total counts every code region; unreachable is a list like the others.
270
277
  codeRegions: {
271
278
  total: codeRegions.length,
272
- ...(loaded.entry === undefined ? {} : { unreachable: list(codeRegions.filter((region) => region.reachable === false)) }),
279
+ ...(roots.length === 0 ? {} : { unreachable: list(codeRegions.filter((region) => region.reachable === false)) }),
273
280
  },
274
281
  ...(coverage === undefined ? {} : { outside: { read: list(outside.read), executed: list(outside.executed), generated: list(outside.generated) } }),
275
282
  ...(written === undefined ? {} : written),
@@ -310,7 +317,8 @@ function leftoversCommand(call: Call): unknown {
310
317
  const written = out === undefined ? undefined : writeReported(out, `${JSON.stringify(all, null, 1)}\n`, { what: "--out" });
311
318
  const list = <T>(items: T[]) => listed(items, max, undefined, out ?? "a larger --max-listed, or --out <file>");
312
319
  return {
313
- ...(program.entry === undefined ? { noEntry: "The program in the knowledge has no entry, so deadCode is empty." } : { entry: formatC64Address(program.entry) }),
320
+ ...(program.entry === undefined ? {} : { entry: formatC64Address(program.entry) }),
321
+ roots: found.roots.length === 0 ? NO_ROOTS : showRoots(found.roots),
314
322
  ...(stages === undefined ? { noStages: NO_STAGES } : { stages: stages.length }),
315
323
  ...(coverage === undefined ? { noCoverage: "The knowledge has no coverage, so residue is empty and no finding has access. Add coverage with coverage of the c64-knowledge skill." } : {}),
316
324
  text: list(all.text.map((item) => (item.text.length > SHOWN_TEXT ? { ...item, text: `${item.text.slice(0, SHOWN_TEXT)} ...`, length: item.text.length } : item))),
@@ -455,7 +463,14 @@ const COMMANDS: CommandSpec[] = [
455
463
  summary: "Compares releases byte by byte, in their common ranges, and suggests shifts when they are placed differently.",
456
464
  subjects: [{ name: "<release>", help: "knowledge (the program in the knowledge), a PRG at its load address, or an image.json of the c64-unpacker skill with the entry_state.json beside it. Two or more", list: true }],
457
465
  options: {
458
- shift: { kind: "text", value: "<n>:<bytes>", multiple: true, help: "move release n (1 is the first) by a number of bytes, for example 2:-256" },
466
+ shift: {
467
+ kind: "text",
468
+ value: "<release>:<bytes>",
469
+ multiple: true,
470
+ help: "move a release (1 is the first) by a number of bytes, for example 2:-256",
471
+ // A bare number is the bytes: the example puts it after a release.
472
+ example: (given) => `2:${given !== undefined && /^-\d+$/.test(given) ? given : "-256"}`,
473
+ },
459
474
  range: { ...OPTIONS.range, help: "compare only the addresses from start to end" },
460
475
  frames: { ...OPTIONS.frames, max: MAX_EXECUTION_COUNT, help: "run each release in its own emulator for n frames, and give each listed difference its first access and whether it changed" },
461
476
  steps: { ...OPTIONS.steps, help: "with --frames: action steps (JSON) to run before the frames" },