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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +5 -2
  3. package/skills/c64-assembler/scripts/assembler.ts +55 -48
  4. package/skills/c64-disk/scripts/disk.ts +3 -3
  5. package/skills/c64-disk/scripts/lib/containers.ts +2 -2
  6. package/skills/c64-docs/SKILL.md +1 -1
  7. package/skills/c64-docs/scripts/docs.ts +12 -20
  8. package/skills/c64-docs/scripts/lib/links.ts +1 -1
  9. package/skills/c64-docs/scripts/lib/markdown.ts +1 -1
  10. package/skills/c64-docs/scripts/lib/reference.ts +59 -13
  11. package/skills/c64-knowledge/SKILL.md +17 -8
  12. package/skills/c64-knowledge/scripts/knowledge.ts +200 -218
  13. package/skills/c64-knowledge/scripts/lib/check.ts +2 -3
  14. package/skills/c64-knowledge/scripts/lib/listing.ts +56 -24
  15. package/skills/c64-packer/scripts/packer.ts +3 -3
  16. package/skills/c64-provenance/SKILL.md +25 -16
  17. package/skills/c64-provenance/scripts/lib/compare.ts +31 -21
  18. package/skills/c64-provenance/scripts/lib/leftovers.ts +17 -35
  19. package/skills/c64-provenance/scripts/lib/library.ts +10 -10
  20. package/skills/c64-provenance/scripts/lib/runtime.ts +3 -14
  21. package/skills/c64-provenance/scripts/provenance.ts +129 -98
  22. package/skills/c64-source/references/loader.md +2 -1
  23. package/skills/c64-source/scripts/lib/export.ts +54 -303
  24. package/skills/c64-source/scripts/lib/loader.ts +31 -51
  25. package/skills/c64-source/scripts/lib/source.ts +51 -41
  26. package/skills/c64-source/scripts/lib/stage.ts +9 -25
  27. package/skills/c64-source/scripts/source.ts +134 -294
  28. package/skills/c64-static-analysis/SKILL.md +10 -5
  29. package/skills/c64-static-analysis/scripts/lib/coverage.ts +1 -3
  30. package/skills/c64-static-analysis/scripts/lib/findings.ts +16 -3
  31. package/skills/c64-static-analysis/scripts/lib/idioms.ts +82 -10
  32. package/skills/c64-static-analysis/scripts/lib/triage.ts +112 -0
  33. package/skills/c64-static-analysis/scripts/static-analysis.ts +239 -147
  34. package/skills/c64-testing/SKILL.md +13 -7
  35. package/skills/c64-testing/scripts/lib/diff-files.ts +6 -13
  36. package/skills/c64-testing/scripts/lib/recording.ts +47 -66
  37. package/skills/c64-testing/scripts/lib/replay.ts +53 -9
  38. package/skills/c64-testing/scripts/lib/runs.ts +11 -29
  39. package/skills/c64-testing/scripts/lib/scenario.ts +30 -31
  40. package/skills/c64-testing/scripts/lib/start-screen.ts +42 -5
  41. package/skills/c64-testing/scripts/testing.ts +32 -7
  42. package/skills/c64-unpacker/SKILL.md +9 -7
  43. package/skills/c64-unpacker/scripts/lib/evidence.ts +23 -38
  44. package/skills/c64-unpacker/scripts/lib/loads.ts +24 -39
  45. package/skills/c64-unpacker/scripts/lib/machine.ts +38 -18
  46. package/skills/c64-unpacker/scripts/lib/stages.ts +124 -40
  47. package/skills/c64-unpacker/scripts/unpacker.ts +81 -68
  48. package/skills/emulator/SKILL.md +1 -0
  49. package/src/c64.ts +117 -10
  50. package/src/cli/ap-sdk.ts +1 -1
  51. package/src/cli/cleanup.ts +4 -2
  52. package/src/compare.ts +36 -16
  53. package/src/errors.ts +10 -1
  54. package/src/host/main.ts +2 -1
  55. package/src/host/server.ts +7 -11
  56. package/src/host/tools/c1541.ts +9 -3
  57. package/src/host/vice/adapter.ts +20 -43
  58. package/src/host/vice/binary-monitor.ts +22 -21
  59. package/src/host/vice/process.ts +31 -40
  60. package/src/host/vice/session.ts +187 -247
  61. package/src/host/vice/text-monitor.ts +3 -3
  62. package/src/host-client/autostart.ts +1 -1
  63. package/src/host-client/connect.ts +2 -1
  64. package/src/host-client/coverage.ts +0 -3
  65. package/src/host-client/entry-state.ts +4 -11
  66. package/src/host-client/image.ts +6 -11
  67. package/src/host-client/steps.ts +13 -113
  68. package/src/host-client/tools.ts +4 -4
  69. package/src/host-client/transfer.ts +10 -0
  70. package/src/host-client/vice-session.ts +10 -6
  71. package/src/knowledge/code-reach.ts +364 -0
  72. package/src/knowledge/conflicts.ts +34 -72
  73. package/src/knowledge/database.ts +40 -28
  74. package/src/knowledge/evidence.ts +2 -2
  75. package/src/knowledge/graph.ts +3 -3
  76. package/src/knowledge/history.ts +50 -90
  77. package/src/knowledge/import.ts +28 -68
  78. package/src/knowledge/join.ts +1 -1
  79. package/src/knowledge/names.ts +12 -7
  80. package/src/knowledge/program.ts +25 -46
  81. package/src/knowledge/read.ts +104 -100
  82. package/src/knowledge/schema.ts +9 -3
  83. package/src/knowledge/separate.ts +47 -19
  84. package/src/knowledge/start-screen.ts +7 -5
  85. package/src/knowledge/text.ts +56 -33
  86. package/src/knowledge/write.ts +274 -515
  87. package/src/loader.ts +7 -25
  88. package/src/mcp/inputs.ts +3 -3
  89. package/src/mcp/server.ts +19 -38
  90. package/src/mcp/session-source.ts +2 -1
  91. package/src/mcp/tools/debug.ts +97 -24
  92. package/src/mcp/tools/execution.ts +1 -1
  93. package/src/mcp/tools/input.ts +3 -3
  94. package/src/mcp/tools/machine.ts +3 -3
  95. package/src/mcp/tools/media.ts +4 -4
  96. package/src/mcp/tools/memory.ts +13 -17
  97. package/src/mcp/tools/video.ts +11 -25
  98. package/src/native/acme.ts +3 -3
  99. package/src/native/c64run.ts +2 -1
  100. package/src/native/decompiler/analyze.ts +10 -7
  101. package/src/native/decompiler/walk.ts +3 -4
  102. package/src/native/decompiler/wasm.ts +2 -2
  103. package/src/native/discover.ts +1 -1
  104. package/src/native/dxa.ts +9 -11
  105. package/src/native/exomizer.ts +1 -1
  106. package/src/native/processes.ts +4 -1
  107. package/src/native/run.ts +3 -3
  108. package/src/native/types.ts +5 -6
  109. package/src/opcodes.ts +3 -0
  110. package/src/platform.ts +9 -10
  111. package/src/program-code.ts +151 -0
  112. package/src/project.ts +8 -5
  113. package/src/protocol/framing.ts +51 -18
  114. package/src/protocol/messages.ts +1 -11
  115. package/src/protocol/tools.ts +0 -3
  116. package/src/protocol/vice.ts +588 -773
  117. package/src/script.ts +9 -14
  118. package/src/time.ts +1 -1
  119. package/src/trace.ts +3 -2
@@ -1,68 +1,42 @@
1
1
  // Semantic knowledge writes. Every accepted change is one
2
2
  // revision in one transaction: superseded rows are closed, never deleted.
3
3
 
4
- import type { DatabaseSync } from "node:sqlite";
4
+ import type { DatabaseSync, SQLInputValue } from "node:sqlite";
5
5
 
6
6
  import { Refusal } from "../errors.ts";
7
- import { type AddressRange, formatC64Address, instructionLength, SPACE_PATTERN, SYMBOL_NAME } from "../c64.ts";
7
+ import { type AddressRange, formatC64Address, formatC64Range, instructionLength, type ReferenceKind, REFERENCE_KINDS, SPACE_PATTERN, subtract, SYMBOL_NAME } from "../c64.ts";
8
8
  import { isoCet } from "../time.ts";
9
9
  import { CONFLICT_RULES, conflicts, conflictTable, type Conflict, type ConflictRow } from "./conflicts.ts";
10
- import { transaction } from "./database.ts";
10
+ import { prepare, transaction } from "./database.ts";
11
11
  import { labelProblem, MNEMONICS } from "../opcodes.ts";
12
- import { checkExpression, evaluate, identifiers, operandText, replaceIdentifiers } from "./expression.ts";
12
+ import { checkExpression, evaluate, identifiers, OPERAND_SELECTS, operandText, replaceIdentifiers, type OperandSelect } from "./expression.ts";
13
13
  import {
14
+ baseLabel,
14
15
  baseValue,
15
- COMMENT_COLUMNS,
16
16
  commentsAt,
17
+ coverageRuns,
17
18
  currentRevision,
19
+ currentStartScreen,
20
+ FACTS,
18
21
  listMacroUses,
19
- listOperands,
20
22
  listPatches,
21
- listReleases,
22
23
  listSwitches,
23
24
  listText,
24
- MACRO_COLUMNS,
25
- MACRO_USE_COLUMNS,
26
25
  macroNamed,
27
26
  macroUsesOverlapping,
28
- MODULE_COLUMNS,
29
27
  moduleAt,
30
28
  moduleWithFile,
31
- OPERAND_COLUMNS,
32
29
  operandAt,
33
- PATCH_COLUMNS,
34
30
  patchesOverlapping,
35
- REFERENCE_COLUMNS,
36
31
  referencesFrom,
37
- REGION_COLUMNS,
38
32
  regionsOverlapping,
39
- RELEASE_COLUMNS,
40
33
  releaseLabeled,
41
- SWITCH_COLUMNS,
42
- START_SCREEN_COLUMNS,
43
- currentStartScreen,
44
- startScreenRanges,
45
- switchNamed,
46
- coverageRuns,
47
34
  resolveRevision,
48
- SUPPRESSION_COLUMNS,
35
+ startScreenRanges,
49
36
  suppressionsOverlapping,
50
- SYMBOL_COLUMNS,
37
+ switchNamed,
51
38
  symbolAt,
52
39
  symbolNamed,
53
- toComment,
54
- toMacro,
55
- toMacroUse,
56
- toModule,
57
- toOperand,
58
- toPatch,
59
- toReference,
60
- toRegion,
61
- toRelease,
62
- toSuppression,
63
- toSwitch,
64
- toStartScreen,
65
- toSymbol,
66
40
  type CommentRow,
67
41
  type CoverageRun,
68
42
  type MacroRow,
@@ -78,8 +52,10 @@ import {
78
52
  type SwitchRow,
79
53
  type SymbolRow,
80
54
  } from "./read.ts";
81
- import { CODE_REGION_TYPES, COMMENT_PLACEMENTS, EVIDENCE_KINDS, MAX_ELEMENT, MEMORY_ROW, MODULE_FILE, DEFAULT_SPACE, GENERATED_FILES, GENERATED_FOLDERS, isGeneratedFile, isSemantic, MACRO_NAME, MACRO_PARAM, OFF_KINDS, RELEASE_DEFINE, RELEASE_LABEL, LEFTOVERS_SWITCH, START_SCREEN_MODES, START_SCREEN_SWITCH, SWITCH_KINDS, SWITCH_NAME, NO_ELEMENT_TYPES, OPERAND_SELECTS, POINTER_KIND, REFERENCE_KINDS, REGION_TYPES, SYMBOL_KINDS, type CommentPlacement, type EvidenceKind, type OperandSelect, type Origin, type ReferenceKind, type RegionType, type Space, type StartScreenMode, type SwitchKind, type SymbolKind } from "./schema.ts";
82
- import { newRevisionId, rowId, sqlName } from "./text.ts";
55
+ import { CODE_REGION_TYPES, COMMENT_PLACEMENTS, EVIDENCE_KINDS, MAX_ELEMENT, MEMORY_ROW, MODULE_FILE, DEFAULT_SPACE, spaceOf, GENERATED_FILES, GENERATED_FOLDERS, isGeneratedFile, isSemantic, MACRO_NAME, MACRO_PARAM, OFF_KINDS, RELEASE_DEFINE, RELEASE_LABEL, LEFTOVERS_SWITCH, START_SCREEN_MODES, START_SCREEN_SWITCH, SWITCH_KINDS, SWITCH_NAME, NO_ELEMENT_TYPES, POINTER_KIND, REGION_TYPES, SYMBOL_KINDS, type CommentPlacement, type EvidenceKind, type Origin, type RegionType, type Space, type StartScreenMode, type SwitchKind, type SymbolKind } from "./schema.ts";
56
+ import { newRevisionId, rowId, sqlName, TABLES, tableSpec } from "./text.ts";
57
+
58
+ type Raw = Record<string, unknown>;
83
59
 
84
60
  /** What a change rests on: a coverage run, a test or another project file with its SHA-256, or a note. */
85
61
  export interface Evidence {
@@ -117,7 +93,6 @@ export interface WriteResult<T, P = never> {
117
93
  previous?: P;
118
94
  }
119
95
 
120
- export { SYMBOL_NAME };
121
96
  const MAX_COMMENT = 4000;
122
97
  /** The most characters of patch code and of a macro body. */
123
98
  const MAX_CODE = 8000;
@@ -133,20 +108,6 @@ function checkOneOf<T extends string>(values: readonly T[], value: string, what:
133
108
  if (!(values as readonly string[]).includes(value)) throw new Refusal("invalid-input", `${what} must be one of: ${values.join(", ")}.`);
134
109
  }
135
110
 
136
- /** Parts of `range` that no range in `holes` covers. */
137
- export function subtract(range: AddressRange, holes: AddressRange[]): AddressRange[] {
138
- let pieces = [range];
139
- for (const hole of holes) {
140
- pieces = pieces.flatMap((piece) => {
141
- if (hole.end < piece.start || hole.start > piece.end) return [piece];
142
- const left = hole.start > piece.start ? [{ start: piece.start, end: hole.start - 1 }] : [];
143
- const right = hole.end < piece.end ? [{ start: hole.end + 1, end: piece.end }] : [];
144
- return [...left, ...right];
145
- });
146
- }
147
- return pieces;
148
- }
149
-
150
111
  /** What a revision records about its writer. Analyzer imports may add tool details. */
151
112
  export interface ChangeContext {
152
113
  origin: Origin;
@@ -159,6 +120,20 @@ export interface ChangeContext {
159
120
  restores?: string;
160
121
  /** A revert of one space: the space whose knowledge it restores. Without it, a revert restores every space. */
161
122
  restoresSpace?: Space;
123
+ /** A merge of the work of two computers: it writes while the knowledge has conflicts, to decide them. */
124
+ allowConflicts?: boolean;
125
+ }
126
+
127
+ /** The value of a row field as its column holds it: a list is text, true is 1, false is 0, and a missing value is null. */
128
+ function columnValue(value: unknown): SQLInputValue {
129
+ if (value === undefined) return null;
130
+ if (typeof value === "boolean") return value ? 1 : 0;
131
+ return Array.isArray(value) ? listText(value as string[]) : (value as SQLInputValue);
132
+ }
133
+
134
+ /** The column values of a row of a table, in the order of its fields. `by` names a value of the row by the key of its field (a row as the reads give it) or by its column. */
135
+ function rowValues(table: string, row: object, by: "key" | "column" = "key"): SQLInputValue[] {
136
+ return tableSpec(table).fields.map((field) => columnValue((row as Raw)[field[by]]));
162
137
  }
163
138
 
164
139
  /**
@@ -169,6 +144,10 @@ export class Change {
169
144
  revision: string | null = null;
170
145
  /** The rows this write inserted, for their ids. */
171
146
  #rows = 0;
147
+ /** The tables that this write inserted rows into. */
148
+ readonly #inserted = new Set<string>();
149
+ /** The program bytes of each space: no step of a write changes the program, so a write reads them once. */
150
+ readonly #programs = new Map<Space, (address: number) => number | undefined>();
172
151
  readonly #db: DatabaseSync;
173
152
  readonly #context: ChangeContext;
174
153
  readonly #operation: string;
@@ -178,7 +157,7 @@ export class Change {
178
157
  this.#context = context;
179
158
  this.#operation = operation;
180
159
  // A merge of two computers' work can leave conflicts: only a merge revision writes then.
181
- const found = operation === "merge" ? [] : conflicts(db);
160
+ const found = context.allowConflicts === true ? [] : conflicts(db);
182
161
  if (found.length > 0) {
183
162
  throw new Refusal(
184
163
  "conflict",
@@ -211,13 +190,35 @@ export class Change {
211
190
  /**
212
191
  * Refuses a write that leaves two current rows where one is allowed: the
213
192
  * index has no unique indexes, because a merged text can hold such rows.
193
+ * The knowledge had no conflict before the write, and a closed row makes
194
+ * none, so only the rules of the tables that it inserted into can break; a
195
+ * merge checks every rule.
214
196
  */
215
197
  check(): void {
216
198
  if (this.revision === null) return;
217
- const [found] = conflicts(this.#db);
199
+ const [found] = conflicts(this.#db, this.#context.allowConflicts === true ? undefined : this.#inserted);
218
200
  if (found !== undefined) throw new Refusal("conflict", `The write would leave ${describe(found)}. Nothing was written.`);
219
201
  }
220
202
 
203
+ /**
204
+ * The bytes of the program of a space in the knowledge, by address: undefined
205
+ * outside it. A module and a comment are checked against them.
206
+ */
207
+ programBytes(space: Space): (address: number) => number | undefined {
208
+ let byteAt = this.#programs.get(space);
209
+ if (byteAt === undefined) {
210
+ const memory = new Uint8Array(0x10000);
211
+ const held = new Uint8Array(0x10000);
212
+ for (const row of prepare(this.#db, "SELECT address, bytes FROM current_memory WHERE space = ?").all(space) as Array<{ address: number; bytes: string }>) {
213
+ const bytes = Buffer.from(row.bytes, "hex");
214
+ memory.set(bytes, row.address);
215
+ held.fill(1, row.address, row.address + bytes.length);
216
+ }
217
+ this.#programs.set(space, (byteAt = (address) => (held[address] === 1 ? memory[address] : undefined)));
218
+ }
219
+ return byteAt;
220
+ }
221
+
221
222
  /** The id of the next row this write inserts. */
222
223
  #rowId(): string {
223
224
  return rowId(this.id(), ++this.#rows);
@@ -225,114 +226,96 @@ export class Change {
225
226
 
226
227
  /** Closes the current rows of `table` that `where` selects. */
227
228
  close(table: string, where: string, ...values: Array<number | string>): void {
228
- this.#db.prepare(`UPDATE ${table} SET valid_to_revision = ? WHERE valid_to_revision IS NULL AND ${where}`).run(this.id(), ...values);
229
+ prepare(this.#db, `UPDATE ${sqlName(table)} SET valid_to_revision = ? WHERE valid_to_revision IS NULL AND ${where}`).run(this.id(), ...values);
230
+ }
231
+
232
+ /** Inserts a row of `table` with the values of its columns, in the order of its fields. */
233
+ #insert(table: string, values: SQLInputValue[]): void {
234
+ const columns = tableSpec(table).fields.map((field) => field.column);
235
+ prepare(this.#db, `INSERT INTO ${sqlName(table)} (id, ${columns.join(", ")}, valid_from_revision) VALUES (?, ${columns.map(() => "?").join(", ")}, ?)`).run(this.#rowId(), ...values, this.id());
236
+ this.#inserted.add(table);
237
+ }
238
+
239
+ /** Inserts a row of `table` with the values that `row` has by column name, as a query of the table gives them. */
240
+ insertColumns(table: string, row: Raw): void {
241
+ this.#insert(table, rowValues(table, row, "column"));
229
242
  }
230
243
 
231
244
  insertSymbol(row: Omit<SymbolRow, "revision">): void {
232
- this.#db.prepare("INSERT INTO symbols (id, space, address, name, kind, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?)").run(this.#rowId(), row.space, row.address, row.name, row.kind, row.origin, this.id());
245
+ this.#insert("symbols", rowValues("symbols", row));
233
246
  }
234
247
 
235
248
  /** A second name of an address from an analyzer. */
236
249
  insertAnalyzerName(row: Omit<SymbolRow, "revision">): void {
237
- this.#db.prepare("INSERT INTO analyzer_names (id, space, address, name, kind, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?)").run(this.#rowId(), row.space, row.address, row.name, row.kind, row.origin, this.id());
250
+ this.#insert("analyzer_names", rowValues("analyzer_names", row));
238
251
  }
239
252
 
240
253
  insertRegion(row: Omit<RegionRow, "revision">): void {
241
- this.#db
242
- .prepare("INSERT INTO regions (id, space, start_address, end_address, type, element, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
243
- .run(this.#rowId(), row.space, row.start, row.end, row.type, row.element ?? null, row.origin, this.id());
254
+ this.#insert("regions", rowValues("regions", row));
244
255
  }
245
256
 
246
257
  insertComment(row: Omit<CommentRow, "revision">): void {
247
- this.#db
248
- .prepare("INSERT INTO comments (id, space, address, placement, text, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?)")
249
- .run(this.#rowId(), row.space, row.address, row.placement, row.text, row.origin, this.id());
258
+ this.#insert("comments", rowValues("comments", row));
250
259
  }
251
260
 
252
261
  insertReference(row: Omit<ReferenceRow, "revision">): void {
253
- this.#db
254
- .prepare('INSERT INTO "references" (id, space, from_address, to_address, kind, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?)')
255
- .run(this.#rowId(), row.space, row.from, row.to, row.kind, row.origin, this.id());
262
+ this.#insert("references", rowValues("references", row));
256
263
  }
257
264
 
258
265
  insertModule(row: Omit<ModuleRow, "revision">): void {
259
- this.#db
260
- .prepare("INSERT INTO modules (id, space, start_address, file, title, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?)")
261
- .run(this.#rowId(), row.space, row.start, row.file, row.title ?? null, row.origin, this.id());
266
+ this.#insert("modules", rowValues("modules", row));
262
267
  }
263
268
 
264
269
  insertOperand(row: Omit<OperandRow, "revision">): void {
265
- this.#db
266
- .prepare("INSERT INTO operands (id, space, address, selector, symbol, offset, expression, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
267
- .run(this.#rowId(), row.space, row.address, row.select, row.symbol ?? null, row.offset, row.expression ?? null, row.origin, this.id());
270
+ this.#insert("operands", rowValues("operands", row));
268
271
  }
269
272
 
270
273
  insertPatch(row: Omit<PatchRow, "revision">): void {
271
- this.#db
272
- .prepare("INSERT INTO patches (id, space, start_address, end_address, switch_name, code, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
273
- .run(this.#rowId(), row.space, row.start, row.end, row.switch, row.code, row.comment ?? null, row.origin, this.id());
274
+ this.#insert("patches", rowValues("patches", row));
274
275
  }
275
276
 
276
277
  insertSwitch(row: Omit<SwitchRow, "revision">): void {
277
- this.#db
278
- .prepare("INSERT INTO switches (id, space, name, kind, default_value, releases, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
279
- .run(this.#rowId(), row.space, row.name, row.kind, row.default, listText(row.releases), row.comment ?? null, row.origin, this.id());
278
+ this.#insert("switches", rowValues("switches", row));
280
279
  }
281
280
 
282
281
  insertRelease(row: Omit<ReleaseRow, "revision">): void {
283
- this.#db
284
- .prepare("INSERT INTO releases (id, space, label, base, file, sha256, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
285
- .run(this.#rowId(), row.space, row.label, row.base ? 1 : 0, row.file ?? null, row.sha256 ?? null, row.comment ?? null, row.origin, this.id());
282
+ this.#insert("releases", rowValues("releases", row));
286
283
  }
287
284
 
288
285
  /** Bytes of a release other than the base release, as a memory row of the program holds them. */
289
286
  insertReleaseMemory(row: { space: Space; label: string; address: number; bytes: string; origin: Origin }): void {
290
- this.#db
291
- .prepare("INSERT INTO release_memory (id, space, label, address, bytes, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?)")
292
- .run(this.#rowId(), row.space, row.label, row.address, row.bytes, row.origin, this.id());
287
+ this.insertColumns("release_memory", row);
293
288
  }
294
289
 
295
290
  insertStartScreen(row: Omit<StartScreenRow, "revision">): void {
296
- this.#db
297
- .prepare("INSERT INTO start_screens (id, space, mode, screen, bitmap, charset, colours, colour, border, background, stage, call_address, colour_ram, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
298
- .run(this.#rowId(), row.space, row.mode, row.screen, row.bitmap ?? null, row.charset ?? null, row.colours ?? null, row.colour ?? null, row.border, row.background, row.stage ?? null, row.call ?? null, row.colourRam === true ? 1 : null, row.comment ?? null, row.origin, this.id());
291
+ this.#insert("start_screens", rowValues("start_screens", row));
299
292
  }
300
293
 
301
294
  insertMacro(row: Omit<MacroRow, "revision">): void {
302
- this.#db
303
- .prepare("INSERT INTO macros (id, space, name, params, body, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
304
- .run(this.#rowId(), row.space, row.name, listText(row.params), row.body, row.comment ?? null, row.origin, this.id());
295
+ this.#insert("macros", rowValues("macros", row));
305
296
  }
306
297
 
307
298
  insertMacroUse(row: Omit<MacroUseRow, "revision">): void {
308
- this.#db
309
- .prepare("INSERT INTO macro_uses (id, space, start_address, end_address, macro, args, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
310
- .run(this.#rowId(), row.space, row.start, row.end, row.macro, listText(row.args), row.origin, this.id());
299
+ this.#insert("macro_uses", rowValues("macro_uses", row));
311
300
  }
312
301
 
313
302
  insertSuppression(row: Omit<SuppressionRow, "revision">): void {
314
- this.#db
315
- .prepare("INSERT INTO suppressions (id, space, entity, start_address, end_address, to_address, kind, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
316
- .run(this.#rowId(), row.space, row.entity, row.start, row.end, row.to ?? null, row.kind ?? null, row.origin, this.id());
303
+ this.#insert("suppressions", rowValues("suppressions", row));
317
304
  }
318
305
 
319
306
  /** Bytes of the program, as hex digits. */
320
307
  insertMemory(row: { space: Space; address: number; bytes: string; origin: Origin }): void {
321
- this.#db.prepare("INSERT INTO memory (id, space, address, bytes, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?)").run(this.#rowId(), row.space, row.address, row.bytes, row.origin, this.id());
308
+ this.insertColumns("memory", row);
322
309
  }
323
310
 
324
311
  /** The entry of the program, with the machine state and the unpacker stages as JSON text when it has them. */
325
312
  insertEntry(row: { space: Space; address: number; state: string | null; stages: string | null; origin: Origin }): void {
326
- this.#db
327
- .prepare("INSERT INTO entries (id, space, address, state, stages, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?)")
328
- .run(this.#rowId(), row.space, row.address, row.state, row.stages, row.origin, this.id());
313
+ this.insertColumns("entries", row);
329
314
  }
330
315
 
331
316
  /** The ranges of one kind of the coverage map at a project path, as text. */
332
317
  insertCoverage(row: { space: Space; map: string; kind: string; ranges: string; origin: Origin }): void {
333
- this.#db
334
- .prepare("INSERT INTO coverage (id, space, map, kind, ranges, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?)")
335
- .run(this.#rowId(), row.space, row.map, row.kind, row.ranges, row.origin, this.id());
318
+ this.insertColumns("coverage", row);
336
319
  }
337
320
  }
338
321
 
@@ -345,7 +328,7 @@ function describe(conflict: Conflict): string {
345
328
  const row = entry.row as { address?: number; start?: number; end?: number; from?: number };
346
329
  if (row.address !== undefined) return formatC64Address(row.address);
347
330
  if (row.from !== undefined && entry.entity === "reference") return formatC64Address(row.from);
348
- return row.end === undefined || row.end === row.start ? formatC64Address(row.start!) : `${formatC64Address(row.start!)}-${formatC64Address(row.end)}`;
331
+ return row.end === undefined || row.end === row.start ? formatC64Address(row.start!) : formatC64Range({ start: row.start!, end: row.end });
349
332
  };
350
333
  return `${CONFLICT_RULES[conflict.rule]} in ${conflict.space} (${[...new Set(conflict.rows.map(place))].join(", ")})`;
351
334
  }
@@ -371,7 +354,7 @@ function checkEvidence(evidence: Evidence[] | undefined): void {
371
354
  }
372
355
 
373
356
  /** Runs semantic writes in one transaction, as one revision. */
374
- export function write<T>(db: DatabaseSync, context: WriteContext & Pick<ChangeContext, "restores">, operation: string, work: (change: Change) => T): { revision: string | null; current: T } {
357
+ export function write<T>(db: DatabaseSync, context: WriteContext & Pick<ChangeContext, "restores" | "allowConflicts">, operation: string, work: (change: Change) => T): { revision: string | null; current: T } {
375
358
  if (context.origin !== "user" && context.origin !== "llm") {
376
359
  throw new Refusal("invalid-input", "A semantic write comes from the user or the LLM.");
377
360
  }
@@ -390,6 +373,9 @@ interface Step<T, P = never> {
390
373
  previous?: P;
391
374
  }
392
375
 
376
+ /** What a step reads of its write: who writes, and the image that operand, patch and macro use writes are checked against. */
377
+ type StepContext = Pick<WriteContext, "origin" | "image">;
378
+
393
379
  const result = <T, P>(written: { revision: string | null; current: Step<T, P> }): WriteResult<T, P> =>
394
380
  written.current.previous === undefined ? { revision: written.revision, current: written.current.current } : { revision: written.revision, current: written.current.current, previous: written.current.previous };
395
381
 
@@ -406,17 +392,6 @@ function confirms(existing: Origin, origin: Origin): boolean {
406
392
  return existing !== origin && (!isSemantic(existing) || origin === "user");
407
393
  }
408
394
 
409
- /**
410
- * The bytes of the program of a space in the knowledge, by address: undefined
411
- * outside it. A module and a comment are checked against them.
412
- */
413
- function programBytes(db: DatabaseSync, space: Space): (address: number) => number | undefined {
414
- const rows = db.prepare("SELECT address, bytes FROM current_memory WHERE space = ?").all(space) as Array<{ address: number; bytes: string }>;
415
- const memory = new Map<number, number>();
416
- for (const row of rows) Buffer.from(row.bytes, "hex").forEach((byte, offset) => memory.set(row.address + offset, byte));
417
- return (address) => memory.get(address);
418
- }
419
-
420
395
  /** Every request names its space; without one it is the C64. */
421
396
  type InSpace = { space?: Space };
422
397
  type SymbolRequest = InSpace & { address: number; name: string; kind?: SymbolKind };
@@ -427,8 +402,6 @@ type PlacementRequest = InSpace & { address: number; placement: CommentPlacement
427
402
  type ReferenceRequest = InSpace & { from: number; to: number; kind: ReferenceKind };
428
403
  type AddressRequest = InSpace & { address: number };
429
404
 
430
- const spaceOf = (request: InSpace): Space => request.space ?? DEFAULT_SPACE;
431
-
432
405
  export function checkSpace(request: InSpace): void {
433
406
  if (request.space !== undefined && !SPACE_PATTERN.test(request.space)) throw new Refusal("invalid-input", "space must be c64, drive8, or bank0 to bank255.");
434
407
  }
@@ -441,7 +414,7 @@ function checkSymbol(request: SymbolRequest): void {
441
414
  if (request.kind !== undefined) checkOneOf(SYMBOL_KINDS, request.kind, "kind");
442
415
  }
443
416
 
444
- function renameStep(db: DatabaseSync, change: Change, origin: Origin, request: SymbolRequest): Step<SymbolRow, SymbolRow> {
417
+ function renameStep(db: DatabaseSync, change: Change, request: SymbolRequest, { origin }: StepContext): Step<SymbolRow, SymbolRow> {
445
418
  const space = spaceOf(request);
446
419
  const existing = symbolAt(db, request.address, space);
447
420
  const kind = request.kind ?? existing?.kind ?? "label";
@@ -466,7 +439,7 @@ function renameStep(db: DatabaseSync, change: Change, origin: Origin, request: S
466
439
  return existing !== undefined && existing.origin !== origin ? { current, previous: existing } : { current };
467
440
  }
468
441
 
469
- function removeSymbolStep(db: DatabaseSync, change: Change, origin: Origin, request: AddressRequest): Step<null> {
442
+ function removeSymbolStep(db: DatabaseSync, change: Change, request: AddressRequest): Step<null> {
470
443
  const space = spaceOf(request);
471
444
  const existing = symbolAt(db, request.address, space);
472
445
  if (existing === undefined) throw new Refusal("not-found", `There is no symbol at ${formatC64Address(request.address)}.`);
@@ -509,7 +482,7 @@ function elementOf(piece: AddressRange, element: number | undefined): { element?
509
482
  }
510
483
 
511
484
  /** Closes the current regions over [start, end] and keeps their parts outside it. */
512
- export function clearRange(db: DatabaseSync, change: Change, start: number, end: number, space: Space = DEFAULT_SPACE): void {
485
+ function clearRange(db: DatabaseSync, change: Change, start: number, end: number, space: Space = DEFAULT_SPACE): void {
513
486
  const overlapping = regionsOverlapping(db, start, end, space);
514
487
  if (overlapping.length === 0) return;
515
488
  change.close("regions", "space = ? AND start_address <= ? AND end_address >= ?", space, end, start);
@@ -521,7 +494,7 @@ export function clearRange(db: DatabaseSync, change: Change, start: number, end:
521
494
  }
522
495
  }
523
496
 
524
- function classifyStep(db: DatabaseSync, change: Change, origin: Origin, request: RegionRequest): Step<RegionRow[], RegionRow[]> {
497
+ function classifyStep(db: DatabaseSync, change: Change, request: RegionRequest, { origin }: StepContext): Step<RegionRow[], RegionRow[]> {
525
498
  const space = spaceOf(request);
526
499
  const overlapping = regionsOverlapping(db, request.start, request.end, space);
527
500
  const [only] = overlapping;
@@ -532,17 +505,17 @@ function classifyStep(db: DatabaseSync, change: Change, origin: Origin, request:
532
505
  liftRegionSuppressions(db, change, request.start, request.end, space);
533
506
  // Data is not code: an analyzer reference from there is false code. dual-use bytes are also code.
534
507
  if (!CODE_REGION_TYPES.includes(request.type) && request.type !== "dual-use") {
535
- change.close('"references"', "space = ? AND from_address BETWEEN ? AND ? AND origin NOT IN ('user', 'llm')", space, request.start, request.end);
508
+ change.close("references", "space = ? AND from_address BETWEEN ? AND ? AND origin NOT IN ('user', 'llm')", space, request.start, request.end);
536
509
  }
537
510
  const previous = overlapping.filter((row) => row.origin !== origin);
538
511
  const current = regionsOverlapping(db, request.start, request.end, space);
539
512
  return previous.length === 0 ? { current } : { current, previous };
540
513
  }
541
514
 
542
- function unclassifyStep(db: DatabaseSync, change: Change, origin: Origin, request: RangeRequest): Step<null> {
515
+ function unclassifyStep(db: DatabaseSync, change: Change, request: RangeRequest, { origin }: StepContext): Step<null> {
543
516
  const space = spaceOf(request);
544
517
  if (regionsOverlapping(db, request.start, request.end, space).length === 0) {
545
- throw new Refusal("not-found", `No region covers ${formatC64Address(request.start)}-${formatC64Address(request.end)}.`);
518
+ throw new Refusal("not-found", `No region covers ${formatC64Range(request)}.`);
546
519
  }
547
520
  clearRange(db, change, request.start, request.end, space);
548
521
  // Suppress only the parts that no region suppression holds yet, so suppressions never overlap.
@@ -561,13 +534,13 @@ function checkComment(request: CommentRequest): string {
561
534
  return text;
562
535
  }
563
536
 
564
- function commentStep(db: DatabaseSync, change: Change, origin: Origin, request: CommentRequest): Step<CommentRow, CommentRow> {
537
+ function commentStep(db: DatabaseSync, change: Change, request: CommentRequest, { origin }: StepContext): Step<CommentRow, CommentRow> {
565
538
  const space = spaceOf(request);
566
539
  const text = request.text.trim();
567
540
  const existing = commentsAt(db, request.address, space).find((comment) => comment.placement === request.placement);
568
541
  if (existing?.text === text && !confirms(existing.origin, origin)) return { current: existing };
569
542
  // A comment belongs to an instruction: the listing and the source show it at the start of the instruction only.
570
- checkInstructionStart(db, space, programBytes(db, space), request.address, "comment");
543
+ checkInstructionStart(db, space, change.programBytes(space), request.address, "comment");
571
544
  if (existing !== undefined) change.close("comments", "space = ? AND address = ? AND placement = ?", space, request.address, request.placement);
572
545
  change.insertComment({ space, address: request.address, placement: request.placement, text, origin });
573
546
  const current = commentsAt(db, request.address, space).find((comment) => comment.placement === request.placement)!;
@@ -580,7 +553,7 @@ function checkPlacement(request: PlacementRequest): void {
580
553
  checkOneOf(COMMENT_PLACEMENTS, request.placement, "placement");
581
554
  }
582
555
 
583
- function uncommentStep(db: DatabaseSync, change: Change, _origin: Origin, request: PlacementRequest): Step<null> {
556
+ function uncommentStep(db: DatabaseSync, change: Change, request: PlacementRequest): Step<null> {
584
557
  const space = spaceOf(request);
585
558
  if (!commentsAt(db, request.address, space).some((comment) => comment.placement === request.placement)) {
586
559
  throw new Refusal("not-found", `There is no ${request.placement} comment at ${formatC64Address(request.address)}.`);
@@ -597,33 +570,35 @@ function checkReference(request: ReferenceRequest): void {
597
570
  if (request.kind === POINTER_KIND) throw new Refusal("invalid-input", "Only an operand expression writes a pointer reference: use operand and unoperand.");
598
571
  }
599
572
 
600
- function referenceStep(db: DatabaseSync, change: Change, origin: Origin, request: ReferenceRequest): Step<ReferenceRow, ReferenceRow> {
573
+ function referenceStep(db: DatabaseSync, change: Change, request: ReferenceRequest, { origin }: StepContext): Step<ReferenceRow, ReferenceRow> {
601
574
  const space = spaceOf(request);
602
575
  const find = () => referencesFrom(db, request.from, space).find((reference) => reference.to === request.to && reference.kind === request.kind);
603
576
  const existing = find();
604
577
  if (existing !== undefined && !confirms(existing.origin, origin)) return { current: existing };
605
578
  // A confirmation of a reference of an analyzer makes it a reference of the writer: the next run of the analyzer keeps it.
606
- if (existing !== undefined) change.close('"references"', "space = ? AND from_address = ? AND to_address = ? AND kind = ?", space, request.from, request.to, request.kind);
579
+ if (existing !== undefined) change.close("references", "space = ? AND from_address = ? AND to_address = ? AND kind = ?", space, request.from, request.to, request.kind);
607
580
  change.insertReference({ space, from: request.from, to: request.to, kind: request.kind, origin });
608
581
  change.close("suppressions", "space = ? AND entity = 'reference' AND start_address = ? AND to_address = ? AND kind = ?", space, request.from, request.to, request.kind);
609
582
  return existing !== undefined ? { current: find()!, previous: existing } : { current: find()! };
610
583
  }
611
584
 
612
- function unreferenceStep(db: DatabaseSync, change: Change, origin: Origin, request: ReferenceRequest): Step<null> {
585
+ function unreferenceStep(db: DatabaseSync, change: Change, request: ReferenceRequest, { origin }: StepContext): Step<null> {
613
586
  const space = spaceOf(request);
614
587
  if (!referencesFrom(db, request.from, space).some((reference) => reference.to === request.to && reference.kind === request.kind)) {
615
588
  throw new Refusal("not-found", `There is no ${request.kind} reference from ${formatC64Address(request.from)} to ${formatC64Address(request.to)}.`);
616
589
  }
617
- change.close('"references"', "space = ? AND from_address = ? AND to_address = ? AND kind = ?", space, request.from, request.to, request.kind);
590
+ change.close("references", "space = ? AND from_address = ? AND to_address = ? AND kind = ?", space, request.from, request.to, request.kind);
618
591
  change.insertSuppression({ space, entity: "reference", start: request.from, end: request.from, to: request.to, kind: request.kind, origin: origin as SuppressionRow["origin"] });
619
592
  return { current: null };
620
593
  }
621
594
 
622
595
  type OperandRequest = InSpace & { address: number; select: OperandSelect; symbol?: string; offset?: number; expression?: string };
623
596
 
624
- /** Current operand expressions that use a name, as a symbol or inside expression text. */
597
+ /** Current operand expressions that use a name, as a symbol or inside expression text. The query keeps the expressions that hold the name as text. */
625
598
  function operandsNaming(db: DatabaseSync, space: Space, name: string): OperandRow[] {
626
- return listOperands(db, undefined, undefined, space).filter((row) => row.symbol === name || (row.expression !== undefined && identifiers(row.expression).includes(name)));
599
+ return (prepare(db, `SELECT ${FACTS.operands.columns} FROM current_operands WHERE space = ? AND (symbol = ? OR instr(expression, ?) > 0) ORDER BY address`).all(space, name, name) as Raw[])
600
+ .map(FACTS.operands.map)
601
+ .filter((row) => row.symbol === name || (row.expression !== undefined && identifiers(row.expression).includes(name)));
627
602
  }
628
603
 
629
604
  /** A rename of a symbol renames it in every operand expression that uses it; the rows keep their origin. */
@@ -675,7 +650,7 @@ function checkInstructionStart(db: DatabaseSync, space: Space, byteAt: (address:
675
650
  const opcode = byteAt(next);
676
651
  if (opcode === undefined) {
677
652
  if (write !== "operand") return;
678
- throw new Refusal("invalid-input", `The code region ${formatC64Address(code.start)}-${formatC64Address(code.end)} has no program byte at ${formatC64Address(next)}, so its instructions up to ${where} are not known. Correct the region (classify), then write the operand.`);
653
+ throw new Refusal("invalid-input", `The code region ${formatC64Range(code)} has no program byte at ${formatC64Address(next)}, so its instructions up to ${where} are not known. Correct the region (classify), then write the operand.`);
679
654
  }
680
655
  start = next;
681
656
  next += instructionLength(opcode);
@@ -720,7 +695,7 @@ function checkOperandValue(db: DatabaseSync, space: Space, image: OperandImage,
720
695
  return identifiers(text).map((name) => resolve(name)!);
721
696
  }
722
697
 
723
- function operandStep(db: DatabaseSync, change: Change, context: ChangeContext & { image?: (space: Space) => OperandImage }, request: OperandRequest): Step<OperandRow, OperandRow> {
698
+ function operandStep(db: DatabaseSync, change: Change, request: OperandRequest, context: StepContext): Step<OperandRow, OperandRow> {
724
699
  const space = spaceOf(request);
725
700
  if (context.image === undefined) throw new Refusal("invalid-input", "An operand expression is checked against the image, and no image was given.");
726
701
  const wanted: Omit<OperandRow, "space" | "address" | "origin" | "revision"> = { select: request.select, offset: request.offset ?? 0 };
@@ -736,7 +711,7 @@ function operandStep(db: DatabaseSync, change: Change, context: ChangeContext &
736
711
  change.insertOperand({ space, address: request.address, ...wanted, origin });
737
712
  const pointers = referencesFrom(db, request.address, space).filter((reference) => reference.kind === POINTER_KIND);
738
713
  for (const reference of pointers) {
739
- if (!targets.has(reference.to)) change.close('"references"', "space = ? AND from_address = ? AND to_address = ? AND kind = ?", space, request.address, reference.to, POINTER_KIND);
714
+ if (!targets.has(reference.to)) change.close("references", "space = ? AND from_address = ? AND to_address = ? AND kind = ?", space, request.address, reference.to, POINTER_KIND);
740
715
  }
741
716
  for (const to of targets) {
742
717
  if (!pointers.some((reference) => reference.to === to)) change.insertReference({ space, from: request.address, to, kind: POINTER_KIND, origin });
@@ -745,11 +720,11 @@ function operandStep(db: DatabaseSync, change: Change, context: ChangeContext &
745
720
  return existing !== undefined && existing.origin !== origin ? { current, previous: existing } : { current };
746
721
  }
747
722
 
748
- function unoperandStep(db: DatabaseSync, change: Change, _origin: Origin, request: AddressRequest): Step<null> {
723
+ function unoperandStep(db: DatabaseSync, change: Change, request: AddressRequest): Step<null> {
749
724
  const space = spaceOf(request);
750
725
  if (operandAt(db, request.address, space) === undefined) throw new Refusal("not-found", `There is no operand expression at ${formatC64Address(request.address)}.`);
751
726
  change.close("operands", "space = ? AND address = ?", space, request.address);
752
- change.close('"references"', "space = ? AND from_address = ? AND kind = ?", space, request.address, POINTER_KIND);
727
+ change.close("references", "space = ? AND from_address = ? AND kind = ?", space, request.address, POINTER_KIND);
753
728
  return { current: null };
754
729
  }
755
730
 
@@ -767,14 +742,14 @@ function checkModule(request: ModuleRequest): void {
767
742
  if (request.title !== undefined && (request.title.trim().length === 0 || request.title.length > MAX_COMMENT)) throw new Refusal("invalid-input", `A module title has 1 to ${MAX_COMMENT} characters.`);
768
743
  }
769
744
 
770
- function moduleStep(db: DatabaseSync, change: Change, origin: Origin, request: ModuleRequest): Step<ModuleRow, ModuleRow> {
745
+ function moduleStep(db: DatabaseSync, change: Change, request: ModuleRequest, { origin }: StepContext): Step<ModuleRow, ModuleRow> {
771
746
  const space = spaceOf(request);
772
747
  const existing = moduleAt(db, request.start, space);
773
748
  // A module write without a title keeps the title it has.
774
749
  const title = request.title === undefined ? existing?.title : request.title.trim();
775
750
  if (existing !== undefined && existing.file === request.file && existing.title === title && !confirms(existing.origin, origin)) return { current: existing };
776
751
  // A file of the source starts at an instruction: a start inside one splits it into bytes.
777
- checkInstructionStart(db, space, programBytes(db, space), request.start, "module");
752
+ checkInstructionStart(db, space, change.programBytes(space), request.start, "module");
778
753
  const owner = moduleWithFile(db, request.file, space);
779
754
  if (owner !== undefined && owner.start !== request.start) {
780
755
  throw new Refusal("conflict", `The file ${request.file} already belongs to the module at ${formatC64Address(owner.start)}. Give this module another file, or remove that module first.`);
@@ -785,7 +760,7 @@ function moduleStep(db: DatabaseSync, change: Change, origin: Origin, request: M
785
760
  return existing !== undefined && existing.origin !== origin ? { current, previous: existing } : { current };
786
761
  }
787
762
 
788
- function unmoduleStep(db: DatabaseSync, change: Change, _origin: Origin, request: InSpace & { start: number }): Step<null> {
763
+ function unmoduleStep(db: DatabaseSync, change: Change, request: InSpace & { start: number }): Step<null> {
789
764
  const space = spaceOf(request);
790
765
  if (moduleAt(db, request.start, space) === undefined) throw new Refusal("not-found", `No module starts at ${formatC64Address(request.start)}.`);
791
766
  change.close("modules", "space = ? AND start_address = ?", space, request.start);
@@ -883,9 +858,9 @@ export function leastPatchBytes(code: string): number | undefined {
883
858
  return bytes;
884
859
  }
885
860
 
886
- function patchStep(db: DatabaseSync, change: Change, context: ChangeContext & { image?: (space: Space) => OperandImage }, request: PatchRequest): Step<PatchRow, PatchRow> {
861
+ function patchStep(db: DatabaseSync, change: Change, request: PatchRequest, context: StepContext): Step<PatchRow, PatchRow> {
887
862
  const space = spaceOf(request);
888
- const range = `${formatC64Address(request.start)}-${formatC64Address(request.end)}`;
863
+ const range = formatC64Range(request);
889
864
  if (context.image === undefined) throw new Refusal("invalid-input", "A patch is checked against the image, and no image was given.");
890
865
  const image = context.image(space);
891
866
  checkInImage(image, request.start, request.end, "a patch");
@@ -902,12 +877,12 @@ function patchStep(db: DatabaseSync, change: Change, context: ChangeContext & {
902
877
  if (other !== undefined) {
903
878
  throw new Refusal(
904
879
  "conflict",
905
- `The patch ${range} of ${request.switch} overlaps the patch of ${other.switch} at ${formatC64Address(other.start)}-${formatC64Address(other.end)}. Patches of different switches can have the same range, as alternatives; no other overlap is allowed. Change or remove that patch first (unpatch).`,
880
+ `The patch ${range} of ${request.switch} overlaps the patch of ${other.switch} at ${formatC64Range(other)}. Patches of different switches can have the same range, as alternatives; no other overlap is allowed. Change or remove that patch first (unpatch).`,
906
881
  );
907
882
  }
908
883
  const [use] = macroUsesOverlapping(db, request.start, request.end, space);
909
884
  if (use !== undefined) {
910
- throw new Refusal("conflict", `The patch ${range} overlaps the use of the macro ${use.macro} at ${formatC64Address(use.start)}-${formatC64Address(use.end)}. Remove that use first (unuse).`);
885
+ throw new Refusal("conflict", `The patch ${range} overlaps the use of the macro ${use.macro} at ${formatC64Range(use)}. Remove that use first (unuse).`);
911
886
  }
912
887
  const find = () => patchesOverlapping(db, request.start, request.start, space).find(mine);
913
888
  const existing = find();
@@ -923,7 +898,7 @@ function patchStep(db: DatabaseSync, change: Change, context: ChangeContext & {
923
898
  return existing !== undefined && existing.origin !== origin ? { current, previous: existing } : { current };
924
899
  }
925
900
 
926
- function unpatchStep(db: DatabaseSync, change: Change, _origin: Origin, request: InSpace & { start: number; switch?: string }): Step<null> {
901
+ function unpatchStep(db: DatabaseSync, change: Change, request: InSpace & { start: number; switch?: string }): Step<null> {
927
902
  const space = spaceOf(request);
928
903
  const found = patchesOverlapping(db, request.start, request.start, space).filter((row) => row.start === request.start && (request.switch === undefined || row.switch === request.switch));
929
904
  if (found.length === 0) throw new Refusal("not-found", `No patch${request.switch === undefined ? "" : ` of ${request.switch}`} starts at ${formatC64Address(request.start)}.`);
@@ -932,11 +907,6 @@ function unpatchStep(db: DatabaseSync, change: Change, _origin: Origin, request:
932
907
  return { current: null };
933
908
  }
934
909
 
935
- /** The label of the base release of a space: its bytes are the program of the knowledge. */
936
- function baseLabel(db: DatabaseSync, space: Space): string | undefined {
937
- return listReleases(db, undefined, space).find((release) => release.base)?.label;
938
- }
939
-
940
910
  /**
941
911
  * Refuses alternatives that are both on in the default build: a patch is on
942
912
  * when its switch does not have its base value. Two patches of one range can
@@ -955,7 +925,7 @@ function checkAlternatives(db: DatabaseSync, space: Space, changed: readonly Swi
955
925
  return owner.default !== baseValue(owner, base);
956
926
  });
957
927
  if (on.length < 2) continue;
958
- const range = `${formatC64Address(patches[0]!.start)}-${formatC64Address(patches[0]!.end)}`;
928
+ const range = formatC64Range(patches[0]!);
959
929
  throw new Refusal(
960
930
  "conflict",
961
931
  `The switches ${on.map((patch) => patch.switch).join(" and ")} have alternative patches at ${range}, and the default build puts in both of them. Give one of the switches the default of the base release (switch <name> --default).`,
@@ -989,7 +959,7 @@ function defaultOf(request: SwitchRequest, existing: SwitchRow | undefined): 0 |
989
959
  throw new Refusal("invalid-input", `A ${request.kind} switch needs a default: give --default 0 or --default 1.`);
990
960
  }
991
961
 
992
- function switchStep(db: DatabaseSync, change: Change, context: ChangeContext & { image?: (space: Space) => OperandImage }, request: SwitchRequest): Step<SwitchRow, SwitchRow> {
962
+ function switchStep(db: DatabaseSync, change: Change, request: SwitchRequest, context: StepContext): Step<SwitchRow, SwitchRow> {
993
963
  const space = spaceOf(request);
994
964
  const base = baseLabel(db, space);
995
965
  if (base === undefined) throw new Refusal("not-found", "The knowledge has no base release. Record the release whose bytes are the program first (release <label> --file <file> --base).");
@@ -1020,7 +990,7 @@ function switchStep(db: DatabaseSync, change: Change, context: ChangeContext & {
1020
990
  return existing !== undefined && existing.origin !== origin ? { current, previous: existing } : { current };
1021
991
  }
1022
992
 
1023
- function unswitchStep(db: DatabaseSync, change: Change, _origin: Origin, request: InSpace & { name: string }): Step<null> {
993
+ function unswitchStep(db: DatabaseSync, change: Change, request: InSpace & { name: string }): Step<null> {
1024
994
  const space = spaceOf(request);
1025
995
  if (switchNamed(db, request.name, space) === undefined) throw new Refusal("not-found", `There is no switch ${request.name}.`);
1026
996
  const patches = listPatches(db, undefined, request.name, undefined, space);
@@ -1052,7 +1022,7 @@ function checkRelease(request: ReleaseRequest): void {
1052
1022
  checkCommentText(request.comment, "A release comment");
1053
1023
  }
1054
1024
 
1055
- function releaseStep(db: DatabaseSync, change: Change, origin: Origin, request: ReleaseRequest): Step<ReleaseRow, ReleaseRow> {
1025
+ function releaseStep(db: DatabaseSync, change: Change, request: ReleaseRequest, { origin }: StepContext): Step<ReleaseRow, ReleaseRow> {
1056
1026
  const space = spaceOf(request);
1057
1027
  const existing = releaseLabeled(db, request.label, space);
1058
1028
  const base = request.base ?? existing?.base ?? false;
@@ -1091,7 +1061,7 @@ function releaseStep(db: DatabaseSync, change: Change, origin: Origin, request:
1091
1061
  return existing !== undefined && existing.origin !== origin ? { current, previous: existing } : { current };
1092
1062
  }
1093
1063
 
1094
- function unreleaseStep(db: DatabaseSync, change: Change, _origin: Origin, request: InSpace & { label: string }): Step<null> {
1064
+ function unreleaseStep(db: DatabaseSync, change: Change, request: InSpace & { label: string }): Step<null> {
1095
1065
  const space = spaceOf(request);
1096
1066
  const existing = releaseLabeled(db, request.label, space);
1097
1067
  if (existing === undefined) throw new Refusal("not-found", `There is no release ${request.label}.`);
@@ -1172,9 +1142,9 @@ function checkStartScreen(request: StartScreenRequest): void {
1172
1142
  }
1173
1143
 
1174
1144
  /** The bytes of a start screen of a stage, and its call, must be in the program of that space. */
1175
- function checkStage(db: DatabaseSync, request: StartScreenRequest): void {
1145
+ function checkStage(db: DatabaseSync, change: Change, request: StartScreenRequest): void {
1176
1146
  if (request.stage === undefined) return;
1177
- const byteAt = programBytes(db, request.stage);
1147
+ const byteAt = change.programBytes(request.stage);
1178
1148
  if (byteAt(request.screen) === undefined && db.prepare("SELECT 1 FROM current_memory WHERE space = ? LIMIT 1").get(request.stage) === undefined) {
1179
1149
  throw new Refusal("not-found", `The knowledge has no program in ${request.stage}. Capture the stage while it shows the start screen, and put the capture into the project knowledge with image --space ${request.stage}. Then record the start screen again.`);
1180
1150
  }
@@ -1183,14 +1153,14 @@ function checkStage(db: DatabaseSync, request: StartScreenRequest): void {
1183
1153
  return true;
1184
1154
  };
1185
1155
  for (const { what, range } of startScreenRanges(request)) {
1186
- if (!inStage(range)) throw new Refusal("invalid-input", `The ${what} at ${formatC64Address(range.start)}-${formatC64Address(range.end)} is not in the program in ${request.stage}. Capture the stage again, and do not exclude the memory of the start screen.`);
1156
+ if (!inStage(range)) throw new Refusal("invalid-input", `The ${what} at ${formatC64Range(range)} is not in the program in ${request.stage}. Capture the stage again, and do not exclude the memory of the start screen.`);
1187
1157
  }
1188
1158
  if (request.call !== undefined && !inStage({ start: request.call, end: request.call })) throw new Refusal("invalid-input", `The call ${formatC64Address(request.call)} is not in the program in ${request.stage}.`);
1189
1159
  }
1190
1160
 
1191
- function startScreenStep(db: DatabaseSync, change: Change, origin: Origin, request: StartScreenRequest): Step<StartScreenRow, StartScreenRow> {
1161
+ function startScreenStep(db: DatabaseSync, change: Change, request: StartScreenRequest, { origin }: StepContext): Step<StartScreenRow, StartScreenRow> {
1192
1162
  const space = spaceOf(request);
1193
- checkStage(db, request);
1163
+ checkStage(db, change, request);
1194
1164
  const existing = currentStartScreen(db, space);
1195
1165
  const comment = request.comment === undefined ? existing?.comment : request.comment.trim();
1196
1166
  const row: Omit<StartScreenRow, "revision"> = {
@@ -1209,7 +1179,7 @@ function startScreenStep(db: DatabaseSync, change: Change, origin: Origin, reque
1209
1179
  ...(comment === undefined ? {} : { comment }),
1210
1180
  origin: origin as StartScreenRow["origin"],
1211
1181
  };
1212
- const same = existing !== undefined && KEYS.start_screens.key(existing) === KEYS.start_screens.key({ ...row, origin: existing.origin, revision: "" });
1182
+ const same = existing !== undefined && JSON.stringify(rowValues("start_screens", existing)) === JSON.stringify(rowValues("start_screens", { ...row, origin: existing.origin }));
1213
1183
  if (same && !confirms(existing.origin, origin)) return { current: existing };
1214
1184
  if (existing !== undefined) change.close("start_screens", "space = ?", space);
1215
1185
  change.insertStartScreen(row);
@@ -1217,7 +1187,7 @@ function startScreenStep(db: DatabaseSync, change: Change, origin: Origin, reque
1217
1187
  return existing !== undefined && existing.origin !== origin ? { current, previous: existing } : { current };
1218
1188
  }
1219
1189
 
1220
- function unstartScreenStep(db: DatabaseSync, change: Change, _origin: Origin, request: InSpace): Step<null> {
1190
+ function unstartScreenStep(db: DatabaseSync, change: Change, request: InSpace): Step<null> {
1221
1191
  const space = spaceOf(request);
1222
1192
  if (currentStartScreen(db, space) === undefined) throw new Refusal("not-found", "The knowledge has no start screen.");
1223
1193
  change.close("start_screens", "space = ?", space);
@@ -1246,7 +1216,7 @@ function checkMacro(request: MacroRequest): void {
1246
1216
  checkCommentText(request.comment, "A macro comment");
1247
1217
  }
1248
1218
 
1249
- function macroStep(db: DatabaseSync, change: Change, origin: Origin, request: MacroRequest): Step<MacroRow, MacroRow> {
1219
+ function macroStep(db: DatabaseSync, change: Change, request: MacroRequest, { origin }: StepContext): Step<MacroRow, MacroRow> {
1250
1220
  const space = spaceOf(request);
1251
1221
  const existing = macroNamed(db, request.name, space);
1252
1222
  const params = request.params ?? [];
@@ -1268,7 +1238,7 @@ function macroStep(db: DatabaseSync, change: Change, origin: Origin, request: Ma
1268
1238
  return existing !== undefined && existing.origin !== origin ? { current, previous: existing } : { current };
1269
1239
  }
1270
1240
 
1271
- function unmacroStep(db: DatabaseSync, change: Change, _origin: Origin, request: InSpace & { name: string }): Step<null> {
1241
+ function unmacroStep(db: DatabaseSync, change: Change, request: InSpace & { name: string }): Step<null> {
1272
1242
  const space = spaceOf(request);
1273
1243
  if (macroNamed(db, request.name, space) === undefined) throw new Refusal("not-found", `There is no macro ${request.name}.`);
1274
1244
  const uses = listMacroUses(db, undefined, request.name, undefined, space);
@@ -1290,9 +1260,11 @@ function checkMacroUse(request: MacroUseRequest): void {
1290
1260
  }
1291
1261
  }
1292
1262
 
1293
- /** Current macro uses that name a symbol in an arg. */
1263
+ /** Current macro uses that name a symbol in an arg. The query keeps the uses whose args hold the name as text. */
1294
1264
  function usesNaming(db: DatabaseSync, space: Space, name: string): MacroUseRow[] {
1295
- return listMacroUses(db, undefined, undefined, undefined, space).filter((row) => row.args.some((arg) => identifiers(arg).includes(name)));
1265
+ return (prepare(db, `SELECT ${FACTS.macro_uses.columns} FROM current_macro_uses WHERE space = ? AND instr(args, ?) > 0 ORDER BY start_address`).all(space, name) as Raw[])
1266
+ .map(FACTS.macro_uses.map)
1267
+ .filter((row) => row.args.some((arg) => identifiers(arg).includes(name)));
1296
1268
  }
1297
1269
 
1298
1270
  /** A rename of a symbol renames it in the args of every macro use; the rows keep their origin. */
@@ -1303,9 +1275,9 @@ function renameInUses(db: DatabaseSync, change: Change, space: Space, from: stri
1303
1275
  }
1304
1276
  }
1305
1277
 
1306
- function useStep(db: DatabaseSync, change: Change, context: ChangeContext & { image?: (space: Space) => OperandImage }, request: MacroUseRequest): Step<MacroUseRow, MacroUseRow> {
1278
+ function useStep(db: DatabaseSync, change: Change, request: MacroUseRequest, context: StepContext): Step<MacroUseRow, MacroUseRow> {
1307
1279
  const space = spaceOf(request);
1308
- const range = `${formatC64Address(request.start)}-${formatC64Address(request.end)}`;
1280
+ const range = formatC64Range(request);
1309
1281
  if (context.image === undefined) throw new Refusal("invalid-input", "A macro use is checked against the image, and no image was given.");
1310
1282
  const image = context.image(space);
1311
1283
  const macro = macroNamed(db, request.macro, space);
@@ -1331,11 +1303,11 @@ function useStep(db: DatabaseSync, change: Change, context: ChangeContext & { im
1331
1303
  }
1332
1304
  const [patch] = patchesOverlapping(db, request.start, request.end, space);
1333
1305
  if (patch !== undefined) {
1334
- throw new Refusal("conflict", `The macro use ${range} overlaps the patch of ${patch.switch} at ${formatC64Address(patch.start)}-${formatC64Address(patch.end)}. Change or remove that patch first (unpatch).`);
1306
+ throw new Refusal("conflict", `The macro use ${range} overlaps the patch of ${patch.switch} at ${formatC64Range(patch)}. Change or remove that patch first (unpatch).`);
1335
1307
  }
1336
1308
  const other = macroUsesOverlapping(db, request.start, request.end, space).find((row) => row.start !== request.start);
1337
1309
  if (other !== undefined) {
1338
- throw new Refusal("conflict", `The macro use ${range} overlaps the use of ${other.macro} at ${formatC64Address(other.start)}-${formatC64Address(other.end)}. Remove that use first (unuse).`);
1310
+ throw new Refusal("conflict", `The macro use ${range} overlaps the use of ${other.macro} at ${formatC64Range(other)}. Remove that use first (unuse).`);
1339
1311
  }
1340
1312
  const existing = macroUsesOverlapping(db, request.start, request.start, space).find((row) => row.start === request.start);
1341
1313
  const origin = context.origin as MacroUseRow["origin"];
@@ -1346,181 +1318,165 @@ function useStep(db: DatabaseSync, change: Change, context: ChangeContext & { im
1346
1318
  return existing !== undefined && existing.origin !== origin ? { current, previous: existing } : { current };
1347
1319
  }
1348
1320
 
1349
- function unuseStep(db: DatabaseSync, change: Change, _origin: Origin, request: InSpace & { start: number }): Step<null> {
1321
+ function unuseStep(db: DatabaseSync, change: Change, request: InSpace & { start: number }): Step<null> {
1350
1322
  const space = spaceOf(request);
1351
1323
  if (!macroUsesOverlapping(db, request.start, request.start, space).some((row) => row.start === request.start)) throw new Refusal("not-found", `No macro use starts at ${formatC64Address(request.start)}.`);
1352
1324
  change.close("macro_uses", "space = ? AND start_address = ?", space, request.start);
1353
1325
  return { current: null };
1354
1326
  }
1355
1327
 
1356
- /** Names the symbol at an address (one current symbol per address, unique names). */
1357
- export function renameSymbol(db: DatabaseSync, context: WriteContext, request: SymbolRequest): WriteResult<SymbolRow, SymbolRow> {
1358
- checkSymbol(request);
1359
- return result(write(db, context, "rename-symbol", (change) => renameStep(db, change, context.origin, request)));
1328
+ /** A write: the operation of its revision, the check that refuses bad input before anything opens, and the step that runs inside a change. */
1329
+ interface WriteOp<R, T, P> {
1330
+ operation: string;
1331
+ check(request: NoInfer<R>): unknown;
1332
+ step(db: DatabaseSync, change: Change, request: R, context: StepContext): Step<T, P>;
1360
1333
  }
1361
1334
 
1362
- export function removeSymbol(db: DatabaseSync, context: WriteContext, request: AddressRequest): WriteResult<null> {
1335
+ /** The write of one request as one revision. */
1336
+ const single =
1337
+ <R, T, P>({ operation, check, step }: WriteOp<R, T, P>) =>
1338
+ (db: DatabaseSync, context: WriteContext, request: R): WriteResult<T, P> => {
1339
+ check(request);
1340
+ return result(write(db, context, operation, (change) => step(db, change, request, context)));
1341
+ };
1342
+
1343
+ /** The check of a write at an address: its space and the address. */
1344
+ function checkAt(request: AddressRequest): void {
1363
1345
  checkSpace(request);
1364
1346
  checkAddress(request.address);
1365
- return result(write(db, context, "remove-symbol", (change) => removeSymbolStep(db, change, context.origin, request)));
1366
1347
  }
1367
1348
 
1368
- /** Classifies [start, end]; overlapping regions are split so current regions never overlap. */
1369
- export function classifyRegion(db: DatabaseSync, context: WriteContext, request: RegionRequest): WriteResult<RegionRow[], RegionRow[]> {
1370
- checkRegion(request);
1371
- return result(write(db, context, "classify-region", (change) => classifyStep(db, change, context.origin, request)));
1349
+ /** The check of a write at a start: its space and the start. */
1350
+ function checkStart(request: InSpace & { start: number }): void {
1351
+ checkSpace(request);
1352
+ checkAddress(request.start, "start");
1372
1353
  }
1373
1354
 
1374
- /** Makes [start, end] unclassified again; parts of regions outside it stay. */
1375
- export function unclassifyRegion(db: DatabaseSync, context: WriteContext, request: RangeRequest): WriteResult<null> {
1376
- checkRange(request);
1377
- return result(write(db, context, "unclassify-region", (change) => unclassifyStep(db, change, context.origin, request)));
1355
+ function checkUnpatch(request: InSpace & { start: number; switch?: string }): void {
1356
+ checkStart(request);
1357
+ if (request.switch !== undefined) checkSwitchName(request.switch);
1378
1358
  }
1379
1359
 
1380
- export function setComment(db: DatabaseSync, context: WriteContext, request: CommentRequest): WriteResult<CommentRow, CommentRow> {
1381
- checkComment(request);
1382
- return result(write(db, context, "set-comment", (change) => commentStep(db, change, context.origin, request)));
1360
+ function checkUnmacro(request: InSpace & { name: string }): void {
1361
+ checkSpace(request);
1362
+ checkMacroName(request.name);
1383
1363
  }
1384
1364
 
1385
- export function removeComment(db: DatabaseSync, context: WriteContext, request: PlacementRequest): WriteResult<null> {
1386
- checkPlacement(request);
1387
- return result(write(db, context, "remove-comment", (change) => uncommentStep(db, change, context.origin, request)));
1365
+ function checkUnswitch(request: InSpace & { name: string }): void {
1366
+ checkSpace(request);
1367
+ checkSwitchName(request.name);
1388
1368
  }
1389
1369
 
1390
- export function addReference(db: DatabaseSync, context: WriteContext, request: ReferenceRequest): WriteResult<ReferenceRow, ReferenceRow> {
1391
- checkReference(request);
1392
- return result(write(db, context, "add-reference", (change) => referenceStep(db, change, context.origin, request)));
1393
- }
1370
+ /** One write of a batch, named as the command that does it alone. */
1371
+ export type BatchOperation =
1372
+ | ({ op: "rename" } & SymbolRequest)
1373
+ | ({ op: "remove-symbol" } & AddressRequest)
1374
+ | ({ op: "classify" } & RegionRequest)
1375
+ | ({ op: "unclassify" } & RangeRequest)
1376
+ | ({ op: "comment" } & CommentRequest)
1377
+ | ({ op: "uncomment" } & PlacementRequest)
1378
+ | ({ op: "reference" } & ReferenceRequest)
1379
+ | ({ op: "unreference" } & ReferenceRequest)
1380
+ | ({ op: "module" } & ModuleRequest)
1381
+ | ({ op: "unmodule" } & InSpace & { start: number })
1382
+ | ({ op: "operand" } & OperandRequest)
1383
+ | ({ op: "unoperand" } & AddressRequest)
1384
+ | ({ op: "patch" } & PatchRequest)
1385
+ | ({ op: "unpatch" } & InSpace & { start: number; switch?: string })
1386
+ | ({ op: "macro" } & MacroRequest)
1387
+ | ({ op: "unmacro" } & InSpace & { name: string })
1388
+ | ({ op: "use" } & MacroUseRequest)
1389
+ | ({ op: "unuse" } & InSpace & { start: number });
1394
1390
 
1395
- export function removeReference(db: DatabaseSync, context: WriteContext, request: ReferenceRequest): WriteResult<null> {
1396
- checkReference(request);
1397
- return result(write(db, context, "remove-reference", (change) => unreferenceStep(db, change, context.origin, request)));
1398
- }
1391
+ /** The writes of a batch by their op. Each is also a write of its own. */
1392
+ const OPS = {
1393
+ rename: { operation: "rename-symbol", check: checkSymbol, step: renameStep },
1394
+ "remove-symbol": { operation: "remove-symbol", check: checkAt, step: removeSymbolStep },
1395
+ classify: { operation: "classify-region", check: checkRegion, step: classifyStep },
1396
+ unclassify: { operation: "unclassify-region", check: checkRange, step: unclassifyStep },
1397
+ comment: { operation: "set-comment", check: checkComment, step: commentStep },
1398
+ uncomment: { operation: "remove-comment", check: checkPlacement, step: uncommentStep },
1399
+ reference: { operation: "add-reference", check: checkReference, step: referenceStep },
1400
+ unreference: { operation: "remove-reference", check: checkReference, step: unreferenceStep },
1401
+ module: { operation: "set-module", check: checkModule, step: moduleStep },
1402
+ unmodule: { operation: "remove-module", check: checkStart, step: unmoduleStep },
1403
+ operand: { operation: "set-operand", check: checkOperand, step: operandStep },
1404
+ unoperand: { operation: "remove-operand", check: checkAt, step: unoperandStep },
1405
+ patch: { operation: "set-patch", check: checkPatch, step: patchStep },
1406
+ unpatch: { operation: "remove-patch", check: checkUnpatch, step: unpatchStep },
1407
+ macro: { operation: "set-macro", check: checkMacro, step: macroStep },
1408
+ unmacro: { operation: "remove-macro", check: checkUnmacro, step: unmacroStep },
1409
+ use: { operation: "set-macro-use", check: checkMacroUse, step: useStep },
1410
+ unuse: { operation: "remove-macro-use", check: checkStart, step: unuseStep },
1411
+ } satisfies { [K in BatchOperation["op"]]: WriteOp<Extract<BatchOperation, { op: K }>, unknown, unknown> };
1412
+
1413
+ /** Names the symbol at an address (one current symbol per address, unique names). */
1414
+ export const renameSymbol = single(OPS.rename);
1415
+
1416
+ export const removeSymbol = single(OPS["remove-symbol"]);
1417
+
1418
+ /** Classifies [start, end]; overlapping regions are split so current regions never overlap. */
1419
+ export const classifyRegion = single(OPS.classify);
1420
+
1421
+ /** Makes [start, end] unclassified again; parts of regions outside it stay. */
1422
+ export const unclassifyRegion = single(OPS.unclassify);
1423
+
1424
+ export const setComment = single(OPS.comment);
1425
+
1426
+ export const removeComment = single(OPS.uncomment);
1427
+
1428
+ export const addReference = single(OPS.reference);
1429
+
1430
+ export const removeReference = single(OPS.unreference);
1399
1431
 
1400
1432
  /** Starts a file of the generated source at an address; one module per address and per file. */
1401
- export function setModule(db: DatabaseSync, context: WriteContext, request: ModuleRequest): WriteResult<ModuleRow, ModuleRow> {
1402
- checkModule(request);
1403
- return result(write(db, context, "set-module", (change) => moduleStep(db, change, context.origin, request)));
1404
- }
1433
+ export const setModule = single(OPS.module);
1405
1434
 
1406
- export function removeModule(db: DatabaseSync, context: WriteContext, request: InSpace & { start: number }): WriteResult<null> {
1407
- checkSpace(request);
1408
- checkAddress(request.start, "start");
1409
- return result(write(db, context, "remove-module", (change) => unmoduleStep(db, change, context.origin, request)));
1410
- }
1435
+ export const removeModule = single(OPS.unmodule);
1411
1436
 
1412
1437
  /**
1413
1438
  * Writes the operand expression of the instruction at an address, after
1414
1439
  * a check against the image, and a pointer reference to each name it uses.
1415
1440
  */
1416
- export function setOperand(db: DatabaseSync, context: WriteContext, request: OperandRequest): WriteResult<OperandRow, OperandRow> {
1417
- checkOperand(request);
1418
- return result(write(db, context, "set-operand", (change) => operandStep(db, change, context, request)));
1419
- }
1441
+ export const setOperand = single(OPS.operand);
1420
1442
 
1421
- export function removeOperand(db: DatabaseSync, context: WriteContext, request: AddressRequest): WriteResult<null> {
1422
- checkSpace(request);
1423
- checkAddress(request.address);
1424
- return result(write(db, context, "remove-operand", (change) => unoperandStep(db, change, context.origin, request)));
1425
- }
1443
+ export const removeOperand = single(OPS.unoperand);
1426
1444
 
1427
1445
  /**
1428
1446
  * Writes code that replaces [start, end] when its switch does not have its
1429
1447
  * base value, after a check that the switch exists, the range is in the image,
1430
1448
  * and it overlaps no macro use and no patch other than an alternative.
1431
1449
  */
1432
- export function setPatch(db: DatabaseSync, context: WriteContext, request: PatchRequest): WriteResult<PatchRow, PatchRow> {
1433
- checkPatch(request);
1434
- return result(write(db, context, "set-patch", (change) => patchStep(db, change, context, request)));
1435
- }
1450
+ export const setPatch = single(OPS.patch);
1436
1451
 
1437
- export function removePatch(db: DatabaseSync, context: WriteContext, request: InSpace & { start: number; switch?: string }): WriteResult<null> {
1438
- checkSpace(request);
1439
- checkAddress(request.start, "start");
1440
- if (request.switch !== undefined) checkSwitchName(request.switch);
1441
- return result(write(db, context, "remove-patch", (change) => unpatchStep(db, change, context.origin, request)));
1442
- }
1452
+ export const removePatch = single(OPS.unpatch);
1443
1453
 
1444
1454
  /** Writes a switch: its kind, its default and the releases that have it on. The knowledge needs a base release first. */
1445
- export function setSwitch(db: DatabaseSync, context: WriteContext, request: SwitchRequest): WriteResult<SwitchRow, SwitchRow> {
1446
- checkSwitch(request);
1447
- return result(write(db, context, "set-switch", (change) => switchStep(db, change, context, request)));
1448
- }
1455
+ export const setSwitch = single({ operation: "set-switch", check: checkSwitch, step: switchStep });
1449
1456
 
1450
- export function removeSwitch(db: DatabaseSync, context: WriteContext, request: InSpace & { name: string }): WriteResult<null> {
1451
- checkSpace(request);
1452
- checkSwitchName(request.name);
1453
- return result(write(db, context, "remove-switch", (change) => unswitchStep(db, change, context.origin, request)));
1454
- }
1457
+ export const removeSwitch = single({ operation: "remove-switch", check: checkUnswitch, step: unswitchStep });
1455
1458
 
1456
1459
  /** Writes a release of the program and its bytes. The caller reads the bytes from the file of the release, and checks the file of the base release. */
1457
- export function setRelease(db: DatabaseSync, context: WriteContext, request: ReleaseRequest): WriteResult<ReleaseRow, ReleaseRow> {
1458
- checkRelease(request);
1459
- return result(write(db, context, "set-release", (change) => releaseStep(db, change, context.origin, request)));
1460
- }
1460
+ export const setRelease = single({ operation: "set-release", check: checkRelease, step: releaseStep });
1461
1461
 
1462
- export function removeRelease(db: DatabaseSync, context: WriteContext, request: InSpace & { label: string }): WriteResult<null> {
1463
- checkSpace(request);
1464
- return result(write(db, context, "remove-release", (change) => unreleaseStep(db, change, context.origin, request)));
1465
- }
1462
+ export const removeRelease = single({ operation: "remove-release", check: checkSpace, step: unreleaseStep });
1466
1463
 
1467
1464
  /** Writes the start screen of the program: the loader of the generated source shows it before the entry. */
1468
- export function setStartScreen(db: DatabaseSync, context: WriteContext, request: StartScreenRequest): WriteResult<StartScreenRow, StartScreenRow> {
1469
- checkStartScreen(request);
1470
- return result(write(db, context, "set-start-screen", (change) => startScreenStep(db, change, context.origin, request)));
1471
- }
1465
+ export const setStartScreen = single({ operation: "set-start-screen", check: checkStartScreen, step: startScreenStep });
1472
1466
 
1473
- export function removeStartScreen(db: DatabaseSync, context: WriteContext, request: InSpace): WriteResult<null> {
1474
- checkSpace(request);
1475
- return result(write(db, context, "remove-start-screen", (change) => unstartScreenStep(db, change, context.origin, request)));
1476
- }
1467
+ export const removeStartScreen = single({ operation: "remove-start-screen", check: checkSpace, step: unstartScreenStep });
1477
1468
 
1478
1469
  /** Writes a macro of the generated source. */
1479
- export function setMacro(db: DatabaseSync, context: WriteContext, request: MacroRequest): WriteResult<MacroRow, MacroRow> {
1480
- checkMacro(request);
1481
- return result(write(db, context, "set-macro", (change) => macroStep(db, change, context.origin, request)));
1482
- }
1470
+ export const setMacro = single(OPS.macro);
1483
1471
 
1484
- export function removeMacro(db: DatabaseSync, context: WriteContext, request: InSpace & { name: string }): WriteResult<null> {
1485
- checkSpace(request);
1486
- checkMacroName(request.name);
1487
- return result(write(db, context, "remove-macro", (change) => unmacroStep(db, change, context.origin, request)));
1488
- }
1472
+ export const removeMacro = single(OPS.unmacro);
1489
1473
 
1490
1474
  /** Writes the instructions in [start, end] as one use of a macro, after a check against the image. */
1491
- export function setMacroUse(db: DatabaseSync, context: WriteContext, request: MacroUseRequest): WriteResult<MacroUseRow, MacroUseRow> {
1492
- checkMacroUse(request);
1493
- return result(write(db, context, "set-macro-use", (change) => useStep(db, change, context, request)));
1494
- }
1495
-
1496
- export function removeMacroUse(db: DatabaseSync, context: WriteContext, request: InSpace & { start: number }): WriteResult<null> {
1497
- checkSpace(request);
1498
- checkAddress(request.start, "start");
1499
- return result(write(db, context, "remove-macro-use", (change) => unuseStep(db, change, context.origin, request)));
1500
- }
1475
+ export const setMacroUse = single(OPS.use);
1501
1476
 
1502
- /** One write of a batch, named as the command that does it alone. */
1503
- export type BatchOperation =
1504
- | ({ op: "rename" } & SymbolRequest)
1505
- | ({ op: "remove-symbol" } & AddressRequest)
1506
- | ({ op: "classify" } & RegionRequest)
1507
- | ({ op: "unclassify" } & RangeRequest)
1508
- | ({ op: "comment" } & CommentRequest)
1509
- | ({ op: "uncomment" } & PlacementRequest)
1510
- | ({ op: "reference" } & ReferenceRequest)
1511
- | ({ op: "unreference" } & ReferenceRequest)
1512
- | ({ op: "module" } & ModuleRequest)
1513
- | ({ op: "unmodule" } & InSpace & { start: number })
1514
- | ({ op: "operand" } & OperandRequest)
1515
- | ({ op: "unoperand" } & AddressRequest)
1516
- | ({ op: "patch" } & PatchRequest)
1517
- | ({ op: "unpatch" } & InSpace & { start: number; switch?: string })
1518
- | ({ op: "macro" } & MacroRequest)
1519
- | ({ op: "unmacro" } & InSpace & { name: string })
1520
- | ({ op: "use" } & MacroUseRequest)
1521
- | ({ op: "unuse" } & InSpace & { start: number });
1477
+ export const removeMacroUse = single(OPS.unuse);
1522
1478
 
1523
- export const MAX_BATCH = 10_000;
1479
+ const MAX_BATCH = 10_000;
1524
1480
 
1525
1481
  /** The result of each write of a batch, in order. */
1526
1482
  export type BatchStep = Step<
@@ -1528,169 +1484,31 @@ export type BatchStep = Step<
1528
1484
  SymbolRow | RegionRow[] | CommentRow | ReferenceRow | ModuleRow | OperandRow | PatchRow | MacroRow | MacroUseRow
1529
1485
  >;
1530
1486
 
1487
+ /** A write of a batch. */
1488
+ type BatchWrite = WriteOp<BatchOperation, BatchStep["current"], NonNullable<BatchStep["previous"]>>;
1489
+
1531
1490
  /**
1532
1491
  * Applies many writes as one revision in one transaction: all of them,
1533
1492
  * or none when one is refused. Every write is checked before anything opens.
1534
1493
  */
1535
1494
  export function applyBatch(db: DatabaseSync, context: WriteContext, operations: BatchOperation[]): { revision: string | null; steps: BatchStep[] } {
1536
1495
  if (operations.length === 0 || operations.length > MAX_BATCH) throw new Refusal("invalid-input", `A batch has 1 to ${MAX_BATCH} writes.`);
1537
- operations.forEach((operation, index) => {
1538
- try {
1539
- switch (operation.op) {
1540
- case "rename":
1541
- return checkSymbol(operation);
1542
- case "remove-symbol":
1543
- checkSpace(operation);
1544
- return checkAddress(operation.address);
1545
- case "classify":
1546
- return checkRegion(operation);
1547
- case "unclassify":
1548
- return checkRange(operation);
1549
- case "comment":
1550
- return void checkComment(operation);
1551
- case "uncomment":
1552
- return checkPlacement(operation);
1553
- case "reference":
1554
- case "unreference":
1555
- return checkReference(operation);
1556
- case "module":
1557
- return checkModule(operation);
1558
- case "unmodule":
1559
- checkSpace(operation);
1560
- return checkAddress(operation.start, "start");
1561
- case "operand":
1562
- return checkOperand(operation);
1563
- case "unoperand":
1564
- checkSpace(operation);
1565
- return checkAddress(operation.address);
1566
- case "patch":
1567
- return checkPatch(operation);
1568
- case "unpatch":
1569
- if (operation.switch !== undefined) checkSwitchName(operation.switch);
1570
- checkSpace(operation);
1571
- return checkAddress(operation.start, "start");
1572
- case "unuse":
1573
- checkSpace(operation);
1574
- return checkAddress(operation.start, "start");
1575
- case "macro":
1576
- return checkMacro(operation);
1577
- case "unmacro":
1578
- checkSpace(operation);
1579
- return checkMacroName(operation.name);
1580
- case "use":
1581
- return checkMacroUse(operation);
1582
- default:
1583
- throw new Refusal(
1584
- "invalid-input",
1585
- `op must be one of rename, remove-symbol, classify, unclassify, comment, uncomment, reference, unreference, module, unmodule, operand, unoperand, patch, unpatch, macro, unmacro, use, unuse.`,
1586
- );
1587
- }
1588
- } catch (error) {
1589
- if (error instanceof Refusal) throw new Refusal(error.code, `Write ${index + 1}: ${error.message} Nothing was written.`);
1590
- throw error;
1591
- }
1592
- });
1593
- const written = write(db, context, "apply", (change) =>
1594
- operations.map((operation, index): BatchStep => {
1496
+ // Runs `work` on each write with its op; a refusal names the write.
1497
+ const eachWrite = <T>(work: (operation: BatchOperation, op: BatchWrite) => T): T[] =>
1498
+ operations.map((operation, index) => {
1595
1499
  try {
1596
- switch (operation.op) {
1597
- case "rename":
1598
- return renameStep(db, change, context.origin, operation);
1599
- case "remove-symbol":
1600
- return removeSymbolStep(db, change, context.origin, operation);
1601
- case "classify":
1602
- return classifyStep(db, change, context.origin, operation);
1603
- case "unclassify":
1604
- return unclassifyStep(db, change, context.origin, operation);
1605
- case "comment":
1606
- return commentStep(db, change, context.origin, operation);
1607
- case "uncomment":
1608
- return uncommentStep(db, change, context.origin, operation);
1609
- case "reference":
1610
- return referenceStep(db, change, context.origin, operation);
1611
- case "unreference":
1612
- return unreferenceStep(db, change, context.origin, operation);
1613
- case "module":
1614
- return moduleStep(db, change, context.origin, operation);
1615
- case "unmodule":
1616
- return unmoduleStep(db, change, context.origin, operation);
1617
- case "operand":
1618
- return operandStep(db, change, context, operation);
1619
- case "unoperand":
1620
- return unoperandStep(db, change, context.origin, operation);
1621
- case "patch":
1622
- return patchStep(db, change, context, operation);
1623
- case "unpatch":
1624
- return unpatchStep(db, change, context.origin, operation);
1625
- case "macro":
1626
- return macroStep(db, change, context.origin, operation);
1627
- case "unmacro":
1628
- return unmacroStep(db, change, context.origin, operation);
1629
- case "use":
1630
- return useStep(db, change, context, operation);
1631
- case "unuse":
1632
- return unuseStep(db, change, context.origin, operation);
1633
- }
1500
+ if (!Object.hasOwn(OPS, operation.op)) throw new Refusal("invalid-input", `op must be one of ${Object.keys(OPS).join(", ")}.`);
1501
+ return work(operation, OPS[operation.op] as BatchWrite);
1634
1502
  } catch (error) {
1635
1503
  if (error instanceof Refusal) throw new Refusal(error.code, `Write ${index + 1}: ${error.message} Nothing was written.`);
1636
1504
  throw error;
1637
1505
  }
1638
- }),
1639
- );
1506
+ });
1507
+ eachWrite((operation, op) => op.check(operation));
1508
+ const written = write(db, context, "apply", (change) => eachWrite((operation, op) => op.step(db, change, operation, context)));
1640
1509
  return { revision: written.revision, steps: written.current };
1641
1510
  }
1642
1511
 
1643
- /** Row content without its revision, as a comparable key. */
1644
- /** The tables of the program and the columns that make a row. */
1645
- const PROGRAM_TABLES = [
1646
- ["memory", "space, address, bytes, origin"],
1647
- ["release_memory", "space, label, address, bytes, origin"],
1648
- ["entries", "space, address, state, stages, origin"],
1649
- ["coverage", "space, map, kind, ranges, origin"],
1650
- ] as const;
1651
-
1652
- const KEYS = {
1653
- symbols: { columns: SYMBOL_COLUMNS, map: toSymbol, key: (row: SymbolRow) => `${row.space}|${row.address}|${row.name}|${row.kind}|${row.origin}` },
1654
- analyzer_names: { columns: SYMBOL_COLUMNS, map: toSymbol, key: (row: SymbolRow) => `${row.space}|${row.address}|${row.name}|${row.kind}|${row.origin}` },
1655
- regions: { columns: REGION_COLUMNS, map: toRegion, key: (row: RegionRow) => `${row.space}|${row.start}|${row.end}|${row.type}|${row.element ?? ""}|${row.origin}` },
1656
- comments: { columns: COMMENT_COLUMNS, map: toComment, key: (row: CommentRow) => `${row.space}|${row.address}|${row.placement}|${row.text}|${row.origin}` },
1657
- references: { columns: REFERENCE_COLUMNS, map: toReference, key: (row: ReferenceRow) => `${row.space}|${row.from}|${row.to}|${row.kind}|${row.origin}` },
1658
- modules: { columns: MODULE_COLUMNS, map: toModule, key: (row: ModuleRow) => `${row.space}|${row.start}|${row.file}|${row.title ?? ""}|${row.origin}` },
1659
- operands: {
1660
- columns: OPERAND_COLUMNS,
1661
- map: toOperand,
1662
- key: (row: OperandRow) => `${row.space}|${row.address}|${row.select}|${row.symbol ?? ""}|${row.offset}|${row.expression ?? ""}|${row.origin}`,
1663
- },
1664
- patches: {
1665
- columns: PATCH_COLUMNS,
1666
- map: toPatch,
1667
- key: (row: PatchRow) => `${row.space}|${row.start}|${row.end}|${row.switch}|${row.code}|${row.comment ?? ""}|${row.origin}`,
1668
- },
1669
- switches: {
1670
- columns: SWITCH_COLUMNS,
1671
- map: toSwitch,
1672
- key: (row: SwitchRow) => `${row.space}|${row.name}|${row.kind}|${row.default}|${listText(row.releases)}|${row.comment ?? ""}|${row.origin}`,
1673
- },
1674
- releases: {
1675
- columns: RELEASE_COLUMNS,
1676
- map: toRelease,
1677
- key: (row: ReleaseRow) => `${row.space}|${row.label}|${row.base}|${row.file ?? ""}|${row.sha256 ?? ""}|${row.comment ?? ""}|${row.origin}`,
1678
- },
1679
- start_screens: {
1680
- columns: START_SCREEN_COLUMNS,
1681
- map: toStartScreen,
1682
- key: (row: StartScreenRow) =>
1683
- `${row.space}|${row.mode}|${row.screen}|${row.bitmap ?? ""}|${row.charset ?? ""}|${row.colours ?? ""}|${row.colour ?? ""}|${row.border}|${row.background}|${row.stage ?? ""}|${row.call ?? ""}|${row.colourRam === true ? 1 : ""}|${row.comment ?? ""}|${row.origin}`,
1684
- },
1685
- macros: { columns: MACRO_COLUMNS, map: toMacro, key: (row: MacroRow) => `${row.space}|${row.name}|${listText(row.params)}|${row.body}|${row.comment ?? ""}|${row.origin}` },
1686
- macro_uses: { columns: MACRO_USE_COLUMNS, map: toMacroUse, key: (row: MacroUseRow) => `${row.space}|${row.start}|${row.end}|${row.macro}|${listText(row.args)}|${row.origin}` },
1687
- suppressions: {
1688
- columns: SUPPRESSION_COLUMNS,
1689
- map: toSuppression,
1690
- key: (row: SuppressionRow) => `${row.space}|${row.entity}|${row.start}|${row.end}|${row.to ?? ""}|${row.kind ?? ""}|${row.origin}`,
1691
- },
1692
- } as const;
1693
-
1694
1512
  /**
1695
1513
  * Makes the current knowledge equal to what it was at `revision`, as a new
1696
1514
  * revision. With `space`, only the rows of that space change; without it,
@@ -1708,77 +1526,18 @@ export function revert(db: DatabaseSync, context: WriteContext, request: { revis
1708
1526
  const spaceArgs = only === undefined ? [] : [only];
1709
1527
  const at = `valid_from_revision <= ? AND (valid_to_revision IS NULL OR valid_to_revision > ?)${inSpace}`;
1710
1528
  const current = `valid_to_revision IS NULL${inSpace}`;
1711
- for (const [table, spec] of Object.entries(KEYS)) {
1712
- const name = table === "references" ? '"references"' : table;
1713
- const then = db.prepare(`SELECT ${spec.columns}, id FROM ${name} WHERE ${at}`).all(restored, restored, ...spaceArgs) as Array<Record<string, unknown>>;
1714
- const now = db.prepare(`SELECT ${spec.columns}, id FROM ${name} WHERE ${current}`).all(...spaceArgs) as Array<Record<string, unknown>>;
1715
- const key = (row: Record<string, unknown>) => (spec.key as (row: unknown) => string)(spec.map(row as never));
1529
+ // A row is the same when all its values are the same.
1530
+ for (const spec of TABLES) {
1531
+ const columns = spec.fields.map((field) => field.column);
1532
+ const select = `SELECT ${columns.join(", ")}, id FROM ${sqlName(spec.table)} WHERE `;
1533
+ const then = db.prepare(select + at).all(restored, restored, ...spaceArgs) as Raw[];
1534
+ const now = db.prepare(select + current).all(...spaceArgs) as Raw[];
1535
+ const key = (row: Raw) => JSON.stringify(columns.map((column) => row[column]));
1716
1536
  const thenKeys = new Set(then.map(key));
1717
1537
  const nowKeys = new Set(now.map(key));
1718
1538
  // Close first, so restored rows never collide with the current-row rules.
1719
- for (const row of now) if (!thenKeys.has(key(row))) change.close(name, "id = ?", row.id as string);
1720
- for (const row of then) {
1721
- if (nowKeys.has(key(row))) continue;
1722
- if (table === "suppressions") {
1723
- change.insertSuppression(spec.map(row as never) as SuppressionRow);
1724
- continue;
1725
- }
1726
- if (table === "modules") {
1727
- change.insertModule(spec.map(row as never) as ModuleRow);
1728
- continue;
1729
- }
1730
- if (table === "operands") {
1731
- change.insertOperand(spec.map(row as never) as OperandRow);
1732
- continue;
1733
- }
1734
- if (table === "patches") {
1735
- change.insertPatch(spec.map(row as never) as PatchRow);
1736
- continue;
1737
- }
1738
- if (table === "macros") {
1739
- change.insertMacro(spec.map(row as never) as MacroRow);
1740
- continue;
1741
- }
1742
- if (table === "switches") {
1743
- change.insertSwitch(spec.map(row as never) as SwitchRow);
1744
- continue;
1745
- }
1746
- if (table === "releases") {
1747
- change.insertRelease(spec.map(row as never) as ReleaseRow);
1748
- continue;
1749
- }
1750
- if (table === "start_screens") {
1751
- change.insertStartScreen(spec.map(row as never) as StartScreenRow);
1752
- continue;
1753
- }
1754
- if (table === "macro_uses") {
1755
- change.insertMacroUse(spec.map(row as never) as MacroUseRow);
1756
- continue;
1757
- }
1758
- const mapped = spec.map(row as never) as SymbolRow & RegionRow & CommentRow & ReferenceRow;
1759
- if (table === "symbols") change.insertSymbol(mapped);
1760
- else if (table === "analyzer_names") change.insertAnalyzerName(mapped);
1761
- else if (table === "regions") change.insertRegion(mapped);
1762
- else if (table === "comments") change.insertComment(mapped);
1763
- else change.insertReference(mapped);
1764
- }
1765
- }
1766
- // The program: a row is the same when all its values are the same.
1767
- for (const [table, columns] of PROGRAM_TABLES) {
1768
- const then = db.prepare(`SELECT ${columns}, id FROM ${table} WHERE ${at}`).all(restored, restored, ...spaceArgs) as Array<Record<string, unknown>>;
1769
- const now = db.prepare(`SELECT ${columns}, id FROM ${table} WHERE ${current}`).all(...spaceArgs) as Array<Record<string, unknown>>;
1770
- const key = (row: Record<string, unknown>) => JSON.stringify(columns.split(", ").map((column) => row[column]));
1771
- const thenKeys = new Set(then.map(key));
1772
- const nowKeys = new Set(now.map(key));
1773
- for (const row of now) if (!thenKeys.has(key(row))) change.close(table, "id = ?", row.id as string);
1774
- for (const row of then) {
1775
- if (nowKeys.has(key(row))) continue;
1776
- const values = row as never;
1777
- if (table === "memory") change.insertMemory(values);
1778
- else if (table === "release_memory") change.insertReleaseMemory(values);
1779
- else if (table === "entries") change.insertEntry(values);
1780
- else change.insertCoverage(values);
1781
- }
1539
+ for (const row of now) if (!thenKeys.has(key(row))) change.close(spec.table, "id = ?", row.id as string);
1540
+ for (const row of then) if (!nowKeys.has(key(row))) change.insertColumns(spec.table, row);
1782
1541
  }
1783
1542
  return { restoredRevision: restored };
1784
1543
  });
@@ -1803,14 +1562,14 @@ const MAX_CHOICES = 100_000;
1803
1562
  * expression that stays. `platform` gives the C64 platform names.
1804
1563
  */
1805
1564
  export function mergeConflicts(db: DatabaseSync, context: WriteContext, platform: ReadonlyMap<string, number>): WriteResult<MergeChoice[]> {
1806
- return write(db, context, "merge", (change) => {
1565
+ return write(db, { ...context, allowConflicts: true }, "merge", (change) => {
1807
1566
  const choices: MergeChoice[] = [];
1808
1567
  for (let found = conflicts(db); found.length > 0; found = conflicts(db)) {
1809
1568
  if (choices.length >= MAX_CHOICES) throw new Refusal("invalid-database", `The merge made ${MAX_CHOICES} choices and still finds conflicts. Nothing was written.`);
1810
1569
  const conflict = found[0]!;
1811
1570
  const newest = conflict.rows.at(-1)!;
1812
1571
  const older = conflict.rows.slice(0, -1);
1813
- const table = sqlName(conflictTable(conflict.rule));
1572
+ const table = conflictTable(conflict.rule);
1814
1573
  for (const entry of older) change.close(table, "id = ?", entry.id);
1815
1574
  if (conflict.rule === "region" || conflict.rule === "suppression-region") keepOutside(change, conflict, conflict.rule === "region");
1816
1575
  if (conflict.rule === "operand") followOperand(db, change, newest.row as OperandRow, platform);
@@ -1841,7 +1600,7 @@ function followOperand(db: DatabaseSync, change: Change, kept: OperandRow, platf
1841
1600
  const targets = new Set(identifiers(operandText(kept)).flatMap((name) => resolve(name) ?? []));
1842
1601
  const pointers = referencesFrom(db, kept.address, kept.space).filter((reference) => reference.kind === POINTER_KIND);
1843
1602
  for (const reference of pointers) {
1844
- if (!targets.has(reference.to)) change.close('"references"', "space = ? AND from_address = ? AND to_address = ? AND kind = ?", kept.space, kept.address, reference.to, POINTER_KIND);
1603
+ if (!targets.has(reference.to)) change.close("references", "space = ? AND from_address = ? AND to_address = ? AND kind = ?", kept.space, kept.address, reference.to, POINTER_KIND);
1845
1604
  }
1846
1605
  for (const to of targets) {
1847
1606
  if (!pointers.some((reference) => reference.to === to)) change.insertReference({ space: kept.space, from: kept.address, to, kind: POINTER_KIND, origin: kept.origin });