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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +5 -2
  3. package/skills/c64-assembler/scripts/assembler.ts +55 -48
  4. package/skills/c64-disk/scripts/disk.ts +3 -3
  5. package/skills/c64-disk/scripts/lib/containers.ts +2 -2
  6. package/skills/c64-docs/SKILL.md +1 -1
  7. package/skills/c64-docs/scripts/docs.ts +12 -20
  8. package/skills/c64-docs/scripts/lib/links.ts +1 -1
  9. package/skills/c64-docs/scripts/lib/markdown.ts +1 -1
  10. package/skills/c64-docs/scripts/lib/reference.ts +59 -13
  11. package/skills/c64-knowledge/SKILL.md +17 -8
  12. package/skills/c64-knowledge/scripts/knowledge.ts +200 -218
  13. package/skills/c64-knowledge/scripts/lib/check.ts +2 -3
  14. package/skills/c64-knowledge/scripts/lib/listing.ts +56 -24
  15. package/skills/c64-packer/scripts/packer.ts +3 -3
  16. package/skills/c64-provenance/SKILL.md +25 -16
  17. package/skills/c64-provenance/scripts/lib/compare.ts +31 -21
  18. package/skills/c64-provenance/scripts/lib/leftovers.ts +17 -35
  19. package/skills/c64-provenance/scripts/lib/library.ts +10 -10
  20. package/skills/c64-provenance/scripts/lib/runtime.ts +3 -14
  21. package/skills/c64-provenance/scripts/provenance.ts +129 -98
  22. package/skills/c64-source/references/loader.md +2 -1
  23. package/skills/c64-source/scripts/lib/export.ts +54 -303
  24. package/skills/c64-source/scripts/lib/loader.ts +31 -51
  25. package/skills/c64-source/scripts/lib/source.ts +51 -41
  26. package/skills/c64-source/scripts/lib/stage.ts +9 -25
  27. package/skills/c64-source/scripts/source.ts +134 -294
  28. package/skills/c64-static-analysis/SKILL.md +12 -7
  29. package/skills/c64-static-analysis/scripts/lib/coverage.ts +1 -3
  30. package/skills/c64-static-analysis/scripts/lib/findings.ts +16 -3
  31. package/skills/c64-static-analysis/scripts/lib/idioms.ts +82 -10
  32. package/skills/c64-static-analysis/scripts/lib/triage.ts +112 -0
  33. package/skills/c64-static-analysis/scripts/static-analysis.ts +239 -147
  34. package/skills/c64-testing/SKILL.md +13 -7
  35. package/skills/c64-testing/scripts/lib/diff-files.ts +6 -13
  36. package/skills/c64-testing/scripts/lib/recording.ts +47 -66
  37. package/skills/c64-testing/scripts/lib/replay.ts +53 -9
  38. package/skills/c64-testing/scripts/lib/runs.ts +11 -29
  39. package/skills/c64-testing/scripts/lib/scenario.ts +30 -31
  40. package/skills/c64-testing/scripts/lib/start-screen.ts +42 -5
  41. package/skills/c64-testing/scripts/testing.ts +32 -7
  42. package/skills/c64-unpacker/SKILL.md +10 -7
  43. package/skills/c64-unpacker/scripts/lib/evidence.ts +23 -38
  44. package/skills/c64-unpacker/scripts/lib/loads.ts +24 -39
  45. package/skills/c64-unpacker/scripts/lib/machine.ts +38 -18
  46. package/skills/c64-unpacker/scripts/lib/stages.ts +142 -41
  47. package/skills/c64-unpacker/scripts/unpacker.ts +85 -68
  48. package/skills/emulator/SKILL.md +1 -0
  49. package/src/c64.ts +117 -10
  50. package/src/cli/ap-sdk.ts +1 -1
  51. package/src/cli/cleanup.ts +4 -2
  52. package/src/compare.ts +36 -16
  53. package/src/errors.ts +10 -1
  54. package/src/host/main.ts +2 -1
  55. package/src/host/server.ts +7 -11
  56. package/src/host/tools/c1541.ts +9 -3
  57. package/src/host/vice/adapter.ts +20 -43
  58. package/src/host/vice/binary-monitor.ts +22 -21
  59. package/src/host/vice/process.ts +31 -40
  60. package/src/host/vice/session.ts +187 -247
  61. package/src/host/vice/text-monitor.ts +3 -3
  62. package/src/host-client/autostart.ts +1 -1
  63. package/src/host-client/connect.ts +2 -1
  64. package/src/host-client/coverage.ts +0 -3
  65. package/src/host-client/entry-state.ts +4 -11
  66. package/src/host-client/image.ts +6 -11
  67. package/src/host-client/steps.ts +13 -113
  68. package/src/host-client/tools.ts +4 -4
  69. package/src/host-client/transfer.ts +10 -0
  70. package/src/host-client/vice-session.ts +10 -6
  71. package/src/knowledge/code-reach.ts +364 -0
  72. package/src/knowledge/conflicts.ts +34 -72
  73. package/src/knowledge/database.ts +40 -28
  74. package/src/knowledge/evidence.ts +2 -2
  75. package/src/knowledge/graph.ts +3 -3
  76. package/src/knowledge/history.ts +50 -90
  77. package/src/knowledge/import.ts +43 -71
  78. package/src/knowledge/join.ts +1 -1
  79. package/src/knowledge/names.ts +12 -7
  80. package/src/knowledge/program.ts +25 -46
  81. package/src/knowledge/read.ts +104 -100
  82. package/src/knowledge/schema.ts +9 -3
  83. package/src/knowledge/separate.ts +47 -19
  84. package/src/knowledge/start-screen.ts +7 -5
  85. package/src/knowledge/text.ts +56 -33
  86. package/src/knowledge/write.ts +274 -515
  87. package/src/loader.ts +7 -25
  88. package/src/mcp/inputs.ts +3 -3
  89. package/src/mcp/server.ts +19 -38
  90. package/src/mcp/session-source.ts +2 -1
  91. package/src/mcp/tools/debug.ts +97 -24
  92. package/src/mcp/tools/execution.ts +1 -1
  93. package/src/mcp/tools/input.ts +3 -3
  94. package/src/mcp/tools/machine.ts +3 -3
  95. package/src/mcp/tools/media.ts +4 -4
  96. package/src/mcp/tools/memory.ts +13 -17
  97. package/src/mcp/tools/video.ts +11 -25
  98. package/src/native/acme.ts +3 -3
  99. package/src/native/c64run.ts +2 -1
  100. package/src/native/decompiler/analyze.ts +10 -7
  101. package/src/native/decompiler/walk.ts +3 -4
  102. package/src/native/decompiler/wasm.ts +2 -2
  103. package/src/native/discover.ts +1 -1
  104. package/src/native/dxa.ts +9 -11
  105. package/src/native/exomizer.ts +1 -1
  106. package/src/native/processes.ts +4 -1
  107. package/src/native/run.ts +3 -3
  108. package/src/native/types.ts +5 -6
  109. package/src/opcodes.ts +3 -0
  110. package/src/platform.ts +9 -10
  111. package/src/program-code.ts +151 -0
  112. package/src/project.ts +8 -5
  113. package/src/protocol/framing.ts +51 -18
  114. package/src/protocol/messages.ts +1 -11
  115. package/src/protocol/tools.ts +0 -3
  116. package/src/protocol/vice.ts +588 -773
  117. package/src/script.ts +9 -14
  118. package/src/time.ts +1 -1
  119. package/src/trace.ts +3 -2
@@ -2,28 +2,28 @@
2
2
  // project folder (--project, or the one found from the working directory).
3
3
  // Each command prints one JSON result.
4
4
 
5
- import { createHash, randomInt } from "node:crypto";
5
+ import { randomInt } from "node:crypto";
6
6
  import { existsSync, readdirSync, readFileSync } from "node:fs";
7
7
  import { join } from "node:path";
8
8
  import type { DatabaseSync } from "node:sqlite";
9
9
 
10
- import { formatC64Address } from "#src/c64.ts";
10
+ import { type AddressRange, formatC64Address, formatC64Range, formatC64RangeFields, inRanges, rangesOverlap, REFERENCE_KINDS } from "#src/c64.ts";
11
11
  import { Refusal } from "#src/errors.ts";
12
+ import { IO_RAM } from "#src/host-client/coverage.ts";
12
13
  import { readImage } from "#src/host-client/image.ts";
13
- import { readProjectFile, writeReported } from "#src/host-client/transfer.ts";
14
+ import { readProjectFile, readProjectJson, writeReported } from "#src/host-client/transfer.ts";
14
15
  import { CONFLICT_RULES, conflicts, type Conflict } from "#src/knowledge/conflicts.ts";
15
- import { openForRead, withWrite } from "#src/knowledge/database.ts";
16
- import { operandText } from "#src/knowledge/expression.ts";
16
+ import { withRead, withWrite } from "#src/knowledge/database.ts";
17
+ import { OPERAND_SELECTS, operandText, type OperandSelect } from "#src/knowledge/expression.ts";
17
18
  import { historyAt, historyNamed, historyOfMacro, historyOfSwitch, revision, revisionCounts, revisionNote, revisions, type HistoryEntry } from "#src/knowledge/history.ts";
18
19
  import { joinBatches, type Batch, type JoinChoice, type JoinClash } from "#src/knowledge/join.ts";
19
20
  import { knowledgeNames } from "#src/knowledge/names.ts";
20
- import { addCoverage, coverageAccess, coverageRangeCounts, memoryRows, operandImages as programImages, programCoverage, programImage, releaseCode, requireProgram, setImage, type ImageRequest } from "#src/knowledge/program.ts";
21
+ import { addCoverage, coverageAccess, coverageRangeCounts, memoryRows, operandImages as programImages, programCoverage, programImage, releaseCode, requireProgram, setImage, type ImageRequest, type ProgramImage } from "#src/knowledge/program.ts";
21
22
  import { coloursOfCapture, startScreenOfCapture, startScreenOfStage } from "#src/knowledge/start-screen.ts";
22
23
  import {
23
- analyzerNamesAt,
24
24
  at,
25
+ baseLabel,
25
26
  baseValue,
26
- commentsAt,
27
27
  coverageRuns,
28
28
  currentRevision,
29
29
  currentStartScreen,
@@ -42,11 +42,8 @@ import {
42
42
  listSwitches,
43
43
  listSuppressions,
44
44
  listSymbols,
45
- operandAt,
46
45
  REFERENCE_DIRECTIONS,
47
46
  referenceCounts,
48
- referencesFrom,
49
- referencesTo,
50
47
  regionCounts,
51
48
  search,
52
49
  symbolAt,
@@ -65,7 +62,7 @@ import {
65
62
  type SwitchRow,
66
63
  type SymbolRow,
67
64
  } from "#src/knowledge/read.ts";
68
- import { ANALYZERS, COMMENT_PLACEMENTS, DEFAULT_SPACE, EVIDENCE_KINDS, isSemantic, OPERAND_SELECTS, ORIGINS, REFERENCE_KINDS, REGION_TYPES, RELEASE_DEFINE, SEMANTIC_ORIGINS, START_SCREEN_MODES, SWITCH_KINDS, SYMBOL_KINDS, type Origin, type OperandSelect, type StartScreenMode, type SwitchKind } from "#src/knowledge/schema.ts";
65
+ import { ANALYZERS, COMMENT_PLACEMENTS, DEFAULT_SPACE, EVIDENCE_KINDS, isSemantic, ORIGINS, REGION_TYPES, RELEASE_DEFINE, SEMANTIC_ORIGINS, START_SCREEN_MODES, SWITCH_KINDS, SYMBOL_KINDS, type Origin, type StartScreenMode, type SwitchKind } from "#src/knowledge/schema.ts";
69
66
  import {
70
67
  addReference,
71
68
  applyBatch,
@@ -101,13 +98,14 @@ import {
101
98
  type OperandImage,
102
99
  type WriteContext,
103
100
  } from "#src/knowledge/write.ts";
104
- import { platformNames } from "#src/platform.ts";
101
+ import { platformAddresses, platformNamesFor, romUseOfProgram } from "#src/platform.ts";
105
102
  import { coverageMapOf } from "#src/knowledge/recording-files.ts";
103
+ import { sha256 } from "#src/knowledge/text.ts";
106
104
  import { isInside, LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRelative, projectRoot, resolveProjectPath } from "#src/project.ts";
107
- import { listed, OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec, type OptionSpec, type SubjectSpec } from "#src/script.ts";
105
+ import { listed, OPTIONS, Reply, reply, runScript, UsageError, type Call, type CommandSpec, type OptionSpec, type SubjectSpec } from "#src/script.ts";
108
106
  import { isoCet } from "#src/time.ts";
109
107
  import { CHECK_CLASSES, CHECK_VERDICTS, checkFolder, checkResult, pickSample, seedOfFolder, withVerdict, type CheckClass, type Sample, type Verdicts } from "./lib/check.ts";
110
- import { listing, listingText, type ListingSource } from "./lib/listing.ts";
108
+ import { listing, listingLines, type ListingSource } from "./lib/listing.ts";
111
109
 
112
110
  function oneOf<T extends string>(values: readonly T[], value: string | undefined, what: string): T {
113
111
  if (value === undefined || !(values as readonly string[]).includes(value)) throw new UsageError(`${what} must be one of: ${values.join(", ")}.`);
@@ -120,8 +118,7 @@ const spaceOf = (row: { space: string }) => (row.space === "c64" ? {} : { space:
120
118
  const symbol = (row: SymbolRow) => ({ ...spaceOf(row), address: formatC64Address(row.address), name: row.name, kind: row.kind, origin: row.origin, revision: row.revision });
121
119
  const region = (row: RegionRow) => ({
122
120
  ...spaceOf(row),
123
- start: formatC64Address(row.start),
124
- end: formatC64Address(row.end),
121
+ ...formatC64RangeFields(row),
125
122
  type: row.type,
126
123
  ...(row.element === undefined ? {} : { element: row.element, count: (row.end - row.start + 1) / row.element }),
127
124
  origin: row.origin,
@@ -142,8 +139,7 @@ const operand = (row: OperandRow) => ({
142
139
  });
143
140
  const patch = (row: PatchRow) => ({
144
141
  ...spaceOf(row),
145
- start: formatC64Address(row.start),
146
- end: formatC64Address(row.end),
142
+ ...formatC64RangeFields(row),
147
143
  bytes: row.end - row.start + 1,
148
144
  switch: row.switch,
149
145
  code: row.code,
@@ -160,7 +156,7 @@ const switchRow = (row: SwitchRow, base?: string, patches?: readonly PatchRow[])
160
156
  base: baseValue(row, base),
161
157
  releases: row.releases,
162
158
  ...(row.comment === undefined ? {} : { comment: row.comment }),
163
- ...(patches === undefined ? {} : { patches: patches.map((patch) => ({ start: formatC64Address(patch.start), end: formatC64Address(patch.end) })) }),
159
+ ...(patches === undefined ? {} : { patches: patches.map((patch) => formatC64RangeFields(patch)) }),
164
160
  origin: row.origin,
165
161
  revision: row.revision,
166
162
  });
@@ -194,8 +190,7 @@ const startScreen = (row: StartScreenRow) => ({
194
190
  const macro = (row: MacroRow) => ({ ...spaceOf(row), name: row.name, params: row.params, body: row.body, ...(row.comment === undefined ? {} : { comment: row.comment }), origin: row.origin, revision: row.revision });
195
191
  const macroUse = (row: MacroUseRow) => ({
196
192
  ...spaceOf(row),
197
- start: formatC64Address(row.start),
198
- end: formatC64Address(row.end),
193
+ ...formatC64RangeFields(row),
199
194
  macro: row.macro,
200
195
  args: row.args,
201
196
  text: `+${row.macro}${row.args.length === 0 ? "" : ` ${row.args.join(", ")}`}`,
@@ -208,7 +203,7 @@ function suppression(row: SuppressionRow) {
208
203
  row.entity === "symbol"
209
204
  ? { address: formatC64Address(row.start) }
210
205
  : row.entity === "region"
211
- ? { start: formatC64Address(row.start), end: formatC64Address(row.end) }
206
+ ? formatC64RangeFields(row)
212
207
  : { from: formatC64Address(row.start), to: formatC64Address(row.to!), kind: row.kind! };
213
208
  return { ...spaceOf(row), suppresses: row.entity, ...place, origin: row.origin, revision: row.revision };
214
209
  }
@@ -220,36 +215,45 @@ function programRow(entry: Extract<HistoryEntry, { entity: "memory" | "entry" |
220
215
  return { ...spaceOf(entry.row), map: entry.row.map, kind: entry.row.kind, ranges: entry.row.ranges, origin: entry.row.origin, revision: entry.row.revision };
221
216
  }
222
217
 
218
+ /** The row of a history entry in its output shape. */
219
+ function historyRow(entry: HistoryEntry) {
220
+ switch (entry.entity) {
221
+ case "memory":
222
+ case "entry":
223
+ case "coverage":
224
+ return programRow(entry);
225
+ case "symbol":
226
+ case "analyzer-name":
227
+ return symbol(entry.row);
228
+ case "region":
229
+ return region(entry.row);
230
+ case "comment":
231
+ return comment(entry.row);
232
+ case "reference":
233
+ return reference(entry.row);
234
+ case "module":
235
+ return module(entry.row);
236
+ case "operand":
237
+ return operand(entry.row);
238
+ case "patch":
239
+ return patch(entry.row);
240
+ case "switch":
241
+ return switchRow(entry.row);
242
+ case "release":
243
+ return release(entry.row);
244
+ case "start-screen":
245
+ return startScreen(entry.row);
246
+ case "macro":
247
+ return macro(entry.row);
248
+ case "macro-use":
249
+ return macroUse(entry.row);
250
+ case "suppression":
251
+ return suppression(entry.row);
252
+ }
253
+ }
254
+
223
255
  function historyEntry(entry: HistoryEntry) {
224
- const shown =
225
- entry.entity === "memory" || entry.entity === "entry" || entry.entity === "coverage"
226
- ? programRow(entry)
227
- : entry.entity === "symbol" || entry.entity === "analyzer-name"
228
- ? symbol(entry.row)
229
- : entry.entity === "region"
230
- ? region(entry.row)
231
- : entry.entity === "comment"
232
- ? comment(entry.row)
233
- : entry.entity === "reference"
234
- ? reference(entry.row)
235
- : entry.entity === "module"
236
- ? module(entry.row)
237
- : entry.entity === "operand"
238
- ? operand(entry.row)
239
- : entry.entity === "patch"
240
- ? patch(entry.row)
241
- : entry.entity === "switch"
242
- ? switchRow(entry.row)
243
- : entry.entity === "release"
244
- ? release(entry.row)
245
- : entry.entity === "start-screen"
246
- ? startScreen(entry.row)
247
- : entry.entity === "macro"
248
- ? macro(entry.row)
249
- : entry.entity === "macro-use"
250
- ? macroUse(entry.row)
251
- : suppression(entry.row);
252
- const { revision: _revision, ...row } = shown;
256
+ const { revision: _revision, ...row } = historyRow(entry);
253
257
  return { entity: entry.entity, ...row, fromRevision: entry.from, ...(entry.to === undefined ? {} : { toRevision: entry.to }) };
254
258
  }
255
259
 
@@ -277,40 +281,75 @@ function reasonsOf(db: DatabaseSync | undefined, rows: SuppressionRow[]): Map<st
277
281
 
278
282
  /** The bytes of a program: the byte at an address inside a segment, else undefined. */
279
283
  function programBytes(image: { segments: ReadonlyArray<{ start: number; end: number }>; byteAt: (address: number) => number }): (address: number) => number | undefined {
280
- return (at) => (image.segments.some((segment) => at >= segment.start && at <= segment.end) ? image.byteAt(at) : undefined);
284
+ return (at) => (inRanges(image.segments, at) ? image.byteAt(at) : undefined);
281
285
  }
282
286
 
283
- /** The name of an address: a user or LLM name, else the platform name; an analyzer name in symbols (knowledge from an older version) gives way to it. */
284
- function nameOf(db: DatabaseSync | undefined, space: string): (at: number) => string | undefined {
285
- const platform = new Map(space === DEFAULT_SPACE ? platformNames().map((entry) => [entry.address, entry.name]) : []);
286
- return (at) => {
287
- const own = symbolAt(db, at, space);
288
- return own !== undefined && isSemantic(own.origin) ? own.name : (platform.get(at) ?? own?.name);
287
+ /** The platform names of the program in a space, as c64-source gives them: only the names of the ROMs that the program uses. None outside the C64. */
288
+ function programPlatform(space: string, coverage: Uint8Array | undefined, state: Record<string, unknown> | undefined): ReturnType<typeof platformNamesFor> {
289
+ return space === DEFAULT_SPACE ? platformNamesFor(romUseOfProgram(coverage, state)) : [];
290
+ }
291
+
292
+ /**
293
+ * The names of addresses: the symbol of the user or the LLM, and the platform name of `platform`.
294
+ * A user or LLM name comes first; an analyzer name in symbols (knowledge from an older version) gives way to a platform name.
295
+ */
296
+ function namesOf(db: DatabaseSync | undefined, space: string, platform: ReturnType<typeof platformNamesFor>): Required<Pick<ListingSource, "symbolOf" | "platformOf">> {
297
+ const names = new Map(platform.map((entry) => [entry.address, entry.name]));
298
+ const symbols = new Map<number, SymbolRow>();
299
+ for (const row of listSymbols(db, undefined, undefined, undefined, space)) if (!symbols.has(row.address)) symbols.set(row.address, row);
300
+ return {
301
+ symbolOf: (at) => {
302
+ const own = symbols.get(at);
303
+ return own === undefined || (!isSemantic(own.origin) && names.has(at)) ? undefined : own.name;
304
+ },
305
+ platformOf: (at) => names.get(at),
289
306
  };
290
307
  }
291
308
 
292
- /** The lookups of a listing: the program and the coverage in the knowledge, the knowledge of the space and the platform names of the C64. */
293
- function listingSource(db: DatabaseSync | undefined, space: string): ListingSource {
294
- const image = requireProgram(db, space);
309
+ /** The rows of each address, in the order of the list. */
310
+ function byAddress<T extends { address: number }>(rows: readonly T[]): Map<number, T[]> {
311
+ const grouped = new Map<number, T[]>();
312
+ for (const row of rows) (grouped.get(row.address) ?? grouped.set(row.address, []).get(row.address)!).push(row);
313
+ return grouped;
314
+ }
315
+
316
+ /**
317
+ * The lookups of a listing of a range: the program and the coverage in the knowledge, the knowledge of the space and the platform names of the ROMs that the program uses.
318
+ * The rows of the range are read once: a listing asks for each line.
319
+ */
320
+ function listingSource(db: DatabaseSync | undefined, image: ProgramImage, range: AddressRange): ListingSource {
321
+ const space = image.space;
295
322
  const coverage = programCoverage(db, space)?.map;
296
323
  const byteAt = programBytes(image);
297
- const entries = space === DEFAULT_SPACE ? platformNames().filter((entry) => entry.end > entry.address) : [];
324
+ const platform = programPlatform(space, coverage, image.state);
325
+ const entries = platform.filter((entry) => entry.end > entry.address);
326
+ const secondNames = byAddress(listAnalyzerNames(db, range, undefined, undefined, space));
327
+ // The comments inside an instruction or a word of the last line are up to 2 bytes after the range.
328
+ const comments = byAddress(listComments(db, { start: range.start, end: Math.min(range.end + 2, 0xffff) }, undefined, space));
329
+ const operands = byAddress(listOperands(db, range, undefined, space));
330
+ const referencesIn = new Map<number, number>();
331
+ const referencesOut = new Map<number, number>();
332
+ for (const row of listReferences(db, range, undefined, undefined, space)) {
333
+ if (inRanges([range], row.to)) referencesIn.set(row.to, (referencesIn.get(row.to) ?? 0) + 1);
334
+ if (inRanges([range], row.from)) referencesOut.set(row.from, (referencesOut.get(row.from) ?? 0) + 1);
335
+ }
298
336
  return {
299
337
  byteAt,
300
338
  entryStart: (at) => (byteAt(at) !== undefined ? undefined : entries.find((entry) => at > entry.address && at <= entry.end)?.address),
301
- nameOf: nameOf(db, space),
302
- secondNames: (at) => analyzerNamesAt(db, at, space).map((row) => row.name),
339
+ ...namesOf(db, space, platform),
340
+ ...(space === DEFAULT_SPACE ? { io: IO_RAM } : {}),
341
+ secondNames: (at) => (secondNames.get(at) ?? []).map((row) => row.name),
303
342
  regions: listRegions(db, undefined, undefined, undefined, space),
304
343
  comments: (at) => {
305
- const rows = commentsAt(db, at, space);
344
+ const rows = comments.get(at) ?? [];
306
345
  const side = rows.find((row) => row.placement === "side")?.text;
307
346
  return { line: rows.filter((row) => row.placement === "line").flatMap((row) => row.text.split(/\r?\n/)), ...(side === undefined ? {} : { side }) };
308
347
  },
309
348
  operand: (at) => {
310
- const row = operandAt(db, at, space);
349
+ const row = operands.get(at)?.[0];
311
350
  return row === undefined ? undefined : operandText(row);
312
351
  },
313
- references: (at) => ({ in: referencesTo(db, at, space).length, out: referencesFrom(db, at, space).length }),
352
+ references: (at) => ({ in: referencesIn.get(at) ?? 0, out: referencesOut.get(at) ?? 0 }),
314
353
  ...(coverage === undefined ? {} : { coverage }),
315
354
  };
316
355
  }
@@ -352,22 +391,17 @@ function evidenceOf(value: string, space: string): Evidence {
352
391
  const ref = knowledgePath(given, `--evidence ${kind}:<file>`);
353
392
  // A coverage map is evidence by the name that coverage imported it with: the latest import into the space of the write.
354
393
  if (kind === "coverage") {
355
- const db = openForRead();
356
- try {
357
- const run = coverageRuns(db).filter((item) => item.name === ref && item.space === space).at(-1);
358
- const where = space === DEFAULT_SPACE ? "" : ` in ${space}`;
359
- if (run === undefined) throw new UsageError(`--evidence coverage:${given} names no coverage map of the knowledge${where}. Import the map with coverage${space === DEFAULT_SPACE ? "" : ` --space ${space}`} first.`);
360
- return { kind, ref, sha256: run.sha256, ...(run.space === DEFAULT_SPACE ? {} : { space: run.space }) };
361
- } finally {
362
- db?.close();
363
- }
394
+ const run = withRead((db) => coverageRuns(db).filter((item) => item.name === ref && item.space === space).at(-1));
395
+ const where = space === DEFAULT_SPACE ? "" : ` in ${space}`;
396
+ if (run === undefined) throw new UsageError(`--evidence coverage:${given} names no coverage map of the knowledge${where}. Import the map with coverage${space === DEFAULT_SPACE ? "" : ` --space ${space}`} first.`);
397
+ return { kind, ref, sha256: run.sha256, ...(run.space === DEFAULT_SPACE ? {} : { space: run.space }) };
364
398
  }
365
399
  const bytes = readProjectFile(ref).bytes;
366
400
  const root = projectRoot();
367
401
  if (isInside(join(root, PROJECT_DIRECTORY, LOCAL_DIRECTORY), resolveProjectPath(ref, root))) {
368
402
  throw new UsageError(`--evidence ${kind}:${ref} is in ${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/, which git ignores. Move it to a folder that git keeps, for example a run folder to runs/<name>/. Then give the new path.`);
369
403
  }
370
- return { kind, ref, sha256: createHash("sha256").update(bytes).digest("hex") };
404
+ return { kind, ref, sha256: sha256(bytes) };
371
405
  }
372
406
 
373
407
  /** An image.json of a capture or a PRG as a write of the program, with the entry state of the capture. */
@@ -382,7 +416,7 @@ function imageRequest(path: string, space: string): ImageRequest {
382
416
 
383
417
  /** The programs that operand, patch and macro use writes are checked against, with the platform names. */
384
418
  function operandImages(db: DatabaseSync): (space: string) => OperandImage {
385
- return programImages(db, new Map(platformNames().map((entry) => [entry.name, entry.address])));
419
+ return programImages(db, platformAddresses());
386
420
  }
387
421
 
388
422
  /** An offset: a whole number in decimal or $ hex, with an optional minus sign. */
@@ -494,12 +528,7 @@ const originsOf = (call: Call) => {
494
528
  function checkFile<T>(seed: number, file: "sample.json" | "verdicts.json"): T | undefined {
495
529
  const path = `${checkFolder(seed)}/${file}`;
496
530
  if (!existsSync(resolveProjectPath(path))) return undefined;
497
- try {
498
- return JSON.parse(readProjectFile(path).bytes.toString("utf8")) as T;
499
- } catch (error) {
500
- if (error instanceof SyntaxError) throw new Refusal("invalid-input", `${path} is not JSON. Start a check with another seed.`);
501
- throw error;
502
- }
531
+ return readProjectJson(path, () => `${path} is not JSON. Start a check with another seed.`) as T;
503
532
  }
504
533
 
505
534
  /** The sample of the check of a seed; refuses a seed without a check. */
@@ -512,39 +541,47 @@ function sampleOf(seed: number): Sample {
512
541
  const SEED: SubjectSpec = { name: "<seed>", help: "the seed of a check" };
513
542
  const seedOf = (call: Call) => call.parseCount(call.subject(0), "<seed>", 0, 999_999);
514
543
 
515
- /** A read command: it opens the knowledge for reading, and its answer shows the conflicts that a git merge left. */
516
- function readCommand(spec: Omit<CommandSpec, "run">, answer: (db: DatabaseSync | undefined, call: Call) => Record<string, unknown>): CommandSpec {
544
+ /** A read command: it opens the knowledge for reading, and its answer shows the conflicts that a git merge left. A hint of the answer comes first. */
545
+ function readCommand(spec: Omit<CommandSpec, "run">, answer: (db: DatabaseSync | undefined, call: Call) => Record<string, unknown> | Reply): CommandSpec {
517
546
  return {
518
547
  ...spec,
519
548
  options: { ...SPACE, ...spec.options },
520
- run: (call) => {
521
- const db = openForRead();
522
- try {
549
+ run: (call) =>
550
+ withRead((db) => {
523
551
  const result = answer(db, call);
524
552
  const found = conflicts(db);
525
553
  if (found.length === 0) return result;
554
+ const { body, hint } = result instanceof Reply ? { body: result.body as Record<string, unknown>, hint: result.hint } : { body: result, hint: undefined };
526
555
  return reply(
527
- { ...result, conflicts: found.map(showConflict) },
528
- { hint: "A git merge left conflicts in the knowledge: see conflicts. Each write stops until you decide them. Run merge, then tell the user each item of its choices.", nextAction: call.next("merge", "--reason", "decide the conflicts of a git merge") },
556
+ { ...body, conflicts: found.map(showConflict) },
557
+ {
558
+ hint: `${hint === undefined ? "" : `${hint} `}A git merge left conflicts in the knowledge: see conflicts. Each write stops until you decide them. Run merge, then tell the user each item of its choices.`,
559
+ nextAction: call.next("merge", "--reason", "decide the conflicts of a git merge"),
560
+ },
529
561
  );
530
- } finally {
531
- db?.close();
532
- }
533
- },
562
+ }),
534
563
  };
535
564
  }
536
565
 
537
- /** A write command: every value is checked before the knowledge opens, so a refused write makes no knowledge folder. */
538
- function writeCommand(spec: Omit<CommandSpec, "run">, prepare: (call: Call) => WriteOperation): CommandSpec {
566
+ /** A write command: every value is checked before the knowledge opens, so a refused write makes no knowledge folder. The write context comes first. */
567
+ function writeCommand(spec: Omit<CommandSpec, "run">, prepare: (call: Call, context: WriteContext) => WriteOperation): CommandSpec {
539
568
  return {
540
569
  ...spec,
541
570
  notes: [spec.notes, "A write is one revision. It makes .c64-re-tools/knowledge/ when it is not there."].filter((note) => note !== undefined).join("\n"),
542
571
  // A command can give a WRITE option its own help or default, for example --space of revert.
543
572
  options: Object.fromEntries(Object.entries({ ...spec.options, ...WRITE }).map(([name, option]) => [name, spec.options?.[name] ?? option])),
544
- run: (call) => withWrite(prepare(call)),
573
+ run: (call) => withWrite(prepare(call, contextOf(call))),
545
574
  };
546
575
  }
547
576
 
577
+ /** A write command that removes a row and reports the revision. */
578
+ function removeCommand<R>(spec: Omit<CommandSpec, "run">, request: (call: Call) => R, remove: (db: DatabaseSync, context: WriteContext, request: R) => { revision: string | null }): CommandSpec {
579
+ return writeCommand(spec, (call, context) => {
580
+ const given = request(call);
581
+ return (db) => ({ revision: remove(db, context, given).revision });
582
+ });
583
+ }
584
+
548
585
  /** The write context of --by, --reason, --expect-revision and --evidence. */
549
586
  function contextOf(call: Call): WriteContext {
550
587
  const context: WriteContext = { origin: call.string("by") as WriteContext["origin"] };
@@ -679,7 +716,8 @@ const READ_COMMANDS: CommandSpec[] = [
679
716
  if (direction !== undefined && range === undefined) throw new UsageError(`--direction needs --range: the direction is seen from that range. Give --range <start>-<end> --direction ${direction}.`);
680
717
  const rows = listReferences(db, rangeOf(call), call.string("kind") as (typeof REFERENCE_KINDS)[number] | undefined, originsOf(call), call.space).filter(direction === undefined ? () => true : goes(range!, direction));
681
718
  const { byKind, byTarget } = referenceCounts(rows);
682
- const named = nameOf(db, call.space);
719
+ const { symbolOf, platformOf } = namesOf(db, call.space, programPlatform(call.space, programCoverage(db, call.space)?.map, programImage(db, call.space)?.state));
720
+ const named = (at: number) => symbolOf(at) ?? platformOf(at);
683
721
  const target = ({ to, count }: { to: number; count: number }) => ((name) => ({ to: formatC64Address(to), ...(name === undefined ? {} : { name }), count }))(named(to));
684
722
  return { references: list(call, rows, reference, RANGE_REST), byKind, byTarget: list(call, byTarget, target, MORE) };
685
723
  },
@@ -695,7 +733,7 @@ const READ_COMMANDS: CommandSpec[] = [
695
733
  patches: list(call, listPatches(db, rangeOf(call), call.string("switch"), originsOf(call), call.space), patch, RANGE_REST),
696
734
  })),
697
735
  readCommand({ name: "switches", summary: "Each switch: its kind, its default, its value in the program (base), the releases that have it on and the ranges of its patches.", options: LIST }, (db, call) => {
698
- const base = listReleases(db, undefined, call.space).find((row) => row.base)?.label;
736
+ const base = baseLabel(db, call.space);
699
737
  const patches = listPatches(db, undefined, undefined, undefined, call.space);
700
738
  const show = (row: SwitchRow) => switchRow(row, base, patches.filter((patch) => patch.switch === row.name));
701
739
  return { switches: list(call, listSwitches(db, undefined, call.space), show, MORE) };
@@ -716,7 +754,7 @@ const READ_COMMANDS: CommandSpec[] = [
716
754
  image === undefined
717
755
  ? null
718
756
  : {
719
- segments: image.segments.map((segment) => ({ start: formatC64Address(segment.start), end: formatC64Address(segment.end) })),
757
+ segments: image.segments.map((segment) => formatC64RangeFields(segment)),
720
758
  bytes: image.segments.reduce((sum, segment) => sum + segment.end - segment.start + 1, 0),
721
759
  ...(image.entry === undefined ? {} : { entry: formatC64Address(image.entry) }),
722
760
  state: image.state !== undefined,
@@ -774,6 +812,7 @@ const READ_COMMANDS: CommandSpec[] = [
774
812
  const range = rangeOf(call);
775
813
  const origins = originsOf(call);
776
814
  const space = call.space;
815
+ const base = baseLabel(db, space);
777
816
  const exported = {
778
817
  revision: currentRevision(db),
779
818
  ...(space === DEFAULT_SPACE ? {} : { space }),
@@ -786,7 +825,7 @@ const READ_COMMANDS: CommandSpec[] = [
786
825
  modules: listModules(db, range, origins, space).map(module),
787
826
  operands: listOperands(db, range, origins, space).map(operand),
788
827
  patches: listPatches(db, range, undefined, origins, space).map(patch),
789
- switches: listSwitches(db, origins, space).map((row) => switchRow(row, listReleases(db, undefined, space).find((item) => item.base)?.label)),
828
+ switches: listSwitches(db, origins, space).map((row) => switchRow(row, base)),
790
829
  releases: listReleases(db, origins, space).map(release),
791
830
  macros: listMacros(db, origins, space).map(macro),
792
831
  macroUses: listMacroUses(db, range, undefined, origins, space).map(macroUse),
@@ -798,35 +837,33 @@ const READ_COMMANDS: CommandSpec[] = [
798
837
  readCommand(
799
838
  {
800
839
  name: "listing",
801
- summary: "The program as ACME lines with names, operand expressions, comments, the access of each line in the coverage (x executed, r read, w written) and the references in and out.",
840
+ summary: "The program as text lines: the address, the bytes, the access in the coverage (x executed, r read, w written), the ACME line with names and operand expressions, the comment, and the references in and out.",
802
841
  subjects: [RANGE],
803
842
  options: {
804
843
  code: { kind: "flag", help: "only the instructions of the code regions: no data lines" },
805
- out: { ...OPTIONS.out, output: "file", value: "<file>", help: "write the listing as text to this file in place of the lines in the result" },
844
+ out: { ...OPTIONS.out, output: "file", value: "<file>", help: "write the lines to this text file, one on each line, in place of the lines in the result" },
806
845
  ...LIST,
807
846
  },
808
847
  },
809
848
  (db, call) => {
810
- const { start, end } = call.parseRange(call.subject(0), "<range>");
811
- const lines = listing(listingSource(db, call.space), start, end, { code: call.flag("code") });
849
+ const range = call.parseRange(call.subject(0), "<range>");
850
+ const image = requireProgram(db, call.space);
851
+ const lines = listingLines(listing(listingSource(db, image, range), range.start, range.end, { code: call.flag("code") }));
812
852
  const out = call.string("out");
813
- if (out !== undefined) return { lines: lines.length, ...writeReported(out, listingText(lines), { what: "--out" }) };
814
- return { lines: list(call, lines, (row) => ({ ...row, address: formatC64Address(row.address) }), "a larger --max-listed, a smaller <range>, or --out <file> for all lines") };
853
+ const body = out !== undefined ? { lines: lines.length, ...writeReported(out, lines.map((line) => `${line}\n`).join(""), { what: "--out" }) } : { lines: list(call, lines, (line) => line, "a larger --max-listed, a smaller <range>, or --out <file> for all lines") };
854
+ // A range outside the program has no lines: the hint names the segments that have them.
855
+ if (image.segments.some((segment) => rangesOverlap(segment, range))) return body;
856
+ return reply(body, { hint: `The range ${formatC64Range(range)} is outside the program. The program has bytes only in ${image.segments.map(formatC64Range).join(", ")}. Give a range in one of them.` });
815
857
  },
816
858
  ),
817
859
  ];
818
860
 
819
861
  const WRITE_COMMANDS: CommandSpec[] = [
820
- writeCommand({ name: "rename", summary: "Gives an address a name.", subjects: [ADDRESS, { name: "<name>", help: "the new name: assembler label syntax" }], options: { kind: SYMBOL_KIND } }, (call) => {
821
- const context = contextOf(call);
862
+ writeCommand({ name: "rename", summary: "Gives an address a name.", subjects: [ADDRESS, { name: "<name>", help: "the new name: assembler label syntax" }], options: { kind: SYMBOL_KIND } }, (call, context) => {
822
863
  const request = { space: call.space, address: call.parseAddress(call.subject(0), "<address>"), name: call.subject(1), ...(call.string("kind") === undefined ? {} : { kind: call.string("kind") as (typeof SYMBOL_KINDS)[number] }) };
823
864
  return (db) => shown(renameSymbol(db, context, request), "symbol", symbol);
824
865
  }),
825
- writeCommand({ name: "remove-symbol", summary: "Removes the name at an address.", subjects: [ADDRESS] }, (call) => {
826
- const context = contextOf(call);
827
- const request = { space: call.space, address: call.parseAddress(call.subject(0), "<address>") };
828
- return (db) => ({ revision: removeSymbol(db, context, request).revision });
829
- }),
866
+ removeCommand({ name: "remove-symbol", summary: "Removes the name at an address.", subjects: [ADDRESS] }, (call) => ({ space: call.space, address: call.parseAddress(call.subject(0), "<address>") }), removeSymbol),
830
867
  writeCommand(
831
868
  {
832
869
  name: "classify",
@@ -834,38 +871,29 @@ const WRITE_COMMANDS: CommandSpec[] = [
834
871
  subjects: [RANGE, { name: "<type>", help: `one of ${REGION_TYPES.join(", ")}` }],
835
872
  options: { element: { kind: "count", value: "<n>", min: 1, max: 0x10000, help: "the bytes of one element of a table: the length of the range is a multiple of it" } },
836
873
  },
837
- (call) => {
838
- const context = contextOf(call);
874
+ (call, context) => {
839
875
  const element = call.count("element");
840
876
  const request = { space: call.space, ...call.parseRange(call.subject(0), "<range>"), type: oneOf(REGION_TYPES, call.subject(1), "<type>"), ...(element === undefined ? {} : { element }) };
841
- return (db) => {
842
- const result = classifyRegion(db, context, request);
843
- return { revision: result.revision, regions: result.current.map(region), ...(result.previous === undefined ? {} : { previous: result.previous.map(region) }) };
844
- };
877
+ return (db) => shown(classifyRegion(db, context, request), "regions", (rows) => rows.map(region));
845
878
  },
846
879
  ),
847
- writeCommand({ name: "unclassify", summary: "Removes the region types of a range.", subjects: [RANGE] }, (call) => {
848
- const context = contextOf(call);
849
- const request = { space: call.space, ...call.parseRange(call.subject(0), "<range>") };
850
- return (db) => ({ revision: unclassifyRegion(db, context, request).revision });
851
- }),
880
+ removeCommand({ name: "unclassify", summary: "Removes the region types of a range.", subjects: [RANGE] }, (call) => ({ space: call.space, ...call.parseRange(call.subject(0), "<range>") }), unclassifyRegion),
852
881
  writeCommand(
853
882
  {
854
883
  name: "comment",
855
884
  summary: "Writes a comment at an address: a line of its own above it, or at the end of its line.",
856
885
  subjects: [ADDRESS, { name: "<placement>", help: `one of ${COMMENT_PLACEMENTS.join(", ")}` }, { name: "<text>", help: "the comment", list: true }],
857
886
  },
858
- (call) => {
859
- const context = contextOf(call);
887
+ (call, context) => {
860
888
  const request = { space: call.space, address: call.parseAddress(call.subject(0), "<address>"), placement: oneOf(COMMENT_PLACEMENTS, call.subject(1), "<placement>"), text: call.rest(2).join(" ") };
861
889
  return (db) => shown(setComment(db, context, request), "comment", comment);
862
890
  },
863
891
  ),
864
- writeCommand({ name: "uncomment", summary: "Removes a comment.", subjects: [ADDRESS, { name: "<placement>", help: `one of ${COMMENT_PLACEMENTS.join(", ")}` }] }, (call) => {
865
- const context = contextOf(call);
866
- const request = { space: call.space, address: call.parseAddress(call.subject(0), "<address>"), placement: oneOf(COMMENT_PLACEMENTS, call.subject(1), "<placement>") };
867
- return (db) => ({ revision: removeComment(db, context, request).revision });
868
- }),
892
+ removeCommand(
893
+ { name: "uncomment", summary: "Removes a comment.", subjects: [ADDRESS, { name: "<placement>", help: `one of ${COMMENT_PLACEMENTS.join(", ")}` }] },
894
+ (call) => ({ space: call.space, address: call.parseAddress(call.subject(0), "<address>"), placement: oneOf(COMMENT_PLACEMENTS, call.subject(1), "<placement>") }),
895
+ removeComment,
896
+ ),
869
897
  ...(["reference", "unreference"] as const).map((name) =>
870
898
  writeCommand(
871
899
  {
@@ -873,8 +901,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
873
901
  summary: name === "reference" ? "Records that code at one address refers to another." : "Removes a reference.",
874
902
  subjects: [{ name: "<from>", help: "the address of the instruction" }, { name: "<to>", help: "the address it refers to" }, { name: "<kind>", help: `one of ${REFERENCE_KINDS.join(", ")}` }],
875
903
  },
876
- (call) => {
877
- const context = contextOf(call);
904
+ (call, context) => {
878
905
  const request = { space: call.space, from: call.parseAddress(call.subject(0), "<from>"), to: call.parseAddress(call.subject(1), "<to>"), kind: oneOf(REFERENCE_KINDS, call.subject(2), "<kind>") };
879
906
  return name === "reference"
880
907
  ? (db) => shown(addReference(db, context, request), "reference", reference)
@@ -884,18 +911,13 @@ const WRITE_COMMANDS: CommandSpec[] = [
884
911
  ),
885
912
  writeCommand(
886
913
  { name: "module", summary: "Records that a file of the generated source starts at an address.", subjects: [START, { name: "<file.asm>", help: "the source file" }], options: { title: { kind: "text", value: "<text>", help: "the title of the file" } } },
887
- (call) => {
888
- const context = contextOf(call);
914
+ (call, context) => {
889
915
  const title = call.string("title");
890
916
  const request = { space: call.space, start: call.parseAddress(call.subject(0), "<start>"), file: call.subject(1), ...(title === undefined ? {} : { title }) };
891
917
  return (db) => shown(setModule(db, context, request), "module", module);
892
918
  },
893
919
  ),
894
- writeCommand({ name: "unmodule", summary: "Removes the module that starts at an address.", subjects: [START] }, (call) => {
895
- const context = contextOf(call);
896
- const request = { space: call.space, start: call.parseAddress(call.subject(0), "<start>") };
897
- return (db) => ({ revision: removeModule(db, context, request).revision });
898
- }),
920
+ removeCommand({ name: "unmodule", summary: "Removes the module that starts at an address.", subjects: [START] }, (call) => ({ space: call.space, start: call.parseAddress(call.subject(0), "<start>") }), removeModule),
899
921
  writeCommand(
900
922
  {
901
923
  name: "operand",
@@ -910,8 +932,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
910
932
  },
911
933
  notes: "Give exactly one of --lo, --hi, --value and --expr. The write is refused when the expression does not give the operand in the program of the knowledge.",
912
934
  },
913
- (call) => {
914
- const context = contextOf(call);
935
+ (call, context) => {
915
936
  const given = (["lo", "hi", "value", "expr"] as const).filter((option) => call.string(option) !== undefined);
916
937
  if (given.length !== 1) throw new UsageError("operand needs exactly one of --lo, --hi, --value or --expr.");
917
938
  const select: OperandSelect = given[0]!;
@@ -927,11 +948,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
927
948
  return (db) => shown(setOperand(db, { ...context, image: operandImages(db) }, request), "operand", operand);
928
949
  },
929
950
  ),
930
- writeCommand({ name: "unoperand", summary: "Removes the operand expression at an address.", subjects: [ADDRESS] }, (call) => {
931
- const context = contextOf(call);
932
- const request = { space: call.space, address: call.parseAddress(call.subject(0), "<address>") };
933
- return (db) => ({ revision: removeOperand(db, context, request).revision });
934
- }),
951
+ removeCommand({ name: "unoperand", summary: "Removes the operand expression at an address.", subjects: [ADDRESS] }, (call) => ({ space: call.space, address: call.parseAddress(call.subject(0), "<address>") }), removeOperand),
935
952
  writeCommand(
936
953
  {
937
954
  name: "patch",
@@ -946,8 +963,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
946
963
  },
947
964
  notes: "Give exactly one of --code, --code-file, --nop and --from-release. Write the switch first (switch). The program holds the bytes of the base release: when the base release has the switch on, the code is the bytes with the switch off. Another switch can have a patch at the same range, as an alternative.",
948
965
  },
949
- (call) => {
950
- const context = contextOf(call);
966
+ (call, context) => {
951
967
  const code = textOrFile(call, "code");
952
968
  const from = call.string("from-release");
953
969
  if ([code !== undefined, call.flag("nop"), from !== undefined].filter(Boolean).length !== 1) throw new UsageError("patch needs exactly one of --code, --code-file, --nop or --from-release.");
@@ -960,7 +976,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
960
976
  };
961
977
  },
962
978
  ),
963
- writeCommand(
979
+ removeCommand(
964
980
  {
965
981
  name: "unpatch",
966
982
  summary: "Removes the patch that starts at an address.",
@@ -968,11 +984,10 @@ const WRITE_COMMANDS: CommandSpec[] = [
968
984
  options: { switch: { kind: "text", value: "<switch>", help: "the switch of the patch, when patches of more than one switch start there" } },
969
985
  },
970
986
  (call) => {
971
- const context = contextOf(call);
972
987
  const switchName = call.string("switch");
973
- const request = { space: call.space, start: call.parseAddress(call.subject(0), "<start>"), ...(switchName === undefined ? {} : { switch: switchName }) };
974
- return (db) => ({ revision: removePatch(db, context, request).revision });
988
+ return { space: call.space, start: call.parseAddress(call.subject(0), "<start>"), ...(switchName === undefined ? {} : { switch: switchName }) };
975
989
  },
990
+ removePatch,
976
991
  ),
977
992
  writeCommand(
978
993
  {
@@ -987,8 +1002,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
987
1002
  },
988
1003
  notes: "Record the base release first (release --base). A write keeps the releases and the comment that it does not give.",
989
1004
  },
990
- (call) => {
991
- const context = contextOf(call);
1005
+ (call, context) => {
992
1006
  const given = call.string("default");
993
1007
  const releases = call.string("releases");
994
1008
  const commentText = call.string("comment");
@@ -1002,16 +1016,12 @@ const WRITE_COMMANDS: CommandSpec[] = [
1002
1016
  };
1003
1017
  return (db) => {
1004
1018
  const result = setSwitch(db, { ...context, image: operandImages(db) }, request);
1005
- const base = listReleases(db, undefined, call.space).find((row) => row.base)?.label;
1019
+ const base = baseLabel(db, call.space);
1006
1020
  return shown(result, "switch", (row: SwitchRow) => switchRow(row, base));
1007
1021
  };
1008
1022
  },
1009
1023
  ),
1010
- writeCommand({ name: "unswitch", summary: "Removes a switch that has no patch.", subjects: [{ name: "<name>", help: "the switch name" }] }, (call) => {
1011
- const context = contextOf(call);
1012
- const request = { space: call.space, name: call.subject(0) };
1013
- return (db) => ({ revision: removeSwitch(db, context, request).revision });
1014
- }),
1024
+ removeCommand({ name: "unswitch", summary: "Removes a switch that has no patch.", subjects: [{ name: "<name>", help: "the switch name" }] }, (call) => ({ space: call.space, name: call.subject(0) }), removeSwitch),
1015
1025
  writeCommand(
1016
1026
  {
1017
1027
  name: "release",
@@ -1024,15 +1034,20 @@ const WRITE_COMMANDS: CommandSpec[] = [
1024
1034
  },
1025
1035
  notes: "The build of a release defines RELEASE_<label>=1: each switch then has the value of that release. The check of the generated source builds each release and compares it with the bytes of the release in the knowledge.",
1026
1036
  },
1027
- (call) => {
1028
- const context = contextOf(call);
1037
+ (call, context) => {
1029
1038
  const file = knowledgePath(call.string("file")!, "--file");
1030
1039
  const image = readImage(file);
1031
- const sha256 = createHash("sha256").update(readProjectFile(file).bytes).digest("hex");
1032
1040
  const commentText = call.string("comment");
1033
1041
  const base = call.flag("base");
1034
1042
  // The base release has no bytes of its own: its bytes are the program.
1035
- const request = { space: call.space, label: call.subject(0), file, sha256, ...(base ? { base } : { rows: memoryRows(image.segments, image.byteAt) }), ...(commentText === undefined ? {} : { comment: commentText }) };
1043
+ const request = {
1044
+ space: call.space,
1045
+ label: call.subject(0),
1046
+ file,
1047
+ sha256: sha256(readProjectFile(file).bytes),
1048
+ ...(base ? { base } : { rows: memoryRows(image.segments, image.byteAt) }),
1049
+ ...(commentText === undefined ? {} : { comment: commentText }),
1050
+ };
1036
1051
  return (db) => {
1037
1052
  if (base) {
1038
1053
  const program = requireProgram(db, call.space);
@@ -1047,11 +1062,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
1047
1062
  };
1048
1063
  },
1049
1064
  ),
1050
- writeCommand({ name: "unrelease", summary: "Removes a release that no switch names.", subjects: [{ name: "<label>", help: "the release label" }] }, (call) => {
1051
- const context = contextOf(call);
1052
- const request = { space: call.space, label: call.subject(0) };
1053
- return (db) => ({ revision: removeRelease(db, context, request).revision });
1054
- }),
1065
+ removeCommand({ name: "unrelease", summary: "Removes a release that no switch names.", subjects: [{ name: "<label>", help: "the release label" }] }, (call) => ({ space: call.space, label: call.subject(0) }), removeRelease),
1055
1066
  writeCommand(
1056
1067
  {
1057
1068
  name: "start-screen",
@@ -1076,8 +1087,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
1076
1087
  },
1077
1088
  notes: "Record only a screen of the program itself, never a screen of a crack. If a release changed the screen, for example with the text of a crack, stop and ask the user how to deal with it. text and multicolour need --colours or --colour; hires uses neither. With --stage, the script takes the screen from the capture of the stage: give only --stage, and --call for a tune. With --capture, the script takes the screen in the program from a capture of the program while it shows the screen. A flag that you give too replaces the value of the capture. A write replaces the start screen of the knowledge.",
1078
1089
  },
1079
- (call) => {
1080
- const context = contextOf(call);
1090
+ (call, context) => {
1081
1091
  const commentText = call.string("comment");
1082
1092
  // The values that the call gives. With --stage, the capture of the stage gives the others.
1083
1093
  const given: { mode?: StartScreenMode; screen?: number; bitmap?: number; charset?: number; colours?: number; colour?: number; border?: number; background?: number } = {};
@@ -1134,11 +1144,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
1134
1144
  };
1135
1145
  },
1136
1146
  ),
1137
- writeCommand({ name: "unstart-screen", summary: "Removes the start screen. The loader of the generated source then starts the program at once." }, (call) => {
1138
- const context = contextOf(call);
1139
- const request = { space: call.space };
1140
- return (db) => ({ revision: removeStartScreen(db, context, request).revision });
1141
- }),
1147
+ removeCommand({ name: "unstart-screen", summary: "Removes the start screen. The loader of the generated source then starts the program at once." }, (call) => ({ space: call.space }), removeStartScreen),
1142
1148
  writeCommand(
1143
1149
  {
1144
1150
  name: "macro",
@@ -1152,8 +1158,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
1152
1158
  },
1153
1159
  notes: "Give --body or --body-file.",
1154
1160
  },
1155
- (call) => {
1156
- const context = contextOf(call);
1161
+ (call, context) => {
1157
1162
  const body = textOrFile(call, "body");
1158
1163
  if (body === undefined || body === "") throw new UsageError("macro needs --body or --body-file with text.");
1159
1164
  const commentText = call.string("comment");
@@ -1161,11 +1166,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
1161
1166
  return (db) => shown(setMacro(db, context, request), "macro", macro);
1162
1167
  },
1163
1168
  ),
1164
- writeCommand({ name: "unmacro", summary: "Removes a macro that no use has.", subjects: [{ name: "<name>", help: "the macro name" }] }, (call) => {
1165
- const context = contextOf(call);
1166
- const request = { space: call.space, name: call.subject(0) };
1167
- return (db) => ({ revision: removeMacro(db, context, request).revision });
1168
- }),
1169
+ removeCommand({ name: "unmacro", summary: "Removes a macro that no use has.", subjects: [{ name: "<name>", help: "the macro name" }] }, (call) => ({ space: call.space, name: call.subject(0) }), removeMacro),
1169
1170
  writeCommand(
1170
1171
  {
1171
1172
  name: "use",
@@ -1173,28 +1174,19 @@ const WRITE_COMMANDS: CommandSpec[] = [
1173
1174
  subjects: [RANGE, { name: "<macro>", help: "the macro name" }],
1174
1175
  options: { args: { kind: "text", value: "<x, y>", help: "one expression for each param, a comma list" } },
1175
1176
  },
1176
- (call) => {
1177
- const context = contextOf(call);
1177
+ (call, context) => {
1178
1178
  const request = { space: call.space, ...call.parseRange(call.subject(0), "<range>"), macro: call.subject(1), args: commaList(call.string("args") ?? "") };
1179
- return (db) => {
1180
- const result = setMacroUse(db, { ...context, image: operandImages(db) }, request);
1181
- return { revision: result.revision, use: macroUse(result.current), ...(result.previous === undefined ? {} : { previous: macroUse(result.previous) }) };
1182
- };
1179
+ return (db) => shown(setMacroUse(db, { ...context, image: operandImages(db) }, request), "use", macroUse);
1183
1180
  },
1184
1181
  ),
1185
- writeCommand({ name: "unuse", summary: "Removes the macro use that starts at an address.", subjects: [START] }, (call) => {
1186
- const context = contextOf(call);
1187
- const request = { space: call.space, start: call.parseAddress(call.subject(0), "<start>") };
1188
- return (db) => ({ revision: removeMacroUse(db, context, request).revision });
1189
- }),
1182
+ removeCommand({ name: "unuse", summary: "Removes the macro use that starts at an address.", subjects: [START] }, (call) => ({ space: call.space, start: call.parseAddress(call.subject(0), "<start>") }), removeMacroUse),
1190
1183
  writeCommand(
1191
1184
  {
1192
1185
  name: "image",
1193
1186
  summary: "Puts the program into the knowledge: its bytes, and for the image.json of a capture also the entry, the entry state and the stages. Only changed bytes write.",
1194
1187
  subjects: [{ name: "<file>", help: "the image.json of a capture or of loads, or a PRG" }],
1195
1188
  },
1196
- (call) => {
1197
- const context = contextOf(call);
1189
+ (call, context) => {
1198
1190
  const request = imageRequest(call.subject(0), call.space);
1199
1191
  return (db) => {
1200
1192
  const { revision, current } = setImage(db, context, request);
@@ -1208,8 +1200,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
1208
1200
  summary: "Puts coverage maps of the emulator, of a run or of a recording folder into the coverage of the knowledge. Each map is named by its path: a new map of a path replaces the earlier map of that path, and --evidence coverage:<path> cites it.",
1209
1201
  subjects: [{ name: "<map>", help: "a 64 KiB coverage map, or a recording folder: then its coverage map", list: true }],
1210
1202
  },
1211
- (call) => {
1212
- const context = contextOf(call);
1203
+ (call, context) => {
1213
1204
  const maps = call.subjects.map((given) => {
1214
1205
  // A recording folder gives its coverage map: the knowledge names it by the path of the map in the folder.
1215
1206
  const path = coverageMapOf(given);
@@ -1236,8 +1227,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
1236
1227
  subjects: [REVISION],
1237
1228
  options: { space: { kind: "space", value: "<space>", help: "revert only this space: c64, drive8, loading, or bank0 to bank255. The other spaces do not change. Without --space, every space reverts" } },
1238
1229
  },
1239
- (call) => {
1240
- const context = contextOf(call);
1230
+ (call, context) => {
1241
1231
  const space = call.string("space");
1242
1232
  const request = { revision: call.subject(0), ...(space === undefined ? {} : { space }) };
1243
1233
  return (db) => {
@@ -1246,9 +1236,8 @@ const WRITE_COMMANDS: CommandSpec[] = [
1246
1236
  };
1247
1237
  },
1248
1238
  ),
1249
- writeCommand({ name: "merge", summary: "Decides the conflicts that a git merge of two computers' work left: of the rows of one conflict, the newest stays. One revision for all." }, (call) => {
1250
- const context = contextOf(call);
1251
- const platform = new Map(platformNames().map((entry) => [entry.name, entry.address]));
1239
+ writeCommand({ name: "merge", summary: "Decides the conflicts that a git merge of two computers' work left: of the rows of one conflict, the newest stays. One revision for all." }, (_call, context) => {
1240
+ const platform = platformAddresses();
1252
1241
  return (db) => {
1253
1242
  const merged = mergeConflicts(db, context, platform);
1254
1243
  return { revision: merged.revision, choices: merged.current.map(showChoice) };
@@ -1261,8 +1250,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
1261
1250
  subjects: [{ name: "<file>", help: "the batch: a JSON list of writes, or - for standard input" }],
1262
1251
  notes: `A write is {"op": "<command>", ...} with the fields of the command, for example {"op": "rename", "address": "$2100", "name": "update_player"}. A range is "start" and "end". A write can name its own "space". The fields of each op, the optional ones in brackets: ${BATCH_OPS}. operand: select is lo, hi or value with symbol and [offset], or expr with expression. patch: an empty or no code is NOP only. macro params and use args: a JSON list of strings or a comma list. operand, patch and use writes are checked against the program of their space.`,
1263
1252
  },
1264
- (call) => {
1265
- const context = contextOf(call);
1253
+ (call, context) => {
1266
1254
  const path = call.subject(0);
1267
1255
  const text = path === "-" ? readFileSync(0, "utf8") : readProjectFile(path).bytes.toString("utf8");
1268
1256
  let parsed: unknown;
@@ -1294,11 +1282,11 @@ const VERDICT: CommandSpec = {
1294
1282
  options: {
1295
1283
  placement: { kind: "choice", value: "<line|side>", choices: COMMENT_PLACEMENTS, help: "the placement of the comment, when the sample has a line and a side comment at the address" },
1296
1284
  class: { kind: "choice", value: "<class>", choices: CHECK_CLASSES, help: `with wrong: the class of the error, one of ${CHECK_CLASSES.join(", ")}` },
1297
- why: { kind: "text", value: "<text>", help: "with wrong: the evidence, with the addresses and the instructions. With unsure: the run that can show the claim" },
1285
+ why: { kind: "text", value: "<text>", help: "with wrong: the evidence, with the addresses and the instructions. With unsure: the run that can show the claim. With correct: the evidence, optional" },
1298
1286
  text: { kind: "text", value: "<text>", help: "with wrong: the correct comment" },
1299
1287
  name: { kind: "text", value: "<name>", help: "with wrong: the correct name at the address" },
1300
1288
  },
1301
- notes: "A wrong verdict needs --class, --why, and --text or --name. An unsure verdict needs --why. A new verdict of a comment replaces its earlier verdict.",
1289
+ notes: "A wrong verdict needs --class, --why, and --text or --name. An unsure verdict needs --why. A correct verdict can have --why. A new verdict of a comment replaces its earlier verdict.",
1302
1290
  run: (call) => {
1303
1291
  const seed = seedOf(call);
1304
1292
  const sample = sampleOf(seed);
@@ -1352,13 +1340,7 @@ const JOIN: CommandSpec = {
1352
1340
  run: (call) => {
1353
1341
  if (call.subjects.length < 2) throw new UsageError("join needs two or more batch files.");
1354
1342
  const batches: Batch[] = call.subjects.map((file) => {
1355
- let value: unknown;
1356
- try {
1357
- value = JSON.parse(readProjectFile(file).bytes.toString("utf8"));
1358
- } catch (error) {
1359
- if (error instanceof SyntaxError) throw new Refusal("invalid-input", `${file} is not JSON: ${error.message}`);
1360
- throw error;
1361
- }
1343
+ const value = readProjectJson(file);
1362
1344
  const shaped = Array.isArray(value) ? { ops: value } : (value as { owner?: unknown; ops?: unknown });
1363
1345
  if (typeof shaped !== "object" || shaped === null || !Array.isArray(shaped.ops)) throw new Refusal("invalid-input", `${file}: a batch is a list of writes, or {"owner": {"start": "$1000", "end": "$1fff"}, "ops": [...]}`);
1364
1346
  let owner: Batch["owner"];