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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +7 -4
  3. package/skills/c64-assembler/scripts/assembler.ts +73 -44
  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 +62 -31
  15. package/skills/c64-packer/scripts/packer.ts +3 -3
  16. package/skills/c64-provenance/SKILL.md +28 -18
  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 +144 -113
  22. package/skills/c64-source/SKILL.md +6 -1
  23. package/skills/c64-source/references/loader.md +2 -1
  24. package/skills/c64-source/scripts/lib/export.ts +54 -301
  25. package/skills/c64-source/scripts/lib/loader.ts +31 -51
  26. package/skills/c64-source/scripts/lib/source.ts +53 -45
  27. package/skills/c64-source/scripts/lib/stage.ts +9 -25
  28. package/skills/c64-source/scripts/source.ts +134 -294
  29. package/skills/c64-static-analysis/SKILL.md +13 -7
  30. package/skills/c64-static-analysis/scripts/lib/coverage.ts +1 -3
  31. package/skills/c64-static-analysis/scripts/lib/findings.ts +16 -3
  32. package/skills/c64-static-analysis/scripts/lib/idioms.ts +98 -19
  33. package/skills/c64-static-analysis/scripts/lib/triage.ts +112 -0
  34. package/skills/c64-static-analysis/scripts/static-analysis.ts +249 -147
  35. package/skills/c64-testing/SKILL.md +13 -7
  36. package/skills/c64-testing/scripts/lib/diff-files.ts +6 -13
  37. package/skills/c64-testing/scripts/lib/recording.ts +47 -66
  38. package/skills/c64-testing/scripts/lib/replay.ts +53 -9
  39. package/skills/c64-testing/scripts/lib/runs.ts +11 -29
  40. package/skills/c64-testing/scripts/lib/scenario.ts +30 -31
  41. package/skills/c64-testing/scripts/lib/start-screen.ts +42 -5
  42. package/skills/c64-testing/scripts/testing.ts +32 -7
  43. package/skills/c64-unpacker/SKILL.md +9 -7
  44. package/skills/c64-unpacker/scripts/lib/evidence.ts +23 -38
  45. package/skills/c64-unpacker/scripts/lib/loads.ts +24 -39
  46. package/skills/c64-unpacker/scripts/lib/machine.ts +38 -18
  47. package/skills/c64-unpacker/scripts/lib/stages.ts +124 -40
  48. package/skills/c64-unpacker/scripts/unpacker.ts +81 -68
  49. package/skills/emulator/SKILL.md +1 -0
  50. package/src/c64.ts +133 -10
  51. package/src/cli/ap-sdk.ts +1 -1
  52. package/src/cli/cleanup.ts +4 -2
  53. package/src/compare.ts +36 -16
  54. package/src/errors.ts +10 -1
  55. package/src/host/main.ts +2 -1
  56. package/src/host/server.ts +7 -11
  57. package/src/host/tools/c1541.ts +9 -3
  58. package/src/host/vice/adapter.ts +20 -43
  59. package/src/host/vice/binary-monitor.ts +22 -21
  60. package/src/host/vice/process.ts +31 -40
  61. package/src/host/vice/session.ts +187 -247
  62. package/src/host/vice/text-monitor.ts +3 -3
  63. package/src/host-client/autostart.ts +1 -1
  64. package/src/host-client/connect.ts +2 -1
  65. package/src/host-client/coverage.ts +0 -3
  66. package/src/host-client/entry-state.ts +4 -11
  67. package/src/host-client/image.ts +6 -11
  68. package/src/host-client/steps.ts +13 -113
  69. package/src/host-client/tools.ts +4 -4
  70. package/src/host-client/transfer.ts +10 -0
  71. package/src/host-client/vice-session.ts +10 -6
  72. package/src/knowledge/code-reach.ts +364 -0
  73. package/src/knowledge/conflicts.ts +34 -72
  74. package/src/knowledge/database.ts +40 -28
  75. package/src/knowledge/evidence.ts +2 -2
  76. package/src/knowledge/graph.ts +3 -3
  77. package/src/knowledge/history.ts +50 -90
  78. package/src/knowledge/import.ts +28 -68
  79. package/src/knowledge/join.ts +1 -1
  80. package/src/knowledge/names.ts +12 -7
  81. package/src/knowledge/program.ts +59 -72
  82. package/src/knowledge/read.ts +104 -100
  83. package/src/knowledge/schema.ts +9 -3
  84. package/src/knowledge/separate.ts +175 -80
  85. package/src/knowledge/start-screen.ts +7 -5
  86. package/src/knowledge/text.ts +56 -33
  87. package/src/knowledge/write.ts +274 -515
  88. package/src/loader.ts +7 -25
  89. package/src/mcp/inputs.ts +3 -3
  90. package/src/mcp/server.ts +19 -38
  91. package/src/mcp/session-source.ts +2 -1
  92. package/src/mcp/tools/debug.ts +97 -24
  93. package/src/mcp/tools/execution.ts +1 -1
  94. package/src/mcp/tools/input.ts +3 -3
  95. package/src/mcp/tools/machine.ts +3 -3
  96. package/src/mcp/tools/media.ts +4 -4
  97. package/src/mcp/tools/memory.ts +13 -17
  98. package/src/mcp/tools/video.ts +11 -25
  99. package/src/native/acme.ts +3 -3
  100. package/src/native/c64run.ts +2 -1
  101. package/src/native/decompiler/analyze.ts +11 -8
  102. package/src/native/decompiler/walk.ts +3 -4
  103. package/src/native/decompiler/wasm.ts +2 -2
  104. package/src/native/discover.ts +1 -1
  105. package/src/native/dxa.ts +9 -11
  106. package/src/native/exomizer.ts +1 -1
  107. package/src/native/processes.ts +4 -1
  108. package/src/native/run.ts +3 -3
  109. package/src/native/types.ts +9 -8
  110. package/src/opcodes.ts +3 -0
  111. package/src/platform.ts +9 -10
  112. package/src/program-code.ts +151 -0
  113. package/src/project.ts +8 -5
  114. package/src/protocol/framing.ts +51 -18
  115. package/src/protocol/messages.ts +1 -11
  116. package/src/protocol/tools.ts +0 -3
  117. package/src/protocol/vice.ts +588 -773
  118. package/src/script.ts +25 -23
  119. package/src/time.ts +1 -1
  120. package/src/trace.ts +3 -2
@@ -1,14 +1,17 @@
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 { type AddressRange, COVERAGE, executedRamCode, inRanges, instructionLength, NO_FALL, rangesOverlap } from "../c64.ts";
13
+ import { JAM_OPCODES, OPCODES } from "../opcodes.ts";
14
+ import { isSemantic } from "./schema.ts";
12
15
 
13
16
  export type Access = "executed" | "read" | "written" | "read-written" | "untouched";
14
17
 
@@ -22,9 +25,8 @@ export interface SeparationInput {
22
25
  /** Joined coverage files. */
23
26
  coverage?: Uint8Array;
24
27
  codeRegions: Array<AddressRange & { type: string }>;
25
- references: Array<{ from: number; to: number; kind: string }>;
26
- /** The instructions with a reference of the user or the LLM from them: the LLM recorded the targets of their flows. */
27
- resolvedSites?: ReadonlySet<number>;
28
+ /** A jump or call reference of the user or the LLM also resolves the flow of its instruction. */
29
+ references: Array<{ from: number; to: number; kind: string; origin?: string | undefined }>;
28
30
  /** More roots after the entry and the hardware vectors, for example code that a run executed. */
29
31
  roots?: Root[];
30
32
  }
@@ -47,12 +49,20 @@ export interface CodeRegionEvidence extends AddressRange {
47
49
 
48
50
  /**
49
51
  * A flow whose targets the knowledge does not give: a JMP (indirect) through
50
- * a vector that a run wrote or that is not in the image, or a JMP or JSR whose
51
- * address bytes a run wrote.
52
+ * a vector that the code's own immediates do not set, a JMP or JSR whose
53
+ * address bytes a run wrote, or an RTS or RTI to an address that the code
54
+ * pushed.
52
55
  */
53
56
  export interface UnresolvedFlow {
54
57
  at: number;
55
- kind: "indirect-jump" | "written-operand";
58
+ kind: "indirect-jump" | "written-operand" | "pushed-return";
59
+ }
60
+
61
+ /** The computed flows of the code: the targets that the bytes of the program give, and the flows that stay open. */
62
+ export interface ComputedFlows {
63
+ /** Also from each store of a handler into an interrupt vector to the handler. */
64
+ targets: Array<{ from: number; to: number }>;
65
+ unresolved: UnresolvedFlow[];
56
66
  }
57
67
 
58
68
  /** An address where the reachability starts, and why: the entry, a hardware vector in the image, or a root that the caller gives. */
@@ -73,7 +83,7 @@ export interface Separation {
73
83
  * pieces of code with gaps of up to two operand bytes.
74
84
  */
75
85
  outside: { read: AddressRange[]; executed: AddressRange[]; generated: AddressRange[] };
76
- /** The unresolved flows of the code regions: while one exists, an unreached code region is unknown. */
86
+ /** The unresolved flows of the code regions that a root reaches or that a run executed: while one exists, an unreached code region is unknown. */
77
87
  unresolved: UnresolvedFlow[];
78
88
  }
79
89
 
@@ -91,21 +101,20 @@ const HARDWARE_VECTORS = [
91
101
  * two bytes are in the image. An interrupt handler runs by its vector, and
92
102
  * no call or jump reference reaches it.
93
103
  */
94
- export function reachabilityRoots(segments: readonly AddressRange[], memory: Uint8Array, entry?: number): Root[] {
95
- const inImage = (address: number) => segments.some((segment) => address >= segment.start && address <= segment.end);
96
- 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 }));
97
106
  return [...(entry === undefined ? [] : [{ address: entry, from: "entry" as const }]), ...vectors];
98
107
  }
99
108
 
100
109
  /** BRK, JMP, RTI, RTS, JMP (indirect) and the JAM opcodes: the CPU does not run on to the next instruction after them. */
101
- 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]);
102
111
 
103
112
  /**
104
113
  * The address after a code region where the CPU runs on, or undefined when
105
114
  * its last instruction does not run on (RTS, RTI, JMP, BRK, JAM). The
106
115
  * instructions follow one another from the start of the region.
107
116
  */
108
- export function fallThrough(region: AddressRange, memory: Uint8Array): number | undefined {
117
+ function fallThrough(region: AddressRange, memory: Uint8Array): number | undefined {
109
118
  let at = region.start;
110
119
  let last = at;
111
120
  while (at <= region.end) {
@@ -116,70 +125,148 @@ export function fallThrough(region: AddressRange, memory: Uint8Array): number |
116
125
  }
117
126
 
118
127
  /** The instruction starts of code regions: each region runs from its start, one instruction after the other. */
119
- export function regionStarts(regions: readonly AddressRange[], memory: Uint8Array): number[] {
128
+ function regionStarts(regions: readonly AddressRange[], memory: Uint8Array): number[] {
120
129
  const starts: number[] = [];
121
130
  for (const region of regions) for (let at = region.start; at <= region.end; at += instructionLength(memory[at]!)) starts.push(at);
122
131
  return starts.sort((a, b) => a - b);
123
132
  }
124
133
 
134
+ /** The address of the high byte of the vector of a JMP (N): the 6510 reads it from N + 1 in the same page, so JMP ($10ff) reads $1000. */
135
+ export const vectorHigh = (vector: number) => (vector & 0xff00) | ((vector + 1) & 0xff);
136
+
137
+ /** The registers that each instruction changes, other than by a load of an immediate or a transfer. */
138
+ export const WRITES_A = new Set(["lda", "adc", "sbc", "and", "ora", "eor", "pla", "lax", "anc", "asr", "arr", "ane", "lxa", "las", "slo", "rla", "sre", "rra", "isc"]);
139
+ export const WRITES_X = new Set(["ldx", "inx", "dex", "tsx", "lax", "sbx", "lxa", "las"]);
140
+ 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. */
143
+ const CHANGES_MEMORY = new Set(["inc", "dec", "asl", "lsr", "rol", "ror", "sax", "slo", "rla", "sre", "rra", "dcp", "isc"]);
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
+
125
152
  /**
126
- * The vectors that the program sets with its own immediates: an LDA, LDX or
127
- * LDY # and a store to N, and the same to N + 1, in one run of instructions.
128
- * A JMP (N) then goes where those immediates point, which the flows of the
129
- * stores give.
153
+ * The computed flows of the instructions at `starts`: a JMP (N), a JMP or JSR
154
+ * whose address bytes a run wrote, and an RTS or RTI after pushes in its run
155
+ * of instructions. A jump or call reference of the user or the LLM from the
156
+ * instruction resolves its flow; for a pushed return, also one of the idiom
157
+ * pass, which reads the table of an RTS dispatch. Else the bytes resolve it:
158
+ * each byte holds its image byte and the immediates that the code stores
159
+ * there, and the flow goes to each word of these values. A byte that another
160
+ * write of the code changes, or that a run wrote while no store of the code
161
+ * does, or that is outside the image without such a store, leaves the flow
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.
130
167
  */
131
- export function immediateVectors(starts: readonly number[], memory: Uint8Array): Set<number> {
132
- const stored = new Set<number>();
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 {
169
+ const { memory } = input;
170
+ const written = (address: number) => input.coverage !== undefined && (input.coverage[address & 0xffff]! & COVERAGE.ramWrite) !== 0;
171
+ const jumpsFrom = (origins: (origin: string | undefined) => boolean) => new Set(input.references.filter((reference) => (reference.kind === "jump" || reference.kind === "call") && origins(reference.origin)).map((reference) => reference.from));
172
+ const resolved = jumpsFrom(isSemantic);
173
+ const fromTable = jumpsFrom((origin) => isSemantic(origin) || origin === "heuristic");
174
+ const starts = [...input.starts].sort((a, b) => a - b);
175
+
176
+ // The immediates that the code stores at each address; null when another write changes it.
177
+ const stored = new Map<number, Set<number> | null>();
178
+ const store = (address: number, value: number | undefined) => {
179
+ const known = stored.get(address);
180
+ if (known === null) return;
181
+ stored.set(address, value === undefined ? null : (known ?? new Set<number>()).add(value));
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]));
186
+ // The return addresses that the code pushed before an RTS or RTI, as far as immediates give them.
187
+ const returns: Array<{ at: number; low: number | undefined; high: number | undefined; offset: 0 | 1 }> = [];
133
188
  let registers: { a?: number | undefined; x?: number | undefined; y?: number | undefined } = {};
189
+ let pushes: Array<number | undefined> = [];
134
190
  let previousEnd = -2;
135
- for (const at of [...starts].sort((a, b) => a - b)) {
136
- if (at > previousEnd + 1) registers = {};
191
+ for (const at of starts) {
192
+ if (at > previousEnd + 1) {
193
+ registers = {};
194
+ pushes = [];
195
+ }
137
196
  const opcode = memory[at]!;
197
+ const { mnemonic, mode } = OPCODES[opcode]!;
138
198
  const length = instructionLength(opcode);
139
199
  previousEnd = at + length - 1;
140
- const operand = length === 3 ? memory[at + 1]! | (memory[(at + 2) & 0xffff]! << 8) : memory[(at + 1) & 0xffff]!;
141
- const store = (value: number | undefined) => {
142
- if (value !== undefined) stored.add(operand);
143
- };
144
- switch (opcode) {
145
- case 0xa9: registers.a = operand; break;
146
- case 0xa2: registers.x = operand; break;
147
- case 0xa0: registers.y = operand; break;
148
- case 0x85: case 0x8d: store(registers.a); break;
149
- case 0x86: case 0x8e: store(registers.x); break;
150
- case 0x84: case 0x8c: store(registers.y); break;
151
- case 0xaa: registers.x = registers.a; break;
152
- case 0xa8: registers.y = registers.a; break;
153
- case 0x8a: registers.a = registers.x; break;
154
- case 0x98: registers.a = registers.y; break;
155
- default: registers = {};
200
+ const operand = length === 3 ? memory[(at + 1) & 0xffff]! | (memory[(at + 2) & 0xffff]! << 8) : memory[(at + 1) & 0xffff]!;
201
+ if (mode === "zp" || mode === "abs") {
202
+ const register = mnemonic === "sta" ? "a" : mnemonic === "stx" ? "x" : mnemonic === "sty" ? "y" : undefined;
203
+ if (register !== undefined) store(operand, registers[register]);
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 }]);
207
+ }
208
+ if (mnemonic === "pha") pushes.push(registers.a);
209
+ if (mnemonic === "php") pushes.push(undefined);
210
+ if (mnemonic === "pla" || mnemonic === "plp") pushes.pop();
211
+ if (mnemonic === "txs") pushes = [];
212
+ if (mnemonic === "rts" && pushes.length >= 2) returns.push({ at, low: pushes.at(-1), high: pushes.at(-2), offset: 1 });
213
+ if (mnemonic === "rti" && pushes.length >= 3) returns.push({ at, low: pushes.at(-2), high: pushes.at(-3), offset: 0 });
214
+ const loaded = mode === "imm" ? operand : undefined;
215
+ if (WRITES_A.has(mnemonic) || (mode === "imp" && ["asl", "lsr", "rol", "ror"].includes(mnemonic))) registers.a = mnemonic === "lda" ? loaded : undefined;
216
+ if (WRITES_X.has(mnemonic)) registers.x = mnemonic === "ldx" ? loaded : undefined;
217
+ if (WRITES_Y.has(mnemonic)) registers.y = mnemonic === "ldy" ? loaded : undefined;
218
+ if (mnemonic === "tax") registers.x = registers.a;
219
+ if (mnemonic === "tay") registers.y = registers.a;
220
+ if (mnemonic === "txa") registers.a = registers.x;
221
+ if (mnemonic === "tya") registers.a = registers.y;
222
+ if (mnemonic === "jsr") registers = {};
223
+ if (NO_FALL_THROUGH.has(opcode)) {
224
+ registers = {};
225
+ pushes = [];
156
226
  }
157
- if (NO_FALL_THROUGH.has(opcode)) registers = {};
158
227
  }
159
- return new Set([...stored].filter((address) => stored.has((address + 1) & 0xffff)));
160
- }
161
228
 
162
- /**
163
- * The unresolved flows of the instructions at `starts`. A flow is resolved
164
- * when a reference of the user or the LLM goes from it. An indirect jump is
165
- * also resolved when the program's own immediates set its vector, or when the
166
- * vector is in the image and no run wrote it.
167
- */
168
- export function unresolvedFlows(input: { starts: readonly number[]; memory: Uint8Array; inImage: (address: number) => boolean; coverage?: Uint8Array | undefined; resolvedSites?: ReadonlySet<number> | undefined }): UnresolvedFlow[] {
169
- const written = (address: number) => input.coverage !== undefined && (input.coverage[address & 0xffff]! & COVERAGE.ramWrite) !== 0;
170
- const vectors = immediateVectors(input.starts, input.memory);
171
- const flows: UnresolvedFlow[] = [];
172
- for (const at of input.starts) {
173
- if (input.resolvedSites?.has(at) === true) continue;
174
- const opcode = input.memory[at]!;
229
+ /** The values of a byte when the code reads it, or undefined when they are not known. */
230
+ const valuesAt = (address: number): number[] | undefined => {
231
+ const own = stored.get(address);
232
+ if (own === null || (own === undefined && (written(address) || !input.inImage(address)))) return undefined;
233
+ return [...new Set([...(own ?? []), ...(input.inImage(address) ? [memory[address]!] : [])])];
234
+ };
235
+ const targets: ComputedFlows["targets"] = [];
236
+ /** Adds a flow from `from` to each word of the bytes at `low` and `high`; false when a byte is not known. */
237
+ const wordsAt = (from: number, low: number, high: number) => {
238
+ const lows = valuesAt(low);
239
+ const highs = valuesAt(high);
240
+ if (lows === undefined || highs === undefined) return false;
241
+ for (const lowByte of lows) for (const highByte of highs) targets.push({ from, to: lowByte | (highByte << 8) });
242
+ return true;
243
+ };
244
+ const unresolved: UnresolvedFlow[] = [];
245
+ for (const at of starts) {
246
+ if (resolved.has(at)) continue;
247
+ const opcode = memory[at]!;
175
248
  if (opcode === 0x6c) {
176
- const vector = input.memory[(at + 1) & 0xffff]! | (input.memory[(at + 2) & 0xffff]! << 8);
177
- if (vectors.has(vector)) continue;
178
- if (input.inImage(vector) && input.inImage((vector + 1) & 0xffff) && !written(vector) && !written(vector + 1)) continue;
179
- flows.push({ at, kind: "indirect-jump" });
180
- } else if ((opcode === 0x4c || opcode === 0x20) && (written(at + 1) || written(at + 2))) flows.push({ at, kind: "written-operand" });
249
+ const vector = memory[(at + 1) & 0xffff]! | (memory[(at + 2) & 0xffff]! << 8);
250
+ if (!wordsAt(at, vector, vectorHigh(vector))) unresolved.push({ at, kind: "indirect-jump" });
251
+ } else if ((opcode === 0x4c || opcode === 0x20) && (written(at + 1) || written(at + 2))) {
252
+ if (!wordsAt(at, (at + 1) & 0xffff, (at + 2) & 0xffff)) unresolved.push({ at, kind: "written-operand" });
253
+ }
181
254
  }
182
- return flows;
255
+ for (const pushed of returns) {
256
+ if (pushed.low !== undefined && pushed.high !== undefined) targets.push({ from: pushed.at, to: ((pushed.low | (pushed.high << 8)) + pushed.offset) & 0xffff });
257
+ else if (!fromTable.has(pushed.at)) unresolved.push({ at: pushed.at, kind: "pushed-return" });
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
+ }
269
+ return { targets, unresolved: unresolved.sort((a, b) => a.at - b.at) };
183
270
  }
184
271
 
185
272
  /** The most instructions outside the code regions that the run on from a region goes through, for example an instruction in a dual-use region. */
@@ -197,7 +284,7 @@ function merge(addresses: number[], gap = 0, joins: (from: number, to: number) =
197
284
  }
198
285
 
199
286
  export function separate(input: SeparationInput): Separation {
200
- const inImage = (address: number) => input.segments.some((segment) => address >= segment.start && address <= segment.end);
287
+ const inImage = (address: number) => inRanges(input.segments, address);
201
288
  const executed = new Uint8Array(0x10000);
202
289
  if (input.coverage !== undefined) for (const range of executedRamCode(input.coverage, 0, input.memory)) executed.fill(1, range.start, range.end + 1);
203
290
  const accessAt = (address: number): Access | undefined => {
@@ -208,11 +295,12 @@ export function separate(input: SeparationInput): Separation {
208
295
  const written = (flags & COVERAGE.ramWrite) !== 0;
209
296
  return read && written ? "read-written" : read ? "read" : written ? "written" : "untouched";
210
297
  };
211
- const stageAt = (address: number): number | undefined => {
212
- const stages = input.stages ?? [];
213
- for (let index = stages.length - 1; index >= 0; index--) if (stages[index]!.wrote.some((range) => address >= range.start && address <= range.end)) return index;
214
- return undefined;
215
- };
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]);
216
304
 
217
305
  const ranges: EvidenceRange[] = [];
218
306
  for (const segment of input.segments) {
@@ -228,7 +316,7 @@ export function separate(input: SeparationInput): Separation {
228
316
  }
229
317
  }
230
318
 
231
- 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)));
232
320
  // The region of each address: the first region that holds it, as a search in region order finds it.
233
321
  const owner = new Int32Array(0x10000).fill(-1);
234
322
  regions.forEach((region, index) => {
@@ -252,9 +340,11 @@ export function separate(input: SeparationInput): Separation {
252
340
  const to = next === undefined ? undefined : runOn(next);
253
341
  return to === undefined ? [] : [{ from: region.end, to }];
254
342
  });
255
- // From the regions that hold a root, through call and jump references and the run on, to every region they reach.
343
+ // A store anywhere in the code can change a vector, so the computed flows read every region.
344
+ const computed = computedFlows({ starts: regionStarts(regions, input.memory), memory: input.memory, inImage, coverage: input.coverage, references: input.references });
345
+ // From the regions that hold a root, through call and jump references, the targets of computed flows and the run on, to every region they reach.
256
346
  const next = regions.map((): number[] => []);
257
- for (const flow of [...input.references.filter((reference) => reference.kind === "call" || reference.kind === "jump"), ...runsOn]) {
347
+ for (const flow of [...input.references.filter((reference) => reference.kind === "call" || reference.kind === "jump"), ...computed.targets, ...runsOn]) {
258
348
  const from = holding(flow.from);
259
349
  const to = holding(flow.to);
260
350
  if (from >= 0 && to >= 0) next[from]!.push(to);
@@ -275,15 +365,20 @@ export function separate(input: SeparationInput): Separation {
275
365
  queue.push(to);
276
366
  }
277
367
  }
278
- const unresolved = unresolvedFlows({ starts: regionStarts(regions, input.memory), memory: input.memory, inImage, coverage: input.coverage, resolvedSites: input.resolvedSites });
368
+ // Undefined without coverage.
369
+ const ran = regions.map((region): boolean | undefined => {
370
+ if (input.coverage === undefined) return undefined;
371
+ for (let address = region.start; address <= region.end; address++) if (executed[address] === 1) return true;
372
+ return false;
373
+ });
374
+ // Only a flow in code that a root reaches or that a run executed can run: a flow in dead code goes nowhere.
375
+ const unresolved = computed.unresolved.filter((flow) => {
376
+ const index = holding(flow.at);
377
+ return index >= 0 && (reached.has(index) || ran[index] === true);
378
+ });
279
379
  const codeRegions = regions.map((region, index): CodeRegionEvidence => {
280
- let ran: boolean | undefined;
281
- if (input.coverage !== undefined) {
282
- ran = false;
283
- for (let address = region.start; address <= region.end && !ran; address++) ran = executed[address] === 1;
284
- }
285
- const unreached = roots.length > 0 && !reached.has(index) && ran !== true;
286
- return { start: region.start, end: region.end, type: region.type, ...(roots.length === 0 ? {} : { reachable: reached.has(index) }), ...(ran === undefined ? {} : { executed: ran }), ...(unreached && (unresolved.length > 0 || input.coverage === undefined) ? { unknown: true as const } : {}) };
380
+ const unreached = roots.length > 0 && !reached.has(index) && ran[index] !== true;
381
+ return { start: region.start, end: region.end, type: region.type, ...(roots.length === 0 ? {} : { reachable: reached.has(index) }), ...(ran[index] === undefined ? {} : { executed: ran[index] }), ...(unreached && (unresolved.length > 0 || input.coverage === undefined) ? { unknown: true as const } : {}) };
287
382
  });
288
383
 
289
384
  const read: number[] = [];
@@ -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]}.`);