@henols/c64-re-tools 2.8.0-rc.2 → 2.8.0-rc.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 (119) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +5 -2
  3. package/skills/c64-assembler/scripts/assembler.ts +55 -48
  4. package/skills/c64-disk/scripts/disk.ts +3 -3
  5. package/skills/c64-disk/scripts/lib/containers.ts +2 -2
  6. package/skills/c64-docs/SKILL.md +1 -1
  7. package/skills/c64-docs/scripts/docs.ts +12 -20
  8. package/skills/c64-docs/scripts/lib/links.ts +1 -1
  9. package/skills/c64-docs/scripts/lib/markdown.ts +1 -1
  10. package/skills/c64-docs/scripts/lib/reference.ts +59 -13
  11. package/skills/c64-knowledge/SKILL.md +17 -8
  12. package/skills/c64-knowledge/scripts/knowledge.ts +200 -218
  13. package/skills/c64-knowledge/scripts/lib/check.ts +2 -3
  14. package/skills/c64-knowledge/scripts/lib/listing.ts +56 -24
  15. package/skills/c64-packer/scripts/packer.ts +3 -3
  16. package/skills/c64-provenance/SKILL.md +25 -16
  17. package/skills/c64-provenance/scripts/lib/compare.ts +31 -21
  18. package/skills/c64-provenance/scripts/lib/leftovers.ts +17 -35
  19. package/skills/c64-provenance/scripts/lib/library.ts +10 -10
  20. package/skills/c64-provenance/scripts/lib/runtime.ts +3 -14
  21. package/skills/c64-provenance/scripts/provenance.ts +129 -98
  22. package/skills/c64-source/references/loader.md +2 -1
  23. package/skills/c64-source/scripts/lib/export.ts +54 -303
  24. package/skills/c64-source/scripts/lib/loader.ts +31 -51
  25. package/skills/c64-source/scripts/lib/source.ts +51 -41
  26. package/skills/c64-source/scripts/lib/stage.ts +9 -25
  27. package/skills/c64-source/scripts/source.ts +134 -294
  28. package/skills/c64-static-analysis/SKILL.md +12 -7
  29. package/skills/c64-static-analysis/scripts/lib/coverage.ts +1 -3
  30. package/skills/c64-static-analysis/scripts/lib/findings.ts +16 -3
  31. package/skills/c64-static-analysis/scripts/lib/idioms.ts +82 -10
  32. package/skills/c64-static-analysis/scripts/lib/triage.ts +112 -0
  33. package/skills/c64-static-analysis/scripts/static-analysis.ts +239 -147
  34. package/skills/c64-testing/SKILL.md +13 -7
  35. package/skills/c64-testing/scripts/lib/diff-files.ts +6 -13
  36. package/skills/c64-testing/scripts/lib/recording.ts +47 -66
  37. package/skills/c64-testing/scripts/lib/replay.ts +53 -9
  38. package/skills/c64-testing/scripts/lib/runs.ts +11 -29
  39. package/skills/c64-testing/scripts/lib/scenario.ts +30 -31
  40. package/skills/c64-testing/scripts/lib/start-screen.ts +42 -5
  41. package/skills/c64-testing/scripts/testing.ts +32 -7
  42. package/skills/c64-unpacker/SKILL.md +10 -7
  43. package/skills/c64-unpacker/scripts/lib/evidence.ts +23 -38
  44. package/skills/c64-unpacker/scripts/lib/loads.ts +24 -39
  45. package/skills/c64-unpacker/scripts/lib/machine.ts +38 -18
  46. package/skills/c64-unpacker/scripts/lib/stages.ts +142 -41
  47. package/skills/c64-unpacker/scripts/unpacker.ts +85 -68
  48. package/skills/emulator/SKILL.md +1 -0
  49. package/src/c64.ts +117 -10
  50. package/src/cli/ap-sdk.ts +1 -1
  51. package/src/cli/cleanup.ts +4 -2
  52. package/src/compare.ts +36 -16
  53. package/src/errors.ts +10 -1
  54. package/src/host/main.ts +2 -1
  55. package/src/host/server.ts +7 -11
  56. package/src/host/tools/c1541.ts +9 -3
  57. package/src/host/vice/adapter.ts +20 -43
  58. package/src/host/vice/binary-monitor.ts +22 -21
  59. package/src/host/vice/process.ts +31 -40
  60. package/src/host/vice/session.ts +187 -247
  61. package/src/host/vice/text-monitor.ts +3 -3
  62. package/src/host-client/autostart.ts +1 -1
  63. package/src/host-client/connect.ts +2 -1
  64. package/src/host-client/coverage.ts +0 -3
  65. package/src/host-client/entry-state.ts +4 -11
  66. package/src/host-client/image.ts +6 -11
  67. package/src/host-client/steps.ts +13 -113
  68. package/src/host-client/tools.ts +4 -4
  69. package/src/host-client/transfer.ts +10 -0
  70. package/src/host-client/vice-session.ts +10 -6
  71. package/src/knowledge/code-reach.ts +364 -0
  72. package/src/knowledge/conflicts.ts +34 -72
  73. package/src/knowledge/database.ts +40 -28
  74. package/src/knowledge/evidence.ts +2 -2
  75. package/src/knowledge/graph.ts +3 -3
  76. package/src/knowledge/history.ts +50 -90
  77. package/src/knowledge/import.ts +43 -71
  78. package/src/knowledge/join.ts +1 -1
  79. package/src/knowledge/names.ts +12 -7
  80. package/src/knowledge/program.ts +25 -46
  81. package/src/knowledge/read.ts +104 -100
  82. package/src/knowledge/schema.ts +9 -3
  83. package/src/knowledge/separate.ts +47 -19
  84. package/src/knowledge/start-screen.ts +7 -5
  85. package/src/knowledge/text.ts +56 -33
  86. package/src/knowledge/write.ts +274 -515
  87. package/src/loader.ts +7 -25
  88. package/src/mcp/inputs.ts +3 -3
  89. package/src/mcp/server.ts +19 -38
  90. package/src/mcp/session-source.ts +2 -1
  91. package/src/mcp/tools/debug.ts +97 -24
  92. package/src/mcp/tools/execution.ts +1 -1
  93. package/src/mcp/tools/input.ts +3 -3
  94. package/src/mcp/tools/machine.ts +3 -3
  95. package/src/mcp/tools/media.ts +4 -4
  96. package/src/mcp/tools/memory.ts +13 -17
  97. package/src/mcp/tools/video.ts +11 -25
  98. package/src/native/acme.ts +3 -3
  99. package/src/native/c64run.ts +2 -1
  100. package/src/native/decompiler/analyze.ts +10 -7
  101. package/src/native/decompiler/walk.ts +3 -4
  102. package/src/native/decompiler/wasm.ts +2 -2
  103. package/src/native/discover.ts +1 -1
  104. package/src/native/dxa.ts +9 -11
  105. package/src/native/exomizer.ts +1 -1
  106. package/src/native/processes.ts +4 -1
  107. package/src/native/run.ts +3 -3
  108. package/src/native/types.ts +5 -6
  109. package/src/opcodes.ts +3 -0
  110. package/src/platform.ts +9 -10
  111. package/src/program-code.ts +151 -0
  112. package/src/project.ts +8 -5
  113. package/src/protocol/framing.ts +51 -18
  114. package/src/protocol/messages.ts +1 -11
  115. package/src/protocol/tools.ts +0 -3
  116. package/src/protocol/vice.ts +588 -773
  117. package/src/script.ts +9 -14
  118. package/src/time.ts +1 -1
  119. package/src/trace.ts +3 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henols/c64-re-tools",
3
- "version": "2.8.0-rc.2",
3
+ "version": "2.8.0-rc.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",
@@ -53,7 +53,8 @@ To get the command list, run the script with no arguments.
53
53
 
54
54
  A source that you generated from the project knowledge has switches in `config.asm`.
55
55
 
56
- - Without `--release`, the build uses the values in `config.asm`. With the default values, the program is the clean program: no copy protection, no trainers, no cheats, no crack changes, and all corrections. This program can be different from the base release. Thus `--compare` can give `FAIL`.
56
+ - Without `--release`, the build uses the values in `config.asm`. With the default values, the program is the clean program: no copy protection, no trainers, no cheats, no crack changes, no leftovers, and all corrections. This program can be different from the base release. Thus `--compare` can give `FAIL`.
57
+ - The default build leaves out the leftovers, because `LEFTOVERS` is 0. A leftover is a range that nothing uses, in a file in `leftovers/`. To build the leftovers, give `--switch LEFTOVERS=1`.
57
58
  - To build other switch values, give `--switch` for each switch, for example `--switch TRAINER=1`. `config.asm` does not change. Do not use `--define` for a switch.
58
59
  - With `--switch` and the entry `main.asm`, a source with `loader.asm` also gives its loader program with these switch values. See "Build".
59
60
  - With `--release <label>`, each switch has the value of that release. A release build does not read `config.asm`.
@@ -132,8 +133,9 @@ Assembles the source and writes the program to `--out`, or to `build/<name>.prg`
132
133
  - `diagnostics`: each item has `severity` (`error`, `warning` or `note`), `file`, `line` and `message`. `file` is relative to the source root. A file in an include folder outside the source root starts with `../`. `file` and `line` are not in an item without a location in the source.
133
134
  - `compare`: only with `--compare`. `identical` is `true` when each segment is identical. `segments` has one item for each segment of the reference program, with `start`, `end` and `result`:
134
135
  - `identical`.
135
- - `different`, with `differences` and `firstDifference`. `firstDifference` gives `address`, and the byte of the build (`built`) and of the reference (`reference`), each as `$` and two hex digits.
136
+ - `different`, with `differences` and `firstDifference`. `firstDifference` gives `address`, and the byte of the build (`built`) and of the reference (`reference`), each as `$` and two hex digits. It is the first different byte outside the leftovers that the build leaves out. When all different bytes are in these leftovers, the segment has no `firstDifference`.
136
137
  - `not covered`, with `uncovered`: the build does not hold all bytes of the segment.
138
+ - A segment in `compare.segments` can also have `leftovers`. These are the leftovers that the build leaves out, where a byte is different or not in the build. Each item has `start`, `end`, `file` (the leftover file, relative to the source root) and `differences`. `differences` and `uncovered` of the segment also count these bytes.
137
139
  - `loader`: only with `--switch`, the entry `main.asm` and a `loader.asm` in the source root. It is the loader program of these switch values, with `out`, `bytes` and `sha256`. `symbolsFile` is its symbols file. `packed` gives `packedBytes` and `unpackedBytes` of the packed form. `verified` is always `false`, because no check of the loader program runs. When the script cannot make the loader program, `loader` holds only `written`, which is `false`, and `reason`.
138
140
 
139
141
  Do as the result tells:
@@ -141,6 +143,7 @@ Do as the result tells:
141
143
  - `result` is `PASS`: the program is at `out`. To run or debug the program, load the file at `out` into the emulator. A generated source with a loader is different: the build of `main.asm` does not set the entry state, and it can hold bytes for $d000-$dfff. Load the loader program in its place: `loader.program` of the generation of the source with the loader, or `loader.out` of a build with `--switch`. Test the loader program of `loader.out` before you trust it.
142
144
  - `result` is `FAIL` and `assembled` is `false`: the source has errors, and the script wrote no program. `hint` tells you to correct the source. Correct the source at the file and the line of each diagnostic. Then run `build` again.
143
145
  - `result` is `FAIL` and `assembled` is `true`: the program is not identical to the reference. The script wrote the program. Read the first difference of each segment in `compare.segments`. Without `--release`, read the section "Switches" first.
146
+ - A segment has `leftovers`: these bytes are different because the build leaves out the leftovers. They are not an error in the source. `hint` tells when all other bytes are identical. To build the leftovers, give `--switch LEFTOVERS=1`.
144
147
  - `hint` tells that `symbols` is cut: give a larger `--max-listed`, or read the symbols file for the full list.
145
148
  - `loader.written` is `false`: the script wrote the program of `main.asm`, but it cannot make the loader program of these switch values. Do as `loader.reason` tells.
146
149
  - Error `not-found` names the entry: give the main source file relative to the source root.
@@ -12,10 +12,10 @@
12
12
  import { posix } from "node:path";
13
13
 
14
14
  import { BUILD_DIRECTORY, type BuildKind, buildName, CONFIG_FILE, configValues, COPIER_LINE, symbolsPath, withConfigValues } from "#src/build-name.ts";
15
- import { type AddressRange, formatC64Address } from "#src/c64.ts";
15
+ import { type AddressRange, formatC64RangeFields } from "#src/c64.ts";
16
16
  import { isRefusal, Refusal } from "#src/errors.ts";
17
17
  import { readSourceTree, writeReported } from "#src/host-client/transfer.ts";
18
- import { openForRead } from "#src/knowledge/database.ts";
18
+ import { withRead } from "#src/knowledge/database.ts";
19
19
  import { knowledgeNames } from "#src/knowledge/names.ts";
20
20
  import { releaseImage, requireProgram } from "#src/knowledge/program.ts";
21
21
  import { currentStartScreen, listSwitches, releaseLabeled } from "#src/knowledge/read.ts";
@@ -26,7 +26,7 @@ import { EXOMIZER, findTool } from "#src/native/discover.ts";
26
26
  import { localToolContext } from "#src/native/local.ts";
27
27
  import type { AcmeParams, AssembledSymbol } from "#src/native/types.ts";
28
28
  import { listed as listedItems, OPTIONS, reply, runScript, UsageError } from "#src/script.ts";
29
- import { compareBuild, type Reference } from "#src/compare.ts";
29
+ import { compareBuild, type LeftOutLeftover, type Reference } from "#src/compare.ts";
30
30
 
31
31
  /** The loader of a generated source, which a build of main.asm with --switch also makes. */
32
32
  const LOADER_FILE = "loader.asm";
@@ -53,26 +53,6 @@ function parseSwitches(texts: readonly string[]): Map<string, 0 | 1> {
53
53
  return values;
54
54
  }
55
55
 
56
- /** The default of each switch of a generated source: the knowledge gives them, the start screen is in and the leftovers are out. */
57
- function switchDefaults(space: Space): Map<string, number> {
58
- const db = openForRead();
59
- try {
60
- return new Map([[START_SCREEN_SWITCH, 1], [LEFTOVERS_SWITCH, 0], ...listSwitches(db, undefined, space).map((row) => [row.name, row.default] as const)]);
61
- } finally {
62
- db?.close();
63
- }
64
- }
65
-
66
- /** What the packed form needs from the knowledge of the space: the loaded ranges. Refuses a start screen of a captured stage and a segment below $0400. */
67
- function packedLoaded(leftovers: readonly AddressRange[], space: Space): AddressRange[] {
68
- const db = openForRead();
69
- try {
70
- return packedRanges(requireProgram(db, space).segments, leftovers, currentStartScreen(db, space)?.stage);
71
- } finally {
72
- db?.close();
73
- }
74
- }
75
-
76
56
  /** The message of a refusal of `work`, or undefined when it did not refuse: a refusal of the loader program does not stop the build of main.asm. */
77
57
  function refusalOf(work: () => void): string | undefined {
78
58
  try {
@@ -84,6 +64,27 @@ function refusalOf(work: () => void): string | undefined {
84
64
  }
85
65
  }
86
66
 
67
+ /**
68
+ * What a generated source needs from the knowledge of the space, in one read:
69
+ * the default of each switch (the knowledge gives them, the start screen is in
70
+ * and the leftovers are out), and for the packed form, given the leftover
71
+ * ranges of the source, the loaded ranges or why the build gets no loader (a
72
+ * start screen of a captured stage, a segment below $0400).
73
+ */
74
+ function generatedKnowledge(space: Space, leftovers: readonly AddressRange[] | undefined) {
75
+ return withRead((db) => {
76
+ const defaults = new Map<string, number>([[START_SCREEN_SWITCH, 1], [LEFTOVERS_SWITCH, 0], ...listSwitches(db, undefined, space).map((row) => [row.name, row.default] as const)]);
77
+ let loaded: AddressRange[] | undefined;
78
+ const noLoader =
79
+ leftovers === undefined
80
+ ? undefined
81
+ : refusalOf(() => {
82
+ loaded = packedRanges(requireProgram(db, space).segments, leftovers, currentStartScreen(db, space)?.stage);
83
+ });
84
+ return { defaults, loaded, noLoader };
85
+ });
86
+ }
87
+
87
88
  await runScript({
88
89
  name: "assembler",
89
90
  summary: "Assembles project source with ACME and writes the program into the project.",
@@ -110,7 +111,7 @@ await runScript({
110
111
  "max-listed": { ...OPTIONS["max-listed"], help: "list at most n symbols (default 50). The count is always given" },
111
112
  },
112
113
  notes:
113
- "Symbol values are $ and at least four hex digits. Before --compare, put the program bytes into the project knowledge. Without --release, the build has the switch values of config.asm and of --switch. With the defaults, this is the clean program, which is not the bytes of a release when a switch has a default that the base release does not have. Give a switch with --switch, not with --define: ACME stops with Symbol already defined. The loader program of --switch is not checked: loader.verified is false.",
114
+ "Symbol values are $ and at least four hex digits. Before --compare, put the program bytes into the project knowledge. Without --release, the build has the switch values of config.asm and of --switch. With the defaults, this is the clean program, which is not the bytes of a release when a switch has a default that the base release does not have. The defaults leave out the leftovers (LEFTOVERS = 0): compare.segments gives each different leftover in leftovers. Give a switch with --switch, not with --define: ACME stops with Symbol already defined. The loader program of --switch is not checked: loader.verified is false.",
114
115
  run: async (call) => {
115
116
  const [sourceRoot, entry] = [call.subject(0), call.subject(1)];
116
117
  // Read the reference before ACME runs, so a project without it stops at once.
@@ -121,8 +122,7 @@ await runScript({
121
122
  if (switches.size > 0 && label !== undefined) throw new UsageError("--switch does not work with --release: a release build has the switch values of that release");
122
123
  let releaseDefine: Record<string, number> = {};
123
124
  if (call.flag("compare") || label !== undefined) {
124
- const db = openForRead();
125
- try {
125
+ withRead((db) => {
126
126
  if (label === undefined) program = requireProgram(db, call.space);
127
127
  else {
128
128
  const release = releaseLabeled(db, label, call.space);
@@ -130,9 +130,7 @@ await runScript({
130
130
  releaseDefine = { [`${RELEASE_DEFINE}${label}`]: 1 };
131
131
  if (call.flag("compare")) program = releaseImage(db, label, call.space);
132
132
  }
133
- } finally {
134
- db?.close();
135
- }
133
+ });
136
134
  }
137
135
  const setPc = call.address("set-pc");
138
136
  const { contents, ...tree } = readSourceTree(sourceRoot, call.strings("include"));
@@ -150,27 +148,30 @@ await runScript({
150
148
  contents[config] = changed;
151
149
  tree.files[config] = { ...tree.files[config]!, size: changed.length };
152
150
  }
151
+ // With --switch, main.asm of a generated source with a loader also gives the loader program of these values.
152
+ const loaderIndex = switches.size > 0 && entry === "main.asm" ? inSource(LOADER_FILE) : -1;
153
+ // The packed form: the loaded ranges are the segments of the program without the leftover files of the source.
154
+ const packedForm = loaderIndex >= 0 && textOf(loaderIndex).split(/\r?\n/).includes(COPIER_LINE);
155
+ // The leftover files of a generated source, each with its range from its first line. A build with LEFTOVERS = 0 skips them; a release has them.
156
+ const folder = posix.join(tree.sourceDir, LEFTOVER_FOLDER);
157
+ const leftovers: LeftOutLeftover[] = tree.files.flatMap((file, index) => {
158
+ const range = posix.dirname(file.path) === folder ? leftoverRange(textOf(index)) : undefined;
159
+ return range === undefined ? [] : [{ ...range, file: `${LEFTOVER_FOLDER}/${posix.basename(file.path)}` }];
160
+ });
161
+ // A source with --switch has config.asm and no --release, so the packed form always gets this read.
162
+ const generated = label === undefined && config >= 0 ? generatedKnowledge(call.space, packedForm ? leftovers : undefined) : undefined;
153
163
  // The name of the build tells what it is: the release, or the switch values.
154
- const kind: BuildKind | undefined = label !== undefined ? { release: label } : config < 0 ? undefined : { values: configValues(textOf(config)), defaults: switchDefaults(call.space) };
164
+ const kind: BuildKind | undefined = label !== undefined ? { release: label } : generated === undefined ? undefined : { values: configValues(textOf(config)), defaults: generated.defaults };
165
+ const leftOut = kind !== undefined && "values" in kind && kind.values.get(LEFTOVERS_SWITCH) === 0 ? leftovers : [];
155
166
  const plain = call.flag("plain");
156
167
  const out = call.string("out") ?? `${BUILD_DIRECTORY}/${buildName(entry, kind, textOf(inSource(entry)))}.${plain ? "bin" : "prg"}`;
157
168
  const params: AcmeParams = { ...tree, entrySource: entry, defines: { ...releaseDefine, ...Object.fromEntries(call.strings("define").map(parseDefine)) }, ...(setPc === undefined ? {} : { setPc }) };
158
169
 
159
- // With --switch, main.asm of a generated source with a loader also gives the loader program of these values.
160
- const loaderIndex = switches.size > 0 && entry === "main.asm" ? inSource(LOADER_FILE) : -1;
161
- let loaded: AddressRange[] | undefined;
170
+ const loaded = generated?.loaded;
162
171
  // Why the build writes no loader program.
163
- let noLoader: string | undefined;
164
- if (loaderIndex >= 0 && textOf(loaderIndex).split(/\r?\n/).includes(COPIER_LINE)) {
165
- // The packed form: the loaded ranges are the segments of the program without the leftover files of the source.
166
- const folder = posix.join(tree.sourceDir, LEFTOVER_FOLDER);
167
- const leftovers = tree.files.flatMap((file, index) => (posix.dirname(file.path) === folder ? (leftoverRange(textOf(index)) ?? []) : []));
168
- noLoader = refusalOf(() => {
169
- loaded = packedLoaded(leftovers, call.space);
170
- });
171
- // The toolkit never installs a tool: without Exomizer the build refuses by name before ACME runs.
172
- if (noLoader === undefined) findTool(EXOMIZER);
173
- }
172
+ let noLoader = generated?.noLoader;
173
+ // The toolkit never installs a tool: without Exomizer the build refuses by name before ACME runs.
174
+ if (packedForm && noLoader === undefined) findTool(EXOMIZER);
174
175
 
175
176
  const { result, attachments } = await assemble(params, contents, localToolContext());
176
177
  if (!result.assembled) return reply({ result: "FAIL", assembled: false, diagnostics: result.diagnostics }, { hint: "The source has errors, and no program was written. Correct the source at the file and the line of each diagnostic. Then run build again." });
@@ -206,14 +207,20 @@ await runScript({
206
207
 
207
208
  const written = writeReported(out, plain ? built.subarray(2) : built, { what: "--out" });
208
209
  const range = result.loadRange!;
209
- const compared = program === undefined ? undefined : compareBuild(built, program);
210
+ const compared = program === undefined ? undefined : compareBuild(built, program, leftOut);
210
211
  const symbols = listedItems(shown, call.count("max-listed")!, showSymbol, `a larger --max-listed, or read ${symbolsPath(out)}`);
211
212
  // A build that differs from its reference is a failed check.
212
213
  const different = compared !== undefined && !compared.identical;
214
+ // The bytes that differ in the leftovers that the build leaves out, and the other bytes that differ or that the build does not hold.
215
+ const inLeftovers = (compared?.segments ?? []).flatMap((segment) => segment.leftovers ?? []).reduce((sum, leftover) => sum + leftover.differences, 0);
216
+ const others = (compared?.segments ?? []).reduce((sum, segment) => sum + (segment.differences ?? 0) + (segment.uncovered ?? 0), 0) - inLeftovers;
217
+ const leftoverHint = `${inLeftovers} different ${inLeftovers === 1 ? "byte is" : "bytes are"} in leftovers that this build leaves out, because ${LEFTOVERS_SWITCH} is 0. compare.segments gives these leftovers in leftovers, each with its file. To build the leftovers, give --switch ${LEFTOVERS_SWITCH}=1.`;
213
218
  const loaderPath = `${BUILD_DIRECTORY}/${buildName(LOADER_FILE, kind)}.prg`;
214
219
  const hints = [
215
- ...(different ? ["The program is not identical to the reference program. Read compare.segments: each segment that is different gives its first difference."] : []),
216
- ...(different && label === undefined ? ["Without --release, a source with switches builds with the values of config.asm and --switch, and that program can differ from the base release. To check a release, give --release <label> with --compare."] : []),
220
+ ...(different && others > 0 ? [`The program is not identical to the reference program. Read compare.segments: each segment that is different gives its first difference${inLeftovers > 0 ? " outside the leftovers that this build leaves out" : ""}.`] : []),
221
+ ...(different && others === 0 ? ["The program is different from the reference program only in the leftovers that this build leaves out. All other bytes are identical."] : []),
222
+ ...(different && inLeftovers > 0 ? [leftoverHint] : []),
223
+ ...(different && others > 0 && label === undefined ? ["Without --release, a source with switches builds with the values of config.asm and --switch, and that program can differ from the base release. To check a release, give --release <label> with --compare."] : []),
217
224
  ...(symbols.rest === undefined ? [] : [`symbols is cut. To get all symbols, give ${symbols.rest}.`]),
218
225
  ...(loader === undefined ? [] : ["loader.out is the loader program of these switch values. No check of the loader program ran, so loader.verified is false."]),
219
226
  ...(noLoader === undefined ? [] : ["The build wrote the program of main.asm, but no loader program of these switch values: loader.reason tells why."]),
@@ -223,7 +230,7 @@ await runScript({
223
230
  assembled: true,
224
231
  ...written,
225
232
  ...(plain ? { plain: true } : {}),
226
- loadRange: { start: formatC64Address(range.start), end: formatC64Address(range.end), bytes: range.bytes },
233
+ loadRange: { ...formatC64RangeFields(range), bytes: range.bytes },
227
234
  symbols,
228
235
  // The symbols of the program for a test run, in symbols/ next to it.
229
236
  symbolsFile: writeReported(symbolsPath(out), symbolsFileText(shown), { what: "--out" }),
@@ -2,7 +2,7 @@
2
2
  // Host Runtime and extracts files into the project. T64 tape files and CRT
3
3
  // cartridge files are read locally: no host tool reads them.
4
4
 
5
- import { formatC64Address } from "#src/c64.ts";
5
+ import { formatC64Address, hexWord, prgOf } from "#src/c64.ts";
6
6
  import { isRefusal, Refusal } from "#src/errors.ts";
7
7
  import { DISK_BLOCK_BYTES, DISK_IMAGE_TYPES, inspectDisk, MAX_DISK_SECTORS } from "#src/host-client/tools.ts";
8
8
  import { readProjectFile, writeReported } from "#src/host-client/transfer.ts";
@@ -68,7 +68,7 @@ function tapeDirectory(image: string) {
68
68
  /** A CRT cartridge file: its header and CHIP packets, each with the PRG file name that crt writes. */
69
69
  function cartridge(image: string) {
70
70
  const crt = about(image, () => parseCrt(readProjectFile(image).bytes));
71
- const chips = crt.chips.map((chip) => ({ bank: chip.bank, address: formatC64Address(chip.address), size: chip.size, space: `bank${chip.bank}`, file: `bank${chip.bank}-${chip.address.toString(16).padStart(4, "0")}.prg` }));
71
+ const chips = crt.chips.map((chip) => ({ bank: chip.bank, address: formatC64Address(chip.address), size: chip.size, space: `bank${chip.bank}`, file: `bank${chip.bank}-${hexWord(chip.address)}.prg` }));
72
72
  return { crt, header: { name: crt.name, type: crt.type, typeName: crt.typeName, exrom: crt.exrom, game: crt.game, ...(crt.mode === undefined ? {} : { mode: crt.mode }) }, chips };
73
73
  }
74
74
 
@@ -196,7 +196,7 @@ await runScript({
196
196
  kindFor("crt", image, ["crt"]);
197
197
  const out = call.string("out")!;
198
198
  const { crt, header, chips } = cartridge(image);
199
- const files = crt.chips.map((chip, index) => writeReported(`${out}/${chips[index]!.file}`, Buffer.concat([Buffer.from([chip.address & 0xff, chip.address >> 8]), chip.data]), { what: "--out" }));
199
+ const files = crt.chips.map((chip, index) => writeReported(`${out}/${chips[index]!.file}`, prgOf(chip.address, chip.data), { what: "--out" }));
200
200
  files.push(writeReported(`${out}/crt.json`, `${JSON.stringify({ ...header, chips }, null, 2)}\n`, { what: "--out" }));
201
201
  return reply({ ...header, chips, files }, { hint: "All banks use the same addresses. Analyze each bank PRG in its own knowledge space: the field space of its chip gives the space." });
202
202
  },
@@ -3,7 +3,7 @@
3
3
  // load address; a T64 file holds a directory of PRG files. TAP files hold
4
4
  // raw pulses and go through the emulator only.
5
5
 
6
- import { formatC64Address, petsciiNameToText } from "#src/c64.ts";
6
+ import { formatC64Address, petsciiNameToText, prgOf } from "#src/c64.ts";
7
7
  import { Refusal } from "#src/errors.ts";
8
8
  import { hasSignature } from "#src/media.ts";
9
9
 
@@ -118,5 +118,5 @@ export function parseT64(bytes: Uint8Array): Tape {
118
118
 
119
119
  /** The PRG of a tape entry: its start address, then its bytes. */
120
120
  export function tapeFile(bytes: Uint8Array, entry: TapeEntry): Buffer {
121
- return Buffer.concat([Buffer.from([entry.start & 0xff, entry.start >> 8]), Buffer.from(bytes.subarray(entry.offset, entry.offset + entry.bytes))]);
121
+ return prgOf(entry.start, bytes.subarray(entry.offset, entry.offset + entry.bytes));
122
122
  }
@@ -67,7 +67,7 @@ Get the values for the commands from these places:
67
67
 
68
68
  A group folder holds one project for each version of a program. It also holds the pages that the versions share.
69
69
 
70
- - A group folder is a folder in a git repository. It holds one or more project folders. It is not a project, and it is not in a project.
70
+ - A group folder is a folder in a git repository. It holds two or more project folders. It is not a project, and it is not in a project.
71
71
  - Each project folder in the group folder is a project of the group. The label of the project is the name of its folder, for example `v1`. A project folder that holds `.git` is not a project of the group.
72
72
  - The shared pages are `README.md` and `docs/` of the group folder.
73
73
  - A page in the group folder can link to each file in the group folder. A link out of the group folder is a problem.
@@ -9,17 +9,17 @@ import { existsSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs
9
9
  import { basename, join, posix } from "node:path";
10
10
  import type { DatabaseSync } from "node:sqlite";
11
11
 
12
- import { formatC64Address } from "#src/c64.ts";
12
+ import { formatC64Address, formatC64RangeFields, inRanges } from "#src/c64.ts";
13
13
  import { Refusal } from "#src/errors.ts";
14
14
  import { WireFailure } from "#src/host-client/tools.ts";
15
15
  import { writeProjectFile, writeReported } from "#src/host-client/transfer.ts";
16
16
  import { conflicts } from "#src/knowledge/conflicts.ts";
17
- import { openForRead, TEXT_DIRECTORY } from "#src/knowledge/database.ts";
17
+ import { openForRead, withRead } from "#src/knowledge/database.ts";
18
18
  import { changedEvidence, type EvidenceChange } from "#src/knowledge/evidence.ts";
19
- import { programImage, type ProgramImage } from "#src/knowledge/program.ts";
19
+ import { programImage } from "#src/knowledge/program.ts";
20
20
  import { listComments, listModules, listReferences, listRegions, listSymbols, sourceRevision } from "#src/knowledge/read.ts";
21
21
  import { compareText } from "#src/knowledge/text.ts";
22
- import { groupOf, namedGroup, PROJECT_DIRECTORY, projectRoot, resolveProjectFile, resolveProjectPath, type ProjectGroup } from "#src/project.ts";
22
+ import { groupOf, KNOWLEDGE_TEXT_DIRECTORY as TEXT_DIRECTORY, namedGroup, PROJECT_DIRECTORY, projectRoot, resolveProjectFile, resolveProjectPath, type ProjectGroup } from "#src/project.ts";
23
23
  import { GENERATED_MARK, referenceStamp } from "#src/reference-pages.ts";
24
24
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type Reply } from "#src/script.ts";
25
25
  import { checkLinks, linkPage, type Files, type LinkContext, type Names, type Problem } from "./lib/links.ts";
@@ -62,11 +62,8 @@ function generate(call: Call): Reply {
62
62
  }
63
63
  }
64
64
  const map = readSourceMap(source);
65
- const db = openForRead();
66
- let knowledge;
67
- let image: ProgramImage | undefined;
68
- try {
69
- image = programImage(db, map.space);
65
+ const { image, knowledge } = withRead((db) => {
66
+ const image = programImage(db, map.space);
70
67
  const found = conflicts(db).length;
71
68
  if (found > 0) throw new Refusal("conflict", `The knowledge has ${found} conflict${found === 1 ? "" : "s"} from a git merge. Nothing was written. Resolve the merge conflicts of the project knowledge. Then generate the source again from the knowledge, and run generate again.`);
72
69
  // A source of another revision has other lines: the links would point to the wrong code. A change in another space does not change the source.
@@ -74,7 +71,7 @@ function generate(call: Call): Reply {
74
71
  if (map.revision !== revision) {
75
72
  throw new WireFailure("invalid-input", `${map.mapPath} is from knowledge revision ${map.revision}, and the knowledge of the source is at revision ${revision}. Nothing was written. Generate the source again from the knowledge. Then run generate again.`);
76
73
  }
77
- knowledge = {
74
+ const knowledge = {
78
75
  revision,
79
76
  symbols: listSymbols(db, undefined, undefined, undefined, map.space),
80
77
  regions: listRegions(db, undefined, undefined, undefined, map.space),
@@ -82,15 +79,14 @@ function generate(call: Call): Reply {
82
79
  references: listReferences(db, undefined, undefined, undefined, map.space),
83
80
  modules: listModules(db, undefined, undefined, map.space),
84
81
  };
85
- } finally {
86
- db?.close();
87
- }
82
+ return { image, knowledge };
83
+ });
88
84
  const old = oldFiles(out, directory);
89
85
  const built = buildReference({
90
86
  out: posix.normalize(out),
91
87
  map,
92
88
  ...knowledge,
93
- ...(image === undefined ? {} : { image: { byteAt: image.byteAt, inImage: (address: number) => image.segments.some((segment) => address >= segment.start && address <= segment.end) } }),
89
+ ...(image === undefined ? {} : { image: { byteAt: image.byteAt, inImage: (address: number) => inRanges(image.segments, address) } }),
94
90
  });
95
91
  for (const path of old) rmSync(join(directory, path), { force: true });
96
92
  const written = built.files.map((file) => writeReported(file.path, file.bytes, { what: "--out" }));
@@ -100,7 +96,7 @@ function generate(call: Call): Reply {
100
96
  const gaps = {
101
97
  routinesWithoutComment: listed(built.gaps.routinesWithoutComment, max, (routine) => ({ name: routine.name, address: formatC64Address(routine.address), file: routine.file })),
102
98
  modulesWithoutRoutines: listed(built.gaps.modulesWithoutRoutines, max, (module) => ({ file: module.file, start: formatC64Address(module.start), ...(module.title === undefined ? {} : { title: module.title }) })),
103
- tablesWithoutName: listed(built.gaps.tablesWithoutName, max, (table) => ({ start: formatC64Address(table.start), end: formatC64Address(table.end), type: table.type })),
99
+ tablesWithoutName: listed(built.gaps.tablesWithoutName, max, (table) => ({ ...formatC64RangeFields(table), type: table.type })),
104
100
  };
105
101
  const hints: string[] = [];
106
102
  if (image === undefined) hints.push("The knowledge has no program bytes. Thus the reference does not decode the tables and does not show the graphics. To get them, put the program bytes into the project knowledge and run generate again.");
@@ -280,15 +276,11 @@ function link(call: Call): Reply {
280
276
  /** The evidence of a project that no page names. */
281
277
  const readEvidence = (member: Member) => {
282
278
  if (evidenceRead.has(member) || unreadableKnowledge.has(member)) return;
283
- let db: DatabaseSync | undefined;
284
279
  try {
285
- db = openForRead(member.root);
286
- addEvidence(member, db);
280
+ withRead((db) => addEvidence(member, db), member.root);
287
281
  } catch (error) {
288
282
  if (!(error instanceof Refusal)) throw error;
289
283
  markUnreadable(member, error);
290
- } finally {
291
- db?.close();
292
284
  }
293
285
  };
294
286
 
@@ -71,7 +71,7 @@ const relative = (page: string, target: string) => {
71
71
  return fragment === undefined ? shown : `${shown}#${fragment}`;
72
72
  };
73
73
  /** The project path of a link target, without its fragment; undefined for a link out of the project (a URL, or a page anchor only). */
74
- export function targetPath(page: string, target: string): string | undefined {
74
+ function targetPath(page: string, target: string): string | undefined {
75
75
  if (/^[a-z][a-z0-9+.-]*:/i.test(target) || target.startsWith("#")) return undefined;
76
76
  const raw = target.split("#")[0]!;
77
77
  let path = raw;
@@ -30,7 +30,7 @@ export function proseLines(text: string): Array<{ text: string; prose: boolean }
30
30
  }
31
31
 
32
32
  /** The id that GitHub and VS Code give a heading: lower case, without punctuation, spaces as hyphens. */
33
- export function headingSlug(heading: string): string {
33
+ function headingSlug(heading: string): string {
34
34
  const text = heading
35
35
  .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1")
36
36
  .replace(/<[^>]+>/g, "")
@@ -5,7 +5,7 @@
5
5
 
6
6
  import { posix } from "node:path";
7
7
 
8
- import { formatC64Address, POINTER_TABLE_TYPES, pointerTableEntries, type PointerTableType } from "#src/c64.ts";
8
+ import { formatC64Address, hexWord, POINTER_TABLE_TYPES, pointerTableEntries, type PointerTableType } from "#src/c64.ts";
9
9
  import { IO_RAM } from "#src/host-client/coverage.ts";
10
10
  import { bitmapFrame, charsetFrame, encodePng, PATTERN_PALETTES, scaleFrame, screenText, spriteSheet, type GraphicsMode } from "#src/graphics.ts";
11
11
  import { mermaidGraph, ownerOf, routineEdges, routineHeads, type GraphReference, type RoutineHead } from "#src/knowledge/graph.ts";
@@ -65,6 +65,23 @@ const hex = (address: number) => formatC64Address(address).toUpperCase();
65
65
  const range = (start: number, end: number) => (start === end ? hex(start) : `${hex(start)}-${hex(end)}`);
66
66
  const stem = (file: string) => file.replace(/\.asm$/, "");
67
67
 
68
+ /** The references with a target in [start, end], in their order in `references`: a binary search in the references sorted by target. */
69
+ function byTarget(references: readonly ReferenceRow[]): (start: number, end: number) => ReferenceRow[] {
70
+ const sorted = references.map((reference, index) => ({ reference, index })).sort((a, b) => a.reference.to - b.reference.to);
71
+ return (start, end) => {
72
+ let low = 0;
73
+ let high = sorted.length;
74
+ while (low < high) {
75
+ const middle = (low + high) >> 1;
76
+ if (sorted[middle]!.reference.to < start) low = middle + 1;
77
+ else high = middle;
78
+ }
79
+ const hits: Array<{ reference: ReferenceRow; index: number }> = [];
80
+ for (let at = low; at < sorted.length && sorted[at]!.reference.to <= end; at++) hits.push(sorted[at]!);
81
+ return hits.sort((a, b) => a.index - b.index).map((hit) => hit.reference);
82
+ };
83
+ }
84
+
68
85
  interface Entry {
69
86
  name: string;
70
87
  address: number;
@@ -115,7 +132,16 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
115
132
  for (const label of map.labels) if (!sourceNameAt.has(label.address)) sourceNameAt.set(label.address, label.name);
116
133
 
117
134
  // --- Links ------------------------------------------------------------------
118
- const rel = (page: string, target: string) => posix.relative(posix.dirname(page), target) || posix.basename(target);
135
+ const relCache = new Map<string, string>();
136
+ const rel = (page: string, target: string) => {
137
+ const key = `${page}\n${target}`;
138
+ let found = relCache.get(key);
139
+ if (found === undefined) {
140
+ found = posix.relative(posix.dirname(page), target) || posix.basename(target);
141
+ relCache.set(key, found);
142
+ }
143
+ return found;
144
+ };
119
145
  const codeOfName = (page: string, name: string) => {
120
146
  const label = map.labelOf(name);
121
147
  return label === undefined ? `\`${name}\`` : `[\`${name}\`](${rel(page, map.pathOf(label.file))}#L${label.line})`;
@@ -163,6 +189,8 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
163
189
  */
164
190
  const named = new Set(input.symbols.map((symbol) => symbol.address));
165
191
  const dataReferences = input.references.filter((reference) => !(reference.to >= IO_RAM.start && reference.to <= IO_RAM.end && input.image?.inImage(reference.to) === true && !named.has(reference.to)));
192
+ const dataReferencesTo = byTarget(dataReferences);
193
+ const referencesTo = byTarget(input.references);
166
194
  /**
167
195
  * How the source line of a reference uses a platform name, as the source writes it: "named", "indexed"
168
196
  * (name,x or name,y: the index can reach the registers after it), or undefined when the line does not
@@ -181,8 +209,8 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
181
209
  const use = platform === undefined ? undefined : new RegExp(`(?<![\\w.])${platform}(?!\\w)([^,)]*,\\s*[xXyY]\\b)?`);
182
210
  // A routine with an indexed use and a direct use shows once, as indexed.
183
211
  const owners = new Map<string, boolean>();
184
- for (const reference of dataReferences) {
185
- if (reference.kind !== kind || reference.to < start || reference.to > end) continue;
212
+ for (const reference of dataReferencesTo(start, end)) {
213
+ if (reference.kind !== kind) continue;
186
214
  const how = use === undefined ? "named" : platformUse(reference, use);
187
215
  if (how === undefined) continue;
188
216
  const name = ownerAt(reference.from)?.name ?? hex(reference.from);
@@ -224,13 +252,17 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
224
252
  symbolKinds.get(address) === "routine" || symbolKinds.get(address) === "label" || input.regions.some((region) => (region.type === "code" || region.type === "jumps") && region.start <= address && region.end >= address);
225
253
  const dispatches: GraphReference[] = [];
226
254
  for (const [table, rows] of tableEntries) {
227
- const readers = input.references.filter((reference) => TABLE_READS.includes(reference.kind) && reference.to >= table.start && reference.to <= table.end).map((reference) => reference.from);
255
+ const readers = referencesTo(table.start, table.end).filter((reference) => TABLE_READS.includes(reference.kind)).map((reference) => reference.from);
228
256
  for (const row of rows) if (row.target !== undefined && table.type !== "words" && inCode(row.target)) for (const from of new Set(readers)) dispatches.push({ from, to: row.target, kind: "table" });
229
257
  }
230
258
  const graphReferences: GraphReference[] = [...input.references, ...dispatches];
231
259
  const heads = routineHeads(input.symbols, graphReferences, (address) => sourceNameAt.get(address) ?? hex(address));
232
260
  const boundaries = input.modules.map((module) => module.start);
233
- const ownerAt = (address: number) => ownerOf(heads, boundaries, address);
261
+ const ownerCache = new Map<number, RoutineHead | undefined>();
262
+ const ownerAt = (address: number) => {
263
+ if (!ownerCache.has(address)) ownerCache.set(address, ownerOf(heads, boundaries, address));
264
+ return ownerCache.get(address);
265
+ };
234
266
  const site = (page: string, from: number) => {
235
267
  const owner = ownerAt(from);
236
268
  const named = owner === undefined ? undefined : entries.has(owner.name) ? entryOfName(page, owner.name, owner.name) : codeOfName(page, owner.name);
@@ -260,13 +292,27 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
260
292
  const write = (path: string, lines: string[]) => files.push({ path, bytes: Buffer.from(`${[header, ...lines].join("\n").replace(/\n{3,}/g, "\n\n")}\n`, "utf8") });
261
293
 
262
294
  // --- One entry --------------------------------------------------------------
295
+ const commentsAt = new Map<number, CommentRow[]>();
296
+ for (const comment of input.comments) {
297
+ const list = commentsAt.get(comment.address);
298
+ if (list === undefined) commentsAt.set(comment.address, [comment]);
299
+ else list.push(comment);
300
+ }
263
301
  const commentLines = (address: number) =>
264
- input.comments
265
- .filter((comment) => comment.address === address)
302
+ [...(commentsAt.get(address) ?? [])]
266
303
  .sort((a, b) => (a.placement === b.placement ? 0 : a.placement === "line" ? -1 : 1))
267
304
  .map((comment) => comment.text.replace(/\s*\r?\n\s*/g, " ").trim());
268
- const incoming = (entry: Entry) => dataReferences.filter((reference) => reference.to >= entry.address && reference.to <= entry.spanEnd);
269
- const outgoing = (head: RoutineHead) => input.references.filter((reference) => ownerAt(reference.from)?.address === head.address);
305
+ const incoming = (entry: Entry) => dataReferencesTo(entry.address, entry.spanEnd);
306
+ /** The references from the code of each routine, in their order in the knowledge. */
307
+ const fromHead = new Map<number, ReferenceRow[]>();
308
+ for (const reference of input.references) {
309
+ const owner = ownerAt(reference.from)?.address;
310
+ if (owner === undefined) continue;
311
+ const list = fromHead.get(owner);
312
+ if (list === undefined) fromHead.set(owner, [reference]);
313
+ else list.push(reference);
314
+ }
315
+ const outgoing = (head: RoutineHead) => fromHead.get(head.address) ?? [];
270
316
  const entryText = (page: string, entry: Entry, labels: readonly Entry[]): string[] => {
271
317
  const lines = ["", `<a id="${entry.name}"></a>`, `### ${codeOfName(page, entry.name)} \`${entry.spanEnd > entry.address ? range(entry.address, entry.spanEnd) : hex(entry.address)}\``, "", `*${entry.kind}*`];
272
318
  const comments = commentLines(entry.address);
@@ -317,7 +363,7 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
317
363
  for (const reference of input.references) if (reference.kind === "call" || reference.kind === "jump") entersAt.set(reference.to, [...(entersAt.get(reference.to) ?? []), reference]);
318
364
  // A pointer to code (lda #<irq_handler) is a vector: the CPU enters there from no file.
319
365
  const pointedAt = new Set(input.references.filter((reference) => reference.kind === "pointer").map((reference) => reference.to));
320
- const tableAnchor = (table: RegionRow) => entryAt.get(table.start)?.name ?? `table_${table.start.toString(16).padStart(4, "0")}`;
366
+ const tableAnchor = (table: RegionRow) => entryAt.get(table.start)?.name ?? `table_${hexWord(table.start)}`;
321
367
  function tableLink(page: string, table: RegionRow): string {
322
368
  return `[\`${entryAt.get(table.start)?.name ?? range(table.start, table.end)}\`](${rel(page, posix.join(out, "tables.md"))}#${tableAnchor(table)})`;
323
369
  }
@@ -404,7 +450,7 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
404
450
  lines.push("", `<a id="${tableAnchor(table)}"></a>`, `## ${name === undefined ? `\`${range(table.start, table.end)}\`` : `${codeOfName(page, name.name)} \`${range(table.start, table.end)}\``}`, "", `*${table.type}*`);
405
451
  const comments = commentLines(table.start);
406
452
  if (comments.length > 0) lines.push("", ...comments);
407
- const readers = [...new Set(input.references.filter((reference) => reference.to >= table.start && reference.to <= table.end && TABLE_READS.includes(reference.kind)).map((reference) => site(page, reference.from)))];
453
+ const readers = [...new Set(referencesTo(table.start, table.end).filter((reference) => TABLE_READS.includes(reference.kind)).map((reference) => site(page, reference.from)))];
408
454
  if (readers.length > 0) lines.push("", `- **Read by:** ${capped(readers)}`);
409
455
  const rows = tableEntries.get(table);
410
456
  if (rows === undefined) continue;
@@ -430,7 +476,7 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
430
476
  ];
431
477
  if (input.image === undefined && graphics.length > 0) lines.push("", "Put the program bytes into the project knowledge. Then generate the reference again to show the graphics.");
432
478
  for (const region of graphics) {
433
- const anchor = entryAt.get(region.start)?.name ?? `${region.type}_${region.start.toString(16).padStart(4, "0")}`;
479
+ const anchor = entryAt.get(region.start)?.name ?? `${region.type}_${hexWord(region.start)}`;
434
480
  const name = entryAt.get(region.start);
435
481
  lines.push("", `<a id="${anchor}"></a>`, `## ${name === undefined ? codeOfAddress(page, region.start) : pair(page, name.name, region.start)} \`${range(region.start, region.end)}\``, "", `*${region.type}*`);
436
482
  const comments = commentLines(region.start);
@@ -121,7 +121,7 @@ Each flag applies only to the commands in the table. On another command, the scr
121
121
  | `--seed <n>` | `sample` | A whole number from 0 to 999999 that selects the sample. Without it, the script selects one. |
122
122
  | `--placement <line\|side>` | `verdict` | The placement of the comment. Give it when the sample has a line and a side comment at the address. |
123
123
  | `--class <class>` | `verdict` | With `wrong`: the class of the error: `callers`, `bits`, `registers`, `bounds`, `units`, `paths`, `tables`, `hardware`, `place` or `scope`. |
124
- | `--why <text>` | `verdict` | With `wrong`: the evidence, with the addresses and the instructions. With `unsure`: the run that can show the claim. |
124
+ | `--why <text>` | `verdict` | With `wrong`: the evidence, with the addresses and the instructions. With `unsure`: the run that can show the claim. With `correct`: the evidence. It is optional. |
125
125
  | `--text <text>` | `verdict` | With `wrong`: the correct comment. |
126
126
  | `--name <name>` | `verdict` | With `wrong`: the correct name at the address. |
127
127
  | `--max-listed <n>` | `search`, `symbols`, `regions`, `comments`, `references`, `suppressions`, `modules`, `operands`, `patches`, `switches`, `releases`, `macros`, `uses`, `spaces`, `history`, `revisions`, `revision`, `listing`, `join`, `checks` | The most items in each list of the body. The default is 50. The counts are always complete. |
@@ -140,7 +140,7 @@ Each flag applies only to the commands in the table. On another command, the scr
140
140
  | `--out <file>` | `export` | Necessary. The JSON file to write. |
141
141
  | `--apply` | `join` | Write the joined writes to the project knowledge as one revision. Without it, `join` writes nothing. |
142
142
  | `--code` | `listing` | Only the instructions of the code regions. No data lines. |
143
- | `--out <file>` | `listing` | Write the listing as text to this file in place of the lines in the body. |
143
+ | `--out <file>` | `listing` | Write the lines to this text file in place of the lines in the body. |
144
144
  | `--element <n>` | `classify` | The bytes of one element of a table. The length of the range must be a multiple of it. |
145
145
  | `--title <text>` | `module` | The title of the file. A `module` write without a title keeps the title that the module has. |
146
146
  | `--lo <symbol>` | `operand` | The operand is the low byte of the symbol plus the offset. |
@@ -258,11 +258,20 @@ When a git merge left conflicts in the knowledge, each read body also has `confl
258
258
 
259
259
  ### `listing <range>`
260
260
 
261
- - `body.lines` has `count` and `listed`. Each line has `address`, `bytes`, `text`, `referencesIn` and `referencesOut`. It can also have `label`, `analyzerNames`, `lineComments` (the line comments before the line), `comment` (the side comment) and `access`.
262
- - `text` is the instruction with the names of its target. An operand expression of the knowledge replaces the operand. A table of addresses or words shows its values as `!word` lines, with the name of each target. A split table and the other bytes show as `!byte` lines.
263
- - `access` is there when the knowledge has coverage: `x`, `r`, `w` or `-`. See "Reads that the program does not do" of `<skill>/references/coverage.md`.
264
- - With `--code`, `lines` has only the instructions of the code regions.
265
- - With `--out`, `body.lines` is a number, and the body has `out`, `bytes` and `sha256` of the text file.
261
+ - `body.lines` has `count` and `listed`. Each item of `listed` is one text line. Read the lines as they are. Do not filter them with code.
262
+ - A line of the program has these parts, with two spaces between them. A part that the line does not have is not there.
263
+ 1. The address, for example `$09bc`.
264
+ 2. The bytes, as hex.
265
+ 3. The access, when the knowledge has coverage: `x` (executed), `r` (read) and `w` (written) as the runs did them, for example `xr`, or `-` for none. See "Reads that the program does not do" of `<skill>/references/coverage.md`.
266
+ 4. The ACME line. The name of the address comes first, with a colon after it, for example `draw_room: lda SCROLY`.
267
+ 5. The notes, after `;` and with `|` between them: the side comment, `refs in <n> out <n>` (the references to the line and from the line), and `also <names>` (the analyzer names).
268
+ - Example: `$09bc ad 11 d0 x draw_room: lda SCROLY ; refs in 3 out 1 | also FUN_09bc`.
269
+ - A line comment is a line of its own before its line, for example `; Draws the room.`.
270
+ - The ACME line is the instruction with the names of its target. An operand expression of the knowledge replaces the operand. A table of addresses or words shows its values as `!word` lines, with the name of each target. A split table and the other bytes show as `!byte` lines.
271
+ - The names are the names of the generated source. A platform name of a ROM shows only when the program uses that ROM. A line in the I/O area (`$D000-$DFFF`) gets no platform name, because that name is the name of the register and not of the RAM. A target inside a data region shows as `<name>+<offset>` only when a symbol is at the start of the region.
272
+ - A range outside the program has no lines. Then the `hint` gives the ranges where the program has bytes.
273
+ - With `--code`, `lines` has only the instructions of the code regions and their line comments.
274
+ - With `--out`, the text file has the lines, one on each line. `body.lines` is the number of lines, and the body has `out`, `bytes` and `sha256` of the text file.
266
275
  - Use `listing` in place of your own disassembler. To find the targets of a table, classify the table with its type. Then read its listing. Do not decode the bytes of a table yourself.
267
276
 
268
277
  ### `export`
@@ -309,7 +318,7 @@ Errors of this group:
309
318
  - `conflict` with "from a git merge": git joined the knowledge of two computers, and two rows are current where the knowledge permits one row. Run `merge`. Then write again.
310
319
  - `stale-revision`: the knowledge changed after the revision of `--expect-revision`. Read the knowledge again. Then decide again.
311
320
  - `not-found`: there is nothing to remove, no such revision, or no such file.
312
- - `invalid-database` or `unsupported-schema`: give `error` and `hint` to the user. Do not edit the knowledge files.
321
+ - `invalid-database`: give `error` and `hint` to the user. Do not edit the knowledge files.
313
322
 
314
323
  ### `rename <address> <name>`
315
324