@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
@@ -3,7 +3,9 @@
3
3
  // from current knowledge and the coverage of the knowledge, and imports the
4
4
  // structural findings into .c64-re-tools/knowledge/.
5
5
 
6
- import { COVERAGE, formatC64Address, prgRange } from "#src/c64.ts";
6
+ import type { DatabaseSync } from "node:sqlite";
7
+
8
+ import { COVERAGE, coverageEntries, coverageSeedKinds, dxaFallThrough, executedStarts, formatC64Address, formatC64Byte, formatC64RangeFields, inRanges, prgRange, rangesOverlap, romOnlyRanges } from "#src/c64.ts";
7
9
  import { isRefusal, Refusal } from "#src/errors.ts";
8
10
  import { WireFailure } from "#src/host-client/tools.ts";
9
11
  import { writeReported } from "#src/host-client/transfer.ts";
@@ -12,21 +14,22 @@ import { analyze as analyzeWithDxa } from "#src/native/dxa.ts";
12
14
  import { analyze as analyzeWithDecompiler } from "#src/native/decompiler/analyze.ts";
13
15
  import { localToolContext } from "#src/native/local.ts";
14
16
  import { DECOMPILER_LIMITS, type RefusedSeed, type SeedReport } from "#src/native/types.ts";
15
- import { openForRead, withWrite } from "#src/knowledge/database.ts";
17
+ import { openForRead, withRead, withWrite } from "#src/knowledge/database.ts";
16
18
  import { analyzedBytes, operandImages, programCoverage, requireProgram } from "#src/knowledge/program.ts";
17
19
  import { applyBatch, type BatchOperation } from "#src/knowledge/write.ts";
18
20
  import { importFindings, lastToolVersion, runProvenance, type ImportConflict, type ImportContext, type ImportResult, type NormalizedFindings } from "#src/knowledge/import.ts";
19
21
  import { currentRevision, listMacros, listMacroUses, listPatches, listReferences, listRegions, listSymbols } from "#src/knowledge/read.ts";
20
- import { DEFAULT_SPACE, SEMANTIC_ORIGINS, type Analyzer } from "#src/knowledge/schema.ts";
21
- import { platformNames, platformNamesFor, romUseOfProgram, type RomUse } from "#src/platform.ts";
22
+ import { CODE_REGION_TYPES, DEFAULT_SPACE, SEMANTIC_ORIGINS, type Analyzer } from "#src/knowledge/schema.ts";
23
+ import { platformAddresses, platformNames, platformNamesFor, romUseOfProgram, type RomUse } from "#src/platform.ts";
22
24
  import { listed, OPTIONS, reply, runScript, UsageError, type Call } from "#src/script.ts";
23
- import { codeEntries, coverageConflicts, coverageEntries, coverageSeedKinds, executedStarts, imageReader, romOnlyRanges, writtenNotExecuted, explainGaps, type GapReason, type ImageByte } from "./lib/coverage.ts";
24
- import { dxaFindings, decompilerFindings, seedsFromKnowledge } from "./lib/findings.ts";
25
+ import { codeEntries, coverageConflicts, imageReader, writtenNotExecuted, explainGaps, type GapReason, type ImageByte } from "./lib/coverage.ts";
26
+ import { decidedFromKnowledge, dxaFindings, decompilerFindings, seedsFromKnowledge } from "./lib/findings.ts";
25
27
  import { findIdioms } from "./lib/idioms.ts";
26
28
  import { instructionList } from "./lib/instructions.ts";
27
29
  import { CATALOGUE, findMacroUses, type MacroCandidate } from "./lib/macros.ts";
28
30
  import { findPitfalls, type Pitfall } from "./lib/pitfalls.ts";
29
31
  import { findPointers, type PointerCandidate } from "./lib/pointers.ts";
32
+ import { flowFromExecuted, rangeFacts, type RangeFacts } from "./lib/triage.ts";
30
33
 
31
34
  /** The rest of a cut label or function list: the knowledge has all of them as analyzer names. */
32
35
  const ALL_NAMES = "a larger --max-listed. The project knowledge has all of them as analyzer names";
@@ -38,8 +41,21 @@ const ALL_REGIONS = "a larger --max-listed. The project knowledge has all of the
38
41
  * analyzer data over executed code to classify, and macro candidates to write.
39
42
  * The envelope adds the sentence for a cut list.
40
43
  */
41
- function withHint(body: Record<string, unknown>, conflicts: number, coverageConflicts: number, macros: { candidates: number; applied: boolean; revision: string | null | undefined }, version: { now: string | undefined; last: string | undefined; revision: string | null }, retiredReferences: number, guards: { refused: number; writtenNotExecuted: number }) {
44
+ function withHint(
45
+ body: Record<string, unknown>,
46
+ facts: {
47
+ conflicts: number;
48
+ coverageConflicts: number;
49
+ macros: { candidates: number; applied: boolean; revision: string | null | undefined };
50
+ version: { now: string | undefined; last: string | undefined; revision: string | null };
51
+ retiredReferences: number;
52
+ guards: { refused: number; writtenNotExecuted: number };
53
+ cut: Cut;
54
+ },
55
+ ) {
56
+ const { conflicts, coverageConflicts, macros, version, retiredReferences, guards, cut } = facts;
42
57
  const hints: string[] = [];
58
+ if (cut.entryPoints.length + cut.codeStarts.length + cut.dataRanges.length > 0) hints.push(overLimitHint(cut));
43
59
  if (guards.refused > 0) hints.push(`The analysis did not decode ${guards.refused} seeds in the program or of --entry: seeds.refused gives each refused seed with its reason. A seed inside an instruction or in data is often a wrong routine or region in the project knowledge. Examine it in the listing, and correct the project knowledge.`);
44
60
  if (guards.writtenNotExecuted > 0) hints.push("Each range in writtenNotExecuted is code of the analyzer on bytes that the runs wrote and never executed. Its from gives the instructions that reach it. Examine the routine that holds them: a wrong entry point leads the analyzer into data. Correct the project knowledge, and run the analysis again.");
45
61
  if (version.revision !== null && version.now !== undefined && version.last !== undefined && version.now !== version.last) {
@@ -47,7 +63,7 @@ function withHint(body: Record<string, unknown>, conflicts: number, coverageConf
47
63
  }
48
64
  // A leftover is data that no reference reads: a retired reference can make one.
49
65
  if (retiredReferences > 0) hints.push("The analysis retired references. A data range that only a retired reference used can be a leftover now. Generate the source again, and examine the leftovers that changed.");
50
- if (conflicts > 0) hints.push("The analysis and the project knowledge disagree at each place in conflicts. Find the correct answer in the emulator. Then correct the project knowledge.");
66
+ if (conflicts > 0) hints.push("The analysis and the project knowledge disagree at each place in conflicts. Use access, references and reachable of each conflict. Code that a run executed is code. A range that static flow reaches and that no run executed is usually code on a branch that no run took. A range that no flow reaches and that a run read or wrote is usually data. If these facts do not decide, find the answer in the emulator. Then correct the project knowledge.");
51
67
  if (coverageConflicts > 0) hints.push("The coverage shows executed code in each range of coverageConflicts. Classify each range as code, or as dual-use when its bytes are also data, in the project knowledge.");
52
68
  if (typeof macros.revision === "string") hints.push("The project knowledge has the macro candidates now. Generate the source again.");
53
69
  else if (!macros.applied && macros.candidates > 0) hints.push("Examine idioms.candidates.macros. To write them to the project knowledge, run the analysis again with --apply-macros.");
@@ -55,6 +71,28 @@ function withHint(body: Record<string, unknown>, conflicts: number, coverageConf
55
71
  return reply(body, { hint: hints.join(" ") });
56
72
  }
57
73
 
74
+ /** The seeds over the limits of the analyzer. */
75
+ interface Cut {
76
+ analyzer: Analyzer;
77
+ entryPoints: readonly number[];
78
+ codeStarts: readonly number[];
79
+ dataRanges: ReadonlyArray<{ start: number; end: number }>;
80
+ }
81
+
82
+ /**
83
+ * What the analyzer did not get because of its limits, and why its findings
84
+ * there are not facts about the program. A routine in the knowledge or an
85
+ * --entry does not help: it is a seed too, and it puts another seed over the limit.
86
+ */
87
+ function overLimitHint(cut: Cut): string {
88
+ const span = (kind: string, ranges: ReadonlyArray<{ start: number; end: number }>) =>
89
+ ranges.length === 0 ? [] : [`${ranges.length} ${kind} from ${formatC64Address(Math.min(...ranges.map((range) => range.start)))} to ${formatC64Address(Math.max(...ranges.map((range) => range.end)))}`];
90
+ const at = (addresses: readonly number[]) => addresses.map((address) => ({ start: address, end: address }));
91
+ const parts = [...span("entry points", at(cut.entryPoints)), ...span("code starts", at(cut.codeStarts)), ...span("data ranges", cut.dataRanges)];
92
+ const decompiler = cut.analyzer === "dxa" && cut.entryPoints.length > 0 ? ` The decompiler takes the coverage starts as code starts, at most ${DECOMPILER_LIMITS.codeStarts}: use its findings at these addresses.` : "";
93
+ return `The analyzer did not get all seeds: they are over its limits (seeds.overLimit). It did not get ${parts.join(", ")}. Thus a finding or a conflict at these addresses can come from this cut, and not from the program. Do not correct the project knowledge for such a finding.${decompiler}`;
94
+ }
95
+
58
96
  /**
59
97
  * The refused seeds that can be a fault of the project knowledge: a routine
60
98
  * outside the program can be code that the program copies there when it
@@ -78,21 +116,10 @@ function seedsResult(given: Record<string, number>, overLimit: Record<string, nu
78
116
  ...given,
79
117
  ...(Object.keys(over).length === 0 ? {} : { overLimit: over }),
80
118
  ...(report.refused.length === 0 ? {} : { refused: { ...listed(report.refused, max, showRefused), byReason } }),
81
- ...(report.dataRangesLeftOut.length === 0 ? {} : { dataRangesLeftOut: listed(report.dataRangesLeftOut, max, (range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end), code: formatC64Address(range.code) })) }),
119
+ ...(report.dataRangesLeftOut.length === 0 ? {} : { dataRangesLeftOut: listed(report.dataRangesLeftOut, max, (range) => ({ ...formatC64RangeFields(range), code: formatC64Address(range.code) })) }),
82
120
  };
83
121
  }
84
122
 
85
- /** The code regions of the analyzer on bytes that the runs wrote and never executed, from the knowledge after the import. */
86
- function writtenNotExecutedOf(analyzer: Analyzer, space: string, coverage: Uint8Array | undefined) {
87
- if (coverage === undefined) return [];
88
- const db = openForRead();
89
- try {
90
- return writtenNotExecuted(db, analyzer, coverage, space);
91
- } finally {
92
- db?.close();
93
- }
94
- }
95
-
96
123
  /** A pitfall with $ addresses and what goes wrong. */
97
124
  function showPitfall(pitfall: Pitfall) {
98
125
  return {
@@ -106,7 +133,7 @@ function showPitfall(pitfall: Pitfall) {
106
133
  /** A pointer candidate with $ addresses, and the operand writes that would name it. */
107
134
  function showPointer(candidate: PointerCandidate) {
108
135
  if (candidate.kind === "sprite pointer") {
109
- return { kind: candidate.kind, at: formatC64Address(candidate.at), to: formatC64Address(candidate.to), value: `$${candidate.value.toString(16).padStart(2, "0")}`, target: formatC64Address(candidate.target), assumes: "VIC bank 0 and the screen at $0400" };
136
+ return { kind: candidate.kind, at: formatC64Address(candidate.at), to: formatC64Address(candidate.to), value: formatC64Byte(candidate.value), target: formatC64Address(candidate.target), assumes: "VIC bank 0 and the screen at $0400" };
110
137
  }
111
138
  return { kind: candidate.kind, to: formatC64Address(candidate.to), target: formatC64Address(candidate.target), low: formatC64Address(candidate.low), high: formatC64Address(candidate.high) };
112
139
  }
@@ -126,53 +153,82 @@ function showMacro(candidate: MacroCandidate) {
126
153
  * candidates that start at an address of `skip`. A macro of the catalogue that
127
154
  * the knowledge has with another body leaves its candidates out of the writes.
128
155
  */
129
- function macroCandidates(space: string, byteAt: ImageByte, romUse: RomUse, skip: ReadonlySet<number>) {
130
- const db = openForRead();
131
- try {
132
- // The platform names that c64-source uses: a name of a ROM that the program does not use is no arg.
133
- const platform = space === DEFAULT_SPACE ? new Map(platformNamesFor(romUse).map((entry) => [entry.address, entry.name])) : new Map<number, string>();
134
- const semantic = new Map(listSymbols(db, undefined, undefined, [...SEMANTIC_ORIGINS], space).map((symbol) => [symbol.address, symbol.name]));
135
- const code = listRegions(db, undefined, "code", undefined, space);
136
- const found = findMacroUses(byteAt, code, (address) => semantic.get(address) ?? platform.get(address));
137
- const named = new Set([...listSymbols(db, undefined, undefined, undefined, space).map((symbol) => symbol.address), ...listReferences(db, undefined, undefined, undefined, space).map((reference) => reference.to)]);
138
- const patches = listPatches(db, undefined, undefined, undefined, space);
139
- const uses = listMacroUses(db, undefined, undefined, undefined, space);
140
- const overlaps = (a: { start: number; end: number }, b: { start: number; end: number }) => a.start <= b.end && b.start <= a.end;
141
- const candidates: MacroCandidate[] = [];
142
- let known = 0;
143
- let leftOut = 0;
144
- for (const candidate of found) {
145
- const same = uses.find((use) => use.start === candidate.start && use.end === candidate.end && use.macro === candidate.macro && use.args.join(",") === candidate.args.join(","));
146
- if (same !== undefined) known++;
147
- else if ([...named].some((address) => address > candidate.start && address <= candidate.end) || patches.some((patch) => overlaps(patch, candidate)) || uses.some((use) => overlaps(use, candidate))) leftOut++;
148
- else candidates.push(candidate);
149
- }
150
- // A macro of the catalogue goes into the writes unless the knowledge has it; with another body, its uses stay out.
151
- const macros = new Map(listMacros(db, undefined, space).map((macro) => [macro.name, macro]));
152
- const writes: BatchOperation[] = [];
153
- const other = new Set<string>();
154
- const chosen = candidates.filter((candidate) => !skip.has(candidate.start));
155
- for (const idiom of CATALOGUE.filter((item) => chosen.some((candidate) => candidate.macro === item.name))) {
156
- const existing = macros.get(idiom.name);
157
- if (existing === undefined) writes.push({ op: "macro", space, name: idiom.name, params: [...idiom.params], body: idiom.body, comment: idiom.comment });
158
- else if (existing.params.join(",") !== idiom.params.join(",") || existing.body !== idiom.body) other.add(idiom.name);
159
- }
160
- for (const candidate of chosen) {
161
- if (other.has(candidate.macro)) continue;
162
- writes.push({ op: "use", space, start: candidate.start, end: candidate.end, macro: candidate.macro, args: candidate.args });
163
- }
164
- const notCandidates = [...skip].filter((address) => !candidates.some((candidate) => candidate.start === address)).sort((a, b) => a - b);
165
- return { candidates, known, leftOut, writes, skipped: candidates.length - chosen.length, notCandidates, otherMacros: [...other].map((name) => `The knowledge has another macro ${name}: its candidates are not written.`) };
166
- } finally {
167
- db?.close();
156
+ function macroCandidates(db: DatabaseSync | undefined, space: string, byteAt: ImageByte, romUse: RomUse, skip: ReadonlySet<number>) {
157
+ // The platform names that c64-source uses: a name of a ROM that the program does not use is no arg.
158
+ const platform = space === DEFAULT_SPACE ? new Map(platformNamesFor(romUse).map((entry) => [entry.address, entry.name])) : new Map<number, string>();
159
+ const semantic = new Map(listSymbols(db, undefined, undefined, [...SEMANTIC_ORIGINS], space).map((symbol) => [symbol.address, symbol.name]));
160
+ const code = listRegions(db, undefined, "code", undefined, space);
161
+ const found = findMacroUses(byteAt, code, (address) => semantic.get(address) ?? platform.get(address));
162
+ const named = new Set([...listSymbols(db, undefined, undefined, undefined, space).map((symbol) => symbol.address), ...listReferences(db, undefined, undefined, undefined, space).map((reference) => reference.to)]);
163
+ const patches = listPatches(db, undefined, undefined, undefined, space);
164
+ const uses = listMacroUses(db, undefined, undefined, undefined, space);
165
+ const candidates: MacroCandidate[] = [];
166
+ let known = 0;
167
+ let leftOut = 0;
168
+ for (const candidate of found) {
169
+ const same = uses.find((use) => use.start === candidate.start && use.end === candidate.end && use.macro === candidate.macro && use.args.join(",") === candidate.args.join(","));
170
+ if (same !== undefined) known++;
171
+ else if ([...named].some((address) => address > candidate.start && address <= candidate.end) || patches.some((patch) => rangesOverlap(patch, candidate)) || uses.some((use) => rangesOverlap(use, candidate))) leftOut++;
172
+ else candidates.push(candidate);
168
173
  }
174
+ // A macro of the catalogue goes into the writes unless the knowledge has it; with another body, its uses stay out.
175
+ const macros = new Map(listMacros(db, undefined, space).map((macro) => [macro.name, macro]));
176
+ const writes: BatchOperation[] = [];
177
+ const other = new Set<string>();
178
+ const chosen = candidates.filter((candidate) => !skip.has(candidate.start));
179
+ for (const idiom of CATALOGUE.filter((item) => chosen.some((candidate) => candidate.macro === item.name))) {
180
+ const existing = macros.get(idiom.name);
181
+ if (existing === undefined) writes.push({ op: "macro", space, name: idiom.name, params: [...idiom.params], body: idiom.body, comment: idiom.comment });
182
+ else if (existing.params.join(",") !== idiom.params.join(",") || existing.body !== idiom.body) other.add(idiom.name);
183
+ }
184
+ for (const candidate of chosen) {
185
+ if (other.has(candidate.macro)) continue;
186
+ writes.push({ op: "use", space, start: candidate.start, end: candidate.end, macro: candidate.macro, args: candidate.args });
187
+ }
188
+ const notCandidates = [...skip].filter((address) => !candidates.some((candidate) => candidate.start === address)).sort((a, b) => a - b);
189
+ return { candidates, known, leftOut, writes, skipped: candidates.length - chosen.length, notCandidates, otherMacros: [...other].map((name) => `The knowledge has another macro ${name}: its candidates are not written.`) };
190
+ }
191
+
192
+ /** The facts of a range with $ addresses; the references are a list that --max-listed cuts. */
193
+ function showFacts(facts: RangeFacts, max: number) {
194
+ return {
195
+ ...(facts.access === undefined ? {} : { access: facts.access }),
196
+ references: listed(facts.references, max, (reference) => ({ from: formatC64Address(reference.from), kind: reference.kind })),
197
+ ...(facts.reachable === undefined ? {} : { reachable: facts.reachable }),
198
+ };
199
+ }
200
+
201
+ /** A conflict of code and data, with the facts of its range; a conflict that evidence decided, or of a name, has no facts. */
202
+ function showConflictFacts(conflict: ImportConflict, analyzer: Analyzer, factsOf: (range: { start: number; end: number }) => RangeFacts, max: number): Record<string, unknown> {
203
+ const shown = showConflict(conflict, analyzer);
204
+ if (conflict.category === "region") return { ...shown, ...showFacts(factsOf(conflict), max) };
205
+ if (conflict.category === "symbol" && conflict.reason === "kind") return { ...shown, ...showFacts(factsOf({ start: conflict.address, end: conflict.address }), max) };
206
+ return shown;
207
+ }
208
+
209
+ /**
210
+ * The facts of the ranges of the conflicts, from the knowledge after both
211
+ * imports: the coverage, the references, and the flow from executed code
212
+ * through the program, which ends in data of the user or the LLM.
213
+ */
214
+ function conflictFacts(db: DatabaseSync | undefined, space: string, memory: Uint8Array, inImage: (address: number) => boolean, coverage: Uint8Array | undefined): (range: { start: number; end: number }) => RangeFacts {
215
+ const references = listReferences(db, undefined, undefined, undefined, space);
216
+ const data = listRegions(db, undefined, undefined, [...SEMANTIC_ORIGINS], space).filter((region) => !CODE_REGION_TYPES.includes(region.type) && region.type !== "dual-use");
217
+ const isData = (address: number) => data.some((region) => address >= region.start && address <= region.end);
218
+ const { removedReference } = decidedFromKnowledge(db, space);
219
+ // The flow is computed only when a conflict asks for it.
220
+ let flow: Set<number> | undefined;
221
+ return (range) => {
222
+ if (coverage !== undefined) flow ??= flowFromExecuted({ memory, inImage, coverage, references, isData, removedReference });
223
+ return rangeFacts(coverage, references, flow)(range);
224
+ };
169
225
  }
170
226
 
171
227
  /** One conflict: what the knowledge has, and what the analyzer found, under the analyzer's name. */
172
228
  function showConflict(conflict: ImportConflict, analyzer: Analyzer): Record<string, unknown> {
173
229
  if (conflict.category === "code-evidence") {
174
230
  return {
175
- range: { start: formatC64Address(conflict.start), end: formatC64Address(conflict.end) },
231
+ range: formatC64RangeFields(conflict),
176
232
  [analyzer]: conflict.finding,
177
233
  ...(conflict.executed === undefined ? {} : { executed: formatC64Address(conflict.executed) }),
178
234
  ...(conflict.symbol === undefined ? {} : { knowledge: { ...conflict.symbol, address: formatC64Address(conflict.symbol.address) } }),
@@ -188,7 +244,7 @@ function showConflict(conflict: ImportConflict, analyzer: Analyzer): Record<stri
188
244
  };
189
245
  }
190
246
  return {
191
- range: { start: formatC64Address(conflict.start), end: formatC64Address(conflict.end) },
247
+ range: formatC64RangeFields(conflict),
192
248
  knowledge: conflict.current,
193
249
  [analyzer]: conflict.finding,
194
250
  problem: "code and data disagree",
@@ -212,8 +268,8 @@ function record(findings: NormalizedFindings, revision: string, description: str
212
268
  }
213
269
  return {
214
270
  revision: imported.revision,
215
- changes: { names: imported.names, ...(imported.symbols.retired === 0 ? {} : { symbols: { retired: imported.symbols.retired } }), regions: imported.regions, references: imported.references },
216
- conflicts: imported.conflicts.map((conflict) => showConflict(conflict, findings.analyzer)),
271
+ changes: { names: imported.names, regions: imported.regions, references: imported.references },
272
+ conflicts: imported.conflicts,
217
273
  };
218
274
  }
219
275
 
@@ -240,65 +296,72 @@ async function analyze(call: Call): Promise<unknown> {
240
296
  const { bytes, kind: imageKind } = analyzedBytes(program);
241
297
  // The analyzer sees all bytes it gets; the coverage seeds only the program, as c64-source does.
242
298
  const byteAt = imageReader(bytes, imageKind);
243
- const inProgram: ImageByte = (address) => (program.segments.some((segment) => address >= segment.start && address <= segment.end) ? program.byteAt(address) : undefined);
299
+ const inProgram: ImageByte = (address) => (inRanges(program.segments, address) ? program.byteAt(address) : undefined);
244
300
  // With coverage, a code finding over an executed instruction start replaces the data of the other analyzer.
245
301
  const executed = coverage === undefined ? {} : { executed: (address: number) => (coverage[address]! & COVERAGE.ramExecute) !== 0 };
246
302
  const loaded = imageKind === "flat64k" ? { start: 0x0000, end: 0xffff } : prgRange(bytes);
247
303
  // The idioms read only the program: a table that runs past a segment gets no targets from the 0 bytes of the 64 KiB.
248
- const idioms = findIdioms(inProgram, { start: loaded.start, end: loaded.end }, covered);
304
+ // The regions and the removals of the user and the LLM win over the idioms.
305
+ const idioms = findIdioms(inProgram, { start: loaded.start, end: loaded.end }, covered, decidedFromKnowledge(reader, space));
249
306
 
250
307
  const revision = currentRevision(reader);
251
308
  const seeds = seedsFromKnowledge(reader, entries, space, executed.executed);
252
- // Knowledge routines and --entry first, then code regions and JMP tables, then idioms, then coverage, up to the seed bound:
253
- // at most DECOMPILER_LIMITS.entryPoints (1024) entry points for both analyzers, and for the decompiler at most
254
- // DECOMPILER_LIMITS.codeStarts (8192) coverage flow starts that are code in a routine. coverageSeeds gives what was used.
255
309
  const fromCoverage = coverage === undefined ? [] : coverageEntries(coverage, inProgram);
256
310
  const known = [...seeds.entryPoints, ...codeEntries(reader, byteAt, space)];
257
- // The decompiler takes the coverage as code starts without a function; DXA has one list.
258
- const kinds = analyzer === "dxa" || coverage === undefined ? { routines: fromCoverage, codeStarts: [] } : coverageSeedKinds(coverage, inProgram);
259
- const ordered = [...new Set([...known, ...idioms.entryPoints, ...kinds.routines])];
260
- seeds.entryPoints = ordered.slice(0, DECOMPILER_LIMITS.entryPoints).sort((a, b) => a - b);
261
- const allCodeStarts = kinds.codeStarts.filter((entry) => !seeds.entryPoints.includes(entry));
262
- const codeStarts = allCodeStarts.slice(0, DECOMPILER_LIMITS.codeStarts);
263
311
  // Idiom tables and the RAM under ROM that the runs never used are data for this run too; semantic data ranges come first.
264
312
  // A range with an entry point of the knowledge or --entry in it is left out: that code stays code.
265
313
  const fromRom = coverage === undefined ? [] : romOnlyRanges(coverage, byteAt).filter((range) => !known.some((entry) => entry >= range.start && entry <= range.end));
266
314
  const dataRanges = [...seeds.dataRanges];
267
315
  for (const range of [...idioms.dataRanges, ...fromRom]) if (!dataRanges.some((seed) => range.start <= seed.end && range.end >= seed.start)) dataRanges.push(range);
268
316
  seeds.dataRanges = dataRanges.slice(0, DECOMPILER_LIMITS.dataRanges);
317
+ // Knowledge routines and --entry first, then code regions and JMP tables, then idioms, then coverage, up to the seed bound:
318
+ // at most DECOMPILER_LIMITS.entryPoints (1024) entry points for both analyzers, and for the decompiler at most
319
+ // DECOMPILER_LIMITS.codeStarts (8192) coverage flow starts that are code in a routine. coverageSeeds gives what was used.
320
+ // The decompiler takes the coverage as code starts without a function. DXA has one list, without the coverage starts
321
+ // that it reaches by fall-through from another seed, for example the instruction after a JSR.
322
+ const fallThrough = (from: readonly number[]) => (coverage === undefined ? new Set<number>() : dxaFallThrough(from, coverage, inProgram, seeds.dataRanges));
323
+ const reached = analyzer === "dxa" ? fallThrough([...known, ...idioms.entryPoints, ...fromCoverage]) : new Set<number>();
324
+ const kinds = analyzer === "dxa" || coverage === undefined ? { routines: fromCoverage.filter((entry) => !reached.has(entry)), codeStarts: [] } : coverageSeedKinds(coverage, inProgram);
325
+ const ordered = [...new Set([...known, ...idioms.entryPoints, ...kinds.routines])];
326
+ seeds.entryPoints = ordered.slice(0, DECOMPILER_LIMITS.entryPoints).sort((a, b) => a - b);
327
+ const allCodeStarts = kinds.codeStarts.filter((entry) => !seeds.entryPoints.includes(entry));
328
+ const codeStarts = allCodeStarts.slice(0, DECOMPILER_LIMITS.codeStarts);
269
329
  // The seeds over the limits of the analyzer: it never sees them.
270
- const overLimit = { entryPoints: Math.max(0, ordered.length - DECOMPILER_LIMITS.entryPoints), codeStarts: allCodeStarts.length - codeStarts.length, dataRanges: Math.max(0, dataRanges.length - DECOMPILER_LIMITS.dataRanges) };
330
+ const cut = { analyzer, entryPoints: ordered.slice(DECOMPILER_LIMITS.entryPoints), codeStarts: allCodeStarts.slice(DECOMPILER_LIMITS.codeStarts), dataRanges: dataRanges.slice(DECOMPILER_LIMITS.dataRanges) };
331
+ const overLimit = { entryPoints: cut.entryPoints.length, codeStarts: cut.codeStarts.length, dataRanges: cut.dataRanges.length };
271
332
  const romUsed = fromRom.filter((range) => seeds.dataRanges.includes(range)).length;
272
- const coverageUsed = fromCoverage.filter((entry) => seeds.entryPoints.includes(entry) || codeStarts.includes(entry)).length;
333
+ // DXA also decodes a coverage start that it did not get, when a seed that it got reaches the start by fall-through.
334
+ const followed = analyzer === "dxa" ? fallThrough(seeds.entryPoints) : new Set<number>();
335
+ const coverageUsed = fromCoverage.filter((entry) => seeds.entryPoints.includes(entry) || codeStarts.includes(entry) || followed.has(entry)).length;
273
336
  // Platform names are C64 names: drive code and banks get none.
274
337
  const platform = space === DEFAULT_SPACE ? platformNames() : [];
275
338
  /** The analyzer version of the last analysis of these bytes: a new version can change the findings by itself. */
276
339
  const lastVersion = reader === undefined ? undefined : lastToolVersion(reader, analyzer, bytes);
277
340
  reader?.close();
278
- /** Imports the idioms as their own revision, after the analyzer's, and gives their part of the result. */
279
- const idiomsResult = () => {
280
- const imported = withWrite((db) => importFindings(db, { ...idioms.findings, space }, { description: "Idioms in the program" }));
341
+ /** Imports the idioms as their own revision, after the analyzer's. */
342
+ const importIdioms = () => withWrite((db) => importFindings(db, { ...idioms.findings, space }, { description: "Idioms in the program" }));
343
+ /** The idioms part of a result, from the knowledge after both imports. */
344
+ const idiomsResult = (db: DatabaseSync | undefined, imported: ImportResult) => {
281
345
  // The macro candidates read the code regions after both imports.
282
- const macros = macroCandidates(space, byteAt, romUseOfProgram(coverage, program.state), skip);
283
- // With --apply-macros, the candidates and their macros are a third revision of the LLM.
284
- const platformNamed = new Map(platformNames().map((entry) => [entry.name, entry.address]));
285
- const written = applyMacros && macros.writes.length > 0 ? withWrite((db) => applyBatch(db, { origin: "llm", description: "Macro candidates in the program", image: operandImages(db, platformNamed) }, macros.writes)) : undefined;
346
+ const macros = macroCandidates(db, space, byteAt, romUseOfProgram(coverage, program.state), skip);
347
+ // With --apply-macros, the candidates and their macros are a third revision of the LLM. It writes only macros and their uses, which the reads below do not read.
348
+ const written = applyMacros && macros.writes.length > 0 ? withWrite((write) => applyBatch(write, { origin: "llm", description: "Macro candidates in the program", image: operandImages(write, platformAddresses()) }, macros.writes)) : undefined;
286
349
  // Platform pitfalls are C64 facts: drive code and banks get none. Pitfalls and pointers read the code regions after both imports.
287
- const codeDb = openForRead();
288
- const code = listRegions(codeDb, undefined, "code", undefined, space);
350
+ const code = listRegions(db, undefined, "code", undefined, space);
289
351
  const pitfalls = space === DEFAULT_SPACE ? findPitfalls(byteAt, code) : [];
290
352
  const pointers = findPointers(byteAt, { start: loaded.start, end: loaded.end }, code, {
291
353
  platform: (address) => platform.some((entry) => address >= entry.address && address <= entry.end),
292
- sprites: listRegions(codeDb, undefined, "sprite", undefined, space),
354
+ sprites: listRegions(db, undefined, "sprite", undefined, space),
293
355
  });
294
- codeDb?.close();
356
+ const factsOf = conflictFacts(db, space, program.memory, (address) => inProgram(address) !== undefined, coverage);
295
357
  return {
358
+ factsOf,
296
359
  idioms: {
297
360
  ...idioms.counts,
298
361
  revision: imported.revision,
299
362
  changes: { regions: imported.regions, references: imported.references },
300
- conflicts: imported.conflicts.map((conflict) => showConflict(conflict, "heuristic")),
301
- ...(idioms.leftOut.length === 0 ? {} : { leftOut: listed(idioms.leftOut, max, (item) => ({ start: formatC64Address(item.start), end: formatC64Address(item.end), kind: item.kind, reason: item.reason })) }),
363
+ conflicts: imported.conflicts.map((conflict) => showConflictFacts(conflict, "heuristic", factsOf, max)),
364
+ ...(idioms.leftOut.length === 0 ? {} : { leftOut: listed(idioms.leftOut, max, (item) => ({ ...formatC64RangeFields(item), kind: item.kind, reason: item.reason })) }),
302
365
  // Candidates are not knowledge: a larger --max-listed gives more of them.
303
366
  candidates: {
304
367
  dop: listed(idioms.candidates.dop, max, formatC64Address, "a larger --max-listed"),
@@ -319,21 +382,53 @@ async function analyze(call: Call): Promise<unknown> {
319
382
  };
320
383
  };
321
384
  /** The coverage part of a result: its seeds, and the analyzer data that it shows to be code. */
322
- const coverageResult = () => {
385
+ const coverageResult = (db: DatabaseSync | undefined) => {
323
386
  if (coverage === undefined) return {};
324
- const db = openForRead();
325
387
  const conflicts = coverageConflicts(db, coverage);
326
- db?.close();
327
388
  return {
328
389
  coverageSeeds: { entryPoints: fromCoverage.length, used: coverageUsed, romOnlyRanges: fromRom.length, romOnlyUsed: romUsed },
329
390
  coverageConflicts: conflicts.map(({ region, executed }) => ({
330
- range: { start: formatC64Address(region.start), end: formatC64Address(region.end) },
391
+ range: formatC64RangeFields(region),
331
392
  knowledge: { type: region.type, origin: region.origin },
332
393
  executed,
333
394
  problem: "coverage shows code",
334
395
  })),
335
396
  };
336
397
  };
398
+ /**
399
+ * The result from the knowledge after both imports: the fields of both
400
+ * analyzers around the fields that only one gives (`gaps` after the
401
+ * coverage, `tail` after the idioms), and the hint.
402
+ */
403
+ const resultOf = (
404
+ db: DatabaseSync | undefined,
405
+ run: { toolVersion: string | undefined; imported: ReturnType<typeof record>; report: SeedReport; seeds: ReturnType<typeof seedsResult>; found: ReturnType<typeof idiomsResult>; gaps?: Record<string, unknown>; tail: Record<string, unknown> },
406
+ ) => {
407
+ const runOnWritten = coverage === undefined ? [] : writtenNotExecuted(db, analyzer, coverage, space);
408
+ const { factsOf, ...found } = run.found;
409
+ const body = {
410
+ analyzer,
411
+ ...(run.toolVersion === undefined ? {} : { analyzerVersion: run.toolVersion }),
412
+ ...(space === DEFAULT_SPACE ? {} : { space }),
413
+ ...run.imported,
414
+ conflicts: run.imported.conflicts.map((conflict) => showConflictFacts(conflict, analyzer, factsOf, max)),
415
+ seeds: run.seeds,
416
+ ...coverageResult(db),
417
+ ...run.gaps,
418
+ ...(runOnWritten.length === 0 ? {} : { writtenNotExecuted: listed(runOnWritten, max, showWritten) }),
419
+ ...found,
420
+ ...run.tail,
421
+ };
422
+ return withHint(body, {
423
+ conflicts: run.imported.conflicts.length + found.idioms.conflicts.length,
424
+ coverageConflicts: body.coverageConflicts?.length ?? 0,
425
+ macros: { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision },
426
+ version: { now: run.toolVersion, last: lastVersion, revision: run.imported.revision },
427
+ retiredReferences: run.imported.changes.references.retired,
428
+ guards: { refused: toCorrect(run.report.refused, entries), writtenNotExecuted: runOnWritten.length },
429
+ cut,
430
+ });
431
+ };
337
432
  if (analyzer === "dxa") {
338
433
  const { result, attachments, seeds: report } = await analyzeWithDxa({ imageKind, ...seeds }, bytes, localToolContext());
339
434
  const listing = attachments[0]!.toString("utf8");
@@ -348,73 +443,70 @@ async function analyze(call: Call): Promise<unknown> {
348
443
  throw new WireFailure(isRefusal(error) ? error.code : "operation-failed", `The script did not write the listing to ${listingPath}: ${(error as Error).message.replace(/\.$/, "")}. ${recorded}`);
349
444
  }
350
445
  }
351
- const found = idiomsResult();
352
- const runOnWritten = writtenNotExecutedOf("dxa", space, coverage);
353
- const body = {
354
- analyzer: "dxa",
355
- ...(result.toolVersion === undefined ? {} : { analyzerVersion: result.toolVersion }),
356
- ...(space === DEFAULT_SPACE ? {} : { space }),
357
- ...imported,
358
- seeds: seedsResult({ entryPoints: seeds.entryPoints.length, dataRanges: seeds.dataRanges.length }, { entryPoints: overLimit.entryPoints, dataRanges: overLimit.dataRanges }, report, max),
359
- ...coverageResult(),
360
- ...(runOnWritten.length === 0 ? {} : { writtenNotExecuted: listed(runOnWritten, max, showWritten) }),
361
- ...found,
362
- coverage: result.coverage.map((range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) })),
363
- regions: listed(result.regions, max, (region) => ({ start: formatC64Address(region.start), end: formatC64Address(region.end), classification: region.classification }), ALL_REGIONS),
364
- labels: listed(result.labels, max, (label) => ({ address: formatC64Address(label.address), name: label.name }), ALL_NAMES),
365
- ...(written === undefined ? {} : { listing: written }),
366
- };
367
- return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision }, imported.changes.references.retired, { refused: toCorrect(report.refused, entries), writtenNotExecuted: runOnWritten.length });
446
+ const idiomsImported = importIdioms();
447
+ return withRead((db) =>
448
+ resultOf(db, {
449
+ toolVersion: result.toolVersion,
450
+ imported,
451
+ report,
452
+ seeds: seedsResult({ entryPoints: seeds.entryPoints.length, dataRanges: seeds.dataRanges.length }, { entryPoints: overLimit.entryPoints, dataRanges: overLimit.dataRanges }, report, max),
453
+ found: idiomsResult(db, idiomsImported),
454
+ tail: {
455
+ coverage: result.coverage.map(formatC64RangeFields),
456
+ regions: listed(result.regions, max, (region) => ({ ...formatC64RangeFields(region), classification: region.classification }), ALL_REGIONS),
457
+ labels: listed(result.labels, max, (label) => ({ address: formatC64Address(label.address), name: label.name }), ALL_NAMES),
458
+ ...(written === undefined ? {} : { listing: written }),
459
+ },
460
+ }),
461
+ );
368
462
  }
369
463
 
370
464
  const { result, seeds: report } = await analyzeWithDecompiler({ imageKind, ...seeds, codeStarts, decompile }, bytes, localToolContext());
371
465
  // Executed instruction starts that the decompiler did not decode: the instruction list and the source miss them.
372
466
  const decoded = new Set(result.instructions.map((instruction) => instruction.address));
373
467
  const imported = record({ ...decompilerFindings(result), space, ...executed }, revision, "Decompiler analysis of the program", runProvenance(bytes, result.toolVersion));
374
- const found = idiomsResult();
375
- // A start inside a dual-use region is a known overlap, for example the second instruction of a BIT skip: one list cannot hold both.
376
- // Read after the idioms, which write those regions.
377
- const overlapDb = coverage === undefined ? undefined : openForRead();
378
- const overlaps = listRegions(overlapDb, undefined, "dual-use", undefined, space);
379
- overlapDb?.close();
380
- const gaps = coverage === undefined ? [] : executedStarts(coverage, inProgram).filter((address) => address >= loaded.start && address <= loaded.end && !decoded.has(address) && !overlaps.some((region) => address >= region.start && address <= region.end));
381
- // The data ranges that the decompiler used: not the ranges that hold a seed, and only the part in the program.
382
- const explained = explainGaps(gaps, result.instructions, report.refused, report.dataRanges);
383
- const runOnWritten = writtenNotExecutedOf("decompiler", space, coverage);
384
- let instructions: Record<string, unknown> | undefined;
385
- if (instructionsPath !== undefined) {
386
- const list = instructionList(result.instructions, coverage);
387
- instructions = { count: list.length, ...writeReported(instructionsPath, `${JSON.stringify(list, null, 1)}\n`, { what: "--out-instructions" }) };
388
- }
389
- const body = {
390
- analyzer: "decompiler",
391
- ...(result.toolVersion === undefined ? {} : { analyzerVersion: result.toolVersion }),
392
- ...(space === DEFAULT_SPACE ? {} : { space }),
393
- ...imported,
394
- seeds: seedsResult({ entryPoints: seeds.entryPoints.length, codeStarts: codeStarts.length, dataRanges: seeds.dataRanges.length }, overLimit, report, max),
395
- ...coverageResult(),
396
- ...(coverage === undefined ? {} : { coverageGaps: listed(explained, max, showGap, "a larger --max-listed") }),
397
- ...(runOnWritten.length === 0 ? {} : { writtenNotExecuted: listed(runOnWritten, max, showWritten) }),
398
- ...found,
399
- ...(instructions === undefined ? {} : { instructions }),
400
- coverage: result.coverage.map((range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) })),
401
- functions: listed(result.functions, max, (fn) => ({ entry: formatC64Address(fn.entry), name: fn.name }), ALL_NAMES),
402
- decompilations: result.decompilations.map((item) => ({ entry: formatC64Address(item.entry), text: item.text, ...(item.truncated ? { truncated: true } : {}) })),
403
- ...((result.notDecompiled ?? []).length === 0
404
- ? {}
405
- : { notDecompiled: result.notDecompiled!.map((item) => ({ entry: formatC64Address(item.entry), reason: item.reason })) }),
406
- };
407
- return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision }, imported.changes.references.retired, { refused: toCorrect(report.refused, entries), writtenNotExecuted: runOnWritten.length });
468
+ const idiomsImported = importIdioms();
469
+ return withRead((db) => {
470
+ const found = idiomsResult(db, idiomsImported);
471
+ // A start inside a dual-use region is a known overlap, for example the second instruction of a BIT skip: one list cannot hold both.
472
+ // Read after the idioms, which write those regions.
473
+ const overlaps = coverage === undefined ? [] : listRegions(db, undefined, "dual-use", undefined, space);
474
+ const gaps = coverage === undefined ? [] : executedStarts(coverage, inProgram).filter((address) => address >= loaded.start && address <= loaded.end && !decoded.has(address) && !inRanges(overlaps, address));
475
+ // The data ranges that the decompiler used: not the ranges that hold a seed, and only the part in the program.
476
+ const explained = explainGaps(gaps, result.instructions, report.refused, report.dataRanges);
477
+ let instructions: Record<string, unknown> | undefined;
478
+ if (instructionsPath !== undefined) {
479
+ const list = instructionList(result.instructions, coverage);
480
+ instructions = { count: list.length, ...writeReported(instructionsPath, `${JSON.stringify(list, null, 1)}\n`, { what: "--out-instructions" }) };
481
+ }
482
+ return resultOf(db, {
483
+ toolVersion: result.toolVersion,
484
+ imported,
485
+ report,
486
+ seeds: seedsResult({ entryPoints: seeds.entryPoints.length, codeStarts: codeStarts.length, dataRanges: seeds.dataRanges.length }, overLimit, report, max),
487
+ found,
488
+ gaps: coverage === undefined ? {} : { coverageGaps: listed(explained, max, showGap, "a larger --max-listed") },
489
+ tail: {
490
+ ...(instructions === undefined ? {} : { instructions }),
491
+ coverage: result.coverage.map(formatC64RangeFields),
492
+ functions: listed(result.functions, max, (fn) => ({ entry: formatC64Address(fn.entry), name: fn.name }), ALL_NAMES),
493
+ decompilations: result.decompilations.map((item) => ({ entry: formatC64Address(item.entry), text: item.text, ...(item.truncated ? { truncated: true } : {}) })),
494
+ ...((result.notDecompiled ?? []).length === 0
495
+ ? {}
496
+ : { notDecompiled: result.notDecompiled!.map((item) => ({ entry: formatC64Address(item.entry), reason: item.reason })) }),
497
+ },
498
+ });
499
+ });
408
500
  }
409
501
 
410
502
  /** A coverage gap with $ addresses. */
411
503
  function showGap(gap: GapReason) {
412
- return { address: formatC64Address(gap.address), reason: gap.reason, ...(gap.at === undefined ? {} : { at: formatC64Address(gap.at) }), ...(gap.range === undefined ? {} : { range: { start: formatC64Address(gap.range.start), end: formatC64Address(gap.range.end) } }) };
504
+ return { address: formatC64Address(gap.address), reason: gap.reason, ...(gap.at === undefined ? {} : { at: formatC64Address(gap.at) }), ...(gap.range === undefined ? {} : { range: formatC64RangeFields(gap.range) }) };
413
505
  }
414
506
 
415
507
  /** A range of writtenNotExecuted with $ addresses. */
416
508
  function showWritten(range: { start: number; end: number; from: number[] }) {
417
- return { start: formatC64Address(range.start), end: formatC64Address(range.end), from: range.from.map(formatC64Address) };
509
+ return { ...formatC64RangeFields(range), from: range.from.map(formatC64Address) };
418
510
  }
419
511
 
420
512
  await runScript({