@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
@@ -1,15 +1,16 @@
1
1
  // Evidence from one release: for each range of the image, the unpack
2
2
  // stage that wrote it and the access class from coverage; for each code
3
- // region of knowledge, whether call and jump references or the run on from
4
- // its last instruction reach it from a root (the entry, and the NMI, RESET
5
- // and IRQ vectors at $fffa-$ffff when the image holds them); and what the program reads
3
+ // region of knowledge, whether call and jump references, the handlers that
4
+ // the code stores in an interrupt vector, or the run on from its last
5
+ // instruction reach it from a root (the entry, and the NMI, RESET and IRQ
6
+ // vectors at $fffa-$ffff when the image holds them); and what the program reads
6
7
  // or executes outside the image. A region that nothing reaches is unknown, not
7
8
  // dead, while the program has a flow whose targets the knowledge does not give,
8
9
  // or when no coverage shows what ran. Evidence only: nothing here decides which
9
10
  // bytes the publisher shipped.
10
11
 
11
- import { type AddressRange, COVERAGE, executedRamCode, instructionLength } from "../c64.ts";
12
- import { OPCODES } from "../opcodes.ts";
12
+ import { type AddressRange, COVERAGE, executedRamCode, inRanges, instructionLength, NO_FALL, rangesOverlap } from "../c64.ts";
13
+ import { JAM_OPCODES, OPCODES } from "../opcodes.ts";
13
14
  import { isSemantic } from "./schema.ts";
14
15
 
15
16
  export type Access = "executed" | "read" | "written" | "read-written" | "untouched";
@@ -59,6 +60,7 @@ export interface UnresolvedFlow {
59
60
 
60
61
  /** The computed flows of the code: the targets that the bytes of the program give, and the flows that stay open. */
61
62
  export interface ComputedFlows {
63
+ /** Also from each store of a handler into an interrupt vector to the handler. */
62
64
  targets: Array<{ from: number; to: number }>;
63
65
  unresolved: UnresolvedFlow[];
64
66
  }
@@ -99,21 +101,20 @@ const HARDWARE_VECTORS = [
99
101
  * two bytes are in the image. An interrupt handler runs by its vector, and
100
102
  * no call or jump reference reaches it.
101
103
  */
102
- export function reachabilityRoots(segments: readonly AddressRange[], memory: Uint8Array, entry?: number): Root[] {
103
- const inImage = (address: number) => segments.some((segment) => address >= segment.start && address <= segment.end);
104
- const vectors = HARDWARE_VECTORS.filter((vector) => inImage(vector.at) && inImage(vector.at + 1)).map((vector): Root => ({ address: memory[vector.at]! | (memory[vector.at + 1]! << 8), from: vector.from }));
104
+ function reachabilityRoots(segments: readonly AddressRange[], memory: Uint8Array, entry?: number): Root[] {
105
+ const vectors = HARDWARE_VECTORS.filter((vector) => inRanges(segments, vector.at) && inRanges(segments, vector.at + 1)).map((vector): Root => ({ address: memory[vector.at]! | (memory[vector.at + 1]! << 8), from: vector.from }));
105
106
  return [...(entry === undefined ? [] : [{ address: entry, from: "entry" as const }]), ...vectors];
106
107
  }
107
108
 
108
109
  /** BRK, JMP, RTI, RTS, JMP (indirect) and the JAM opcodes: the CPU does not run on to the next instruction after them. */
109
- export const NO_FALL_THROUGH = new Set([0x00, 0x4c, 0x40, 0x60, 0x6c, 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72, 0x92, 0xb2, 0xd2, 0xf2]);
110
+ export const NO_FALL_THROUGH: ReadonlySet<number> = new Set([...NO_FALL, ...JAM_OPCODES]);
110
111
 
111
112
  /**
112
113
  * The address after a code region where the CPU runs on, or undefined when
113
114
  * its last instruction does not run on (RTS, RTI, JMP, BRK, JAM). The
114
115
  * instructions follow one another from the start of the region.
115
116
  */
116
- export function fallThrough(region: AddressRange, memory: Uint8Array): number | undefined {
117
+ function fallThrough(region: AddressRange, memory: Uint8Array): number | undefined {
117
118
  let at = region.start;
118
119
  let last = at;
119
120
  while (at <= region.end) {
@@ -124,7 +125,7 @@ export function fallThrough(region: AddressRange, memory: Uint8Array): number |
124
125
  }
125
126
 
126
127
  /** The instruction starts of code regions: each region runs from its start, one instruction after the other. */
127
- export function regionStarts(regions: readonly AddressRange[], memory: Uint8Array): number[] {
128
+ function regionStarts(regions: readonly AddressRange[], memory: Uint8Array): number[] {
128
129
  const starts: number[] = [];
129
130
  for (const region of regions) for (let at = region.start; at <= region.end; at += instructionLength(memory[at]!)) starts.push(at);
130
131
  return starts.sort((a, b) => a - b);
@@ -141,6 +142,13 @@ export const WRITES_Y = new Set(["ldy", "iny", "dey"]);
141
142
  /** The instructions that change the byte at their operand with a value that no immediate gives. */
142
143
  const CHANGES_MEMORY = new Set(["inc", "dec", "asl", "lsr", "rol", "ror", "sax", "slo", "rla", "sre", "rra", "dcp", "isc"]);
143
144
 
145
+ /**
146
+ * The low bytes of the interrupt vectors: the KERNAL goes through the IRQ, BRK
147
+ * and NMI vectors at $0314-$0319, and the CPU through $fffa-$ffff when the
148
+ * KERNAL is banked out. No instruction of the program goes to their handlers.
149
+ */
150
+ const INTERRUPT_VECTORS = [0x0314, 0x0316, 0x0318, 0xfffa, 0xfffc, 0xfffe];
151
+
144
152
  /**
145
153
  * The computed flows of the instructions at `starts`: a JMP (N), a JMP or JSR
146
154
  * whose address bytes a run wrote, and an RTS or RTI after pushes in its run
@@ -151,7 +159,11 @@ const CHANGES_MEMORY = new Set(["inc", "dec", "asl", "lsr", "rol", "ror", "sax",
151
159
  * there, and the flow goes to each word of these values. A byte that another
152
160
  * write of the code changes, or that a run wrote while no store of the code
153
161
  * does, or that is outside the image without such a store, leaves the flow
154
- * unresolved.
162
+ * unresolved. An immediate that the code stores in an interrupt vector
163
+ * installs a handler: a flow goes from each such store to each word of the
164
+ * immediates of the two bytes, or of the image byte where the code stores
165
+ * none. Another write of the vector, for example a restore of the KERNAL
166
+ * handler, does not remove the handler.
155
167
  */
156
168
  export function computedFlows(input: { starts: readonly number[]; memory: Uint8Array; inImage: (address: number) => boolean; coverage?: Uint8Array | undefined; references: ReadonlyArray<{ from: number; kind: string; origin?: string | undefined }> }): ComputedFlows {
157
169
  const { memory } = input;
@@ -168,6 +180,9 @@ export function computedFlows(input: { starts: readonly number[]; memory: Uint8A
168
180
  if (known === null) return;
169
181
  stored.set(address, value === undefined ? null : (known ?? new Set<number>()).add(value));
170
182
  };
183
+ // The immediates that the code stores in each byte of an interrupt vector, with the address of the store.
184
+ const installs = new Map<number, Array<{ at: number; value: number }>>();
185
+ const vectorBytes = new Set(INTERRUPT_VECTORS.flatMap((vector) => [vector, vector + 1]));
171
186
  // The return addresses that the code pushed before an RTS or RTI, as far as immediates give them.
172
187
  const returns: Array<{ at: number; low: number | undefined; high: number | undefined; offset: 0 | 1 }> = [];
173
188
  let registers: { a?: number | undefined; x?: number | undefined; y?: number | undefined } = {};
@@ -187,6 +202,8 @@ export function computedFlows(input: { starts: readonly number[]; memory: Uint8A
187
202
  const register = mnemonic === "sta" ? "a" : mnemonic === "stx" ? "x" : mnemonic === "sty" ? "y" : undefined;
188
203
  if (register !== undefined) store(operand, registers[register]);
189
204
  else if (CHANGES_MEMORY.has(mnemonic)) store(operand, undefined);
205
+ const value = register === undefined ? undefined : registers[register];
206
+ if (value !== undefined && vectorBytes.has(operand)) installs.set(operand, [...(installs.get(operand) ?? []), { at, value }]);
190
207
  }
191
208
  if (mnemonic === "pha") pushes.push(registers.a);
192
209
  if (mnemonic === "php") pushes.push(undefined);
@@ -239,6 +256,16 @@ export function computedFlows(input: { starts: readonly number[]; memory: Uint8A
239
256
  if (pushed.low !== undefined && pushed.high !== undefined) targets.push({ from: pushed.at, to: ((pushed.low | (pushed.high << 8)) + pushed.offset) & 0xffff });
240
257
  else if (!fromTable.has(pushed.at)) unresolved.push({ at: pushed.at, kind: "pushed-return" });
241
258
  }
259
+ for (const vector of INTERRUPT_VECTORS) {
260
+ const stores = [...(installs.get(vector) ?? []), ...(installs.get(vector + 1) ?? [])];
261
+ if (stores.length === 0) continue;
262
+ const valuesOf = (address: number) => {
263
+ const own = installs.get(address);
264
+ return own !== undefined ? [...new Set(own.map((item) => item.value))] : input.inImage(address) ? [memory[address]!] : [];
265
+ };
266
+ const handlers = valuesOf(vector).flatMap((low) => valuesOf(vector + 1).map((high) => low | (high << 8)));
267
+ for (const from of new Set(stores.map((item) => item.at))) for (const to of handlers) targets.push({ from, to });
268
+ }
242
269
  return { targets, unresolved: unresolved.sort((a, b) => a.at - b.at) };
243
270
  }
244
271
 
@@ -257,7 +284,7 @@ function merge(addresses: number[], gap = 0, joins: (from: number, to: number) =
257
284
  }
258
285
 
259
286
  export function separate(input: SeparationInput): Separation {
260
- const inImage = (address: number) => input.segments.some((segment) => address >= segment.start && address <= segment.end);
287
+ const inImage = (address: number) => inRanges(input.segments, address);
261
288
  const executed = new Uint8Array(0x10000);
262
289
  if (input.coverage !== undefined) for (const range of executedRamCode(input.coverage, 0, input.memory)) executed.fill(1, range.start, range.end + 1);
263
290
  const accessAt = (address: number): Access | undefined => {
@@ -268,11 +295,12 @@ export function separate(input: SeparationInput): Separation {
268
295
  const written = (flags & COVERAGE.ramWrite) !== 0;
269
296
  return read && written ? "read-written" : read ? "read" : written ? "written" : "untouched";
270
297
  };
271
- const stageAt = (address: number): number | undefined => {
272
- const stages = input.stages ?? [];
273
- for (let index = stages.length - 1; index >= 0; index--) if (stages[index]!.wrote.some((range) => address >= range.start && address <= range.end)) return index;
274
- return undefined;
275
- };
298
+ // The newest stage that wrote each address.
299
+ const stageOf = new Int32Array(0x10000).fill(-1);
300
+ (input.stages ?? []).forEach((stage, index) => {
301
+ for (const range of stage.wrote) stageOf.fill(index, range.start, range.end + 1);
302
+ });
303
+ const stageAt = (address: number): number | undefined => (stageOf[address] === -1 ? undefined : stageOf[address]);
276
304
 
277
305
  const ranges: EvidenceRange[] = [];
278
306
  for (const segment of input.segments) {
@@ -288,7 +316,7 @@ export function separate(input: SeparationInput): Separation {
288
316
  }
289
317
  }
290
318
 
291
- const regions = input.codeRegions.filter((region) => input.segments.some((segment) => region.start <= segment.end && segment.start <= region.end));
319
+ const regions = input.codeRegions.filter((region) => input.segments.some((segment) => rangesOverlap(region, segment)));
292
320
  // The region of each address: the first region that holds it, as a search in region order finds it.
293
321
  const owner = new Int32Array(0x10000).fill(-1);
294
322
  regions.forEach((region, index) => {
@@ -3,6 +3,7 @@
3
3
  // the colour RAM of the capture gives the colours. Thus the start screen of a
4
4
  // stage needs no address from the user.
5
5
 
6
+ import { d018Offsets, formatC64Byte, vicBankBase } from "../c64.ts";
6
7
  import { Refusal } from "../errors.ts";
7
8
  import { LEFTOVERS_SWITCH, START_SCREEN_SWITCH, type StartScreenMode } from "./schema.ts";
8
9
 
@@ -70,16 +71,17 @@ function vicScreen(state: Record<string, unknown> | undefined, named: Named): Om
70
71
  const cia2 = ioBytes(state, "cia2");
71
72
  if (state === undefined || vic === undefined || vic.length < 0x2f || cia2 === undefined) throw new Refusal("not-found", `${named.program} has no entry state with the VIC-II and CIA 2. ${named.again}`);
72
73
  const [d011, d016, d018] = [vic[0x11]!, vic[0x16]!, vic[0x18]!];
73
- if ((d011 & 0x10) === 0) throw new Refusal("invalid-input", `${named.capture} has the display off ($d011 = $${d011.toString(16).padStart(2, "0")}). ${named.again}`);
74
+ if ((d011 & 0x10) === 0) throw new Refusal("invalid-input", `${named.capture} has the display off ($d011 = ${formatC64Byte(d011)}). ${named.again}`);
74
75
  if ((d011 & 0x40) !== 0) throw new Refusal("invalid-input", `${named.capture} shows a screen in the extended colour mode, which a start screen does not have.`);
75
76
  const bitmap = (d011 & 0x20) !== 0;
76
77
  const multicolour = (d016 & 0x10) !== 0;
77
78
  if (!bitmap && multicolour) throw new Refusal("invalid-input", `${named.capture} shows a multicolour text screen, which a start screen does not have.`);
78
- const bank = (3 - (cia2[0]! & 0x03)) << 14;
79
+ const bank = vicBankBase(cia2[0]!, cia2[2]);
80
+ const offsets = d018Offsets(d018);
79
81
  return {
80
82
  mode: bitmap ? (multicolour ? "multicolour" : "hires") : "text",
81
- screen: bank + ((d018 >> 4) & 0x0f) * 0x400,
82
- ...(bitmap ? { bitmap: bank + ((d018 >> 3) & 1) * 0x2000 } : { charset: bank + ((d018 >> 1) & 7) * 0x800 }),
83
+ screen: bank + offsets.screen,
84
+ ...(bitmap ? { bitmap: bank + offsets.bitmap } : { charset: bank + offsets.characters }),
83
85
  border: vic[0x20]! & 0x0f,
84
86
  background: vic[0x21]! & 0x0f,
85
87
  };
@@ -106,7 +108,7 @@ const COLOURS = 1000;
106
108
  * colours (the low 4 bits of each byte), outside $d000-$dfff, where the loader
107
109
  * sees the I/O area. Undefined when the program has no such bytes.
108
110
  */
109
- export function findColours(colours: Uint8Array, byteAt: (address: number) => number | undefined): number | undefined {
111
+ function findColours(colours: Uint8Array, byteAt: (address: number) => number | undefined): number | undefined {
110
112
  for (let start = 0x0400; start + COLOURS - 1 <= 0xffff; start++) {
111
113
  if (start <= 0xdfff && start + COLOURS - 1 >= 0xd000) continue;
112
114
  let offset = 0;
@@ -10,8 +10,10 @@ import { readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "no
10
10
  import type { DatabaseSync } from "node:sqlite";
11
11
  import { join } from "node:path";
12
12
 
13
+ import { hexWord } from "../c64.ts";
13
14
  import { Refusal } from "../errors.ts";
14
- import { isoCet } from "../time.ts";
15
+ import { CET_OFFSET_MS, isoCet } from "../time.ts";
16
+ import { spaceOrder } from "./schema.ts";
15
17
 
16
18
  /** The value of "no revision": empty knowledge. It sorts before every revision id. */
17
19
  export const NO_REVISION = "0";
@@ -22,8 +24,6 @@ export const REVISION_ID = /^[0-9]{8}T[0-9]{6}\.[0-9]{3}-[0-9a-z]{6}$/;
22
24
  /** A row id: the id of the revision that added the row, then the order of the row in that revision. */
23
25
  const ROW_ID = /^([0-9]{8}T[0-9]{6}\.[0-9]{3}-[0-9a-z]{6})\/([1-9][0-9]*)$/;
24
26
 
25
- const CET_OFFSET_MS = 60 * 60 * 1000;
26
-
27
27
  /** `time` as `20261015T214501.123`: CET at +01:00, ISO 8601 basic form. */
28
28
  function stamp(ms: number): string {
29
29
  return isoCet(new Date(ms)).slice(0, 23).replace(/[-:]/g, "");
@@ -64,13 +64,11 @@ type Format = "address" | "integer" | "text" | "hex" | "json" | "ranges";
64
64
  /** Address ranges as text: "$1000-$1002 $1005", in address order, one space between them. */
65
65
  const RANGES = /^\$[0-9a-f]{4}(?:-\$[0-9a-f]{4})?(?: \$[0-9a-f]{4}(?:-\$[0-9a-f]{4})?)*$/;
66
66
 
67
- interface Field {
67
+ export interface Field {
68
68
  key: string;
69
69
  column: string;
70
70
  format: Format;
71
71
  optional?: boolean;
72
- /** What to do when a line does not have this key: a key that an earlier toolkit version did not write. */
73
- remedy?: string;
74
72
  }
75
73
 
76
74
  /** One fact table: its file, its fields in line order, and the column that sorts its lines after the space (an address, or a name). */
@@ -231,11 +229,7 @@ export const TABLES: readonly TableSpec[] = [
231
229
  sort: "map",
232
230
  fields: [
233
231
  space,
234
- {
235
- ...field("map", "map", "text"),
236
- remedy:
237
- "The coverage of an earlier toolkit version does not keep the ranges of each map. Delete .c64-re-tools/knowledge/coverage.jsonl. Then put the coverage maps that you have into the project knowledge again.",
238
- },
232
+ field("map", "map", "text"),
239
233
  field("kind", "kind", "text"),
240
234
  field("ranges", "ranges", "ranges"),
241
235
  origin,
@@ -243,6 +237,13 @@ export const TABLES: readonly TableSpec[] = [
243
237
  },
244
238
  ];
245
239
 
240
+ const SPECS = new Map(TABLES.map((spec) => [spec.table, spec]));
241
+
242
+ /** The spec of a fact table, by its name. */
243
+ export function tableSpec(table: string): TableSpec {
244
+ return SPECS.get(table)!;
245
+ }
246
+
246
247
  export const REVISIONS_FILE = "revisions.jsonl";
247
248
 
248
249
  /** The revision fields in line order; `evidence` comes last. */
@@ -264,7 +265,7 @@ export const sqlName = (table: string) => (table === "references" ? '"references
264
265
  type Raw = Record<string, unknown>;
265
266
 
266
267
  function formatted(value: unknown, format: Format): unknown {
267
- if (format === "address") return `$${(value as number).toString(16).padStart(4, "0")}`;
268
+ if (format === "address") return `$${hexWord(value as number)}`;
268
269
  return format === "json" ? JSON.parse(value as string) : value;
269
270
  }
270
271
 
@@ -278,46 +279,65 @@ function lineOf(raw: Raw, fields: readonly Field[], extra: Raw): string {
278
279
  return JSON.stringify({ ...line, ...extra });
279
280
  }
280
281
 
281
- const spaceOrder = (space: string) => (space === "c64" ? -2 : space === "drive8" ? -1 : Number(space.slice(4)));
282
+ /** A row with the order of the row in the revision that added it, from its id. */
283
+ interface Ordered {
284
+ raw: Raw;
285
+ order: number;
286
+ }
282
287
 
283
288
  /** The sort key of a row: space, address (or name), the revision that added it, its order in that revision. */
284
289
  function compareRows(spec: TableSpec) {
285
- const order = (raw: Raw) => Number(ROW_ID.exec(raw.id as string)?.[2] ?? 0);
286
290
  const key = (a: unknown, b: unknown) => (typeof a === "number" ? a - (b as number) : compareText(a as string, b as string));
287
- return (a: Raw, b: Raw) =>
291
+ return ({ raw: a, order: orderA }: Ordered, { raw: b, order: orderB }: Ordered) =>
288
292
  spaceOrder(a.space as string) - spaceOrder(b.space as string) ||
289
293
  key(a[spec.sort], b[spec.sort]) ||
290
294
  compareText(a.valid_from_revision as string, b.valid_from_revision as string) ||
291
- order(a) - order(b) ||
295
+ orderA - orderB ||
292
296
  compareText(a.id as string, b.id as string);
293
297
  }
294
298
 
295
299
  /** The text of one fact table: every row, current and closed, one line each, sorted. */
296
300
  export function tableText(db: DatabaseSync, spec: TableSpec): string {
297
- const rows = (db.prepare(`SELECT * FROM ${sqlName(spec.table)}`).all() as Raw[]).sort(compareRows(spec));
298
- return rows.map((raw) => `${lineOf(raw, [field("id", "id", "text"), ...spec.fields], { added: raw.valid_from_revision, closed: raw.valid_to_revision })}\n`).join("");
301
+ const rows = (db.prepare(`SELECT * FROM ${sqlName(spec.table)}`).all() as Raw[]).map((raw): Ordered => ({ raw, order: Number(ROW_ID.exec(raw.id as string)?.[2] ?? 0) }));
302
+ const fields = [field("id", "id", "text"), ...spec.fields];
303
+ return rows
304
+ .sort(compareRows(spec))
305
+ .map(({ raw }) => `${lineOf(raw, fields, { added: raw.valid_from_revision, closed: raw.valid_to_revision })}\n`)
306
+ .join("");
299
307
  }
300
308
 
301
309
  /** The text of the revision log: every revision with its evidence, oldest first. */
302
310
  export function revisionsText(db: DatabaseSync): string {
303
- const evidence = db.prepare("SELECT kind, ref, sha256, space FROM evidence WHERE revision = ? ORDER BY id");
311
+ const evidence = new Map<string, Raw[]>();
312
+ for (const item of db.prepare("SELECT revision, kind, ref, sha256, space FROM evidence ORDER BY revision, id").all() as Raw[]) {
313
+ const items = evidence.get(item.revision as string) ?? [];
314
+ items.push({ kind: item.kind, ref: item.ref, ...(item.sha256 === null ? {} : { sha256: item.sha256 }), ...(item.space === null ? {} : { space: item.space }) });
315
+ evidence.set(item.revision as string, items);
316
+ }
304
317
  return (db.prepare("SELECT * FROM revisions ORDER BY id").all() as Raw[])
305
318
  .map((raw) => {
306
- const items = (evidence.all(raw.id as string) as Raw[]).map((item) => ({ kind: item.kind, ref: item.ref, ...(item.sha256 === null ? {} : { sha256: item.sha256 }), ...(item.space === null ? {} : { space: item.space }) }));
307
- return `${lineOf(raw, REVISION_FIELDS, items.length === 0 ? {} : { evidence: items })}\n`;
319
+ const items = evidence.get(raw.id as string);
320
+ return `${lineOf(raw, REVISION_FIELDS, items === undefined ? {} : { evidence: items })}\n`;
308
321
  })
309
322
  .join("");
310
323
  }
311
324
 
312
- export const sha256 = (text: string | Buffer) => createHash("sha256").update(text).digest("hex");
325
+ export const sha256 = (data: string | Uint8Array) => createHash("sha256").update(data).digest("hex");
326
+
327
+ /** The names of the knowledge files in the folder, in name order. A file that is not knowledge text is refused. */
328
+ export function knowledgeFiles(directory: string): string[] {
329
+ const known = new Set([REVISIONS_FILE, ...TABLES.map((spec) => spec.file)]);
330
+ const names = readdirSync(directory)
331
+ .sort()
332
+ .filter((name) => name.endsWith(".jsonl"));
333
+ for (const name of names) if (!known.has(name)) throw new Refusal("invalid-database", `.c64-re-tools/knowledge/${name} is not a knowledge file. Knowledge files are ${[...known].join(", ")}.`);
334
+ return names;
335
+ }
313
336
 
314
337
  /** The files of the knowledge: their text and its SHA-256. A file that is not knowledge text is refused. */
315
338
  export function readText(directory: string): Map<string, { text: string; sha256: string }> {
316
- const known = new Set([REVISIONS_FILE, ...TABLES.map((spec) => spec.file)]);
317
339
  const files = new Map<string, { text: string; sha256: string }>();
318
- for (const name of readdirSync(directory).sort()) {
319
- if (!name.endsWith(".jsonl")) continue;
320
- if (!known.has(name)) throw new Refusal("invalid-database", `.c64-re-tools/knowledge/${name} is not a knowledge file. Knowledge files are ${[...known].join(", ")}.`);
340
+ for (const name of knowledgeFiles(directory)) {
321
341
  const bytes = readFileSync(join(directory, name));
322
342
  files.set(name, { text: bytes.toString("utf8"), sha256: sha256(bytes) });
323
343
  }
@@ -357,11 +377,11 @@ function parseLines(file: string, text: string): Array<{ line: number; value: Ra
357
377
  return lines;
358
378
  }
359
379
 
360
- /** The column values of one line, checked against its fields. */
361
- function columnsOf(file: string, line: number, value: Raw, fields: readonly Field[], extra: readonly string[]): Raw {
362
- // A line of an earlier format: the key that this format added is missing, and the remedy tells what to do.
363
- for (const { key, remedy } of fields) if (remedy !== undefined && (value[key] === undefined || value[key] === null)) bad(file, line, `the key ${JSON.stringify(key)} is missing. ${remedy}`);
364
- const allowed = new Set([...fields.map((item) => item.key), ...extra]);
380
+ /** The keys of a line: the keys of its fields and the extra keys. */
381
+ const keysOf = (fields: readonly Field[], extra: readonly string[] = []): ReadonlySet<string> => new Set([...fields.map((item) => item.key), ...extra]);
382
+
383
+ /** The column values of one line, checked against its fields; `allowed` holds the keys of the line (keysOf). */
384
+ function columnsOf(file: string, line: number, value: Raw, fields: readonly Field[], allowed: ReadonlySet<string>): Raw {
365
385
  for (const key of Object.keys(value)) if (!allowed.has(key)) bad(file, line, `the key ${JSON.stringify(key)} is not known.`);
366
386
  const columns: Raw = {};
367
387
  for (const { key, column, format, optional } of fields) {
@@ -417,8 +437,9 @@ interface RevisionLine {
417
437
  const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
418
438
 
419
439
  function parseRevisions(text: string): RevisionLine[] {
440
+ const allowed = keysOf(REVISION_FIELDS, ["evidence"]);
420
441
  const entries = parseLines(REVISIONS_FILE, text).map(({ line, value }) => {
421
- const columns = columnsOf(REVISIONS_FILE, line, value, REVISION_FIELDS, ["evidence"]);
442
+ const columns = columnsOf(REVISIONS_FILE, line, value, REVISION_FIELDS, allowed);
422
443
  if (!REVISION_ID.test(columns.id as string)) bad(REVISIONS_FILE, line, `${JSON.stringify(columns.id)} is not a revision id.`);
423
444
  const evidence = value.evidence ?? [];
424
445
  if (!Array.isArray(evidence) || evidence.some((item) => typeof item !== "object" || item === null)) bad(REVISIONS_FILE, line, "evidence must be a list of objects.");
@@ -437,8 +458,10 @@ interface RowLine {
437
458
  }
438
459
 
439
460
  function parseRows(spec: TableSpec, text: string): RowLine[] {
461
+ const fields = [field("id", "id", "text"), ...spec.fields, field("added", "valid_from_revision", "text"), field("closed", "valid_to_revision", "text", true)];
462
+ const allowed = keysOf(fields);
440
463
  const entries = parseLines(spec.file, text).map(({ line, value }) => {
441
- const columns = columnsOf(spec.file, line, value, [field("id", "id", "text"), ...spec.fields, field("added", "valid_from_revision", "text"), field("closed", "valid_to_revision", "text", true)], []);
464
+ const columns = columnsOf(spec.file, line, value, fields, allowed);
442
465
  const id = ROW_ID.exec(columns.id as string);
443
466
  if (id === null) bad(spec.file, line, `${JSON.stringify(columns.id)} is not a row id.`);
444
467
  if (id[1] !== columns.valid_from_revision) bad(spec.file, line, `the row ${columns.id} must be added in revision ${id[1]}.`);