@henols/c64-re-tools 2.8.0-rc.2 → 2.8.0-rc.3

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 +10 -5
  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 +9 -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 +124 -40
  47. package/skills/c64-unpacker/scripts/unpacker.ts +81 -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 +28 -68
  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
@@ -4,15 +4,14 @@
4
4
  // Watchpoints and range breakpoints stop the run at an access; the coverage
5
5
  // map then tells which range and which access it was.
6
6
 
7
- import { type AddressRange, COVERAGE, formatC64Address, instructionLength } from "#src/c64.ts";
7
+ import { type AddressRange, COVERAGE, EXECUTE, instructionLength, READ, WRITE } from "#src/c64.ts";
8
8
  import { runProgram } from "#src/host-client/autostart.ts";
9
9
  import { readCoverage } from "#src/host-client/coverage.ts";
10
10
  import { startAtEntry, type EntryState } from "#src/host-client/entry-state.ts";
11
11
  import { runActionStep, type ActionStep } from "#src/host-client/steps.ts";
12
12
  import { knowledgeAt } from "#src/knowledge/names.ts";
13
- import { MAX_MEMORY_READ } from "#src/host-client/tools.ts";
14
13
  import { readProjectFile } from "#src/host-client/transfer.ts";
15
- import type { ViceSessionClient } from "#src/host-client/vice-session.ts";
14
+ import { readMemoryInParts, type ViceSessionClient } from "#src/host-client/vice-session.ts";
16
15
 
17
16
  export type FirstAccess = "read" | "write" | "execute" | "none";
18
17
 
@@ -29,10 +28,6 @@ export type Start =
29
28
 
30
29
  const MAX_WATCH = 256;
31
30
 
32
- const READ = COVERAGE.ramRead | COVERAGE.romRead | COVERAGE.ioRead;
33
- const WRITE = COVERAGE.ramWrite | COVERAGE.ioWrite;
34
- const EXECUTE = COVERAGE.ramExecute | COVERAGE.romExecute | COVERAGE.ioExecute;
35
-
36
31
  /** The first access that coverage flags show; a read-modify-write reads first. */
37
32
  export function accessOf(flags: number): FirstAccess {
38
33
  if ((flags & EXECUTE) !== 0) return "execute";
@@ -147,11 +142,7 @@ export async function watchRelease(
147
142
 
148
143
  const accesses: RangeAccess[] = [];
149
144
  for (const [index, range] of ranges.entries()) {
150
- const parts: Buffer[] = [];
151
- for (let at = range.start; at <= range.end; at += MAX_MEMORY_READ) {
152
- parts.push(Buffer.from((await client.memoryRead({ address: at, size: Math.min(MAX_MEMORY_READ, range.end - at + 1), space: "c64", view: "ram" })).data, "hex"));
153
- }
154
- const now = Buffer.concat(parts);
145
+ const now = await readMemoryInParts(client, range.start, range.end - range.start + 1, "ram");
155
146
  accesses.push({ first: first[index]!, changed: now.some((byte, offset) => byte !== release(range.start + offset)) });
156
147
  }
157
148
  for (const ids of points.values()) {
@@ -162,5 +153,3 @@ export async function watchRelease(
162
153
  }
163
154
  return { started: true, accesses };
164
155
  }
165
-
166
- export const showRange = (range: AddressRange) => `${formatC64Address(range.start)}-${formatC64Address(range.end)}`;
@@ -9,8 +9,9 @@
9
9
  // program.
10
10
 
11
11
  import { basename } from "node:path";
12
+ import type { DatabaseSync } from "node:sqlite";
12
13
 
13
- import { type AddressRange, c64AddressOf, formatC64Address, parseC64Address } from "#src/c64.ts";
14
+ import { type AddressRange, c64AddressOf, formatC64Address, formatC64Byte, formatC64Range, formatC64RangeFields, parseC64Address } from "#src/c64.ts";
14
15
  import { Refusal } from "#src/errors.ts";
15
16
  import { parseEntryState, type EntryState } from "#src/host-client/entry-state.ts";
16
17
  import { readImage } from "#src/host-client/image.ts";
@@ -18,8 +19,9 @@ import { readActionSteps, type ActionStep } from "#src/host-client/steps.ts";
18
19
  import { MAX_EXECUTION_COUNT } from "#src/host-client/tools.ts";
19
20
  import { writeReported } from "#src/host-client/transfer.ts";
20
21
  import { ViceSessionClient } from "#src/host-client/vice-session.ts";
21
- import { openForRead, withWrite } from "#src/knowledge/database.ts";
22
- import { operandImages, programCoverage, requireProgram } from "#src/knowledge/program.ts";
22
+ import { withRead, withWrite } from "#src/knowledge/database.ts";
23
+ import { codeKnowledge, codeReach } from "#src/knowledge/code-reach.ts";
24
+ import { operandImages, releaseImage, requireProgram } from "#src/knowledge/program.ts";
23
25
  import { applyBatch, type BatchOperation } from "#src/knowledge/write.ts";
24
26
  import {
25
27
  commentsAt,
@@ -29,18 +31,21 @@ import {
29
31
  listOperands,
30
32
  listReferences,
31
33
  listRegions,
34
+ listReleases,
32
35
  listSymbols,
33
36
  operandAt,
34
37
  referencesFrom,
35
38
  referenceSuppressed,
39
+ releaseLabeled,
36
40
  regionsOverlapping,
37
41
  suppressionsOverlapping,
38
42
  symbolAt,
39
43
  symbolNamed,
40
44
  symbolSuppressed,
41
45
  } from "#src/knowledge/read.ts";
42
- import { CODE_REGION_TYPES, DEFAULT_SPACE, SEMANTIC_ORIGINS } from "#src/knowledge/schema.ts";
43
- import { platformNames } from "#src/platform.ts";
46
+ import { CODE_REGION_TYPES, DEFAULT_SPACE, RELEASE_LABEL, SEMANTIC_ORIGINS } from "#src/knowledge/schema.ts";
47
+ import { platformAddresses } from "#src/platform.ts";
48
+ import { decodeProgram, leftoverInput } from "#src/program-code.ts";
44
49
  import { projectRoot } from "#src/project.ts";
45
50
  import { knowledgeAt, knowledgeNames } from "#src/knowledge/names.ts";
46
51
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec } from "#src/script.ts";
@@ -62,34 +67,68 @@ interface LoadedRelease {
62
67
  stages?: Array<{ entry: number; wrote: AddressRange[] }>;
63
68
  }
64
69
 
70
+ /** The bytes of a release, and its entry, stages and entry state when it has them. */
71
+ interface ReleaseImage {
72
+ segments: AddressRange[];
73
+ byteAt: (address: number) => number;
74
+ memory?: Uint8Array;
75
+ entry?: number;
76
+ stages?: Array<Record<string, unknown>>;
77
+ state?: EntryState;
78
+ }
79
+
80
+ /**
81
+ * A release of the knowledge by its label. The base release is the program of
82
+ * the knowledge, with its entry state and stages. The knowledge keeps only the
83
+ * bytes of another release, so it cannot start. A label that is not a release
84
+ * is refused with the labels.
85
+ */
86
+ function labeledRelease(label: string): { image: ReleaseImage; noState: string } {
87
+ return withRead((db) => {
88
+ const release = releaseLabeled(db, label);
89
+ if (release === undefined) {
90
+ const labels = listReleases(db).map((row) => row.label);
91
+ const known = labels.length === 0 ? "The knowledge has no release." : `The releases of the knowledge are ${labels.join(", ")}.`;
92
+ throw new Refusal("not-found", `There is no release ${label} in the project knowledge. ${known}`, { hint: `Give a release label, knowledge, or the path of a file. For a file with the name ${label}, give ./${label}.` });
93
+ }
94
+ if (release.base) return knowledgeProgram(db);
95
+ const file = release.file === undefined ? "its file" : `its file ${release.file}`;
96
+ return { image: releaseImage(db, label)!, noState: `The knowledge keeps only the bytes of the release ${label}, not its entry state. To run the release, give ${file} in place of ${label}.` };
97
+ });
98
+ }
99
+
100
+ /** The program of the knowledge with its entry state and stages. */
101
+ function knowledgeProgram(db: DatabaseSync | undefined): { image: ReleaseImage; noState: string } {
102
+ const program = requireProgram(db);
103
+ return {
104
+ image: { ...program, ...(program.state === undefined ? {} : { state: parseEntryState(program.state, "the entry state of the knowledge") }) } as ReleaseImage,
105
+ noState: "The knowledge has no entry state. Put a capture of the unpacked program, with its entry state, into the project knowledge.",
106
+ };
107
+ }
108
+
65
109
  /**
66
110
  * A release to compare: "knowledge" (the program of the knowledge, with its
67
- * entry state and stages), a PRG at its load address, or an image.json of an
68
- * unpacked program (a capture) with the entry_state.json beside it.
111
+ * entry state and stages), the label of a release in the knowledge, a PRG at
112
+ * its load address, or an image.json of an unpacked program (a capture) with
113
+ * the entry_state.json beside it.
69
114
  */
70
115
  function readRelease(name: string, shift: number): LoadedRelease {
71
116
  const moved = (range: AddressRange) => ({ start: range.start + shift, end: range.end + shift });
72
117
  const inside = (range: AddressRange) => range.start >= 0 && range.end <= 0xffff;
73
- let image: { segments: AddressRange[]; byteAt: (address: number) => number; memory?: Uint8Array; entry?: number; stages?: Array<Record<string, unknown>>; state?: EntryState };
118
+ let image: ReleaseImage;
74
119
  let noState: string;
75
- if (name === "knowledge") {
76
- const db = openForRead();
77
- try {
78
- const program = requireProgram(db);
79
- image = { ...program, ...(program.state === undefined ? {} : { state: parseEntryState(program.state, "the entry state of the knowledge") }) } as typeof image;
80
- } finally {
81
- db?.close();
82
- }
83
- noState = "The knowledge has no entry state. Put a capture of the unpacked program, with its entry state, into the project knowledge.";
84
- } else {
120
+ let prg = false;
121
+ if (name === "knowledge") ({ image, noState } = withRead(knowledgeProgram));
122
+ else if (RELEASE_LABEL.test(name)) ({ image, noState } = labeledRelease(name));
123
+ else {
85
124
  image = readImage(name);
86
125
  noState = "It has no entry_state.json beside it. Capture the unpacked program again, with its entry state.";
126
+ prg = !name.endsWith(".json");
87
127
  }
88
128
  const segments = image.segments.map(moved);
89
129
  if (!segments.every(inside)) throw new UsageError(`The shift moves ${name} outside $0000-$ffff.`, { hint: "Give a shift that keeps each segment of the release in $0000-$ffff." });
90
130
  const memory = image.memory ?? new Uint8Array(0x10000);
91
131
  if (image.memory === undefined) for (const segment of image.segments) for (let at = segment.start; at <= segment.end; at++) memory[at] = image.byteAt(at);
92
- const prg = name !== "knowledge" && !name.endsWith(".json");
93
132
  const stages = stagesOf(image.stages, name);
94
133
  return {
95
134
  release: { name, segments, byteAt: (at) => memory[at - shift]! },
@@ -107,7 +146,7 @@ const MAX_ALIGNED = 64;
107
146
  /** compare: the releases byte by byte, with --align a map of two releases in blocks, and with --frames the first access of each difference in each release. */
108
147
  async function compare(call: Call): Promise<unknown> {
109
148
  const positionals = call.subjects;
110
- if (positionals.length < 2) throw new UsageError("compare needs two or more releases.", { hint: "Give the paths of two or more releases, or knowledge for the program in the knowledge." });
149
+ if (positionals.length < 2) throw new UsageError("compare needs two or more releases.", { hint: "Give two or more releases: the path of a PRG or image.json, the label of a release in the knowledge, or knowledge for the program in the knowledge." });
111
150
  const shifts = new Map<number, number>();
112
151
  for (const text of call.strings("shift")) {
113
152
  const match = /^(\d+):([+-]?\d+)$/.exec(text);
@@ -135,9 +174,15 @@ async function compare(call: Call): Promise<unknown> {
135
174
  const range = call.range("range");
136
175
  const comparison = compareReleases(releases, range === undefined ? {} : { from: range.start, to: range.end });
137
176
  const share = identicalShare(comparison.identicalBytes, comparison.differingBytes);
138
- const show = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
177
+ const show = formatC64RangeFields;
139
178
  const compared = {
140
- releases: loaded.map((item) => ({ name: item.release.name, shift: item.shift, segments: item.release.segments.map(show) })),
179
+ releases: loaded.map((item, index) => ({
180
+ release: index + 1,
181
+ name: item.release.name,
182
+ shift: item.shift,
183
+ segments: item.release.segments.map(show),
184
+ ...(comparison.outsideCommon[index]!.length === 0 ? {} : { outsideCommon: comparison.outsideCommon[index]!.map(show) }),
185
+ })),
141
186
  common: comparison.common.map(show),
142
187
  identicalBytes: comparison.identicalBytes,
143
188
  differingBytes: comparison.differingBytes,
@@ -158,12 +203,12 @@ async function compare(call: Call): Promise<unknown> {
158
203
  return cut ? reply(mapped, { hint: `A list holds only its first ${MAX_ALIGNED} items: moreBlocks, moreOnlyInA and moreOnlyInB count the others. Give --range to map a part of the releases.` }) : mapped;
159
204
  }
160
205
  // A poor match at the load addresses can mean that the releases are placed differently.
161
- // Each release gets its best shifts: data that stayed can outvote code that moved, so one is not enough.
206
+ // Each release gets its best shifts for the bytes of release 1 in the range: data that stayed can outvote code that moved, so one is not enough.
162
207
  const applied = loaded.map((item) => item.shift);
163
208
  const suggestions =
164
209
  share < 0.5
165
210
  ? releases.slice(1).flatMap((release, index) =>
166
- suggestShifts(releases[0]!, release).map((found) => {
211
+ suggestShifts(releases[0]!, release, range).map((found) => {
167
212
  const suggestion = shiftSuggestion(releases, applied, index + 1, found);
168
213
  // The shift that the run already has: its votes tell how good the present alignment is.
169
214
  return "shift" in suggestion && suggestion.shift === applied[suggestion.release - 1] ? { ...suggestion, current: true } : suggestion;
@@ -174,11 +219,12 @@ async function compare(call: Call): Promise<unknown> {
174
219
  const notSuggested = suggestions.filter((suggestion) => "reason" in suggestion);
175
220
 
176
221
  // The runtime evidence: one emulator for each release, the differences at the release's own addresses.
222
+ // Each release by its number: a file can be given two times, with another shift.
177
223
  const runtime = new Map<string, Array<AddressRange & { first: string; changed: boolean }>>();
178
224
  const runs: Record<string, unknown> = {};
179
225
  if (frames !== undefined && comparison.differences.length > 0) {
180
- for (const item of loaded) {
181
- const name = item.release.name;
226
+ for (const [index, item] of loaded.entries()) {
227
+ const name = String(index + 1);
182
228
  if (item.start.kind === "none") {
183
229
  runs[name] = { started: false, reason: item.start.reason };
184
230
  continue;
@@ -199,7 +245,7 @@ async function compare(call: Call): Promise<unknown> {
199
245
  }
200
246
 
201
247
  // The next compare: the best suggested shift that the run does not have yet, else --align for two releases.
202
- const rangeArgs = range === undefined ? [] : ["--range", `${formatC64Address(range.start)}-${formatC64Address(range.end)}`];
248
+ const rangeArgs = range === undefined ? [] : ["--range", formatC64Range(range)];
203
249
  const runArgs = frames === undefined ? [] : ["--frames", String(frames), ...(stepsFile === undefined ? [] : ["--steps", stepsFile])];
204
250
  const best = suggested.find((suggestion) => !("current" in suggestion));
205
251
  const hints: string[] = [];
@@ -210,7 +256,8 @@ async function compare(call: Call): Promise<unknown> {
210
256
  const shiftArgs = next.flatMap((shift, index) => (shift === 0 ? [] : ["--shift", `${index + 1}:${shift}`]));
211
257
  hints.push("identicalShare is low: the releases can be at different addresses. nextAction runs compare with the first suggested shift. Try each shift in suggestedShifts. If no shift gives a high identicalShare, run compare with --align.");
212
258
  nextAction = call.next("compare", ...positionals, ...shiftArgs, ...rangeArgs, ...runArgs);
213
- } else if (share < 0.5 && positionals.length === 2 && shifts.size === 0 && frames === undefined) {
259
+ } else if (share < 0.5 && suggestions.length > 0 && positionals.length === 2 && shifts.size === 0 && frames === undefined) {
260
+ // Only when release 2 has sequences of release 1 at some shift: else --align finds no block either.
214
261
  hints.push("identicalShare is low, and no suggested shift is better. The code and the data can be at other addresses in each release. Map the releases in blocks with --align.");
215
262
  nextAction = call.next("compare", ...positionals, "--align", ...rangeArgs);
216
263
  }
@@ -220,7 +267,7 @@ async function compare(call: Call): Promise<unknown> {
220
267
  differences: comparison.differences.map((difference, index) => ({
221
268
  start: formatC64Address(difference.start),
222
269
  end: formatC64Address(difference.end),
223
- values: Object.fromEntries(Object.entries(difference.values).map(([name, bytes]) => [name, hexBytes(bytes.slice(0, 32)) + (bytes.length > 32 ? " ..." : "")])),
270
+ values: Object.fromEntries(difference.values.map((bytes, at) => [String(at + 1), hexBytes(bytes.slice(0, 32)) + (bytes.length > 32 ? " ..." : "")])),
224
271
  groups: difference.groups,
225
272
  // runtime gives the release's own addresses: with a shift, they are not the addresses of the difference.
226
273
  ...(runtime.size === 0
@@ -258,21 +305,10 @@ function stagesOf(stages: Array<Record<string, unknown>> | undefined, where = "t
258
305
  }));
259
306
  }
260
307
 
261
- /** The program in the knowledge with its stages and coverage, and the separation of its bytes. */
308
+ /** The program in the knowledge with its stages and coverage, the knowledge of its code, and the separation of its bytes. */
262
309
  function programEvidence() {
263
- const db = openForRead();
264
- let program: ReturnType<typeof requireProgram>;
265
- let coverage: Uint8Array | undefined;
266
- let regions: ReturnType<typeof listRegions>;
267
- let references: ReturnType<typeof listReferences>;
268
- try {
269
- program = requireProgram(db);
270
- coverage = programCoverage(db)?.map;
271
- regions = listRegions(db).filter((region) => CODE_REGION_TYPES.includes(region.type));
272
- references = listReferences(db);
273
- } finally {
274
- db?.close();
275
- }
310
+ const knowledge = withRead((db) => codeKnowledge(db));
311
+ const { program, coverage } = knowledge;
276
312
  const stages = stagesOf(program.stages);
277
313
  const found = separate({
278
314
  segments: program.segments,
@@ -280,10 +316,10 @@ function programEvidence() {
280
316
  ...(program.entry === undefined ? {} : { entry: program.entry }),
281
317
  ...(stages === undefined ? {} : { stages }),
282
318
  ...(coverage === undefined ? {} : { coverage }),
283
- codeRegions: regions,
284
- references,
319
+ codeRegions: knowledge.regions.filter((region) => CODE_REGION_TYPES.includes(region.type)),
320
+ references: knowledge.references,
285
321
  });
286
- return { program, stages, coverage, found };
322
+ return { knowledge, program, stages, coverage, found };
287
323
  }
288
324
 
289
325
  /** The roots of the reachability as a person reads them. */
@@ -298,7 +334,7 @@ function separateCommand(call: Call): unknown {
298
334
  const out = call.string("out");
299
335
  const { program, stages, coverage, found } = programEvidence();
300
336
  const loaded = { entry: program.entry, stages };
301
- const show = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
337
+ const show = formatC64RangeFields;
302
338
  const ranges = found.ranges.map((range) => ({ ...show(range), ...(range.stage === undefined ? {} : { stage: range.stage }), ...(range.access === undefined ? {} : { access: range.access }) }));
303
339
  const codeRegions = found.codeRegions.map((region) => ({ ...show(region), type: region.type, ...(region.reachable === undefined ? {} : { reachable: region.reachable }), ...(region.executed === undefined ? {} : { executed: region.executed }), ...(region.unknown === undefined ? {} : { unknown: true }) }));
304
340
  const unresolved = found.unresolved.map((flow) => ({ at: formatC64Address(flow.at), kind: flow.kind }));
@@ -359,15 +395,23 @@ function withFile(bodyOf: (most: number, rest: string) => Record<string, unknown
359
395
  /** The longest text that the result shows; --out has all of it. */
360
396
  const SHOWN_TEXT = 120;
361
397
 
362
- /** leftovers: what the program in the knowledge holds besides its working code. --out gets the fields of the body with all items and the full texts. */
363
- function leftoversCommand(call: Call): unknown {
398
+ /**
399
+ * leftovers: what the program in the knowledge holds besides its working
400
+ * code. The dead and the unknown code come from the code reach of the decoded
401
+ * program, as the leftovers of a generated source do. --out gets the fields of
402
+ * the body with all items and the full texts.
403
+ */
404
+ async function leftoversCommand(call: Call): Promise<unknown> {
364
405
  const out = call.string("out");
365
406
  const min = call.count("min-text")!;
366
- const { program, stages, coverage, found } = programEvidence();
407
+ const { knowledge, program, stages, coverage, found } = programEvidence();
408
+ const { instructions } = await decodeProgram(program, knowledge, [], coverage);
409
+ const code = codeReach(leftoverInput(knowledge, instructions));
367
410
  const leftovers = findLeftovers({
368
411
  segments: program.segments,
369
412
  memory: program.memory,
370
413
  separation: found,
414
+ code,
371
415
  ...(program.segments.some((segment) => segment.start === 0x0801) ? { basicStart: 0x0801 } : {}),
372
416
  minText: min,
373
417
  });
@@ -386,7 +430,7 @@ function leftoversCommand(call: Call): unknown {
386
430
  copies: leftovers.copies.map(({ copyOf, ...rest }) => ({ ...show(rest), copyOf: formatC64Address(copyOf) })),
387
431
  deadCode: leftovers.deadCode.map(show),
388
432
  unknownCode: leftovers.unknownCode.map(show),
389
- unresolved: found.unresolved.map((flow) => ({ at: formatC64Address(flow.at), kind: flow.kind })),
433
+ unresolved: code.unresolved.map((flow) => ({ at: formatC64Address(flow.at), kind: flow.kind })),
390
434
  };
391
435
  /** The body with at most `most` items in each list; the file has the full texts. */
392
436
  const bodyOf = (most: number, rest: string) => {
@@ -396,7 +440,7 @@ function leftoversCommand(call: Call): unknown {
396
440
  ...(program.entry === undefined ? {} : { entry: formatC64Address(program.entry) }),
397
441
  roots: found.roots.length === 0 ? NO_ROOTS : showRoots(found.roots),
398
442
  ...(stages === undefined ? { noStages: NO_STAGES } : { stages: stages.length }),
399
- ...(coverage === undefined ? { noCoverage: "The knowledge has no coverage, so residue is empty and no finding has access. Put the coverage of runs into the project knowledge." } : {}),
443
+ ...(coverage === undefined ? { noCoverage: "The knowledge has no coverage, so residue, deadCode and unknownCode are empty, and no finding has access. Put the coverage of runs into the project knowledge." } : {}),
400
444
  text: list(all.text.map((item) => (item.text.length > shown ? { ...item, text: `${item.text.slice(0, shown)} ...`, length: item.text.length } : item))),
401
445
  basic: list(all.basic),
402
446
  fill: list(all.fill),
@@ -409,14 +453,11 @@ function leftoversCommand(call: Call): unknown {
409
453
  return withFile(bodyOf, call.count("max-listed")!, out);
410
454
  }
411
455
 
412
- const platform = () => new Map(platformNames().map((entry) => [entry.name, entry.address]));
413
-
414
456
  /** routine: saves a module or a range of the program in the knowledge, with its knowledge, as a routine of the library. */
415
457
  function routineCommand(call: Call): unknown {
416
458
  const given = call.subject(0);
417
459
  const library = call.string("library")!;
418
- const db = openForRead();
419
- try {
460
+ return withRead((db) => {
420
461
  const image = requireProgram(db);
421
462
  const segmentOf = (at: number) => image.segments.find((segment) => at >= segment.start && at <= segment.end);
422
463
  let start: number;
@@ -433,7 +474,7 @@ function routineCommand(call: Call): unknown {
433
474
  title ??= module.title;
434
475
  } else {
435
476
  ({ start, end } = call.parseRange(given, "<range>"));
436
- if (segmentOf(start) === undefined || segmentOf(start) !== segmentOf(end)) throw new UsageError(`${formatC64Address(start)}-${formatC64Address(end)} is not inside one segment of the program.`, { hint: "Give a range in one segment of the program." });
477
+ if (segmentOf(start) === undefined || segmentOf(start) !== segmentOf(end)) throw new UsageError(`${formatC64Range({ start, end })} is not inside one segment of the program.`, { hint: "Give a range in one segment of the program." });
437
478
  }
438
479
  const range = { start, end };
439
480
  const name = call.string("name") ?? listSymbols(db, { start, end: start }, undefined, SEMANTIC_ORIGINS)[0]?.name;
@@ -452,7 +493,7 @@ function routineCommand(call: Call): unknown {
452
493
  comments: listComments(db, range, SEMANTIC_ORIGINS),
453
494
  references: listReferences(db, range, undefined, SEMANTIC_ORIGINS),
454
495
  operands: listOperands(db, range, SEMANTIC_ORIGINS),
455
- platform: platform(),
496
+ platform: platformAddresses(),
456
497
  });
457
498
  const written = saveRoutine(libraryFolder(library, { create: true, cwd: projectRoot() }), routine, call.flag("replace"), projectRoot());
458
499
  return {
@@ -467,9 +508,7 @@ function routineCommand(call: Call): unknown {
467
508
  counts: { symbols: routine.symbols.length, regions: routine.regions.length, comments: routine.comments.length, references: routine.references.length, operands: routine.operands.length },
468
509
  ...(leftOut.length === 0 ? {} : { leftOut }),
469
510
  };
470
- } finally {
471
- db?.close();
472
- }
511
+ });
473
512
  }
474
513
 
475
514
  /**
@@ -484,34 +523,12 @@ function matchCommand(call: Call): unknown {
484
523
  const list = <T>(items: T[]) => listed(items, max);
485
524
  const routines = readLibrary(libraryFolder(library, { create: false, cwd: projectRoot() }));
486
525
  if (routines.length === 0) throw new Refusal("not-found", `The library ${library} has no routine files. Save a routine with routine first.`);
487
- const programDb = openForRead();
488
- let image: ReturnType<typeof requireProgram>;
489
- try {
490
- image = requireProgram(programDb);
491
- } finally {
492
- programDb?.close();
493
- }
494
- const found = routines.map((routine) => ({ routine, matches: findRoutine(routine, image) }));
495
- const show = (value: number, size: 1 | 2) => `$${value.toString(16).padStart(2 * size, "0")}`;
496
- const matches = found
497
- .flatMap(({ routine, matches: each }) =>
498
- each.map((match) => ({
499
- routine: match.routine,
500
- start: formatC64Address(match.start),
501
- end: formatC64Address(match.start + routine.bytes.length - 1),
502
- shift: match.shift,
503
- differing: match.differing.map((operand) => ({ address: formatC64Address(operand.address), library: show(operand.library, operand.size), program: show(operand.program, operand.size) })),
504
- })),
505
- )
506
- .sort((a, b) => a.start.localeCompare(b.start));
507
- const result: Record<string, unknown> = { library, routines: routines.length, matches: list(matches) };
508
- const noMatch = "No routine of the library is in the program. A packed program can hold a routine in a packed form. Unpack the program, put the unpacked program into the project knowledge, and run match again.";
509
- const withNote = (shown: unknown, hint: string) => [cutNote(shown), hint].filter((part) => part !== undefined).join(" ");
510
- if (matches.length === 0) return reply(result, { hint: noMatch });
511
- const db = openForRead();
512
- let suggestions: ReturnType<typeof suggest>;
513
- try {
514
- suggestions = suggest(
526
+ // One read of the knowledge: the program to search, and the knowledge that the suggestions of the matches check.
527
+ const { found, suggestions } = withRead((db) => {
528
+ const image = requireProgram(db);
529
+ const found = routines.map((routine) => ({ routine, matches: findRoutine(routine, image) }));
530
+ if (found.every((item) => item.matches.length === 0)) return { found, suggestions: undefined };
531
+ const suggestions = suggest(
515
532
  found,
516
533
  {
517
534
  symbolAt: (at) => symbolAt(db, at),
@@ -525,11 +542,26 @@ function matchCommand(call: Call): unknown {
525
542
  referenceSuppressed: (reference) => referenceSuppressed(db, reference),
526
543
  },
527
544
  image,
528
- platform(),
545
+ platformAddresses(),
529
546
  );
530
- } finally {
531
- db?.close();
532
- }
547
+ return { found, suggestions };
548
+ });
549
+ const show = (value: number, size: 1 | 2) => (size === 1 ? formatC64Byte(value) : formatC64Address(value));
550
+ const matches = found
551
+ .flatMap(({ routine, matches: each }) =>
552
+ each.map((match) => ({
553
+ routine: match.routine,
554
+ start: formatC64Address(match.start),
555
+ end: formatC64Address(match.start + routine.bytes.length - 1),
556
+ shift: match.shift,
557
+ differing: match.differing.map((operand) => ({ address: formatC64Address(operand.address), library: show(operand.library, operand.size), program: show(operand.program, operand.size) })),
558
+ })),
559
+ )
560
+ .sort((a, b) => a.start.localeCompare(b.start));
561
+ const result: Record<string, unknown> = { library, routines: routines.length, matches: list(matches) };
562
+ const noMatch = "No routine of the library is in the program. A packed program can hold a routine in a packed form. Unpack the program, put the unpacked program into the project knowledge, and run match again.";
563
+ const withNote = (shown: unknown, hint: string) => [cutNote(shown), hint].filter((part) => part !== undefined).join(" ");
564
+ if (suggestions === undefined) return reply(result, { hint: noMatch });
533
565
  const { writes, known, leftOut, check } = suggestions;
534
566
  const changes: Record<string, unknown> = { writes: list(writes), known, leftOut: list(leftOut), check: list(check) };
535
567
  const body = { ...result, changes };
@@ -538,8 +570,7 @@ function matchCommand(call: Call): unknown {
538
570
  if (!apply) {
539
571
  return reply(body, { hint: withNote(body, `Examine differing of each match, and changes.writes and changes.leftOut. Then nextAction writes the changes to the project knowledge.${review}`), nextAction: call.next("match", "--library", library, "--apply") });
540
572
  }
541
- const platformNamed = new Map(platformNames().map((entry) => [entry.name, entry.address]));
542
- const applied = withWrite((write) => applyBatch(write, { origin: "llm", description: `Names of the routines of the library ${library}`, image: operandImages(write, platformNamed) }, writes.map(toOperation)));
573
+ const applied = withWrite((write) => applyBatch(write, { origin: "llm", description: `Names of the routines of the library ${library}`, image: operandImages(write, platformAddresses()) }, writes.map(toOperation)));
543
574
  changes.revision = applied.revision;
544
575
  return reply(body, { hint: withNote(body, `The project knowledge has the changes in revision ${applied.revision}.${review}`) });
545
576
  }
@@ -557,7 +588,7 @@ const COMMANDS: CommandSpec[] = [
557
588
  {
558
589
  name: "compare",
559
590
  summary: "Compares releases byte by byte, in their common ranges, and suggests shifts when they are placed differently. With --align, maps two releases with moved code in blocks of equal bytes, each with its own shift.",
560
- subjects: [{ name: "<release>", help: "knowledge (the program in the knowledge), a PRG at its load address, or the image.json of a capture of the unpacked program with the entry_state.json beside it. Two or more", list: true }],
591
+ subjects: [{ name: "<release>", help: "knowledge (the program in the knowledge), the label of a release in the knowledge, a PRG at its load address, or the image.json of a capture of the unpacked program with the entry_state.json beside it. Two or more", list: true }],
561
592
  options: {
562
593
  shift: {
563
594
  kind: "text",
@@ -577,13 +608,13 @@ const COMMANDS: CommandSpec[] = [
577
608
  },
578
609
  {
579
610
  name: "separate",
580
- summary: "Evidence from the program in the knowledge: the unpack stage that wrote each range, its access in the coverage, whether call and jump references, or the run on from the code before it, reach each code region from the entry, and what the program reads or executes outside its segments.",
611
+ summary: "Evidence from the program in the knowledge: the unpack stage that wrote each range, its access in the coverage, whether call and jump references, a handler that the code stores in an interrupt vector, or the run on from the code before it, reach each code region from the entry, and what the program reads or executes outside its segments.",
581
612
  options: { out: { ...OPTIONS.out, output: "file", value: "<file>", help: "write the fields of the body, with all items of each list, to this file" }, "max-listed": OPTIONS["max-listed"] },
582
613
  run: separateCommand,
583
614
  },
584
615
  {
585
616
  name: "leftovers",
586
- summary: "What the program in the knowledge holds besides its working code: texts in PETSCII, screen codes, ASCII or with bit 7 set (Apple II), assembler source, BASIC lines away from the BASIC start, fills, untouched bytes outside code, copies of earlier bytes, and code regions that nothing reaches and no run executed.",
617
+ summary: "What the program in the knowledge holds besides its working code: texts in PETSCII, screen codes, ASCII or with bit 7 set (Apple II), assembler source, BASIC lines away from the BASIC start, fills, untouched bytes outside code, copies of earlier bytes, and code that nothing reaches and no run executed.",
587
618
  options: {
588
619
  out: { ...OPTIONS.out, output: "file", value: "<file>", help: "write the fields of the body, with all findings and the full texts, to this file" },
589
620
  "min-text": { kind: "count", value: "<n>", min: 4, max: 999, default: 8, help: "the shortest text to find (default 8)" },
@@ -40,7 +40,8 @@ In these cases, set the switch values in `config.asm`. Then run `generate --out
40
40
  - `program` and `symbols`: the loader program and its symbols file.
41
41
  - The `copies` in their order, `copier` and `stackByte`.
42
42
  - `verified: true`: the check ran the loader program to its jump to the entry. There, the memory, $00/$01, the registers, the VIC-II and the colour RAM are equal to the entry state. The raster line and the CIA values are also equal. An interrupt can run right at the entry, as in the program of the base release.
43
- - `limits`: each CIA value that the loader cannot set as it was at the entry. An old capture has no CIA values or no colour RAM. Then capture the program again at its entry point.
43
+ - `limits`: each CIA value that the loader cannot set as it was at the entry. An old capture has no CIA values. Then capture the program again at its entry point.
44
+ When the entry state has no colour RAM, the loader does not set the colour RAM. The colour RAM of a capture of a crack is the state of the crack.
44
45
  When no free RAM outside the segments has room for the 1000 colours, the loader does not set the colour RAM, and `limits` tells this. Then the program starts with other colours where it does not write them.
45
46
  - `startScreen`: with a start screen, `shown: true` when the VIC-II had the values of the start screen, and `waits: true` when the start screen waited without a key.
46
47
  - `packed`: `packedBytes` and `unpackedBytes` of the packed form. A program that is too large for one loader file gets the packed form. With a start screen of a captured stage, this is the packed program in the loader program.