@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
@@ -10,30 +10,15 @@
10
10
  //: where a run executed an instruction start, a code finding replaces
11
11
  // the data of another analyzer, never of the user, the LLM or a heuristic.
12
12
 
13
- import { createHash } from "node:crypto";
14
13
  import type { DatabaseSync } from "node:sqlite";
15
14
 
16
- import { type AddressRange, formatC64Address } from "../c64.ts";
15
+ import { type AddressRange, formatC64Address, formatC64Range, inRanges, mergeRanges, rangesOverlap, type ReferenceKind, REFERENCE_KINDS, subtract, SYMBOL_NAME } from "../c64.ts";
17
16
  import { Refusal } from "../errors.ts";
18
17
  import { transaction } from "./database.ts";
19
- import {
20
- analyzerNamed,
21
- REFERENCE_COLUMNS,
22
- referenceSuppressed,
23
- regionsOverlapping,
24
- suppressionsOverlapping,
25
- SYMBOL_COLUMNS,
26
- symbolAt,
27
- toReference,
28
- toSymbol,
29
- type ReferenceRow,
30
- type RegionRow,
31
- type SymbolRow,
32
- } from "./read.ts";
33
- import { ANALYZERS, CODE_REGION_TYPES, DEFAULT_SPACE, POINTER_KIND, REFERENCE_KINDS, REGION_TYPES, SEMANTIC_ORIGINS, SYMBOL_KINDS, type Analyzer, type Origin, type ReferenceKind, type RegionType, type Space, type SymbolKind } from "./schema.ts";
34
- import { Change, checkAddress, checkSpace, subtract, SYMBOL_NAME, type Evidence } from "./write.ts";
35
-
36
-
18
+ import { analyzerNamed, FACTS, referenceSuppressed, regionsOverlapping, suppressionsOverlapping, symbolAt, type ReferenceRow, type RegionRow, type SymbolRow } from "./read.ts";
19
+ import { ANALYZERS, CODE_REGION_TYPES, DEFAULT_SPACE, POINTER_KIND, REGION_TYPES, SEMANTIC_ORIGINS, SYMBOL_KINDS, type Analyzer, type Origin, type RegionType, type Space, type SymbolKind } from "./schema.ts";
20
+ import { sha256 } from "./text.ts";
21
+ import { Change, checkAddress, checkSpace, type Evidence } from "./write.ts";
37
22
 
38
23
  export interface NormalizedFindings {
39
24
  analyzer: Analyzer;
@@ -65,7 +50,7 @@ export interface ImportContext {
65
50
 
66
51
  /** What a revision records about one analyzer run: the hash of the image bytes and, when the analyzer tells it, its version. */
67
52
  export function runProvenance(image: Uint8Array, toolVersion: string | undefined): Pick<ImportContext, "inputHash" | "toolVersion"> {
68
- const inputHash = createHash("sha256").update(image).digest("hex");
53
+ const inputHash = sha256(image);
69
54
  return toolVersion === undefined ? { inputHash } : { inputHash, toolVersion };
70
55
  }
71
56
 
@@ -111,9 +96,10 @@ export interface ImportResult {
111
96
  revision: string | null;
112
97
  /** The analyzer names. */
113
98
  names: ImportCounts;
114
- /** The analyzer's own rows from an older version that the run closed in symbols: only `retired` counts. */
115
- symbols: ImportCounts;
116
- regions: ImportCounts;
99
+ regions: ImportCounts & {
100
+ /** Data findings on executed code that the knowledge holds as code: not written, and no conflict. */
101
+ onExecutedCode: number;
102
+ };
117
103
  references: ImportCounts & {
118
104
  /** Findings from an address in a data region of the user, the LLM or a heuristic: false code, not written. */
119
105
  inData: number;
@@ -129,33 +115,21 @@ function invalid(message: string): never {
129
115
  throw new Refusal("invalid-input", `The analyzer result is not usable: ${message} Nothing was imported.`);
130
116
  }
131
117
 
132
- /** Sorted, merged coverage ranges. */
133
- function mergeCoverage(coverage: AddressRange[]): AddressRange[] {
134
- const sorted = [...coverage].sort((a, b) => a.start - b.start);
135
- const merged: AddressRange[] = [];
136
- for (const range of sorted) {
137
- const last = merged.at(-1);
138
- if (last !== undefined && range.start <= last.end + 1) last.end = Math.max(last.end, range.end);
139
- else merged.push({ ...range });
140
- }
141
- return merged;
142
- }
143
-
144
118
  /**
145
119
  * Checks complete findings before anything is written. Every finding
146
120
  * lies in coverage, names are valid and unique, regions do not overlap.
147
121
  * Returns the merged coverage.
148
122
  */
149
- export function validateFindings(findings: NormalizedFindings): AddressRange[] {
123
+ function validateFindings(findings: NormalizedFindings): AddressRange[] {
150
124
  if (!(ANALYZERS as readonly string[]).includes(findings.analyzer)) invalid(`the analyzer must be one of ${ANALYZERS.join(", ")}.`);
151
125
  checkSpace(findings);
152
126
  if (!Array.isArray(findings.coverage) || findings.coverage.length === 0) invalid("the result has no coverage.");
153
127
  for (const range of findings.coverage) {
154
128
  checkAddress(range.start, "coverage start");
155
129
  checkAddress(range.end, "coverage end");
156
- if (range.end < range.start) invalid(`coverage ${formatC64Address(range.start)}-${formatC64Address(range.end)} ends before it starts.`);
130
+ if (range.end < range.start) invalid(`coverage ${formatC64Range(range)} ends before it starts.`);
157
131
  }
158
- const coverage = mergeCoverage(findings.coverage);
132
+ const coverage = mergeRanges(findings.coverage);
159
133
  const covering = (start: number, end: number) => coverage.some((range) => range.start <= start && end <= range.end);
160
134
 
161
135
  const addresses = new Set<number>();
@@ -174,8 +148,8 @@ export function validateFindings(findings: NormalizedFindings): AddressRange[] {
174
148
  regions.forEach((region, index) => {
175
149
  checkAddress(region.start, "region start");
176
150
  checkAddress(region.end, "region end");
177
- if (region.end < region.start) invalid(`the region ${formatC64Address(region.start)}-${formatC64Address(region.end)} ends before it starts.`);
178
- if (!covering(region.start, region.end)) invalid(`the region ${formatC64Address(region.start)}-${formatC64Address(region.end)} is not inside the coverage.`);
151
+ if (region.end < region.start) invalid(`the region ${formatC64Range(region)} ends before it starts.`);
152
+ if (!covering(region.start, region.end)) invalid(`the region ${formatC64Range(region)} is not inside the coverage.`);
179
153
  if (!(REGION_TYPES as readonly string[]).includes(region.type)) invalid(`the region type ${region.type} is not known.`);
180
154
  const previous = regions[index - 1];
181
155
  if (previous !== undefined && region.start <= previous.end) invalid(`the regions at ${formatC64Address(previous.start)} and ${formatC64Address(region.start)} overlap.`);
@@ -190,44 +164,30 @@ export function validateFindings(findings: NormalizedFindings): AddressRange[] {
190
164
  return coverage;
191
165
  }
192
166
 
193
- function ownSymbols(db: DatabaseSync, analyzer: Analyzer, range: AddressRange, space: Space): SymbolRow[] {
194
- return db
195
- .prepare(`SELECT ${SYMBOL_COLUMNS} FROM current_symbols WHERE space = ? AND origin = ? AND address BETWEEN ? AND ? ORDER BY address`)
196
- .all(space, analyzer, range.start, range.end)
197
- .map((row) => toSymbol(row as Record<string, unknown>));
198
- }
199
-
200
167
  function ownReferences(db: DatabaseSync, analyzer: Analyzer, range: AddressRange, space: Space): ReferenceRow[] {
201
168
  return db
202
- .prepare(`SELECT ${REFERENCE_COLUMNS} FROM current_references WHERE space = ? AND origin = ? AND from_address BETWEEN ? AND ? ORDER BY from_address`)
169
+ .prepare(`SELECT ${FACTS.references.columns} FROM current_references WHERE space = ? AND origin = ? AND from_address BETWEEN ? AND ? ORDER BY from_address`)
203
170
  .all(space, analyzer, range.start, range.end)
204
- .map((row) => toReference(row as Record<string, unknown>));
171
+ .map((row) => FACTS.references.map(row as Record<string, unknown>));
205
172
  }
206
173
 
207
174
  function ownNames(db: DatabaseSync, analyzer: Analyzer, range: AddressRange, space: Space): SymbolRow[] {
208
175
  return db
209
- .prepare(`SELECT ${SYMBOL_COLUMNS} FROM current_analyzer_names WHERE space = ? AND origin = ? AND address BETWEEN ? AND ? ORDER BY address`)
176
+ .prepare(`SELECT ${FACTS.analyzer_names.columns} FROM current_analyzer_names WHERE space = ? AND origin = ? AND address BETWEEN ? AND ? ORDER BY address`)
210
177
  .all(space, analyzer, range.start, range.end)
211
- .map((row) => toSymbol(row as Record<string, unknown>));
178
+ .map((row) => FACTS.analyzer_names.map(row as Record<string, unknown>));
212
179
  }
213
180
 
214
181
  /**
215
182
  * The names of an analyzer are second names: they go to analyzer_names,
216
183
  * one for each analyzer at an address, and never to symbols. A run replaces
217
- * the analyzer's own names in its coverage, and closes the analyzer's old rows
218
- * in symbols there (knowledge from an older version). A name that the user or the LLM
184
+ * the analyzer's own names in its coverage. A name that the user or the LLM
219
185
  * gave the address already is not kept twice. A code or data kind that
220
186
  * disagrees with the name of the address is a conflict.
221
187
  */
222
188
  function importNames(db: DatabaseSync, change: Change, findings: NormalizedFindings, coverage: AddressRange[], result: ImportResult): void {
223
189
  const { analyzer } = findings;
224
190
  const space = findings.space ?? DEFAULT_SPACE;
225
- for (const range of coverage) {
226
- for (const own of ownSymbols(db, analyzer, range, space)) {
227
- change.close("symbols", "space = ? AND address = ? AND origin = ?", space, own.address, analyzer);
228
- result.symbols.retired++;
229
- }
230
- }
231
191
  const wanted = new Map(findings.symbols.map((symbol) => [symbol.address, symbol]));
232
192
  const settled = new Set<number>();
233
193
  const replaced = new Set<number>();
@@ -293,14 +253,14 @@ function holdsExecuted(findings: NormalizedFindings, start: number, end: number)
293
253
  */
294
254
  function contradictedData(db: DatabaseSync, findings: NormalizedFindings, space: Space): Array<ImportConflict & { category: "code-evidence" }> {
295
255
  if (!YIELDS_TO_EXECUTED_CODE.has(findings.analyzer)) return [];
296
- const names = db.prepare(`SELECT ${SYMBOL_COLUMNS} FROM current_symbols WHERE space = ? AND origin IN ('user', 'llm') AND kind IN ('label', 'routine') AND address BETWEEN ? AND ? ORDER BY address LIMIT 1`);
256
+ const names = db.prepare(`SELECT ${FACTS.symbols.columns} FROM current_symbols WHERE space = ? AND origin IN ('user', 'llm') AND kind IN ('label', 'routine') AND address BETWEEN ? AND ? ORDER BY address LIMIT 1`);
297
257
  const found: Array<ImportConflict & { category: "code-evidence" }> = [];
298
258
  for (const region of findings.regions) {
299
259
  if (isCode(region.type) || region.type === "dual-use") continue;
300
260
  const executed = firstExecuted(findings, region.start, region.end);
301
261
  const raw = names.get(space, region.start, region.end) as Record<string, unknown> | undefined;
302
262
  if (executed === undefined && raw === undefined) continue;
303
- const symbol = raw === undefined ? undefined : toSymbol(raw);
263
+ const symbol = raw === undefined ? undefined : FACTS.symbols.map(raw);
304
264
  found.push({
305
265
  category: "code-evidence",
306
266
  start: region.start,
@@ -313,12 +273,21 @@ function contradictedData(db: DatabaseSync, findings: NormalizedFindings, space:
313
273
  return found;
314
274
  }
315
275
 
276
+ /** True when the knowledge holds each executed instruction start in the range in a code or dual-use region. */
277
+ function executedIsCode(db: DatabaseSync, findings: NormalizedFindings, range: AddressRange, space: Space): boolean {
278
+ const code = regionsOverlapping(db, range.start, range.end, space).filter((row) => isCode(row.type) || row.type === "dual-use");
279
+ for (let address = range.start; address <= range.end; address++) if (findings.executed!(address) && !inRanges(code, address)) return false;
280
+ return true;
281
+ }
282
+
316
283
  function importRegions(db: DatabaseSync, change: Change, given: NormalizedFindings, coverage: AddressRange[], result: ImportResult): void {
317
284
  const { analyzer } = given;
318
285
  const space = given.space ?? DEFAULT_SPACE;
319
- // Data findings over code evidence are conflicts, not facts.
286
+ // Data findings over code evidence are conflicts, not facts. Where a run executed the code and the knowledge holds it as code, nothing is left to decide: the finding is only counted.
320
287
  const contradicted = contradictedData(db, given, space);
321
- result.conflicts.push(...contradicted);
288
+ const decided = contradicted.filter((item) => item.executed !== undefined && executedIsCode(db, given, item, space));
289
+ result.regions.onExecutedCode = decided.length;
290
+ result.conflicts.push(...contradicted.filter((item) => !decided.includes(item)));
322
291
  const findings = { ...given, regions: given.regions.filter((region) => !contradicted.some((item) => item.start === region.start && item.end === region.end)) };
323
292
  if (analyzer === "heuristic") {
324
293
  // An idiom is specific evidence about its bytes: the DXA or decompiler region there gives way, its parts outside stay.
@@ -386,7 +355,7 @@ function importRegions(db: DatabaseSync, change: Change, given: NormalizedFindin
386
355
  // What the analyzer may own here: its regions minus protected rows.
387
356
  const desired = new Map<string, { start: number; end: number; type: RegionType }>();
388
357
  for (const region of findings.regions.filter((candidate) => candidate.start >= range.start && candidate.end <= range.end)) {
389
- for (const row of protectedRows) if (row.start <= region.end && row.end >= region.start) conflictWith(row, region);
358
+ for (const row of protectedRows) if (rangesOverlap(row, region)) conflictWith(row, region);
390
359
  const suppressed = suppressionsOverlapping(db, "region", region.start, region.end, space);
391
360
  if (suppressed.length > 0) result.regions.suppressed++;
392
361
  for (const piece of subtract(region, [...protectedRows, ...suppressed])) desired.set(`${piece.start}-${piece.end}`, { ...piece, type: region.type });
@@ -444,10 +413,13 @@ const DATA_HOLDS_NO_REFERENCES = new Set<Origin>([...SEMANTIC_ORIGINS, "heuristi
444
413
 
445
414
  /** True for an address in a data region of the user, the LLM or a heuristic, other than the analyzer itself; dual-use bytes are also code. */
446
415
  function inDataRegion(db: DatabaseSync, analyzer: Analyzer, coverage: AddressRange[], space: Space): (address: number) => boolean {
447
- const data = coverage
448
- .flatMap((range) => regionsOverlapping(db, range.start, range.end, space))
449
- .filter((row) => row.origin !== analyzer && DATA_HOLDS_NO_REFERENCES.has(row.origin) && !isCode(row.type) && row.type !== "dual-use");
450
- return (address) => data.some((row) => row.start <= address && address <= row.end);
416
+ const data = new Uint8Array(0x10000);
417
+ for (const range of coverage) {
418
+ for (const row of regionsOverlapping(db, range.start, range.end, space)) {
419
+ if (row.origin !== analyzer && DATA_HOLDS_NO_REFERENCES.has(row.origin) && !isCode(row.type) && row.type !== "dual-use") data.fill(1, row.start, row.end + 1);
420
+ }
421
+ }
422
+ return (address) => data[address] === 1;
451
423
  }
452
424
 
453
425
  /**
@@ -468,7 +440,7 @@ function importReferences(db: DatabaseSync, change: Change, findings: Normalized
468
440
  for (const own of ownReferences(db, analyzer, range, space)) {
469
441
  if (wanted.has(key(own))) continue;
470
442
  if (!findings.authoritative.references && !inData(own.from)) continue;
471
- change.close('"references"', "space = ? AND from_address = ? AND to_address = ? AND kind = ? AND origin = ?", space, own.from, own.to, own.kind, analyzer);
443
+ change.close("references", "space = ? AND from_address = ? AND to_address = ? AND kind = ? AND origin = ?", space, own.from, own.to, own.kind, analyzer);
472
444
  result.references.retired++;
473
445
  }
474
446
  }
@@ -490,7 +462,7 @@ export function importFindings(db: DatabaseSync, findings: NormalizedFindings, c
490
462
  const coverage = validateFindings(findings);
491
463
  return transaction(db, () => {
492
464
  const change = new Change(db, { origin: findings.analyzer, ...context }, `import-${findings.analyzer}`);
493
- const result: ImportResult = { revision: null, names: counts(), symbols: counts(), regions: counts(), references: { ...counts(), inData: 0 }, conflicts: [] };
465
+ const result: ImportResult = { revision: null, names: counts(), regions: { ...counts(), onExecutedCode: 0 }, references: { ...counts(), inData: 0 }, conflicts: [] };
494
466
  importNames(db, change, findings, coverage, result);
495
467
  importRegions(db, change, findings, coverage, result);
496
468
  importReferences(db, change, findings, coverage, result);
@@ -7,6 +7,7 @@
7
7
  // expressions and macro args too. The join writes no knowledge.
8
8
 
9
9
  import { replaceIdentifiers } from "./expression.ts";
10
+ import { spaceOf } from "./schema.ts";
10
11
  import type { BatchOperation } from "./write.ts";
11
12
 
12
13
  export interface Batch {
@@ -44,7 +45,6 @@ export interface JoinResult {
44
45
  }
45
46
 
46
47
  type Op<K extends BatchOperation["op"]> = Extract<BatchOperation, { op: K }>;
47
- const spaceOf = (op: { space?: string }) => op.space ?? "c64";
48
48
 
49
49
  /** The value of a keyed write as text, to compare and report it. */
50
50
  function valueOf(op: BatchOperation): string {
@@ -7,7 +7,8 @@ import type { DatabaseSync } from "node:sqlite";
7
7
 
8
8
  import { c64AddressOf, formatC64Address } from "../c64.ts";
9
9
  import { Refusal } from "../errors.ts";
10
- import { openForRead } from "./database.ts";
10
+ import { projectRoot } from "../project.ts";
11
+ import { withRead } from "./database.ts";
11
12
  import { analyzerNamed, listAnalyzerNames, listSymbols, symbolNamed } from "./read.ts";
12
13
  import { DEFAULT_SPACE, type Space, type SymbolKind } from "./schema.ts";
13
14
 
@@ -34,14 +35,18 @@ export function nameTable(db: DatabaseSync | undefined, space: Space = DEFAULT_S
34
35
  return names;
35
36
  }
36
37
 
37
- /** addressOfName on the knowledge of the project: the name resolver of the scripts. */
38
+ /** The name table of each project folder and space that knowledgeNames read in this process. A script resolves its names before it writes. */
39
+ const tables = new Map<string, Map<string, number>>();
40
+
41
+ /** addressOfName on the knowledge of the project: the name resolver of the scripts. It reads the knowledge once for each space, and again only to refuse a name. */
38
42
  export function knowledgeNames(name: string, space: string): number {
39
- const db = openForRead();
40
- try {
41
- return addressOfName(db, name, space);
42
- } finally {
43
- db?.close();
43
+ const key = `${projectRoot()}\n${space}`;
44
+ let table = tables.get(key);
45
+ if (table === undefined) {
46
+ table = withRead((db) => nameTable(db, space));
47
+ tables.set(key, table);
44
48
  }
49
+ return table.get(name) ?? withRead((db) => addressOfName(db, name, space));
45
50
  }
46
51
 
47
52
  /** An address of a step or a file: $ and 1 to 4 hex digits, else a name of the knowledge in the space. */
@@ -3,15 +3,14 @@
3
3
  // capture and the coverage maps are imported one time; every later step reads
4
4
  // them here, so a project needs no image or coverage files to be made again.
5
5
 
6
- import { createHash } from "node:crypto";
7
6
  import type { DatabaseSync } from "node:sqlite";
8
7
 
9
8
  import { Refusal } from "../errors.ts";
10
- import { type AddressRange, COVERAGE, formatC64Address, formatC64Byte } from "../c64.ts";
11
-
9
+ import { type AddressRange, COVERAGE, formatC64Address, formatC64Byte, formatC64Range, inRanges, prgOf, rangesWhere } from "../c64.ts";
12
10
  import { COVERAGE_KINDS, DEFAULT_SPACE, MEMORY_ROW, type CoverageKind, type Space } from "./schema.ts";
13
11
  import { coverageRuns } from "./read.ts";
14
- import { checkSpace, write, type Evidence, type OperandImage, type WriteContext } from "./write.ts";
12
+ import { sha256 } from "./text.ts";
13
+ import { checkAddress, checkSpace, write, type Evidence, type OperandImage, type WriteContext } from "./write.ts";
15
14
 
16
15
  /** The 64 KiB of one space: offset n is address n. */
17
16
  const SIZE = 0x10000;
@@ -60,18 +59,6 @@ export interface CoverageMap {
60
59
  bytes: Uint8Array;
61
60
  }
62
61
 
63
- /** The address ranges where `has` is true, in address order. */
64
- function rangesWhere(has: (address: number) => boolean): AddressRange[] {
65
- const ranges: AddressRange[] = [];
66
- for (let address = 0; address < SIZE; address++) {
67
- if (!has(address)) continue;
68
- const start = address;
69
- while (address + 1 < SIZE && has(address + 1)) address++;
70
- ranges.push({ start, end: address });
71
- }
72
- return ranges;
73
- }
74
-
75
62
  /** The memory rows of the segments: at most MEMORY_ROW bytes, never across a multiple of MEMORY_ROW. */
76
63
  export function memoryRows(segments: readonly AddressRange[], byteAt: (address: number) => number): Map<number, string> {
77
64
  const rows = new Map<number, string>();
@@ -90,7 +77,7 @@ function checkSegments(segments: readonly AddressRange[]): void {
90
77
  const sorted = [...segments].sort((a, b) => a.start - b.start);
91
78
  sorted.forEach((segment, index) => {
92
79
  if (!Number.isInteger(segment.start) || !Number.isInteger(segment.end) || segment.start < 0 || segment.end > 0xffff || segment.end < segment.start) {
93
- throw new Refusal("invalid-input", `The segment ${formatC64Address(segment.start)}-${formatC64Address(segment.end)} is not a range from $0000 to $ffff.`);
80
+ throw new Refusal("invalid-input", `The segment ${formatC64Range(segment)} is not a range from $0000 to $ffff.`);
94
81
  }
95
82
  if (index > 0 && segment.start <= sorted[index - 1]!.end) throw new Refusal("invalid-input", `The segments at ${formatC64Address(sorted[index - 1]!.start)} and ${formatC64Address(segment.start)} overlap.`);
96
83
  });
@@ -104,7 +91,7 @@ function checkSegments(segments: readonly AddressRange[]): void {
104
91
  export function setImage(db: DatabaseSync, context: WriteContext, request: ImageRequest): { revision: string | null; current: { space: Space; bytes: number; rowsAdded: number; rowsClosed: number; entry: boolean } } {
105
92
  checkSpace(request);
106
93
  checkSegments(request.segments);
107
- if (request.entry !== undefined && (!Number.isInteger(request.entry) || request.entry < 0 || request.entry > 0xffff)) throw new Refusal("invalid-input", "The entry must be from $0000 to $ffff.");
94
+ if (request.entry !== undefined) checkAddress(request.entry, "The entry");
108
95
  if (request.entry === undefined && (request.state !== undefined || request.stages !== undefined)) throw new Refusal("invalid-input", "A machine state or stages need an entry.");
109
96
  const space = request.space ?? DEFAULT_SPACE;
110
97
  const wanted = memoryRows(request.segments, request.byteAt);
@@ -141,8 +128,7 @@ export function setImage(db: DatabaseSync, context: WriteContext, request: Image
141
128
 
142
129
  /** Address ranges as the knowledge text keeps them: "$1000-$1002 $1005". */
143
130
  function rangesText(ranges: readonly AddressRange[]): string {
144
- const at = (address: number) => `$${address.toString(16).padStart(4, "0")}`;
145
- return ranges.map((range) => (range.start === range.end ? at(range.start) : `${at(range.start)}-${at(range.end)}`)).join(" ");
131
+ return ranges.map((range) => (range.start === range.end ? formatC64Address(range.start) : formatC64Range(range))).join(" ");
146
132
  }
147
133
 
148
134
  /** Calls `each` with the start and the end of each range of ranges as text. */
@@ -215,7 +201,7 @@ export function addCoverage(
215
201
  }
216
202
  // A path given twice is one map: the last one.
217
203
  const byName = new Map(request.maps.map((map) => [map.name, map]));
218
- const hashed = [...byName.values()].map((map) => ({ ...map, sha256: createHash("sha256").update(map.bytes).digest("hex") }));
204
+ const hashed = [...byName.values()].map((map) => ({ ...map, sha256: sha256(map.bytes) }));
219
205
  // The runs of a name are oldest first: the last one is the latest map of the path.
220
206
  const latest = new Map(coverageRuns(db).filter((run) => run.space === space).map((run) => [run.name, run.sha256]));
221
207
  const withRows = new Set((db.prepare("SELECT DISTINCT map FROM current_coverage WHERE space = ?").all(space) as Array<{ map: string }>).map((row) => row.map));
@@ -295,11 +281,8 @@ export function coverageAccess(db: DatabaseSync | undefined, space: Space = DEFA
295
281
  };
296
282
  }
297
283
 
298
- /** The program of a space, or undefined when the knowledge has no bytes for it. */
299
- export function programImage(db: DatabaseSync | undefined, space: Space = DEFAULT_SPACE): ProgramImage | undefined {
300
- if (db === undefined) return undefined;
301
- const rows = db.prepare("SELECT address, bytes FROM current_memory WHERE space = ? ORDER BY address").all(space) as Array<{ address: number; bytes: string }>;
302
- if (rows.length === 0) return undefined;
284
+ /** The bytes of memory rows in address order, in 64 KiB, and the ranges that they fill: rows that touch are one range. */
285
+ function rowsImage(rows: ReadonlyArray<{ address: number; bytes: string }>): { segments: AddressRange[]; memory: Uint8Array } {
303
286
  const memory = new Uint8Array(SIZE);
304
287
  const segments: AddressRange[] = [];
305
288
  for (const row of rows) {
@@ -310,6 +293,15 @@ export function programImage(db: DatabaseSync | undefined, space: Space = DEFAUL
310
293
  if (last !== undefined && last.end + 1 === row.address) last.end = end;
311
294
  else segments.push({ start: row.address, end });
312
295
  }
296
+ return { segments, memory };
297
+ }
298
+
299
+ /** The program of a space, or undefined when the knowledge has no bytes for it. */
300
+ export function programImage(db: DatabaseSync | undefined, space: Space = DEFAULT_SPACE): ProgramImage | undefined {
301
+ if (db === undefined) return undefined;
302
+ const rows = db.prepare("SELECT address, bytes FROM current_memory WHERE space = ? ORDER BY address").all(space) as Array<{ address: number; bytes: string }>;
303
+ if (rows.length === 0) return undefined;
304
+ const { segments, memory } = rowsImage(rows);
313
305
  const image: ProgramImage = { space, segments, memory, byteAt: (address) => memory[address]! };
314
306
  const entry = db.prepare("SELECT address, state, stages FROM current_entries WHERE space = ?").get(space) as { address: number; state: string | null; stages: string | null } | undefined;
315
307
  if (entry !== undefined) {
@@ -337,17 +329,16 @@ const STATE_PAGES = ["$0000", "$0100", "$0200", "$0300"] as const;
337
329
  * pages hold code and data that the loader left). $0000 and $0001 are the
338
330
  * CPU port, not memory. A segment byte wins over a state byte.
339
331
  */
340
- export function entryMemory(image: ProgramImage): Uint8Array {
332
+ function entryMemory(image: ProgramImage): Uint8Array {
341
333
  const memory = new Uint8Array(image.memory);
342
334
  const pages = image.state?.pages;
343
335
  if (typeof pages !== "object" || pages === null) return memory;
344
- const inSegment = (address: number) => image.segments.some((segment) => address >= segment.start && address <= segment.end);
345
336
  STATE_PAGES.forEach((page, index) => {
346
337
  const hex = (pages as Record<string, unknown>)[page];
347
338
  if (typeof hex !== "string" || !/^(?:[0-9a-fA-F]{2}){1,256}$/.test(hex)) return;
348
339
  Buffer.from(hex, "hex").forEach((byte, offset) => {
349
340
  const address = index * 0x100 + offset;
350
- if (address >= 2 && !inSegment(address)) memory[address] = byte;
341
+ if (address >= 2 && !inRanges(image.segments, address)) memory[address] = byte;
351
342
  });
352
343
  });
353
344
  return memory;
@@ -361,7 +352,7 @@ export function entryMemory(image: ProgramImage): Uint8Array {
361
352
  export function analyzedBytes(image: ProgramImage): { bytes: Buffer; kind: "prg" | "flat64k" } {
362
353
  if (image.segments.length === 1 && image.state === undefined) {
363
354
  const [segment] = image.segments;
364
- return { bytes: Buffer.concat([Buffer.from([segment!.start & 0xff, segment!.start >> 8]), Buffer.from(image.memory.subarray(segment!.start, segment!.end + 1))]), kind: "prg" };
355
+ return { bytes: prgOf(segment!.start, image.memory.subarray(segment!.start, segment!.end + 1)), kind: "prg" };
365
356
  }
366
357
  return { bytes: Buffer.from(entryMemory(image)), kind: "flat64k" };
367
358
  }
@@ -393,8 +384,7 @@ export function operandImages(db: DatabaseSync, platform: ReadonlyMap<string, nu
393
384
  const known = images.get(space);
394
385
  if (known !== undefined) return known;
395
386
  const image = requireProgram(db, space);
396
- const inside = (at: number) => image.segments.some((segment) => at >= segment.start && at <= segment.end);
397
- const made: OperandImage = { byteAt: (at) => (inside(at) ? image.byteAt(at) : undefined), platform };
387
+ const made: OperandImage = { byteAt: (at) => (inRanges(image.segments, at) ? image.byteAt(at) : undefined), platform };
398
388
  images.set(space, made);
399
389
  return made;
400
390
  };
@@ -410,17 +400,7 @@ export function releaseImage(db: DatabaseSync | undefined, label: string, space:
410
400
  const release = db.prepare("SELECT base FROM current_releases WHERE space = ? AND label = ?").get(space, label) as { base: number } | undefined;
411
401
  if (release === undefined) return undefined;
412
402
  if (release.base === 1) return programImage(db, space);
413
- const rows = db.prepare("SELECT address, bytes FROM current_release_memory WHERE space = ? AND label = ? ORDER BY address").all(space, label) as Array<{ address: number; bytes: string }>;
414
- const memory = new Uint8Array(SIZE);
415
- const segments: AddressRange[] = [];
416
- for (const row of rows) {
417
- const bytes = Buffer.from(row.bytes, "hex");
418
- memory.set(bytes, row.address);
419
- const end = row.address + bytes.length - 1;
420
- const last = segments.at(-1);
421
- if (last !== undefined && last.end + 1 === row.address) last.end = end;
422
- else segments.push({ start: row.address, end });
423
- }
403
+ const { segments, memory } = rowsImage(db.prepare("SELECT address, bytes FROM current_release_memory WHERE space = ? AND label = ? ORDER BY address").all(space, label) as Array<{ address: number; bytes: string }>);
424
404
  return { segments, byteAt: (address) => memory[address]! };
425
405
  }
426
406
 
@@ -433,14 +413,13 @@ const PATCH_LINE_BYTES = 8;
433
413
  * state. A release without a byte at each address of the range is refused.
434
414
  */
435
415
  export function releaseCode(db: DatabaseSync | undefined, label: string, start: number, end: number, space: Space = DEFAULT_SPACE): string {
436
- const range = `${formatC64Address(start)}-${formatC64Address(end)}`;
416
+ const range = formatC64Range({ start, end });
437
417
  const release = db?.prepare("SELECT base FROM current_releases WHERE space = ? AND label = ?").get(space, label) as { base: number } | undefined;
438
418
  if (release === undefined) throw new Refusal("not-found", `There is no release ${label}${space === DEFAULT_SPACE ? "" : ` in ${space}`}. Record it first with its file.`);
439
419
  if (release.base === 1) throw new Refusal("invalid-input", `${label} is the base release: its bytes are the program, and a patch holds the bytes of the other state. Give the release that has the other bytes in ${range}.`);
440
420
  const image = releaseImage(db, label, space)!;
441
- const inside = (address: number) => image.segments.some((segment) => address >= segment.start && address <= segment.end);
442
421
  for (let address = start; address <= end; address++) {
443
- if (!inside(address)) throw new Refusal("invalid-input", `The release ${label} has no byte at ${formatC64Address(address)}, in the range ${range}. Give a range inside the bytes of the release.`);
422
+ if (!inRanges(image.segments, address)) throw new Refusal("invalid-input", `The release ${label} has no byte at ${formatC64Address(address)}, in the range ${range}. Give a range inside the bytes of the release.`);
444
423
  }
445
424
  const lines: string[] = [];
446
425
  for (let at = start; at <= end; at += PATCH_LINE_BYTES) {