@henols/c64-re-tools 2.6.0-rc.9 → 2.6.0

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 (68) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +3 -3
  3. package/skills/c64-assembler/scripts/assembler.ts +4 -3
  4. package/skills/c64-development/SKILL.md +3 -3
  5. package/skills/c64-docs/SKILL.md +5 -3
  6. package/skills/c64-docs/scripts/docs.ts +17 -4
  7. package/skills/c64-docs/scripts/lib/reference.ts +117 -31
  8. package/skills/c64-docs/scripts/lib/source-map.ts +14 -0
  9. package/skills/c64-knowledge/SKILL.md +8 -7
  10. package/skills/c64-knowledge/scripts/knowledge.ts +16 -9
  11. package/skills/c64-reverse-engineering/SKILL.md +9 -3
  12. package/skills/c64-source/SKILL.md +11 -8
  13. package/skills/c64-source/scripts/lib/export.ts +13 -2
  14. package/skills/c64-source/scripts/lib/loader.ts +51 -28
  15. package/skills/c64-source/scripts/lib/source.ts +24 -17
  16. package/skills/c64-source/scripts/source.ts +51 -36
  17. package/skills/c64-static-analysis/SKILL.md +23 -21
  18. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  19. package/skills/c64-static-analysis/scripts/lib/instructions.ts +4 -4
  20. package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
  21. package/skills/c64-static-analysis/scripts/static-analysis.ts +36 -27
  22. package/skills/c64-testing/SKILL.md +10 -3
  23. package/skills/c64-testing/references/recording-format.md +8 -2
  24. package/skills/c64-testing/references/scenario-format.md +4 -2
  25. package/skills/c64-testing/scripts/lib/recording.ts +193 -28
  26. package/skills/c64-testing/scripts/lib/replay.ts +31 -5
  27. package/skills/c64-testing/scripts/lib/runs.ts +7 -2
  28. package/skills/c64-testing/scripts/lib/scenario.ts +3 -3
  29. package/skills/c64-testing/scripts/testing.ts +23 -2
  30. package/skills/c64-unpacker/SKILL.md +4 -2
  31. package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
  32. package/skills/c64-unpacker/scripts/unpacker.ts +38 -6
  33. package/src/build-name.ts +9 -4
  34. package/src/c64.ts +1 -1
  35. package/src/host/main.ts +2 -2
  36. package/src/host/server.ts +3 -1
  37. package/src/host/tools/index.ts +1 -1
  38. package/src/host/vice/process.ts +34 -17
  39. package/src/host/vice/session.ts +55 -27
  40. package/src/host-client/steps.ts +4 -1
  41. package/src/host-client/tools.ts +1 -1
  42. package/src/knowledge/evidence.ts +66 -0
  43. package/src/knowledge/history.ts +5 -5
  44. package/src/knowledge/import.ts +12 -5
  45. package/src/knowledge/program.ts +81 -33
  46. package/src/knowledge/read.ts +3 -3
  47. package/src/knowledge/schema.ts +7 -7
  48. package/src/knowledge/start-screen.ts +2 -0
  49. package/src/knowledge/text.ts +28 -3
  50. package/src/knowledge/write.ts +6 -6
  51. package/src/mcp/tools/debug.ts +23 -21
  52. package/src/mcp/tools/memory.ts +12 -9
  53. package/src/native/c64run.ts +7 -4
  54. package/src/native/{ghidra → decompiler}/analyze.ts +17 -17
  55. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  56. package/src/native/{ghidra → decompiler}/walk.ts +6 -6
  57. package/src/native/types.ts +25 -25
  58. package/src/opcodes.ts +1 -1
  59. package/src/reference-pages.ts +64 -0
  60. package/src/script.ts +1 -1
  61. package/tools/c64run.c +150 -4
  62. /package/src/native/{ghidra → decompiler}/c64rt-wasm.ts +0 -0
  63. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  64. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  65. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
  66. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.sla +0 -0
  67. /package/src/native/{ghidra → decompiler}/pcode.ts +0 -0
  68. /package/src/native/{ghidra → decompiler}/wasm.ts +0 -0
@@ -69,6 +69,13 @@ export function runProvenance(image: Uint8Array, toolVersion: string | undefined
69
69
  return toolVersion === undefined ? { inputHash } : { inputHash, toolVersion };
70
70
  }
71
71
 
72
+ /** The version of the analyzer in its last revision of these image bytes: undefined when it has none, or when that revision does not tell it. */
73
+ export function lastToolVersion(db: DatabaseSync, analyzer: Analyzer, image: Uint8Array): string | undefined {
74
+ const { inputHash } = runProvenance(image, undefined);
75
+ const row = db.prepare("SELECT tool_version FROM revisions WHERE origin = ? AND input_hash = ? ORDER BY id DESC LIMIT 1").get(analyzer, inputHash!) as { tool_version: string | null } | undefined;
76
+ return row?.tool_version ?? undefined;
77
+ }
78
+
72
79
  export type ImportConflict =
73
80
  | {
74
81
  category: "symbol";
@@ -261,10 +268,10 @@ function importNames(db: DatabaseSync, change: Change, findings: NormalizedFindi
261
268
  }
262
269
  }
263
270
 
264
- /** Analyzers whose regions a heuristic finding replaces where it lies: user/LLM > heuristic > DXA/Ghidra. */
265
- const YIELDS_TO_HEURISTIC = new Set<Origin>(["dxa", "ghidra"]);
271
+ /** Analyzers whose regions a heuristic finding replaces where it lies: user/LLM > heuristic > DXA/decompiler. */
272
+ const YIELDS_TO_HEURISTIC = new Set<Origin>(["dxa", "decompiler"]);
266
273
  /** Analyzers whose data gives way to a code finding over an executed instruction start. */
267
- const YIELDS_TO_EXECUTED_CODE = new Set<Origin>(["dxa", "ghidra"]);
274
+ const YIELDS_TO_EXECUTED_CODE = new Set<Origin>(["dxa", "decompiler"]);
268
275
 
269
276
  /** The first address in the range that is an executed instruction start, or undefined. */
270
277
  function firstExecuted(findings: NormalizedFindings, start: number, end: number): number | undefined {
@@ -279,7 +286,7 @@ function holdsExecuted(findings: NormalizedFindings, start: number, end: number)
279
286
  }
280
287
 
281
288
  /**
282
- * The data findings of DXA or Ghidra that code evidence contradicts: an
289
+ * The data findings of DXA or the decompiler that code evidence contradicts: an
283
290
  * executed instruction start, or a code name (label or routine) of the user or
284
291
  * the LLM, in the range. Evidence wins over an analyzer guess: such a finding
285
292
  * is not imported, and the analyzer's own code there stays.
@@ -314,7 +321,7 @@ function importRegions(db: DatabaseSync, change: Change, given: NormalizedFindin
314
321
  result.conflicts.push(...contradicted);
315
322
  const findings = { ...given, regions: given.regions.filter((region) => !contradicted.some((item) => item.start === region.start && item.end === region.end)) };
316
323
  if (analyzer === "heuristic") {
317
- // An idiom is specific evidence about its bytes: the DXA or Ghidra region there gives way, its parts outside stay.
324
+ // An idiom is specific evidence about its bytes: the DXA or decompiler region there gives way, its parts outside stay.
318
325
  for (const region of findings.regions) {
319
326
  for (const row of regionsOverlapping(db, region.start, region.end, space).filter((candidate) => YIELDS_TO_HEURISTIC.has(candidate.origin))) {
320
327
  change.close("regions", "space = ? AND start_address = ? AND end_address = ? AND origin = ?", space, row.start, row.end, row.origin);
@@ -139,53 +139,104 @@ export function setImage(db: DatabaseSync, context: WriteContext, request: Image
139
139
  });
140
140
  }
141
141
 
142
- /** The coverage of one space as ranges of each kind. */
142
+ /** Address ranges as the knowledge text keeps them: "$1000-$1002 $1005". */
143
+ function rangesText(ranges: readonly AddressRange[]): string {
144
+ const at = (address: number) => `$${address.toString(16).padStart(4, "0")}`;
145
+ return ranges.map((range) => (range.start === range.end ? at(range.start) : `${at(range.start)}-${at(range.end)}`)).join(" ");
146
+ }
147
+
148
+ /** Sets 1 in `map` at each address of ranges as text. */
149
+ function fillRanges(map: Uint8Array, text: string): void {
150
+ for (const item of text.split(" ")) {
151
+ const [start, end] = item.split("-");
152
+ map.fill(1, Number.parseInt(start!.slice(1), 16), Number.parseInt((end ?? start)!.slice(1), 16) + 1);
153
+ }
154
+ }
155
+
156
+ /** The union of the coverage of one space: a map of each kind, 1 at each address that a map of the space has. */
143
157
  function currentCoverage(db: DatabaseSync, space: Space): Map<CoverageKind, Uint8Array> {
144
158
  const maps = new Map<CoverageKind, Uint8Array>(COVERAGE_KINDS.map((kind) => [kind, new Uint8Array(SIZE)]));
145
- for (const row of db.prepare("SELECT kind, start_address, end_address FROM current_coverage WHERE space = ?").all(space) as Array<{ kind: CoverageKind; start_address: number; end_address: number }>) {
146
- maps.get(row.kind)!.fill(1, row.start_address, row.end_address + 1);
147
- }
159
+ for (const row of db.prepare("SELECT kind, ranges FROM current_coverage WHERE space = ?").all(space) as Array<{ kind: CoverageKind; ranges: string }>) fillRanges(maps.get(row.kind)!, row.ranges);
148
160
  return maps;
149
161
  }
150
162
 
163
+ /** The number of address ranges of each kind in the coverage of a space: the ranges of the union of its maps. */
164
+ export function coverageRangeCounts(db: DatabaseSync | undefined, space: Space = DEFAULT_SPACE): Partial<Record<CoverageKind, number>> {
165
+ if (db === undefined) return {};
166
+ const counts: Partial<Record<CoverageKind, number>> = {};
167
+ for (const [kind, map] of currentCoverage(db, space)) {
168
+ const count = rangesWhere((address) => map[address] === 1).length;
169
+ if (count > 0) counts[kind] = count;
170
+ }
171
+ return counts;
172
+ }
173
+
174
+ /** The ranges of each kind of one coverage map as text, for each kind that it has. wx is each address that the run both wrote and executed. */
175
+ function mapRanges(bytes: Uint8Array): Map<CoverageKind, string> {
176
+ const ranges = new Map<CoverageKind, string>();
177
+ for (const kind of COVERAGE_KINDS) {
178
+ const has = kind === "wx" ? (address: number) => (bytes[address]! & (COVERAGE.ramWrite | COVERAGE.ramExecute)) === (COVERAGE.ramWrite | COVERAGE.ramExecute) : (address: number) => (bytes[address]! & KIND_BITS[kind]) !== 0;
179
+ const found = rangesWhere(has);
180
+ if (found.length > 0) ranges.set(kind, rangesText(found));
181
+ }
182
+ return ranges;
183
+ }
184
+
185
+ /** The number of ranges of each kind that are in `after` and not in `before`. */
186
+ function gained(before: Map<CoverageKind, Uint8Array>, after: Map<CoverageKind, Uint8Array>): number {
187
+ let count = 0;
188
+ for (const kind of COVERAGE_KINDS) count += rangesWhere((address) => after.get(kind)![address] === 1 && before.get(kind)![address] === 0).length;
189
+ return count;
190
+ }
191
+
151
192
  /**
152
- * Joins coverage maps into the coverage of a space: adds the ranges of
153
- * the flags that no imported run set before, and as wx the addresses that one
154
- * run both wrote and executed. Each new map is evidence of the revision, with
155
- * its space. A map that the space has with the same name and bytes is not
156
- * imported again.
193
+ * Puts coverage maps into the coverage of a space. The knowledge keeps the
194
+ * ranges of each map by its project path; the coverage of the space is the
195
+ * union of the maps. A map for a path that the space has already replaces
196
+ * the earlier map of that path: a run that is recorded again counts only
197
+ * with its new map. wx is each address that one run both wrote and
198
+ * executed. Each new map is evidence of the revision, with its space. A map
199
+ * that is the latest map of its path in the space is not imported again.
157
200
  */
158
201
  export function addCoverage(
159
202
  db: DatabaseSync,
160
203
  context: WriteContext,
161
204
  request: { space?: Space; maps: CoverageMap[] },
162
- ): { revision: string | null; current: { space: Space; imported: string[]; known: string[]; ranges: number } } {
205
+ ): { revision: string | null; current: { space: Space; imported: string[]; replaced: string[]; known: string[]; added: number; removed: number } } {
163
206
  checkSpace(request);
164
207
  const space = request.space ?? DEFAULT_SPACE;
165
208
  for (const map of request.maps) {
166
209
  if (map.bytes.length !== SIZE) throw new Refusal("invalid-input", `${map.name} has ${map.bytes.length} bytes; a coverage map has 65536, one for each address.`);
167
210
  }
168
- const hashed = request.maps.map((map) => ({ ...map, sha256: createHash("sha256").update(map.bytes).digest("hex") }));
169
- const known = new Set(coverageRuns(db).filter((run) => run.space === space).map((run) => `${run.name}\n${run.sha256}`));
170
- const fresh = hashed.filter((map) => !known.has(`${map.name}\n${map.sha256}`));
211
+ // A path given twice is one map: the last one.
212
+ const byName = new Map(request.maps.map((map) => [map.name, map]));
213
+ const hashed = [...byName.values()].map((map) => ({ ...map, sha256: createHash("sha256").update(map.bytes).digest("hex") }));
214
+ // The runs of a name are oldest first: the last one is the latest map of the path.
215
+ const latest = new Map(coverageRuns(db).filter((run) => run.space === space).map((run) => [run.name, run.sha256]));
216
+ const withRows = new Set((db.prepare("SELECT DISTINCT map FROM current_coverage WHERE space = ?").all(space) as Array<{ map: string }>).map((row) => row.map));
217
+ // A map that has no access has no rows: it is known by its SHA-256 alone.
218
+ const isKnown = (map: (typeof hashed)[number]) => latest.get(map.name) === map.sha256 && (withRows.has(map.name) || map.bytes.every((byte) => byte === 0));
219
+ const fresh = hashed.filter((map) => !isKnown(map));
171
220
  const evidence: Evidence[] = [...(context.evidence ?? []), ...fresh.map((map): Evidence => ({ kind: "coverage", ref: map.name, sha256: map.sha256, ...(space === DEFAULT_SPACE ? {} : { space }) }))];
172
221
  return write(db, { ...context, evidence }, "coverage", (change) => {
173
- const result = { space, imported: fresh.map((map) => map.name), known: hashed.filter((map) => !fresh.includes(map)).map((map) => map.name), ranges: 0 };
222
+ const result = { space, imported: fresh.map((map) => map.name), replaced: fresh.filter((map) => latest.has(map.name) && latest.get(map.name) !== map.sha256).map((map) => map.name), known: hashed.filter((map) => !fresh.includes(map)).map((map) => map.name), added: 0, removed: 0 };
174
223
  if (fresh.length === 0) return result;
175
- // A revision for each import, also when no flag is new: the maps are its evidence.
224
+ // A revision for each import, also when the coverage does not change: the maps are its evidence.
176
225
  change.id();
177
- const union = currentCoverage(db, space);
226
+ const before = currentCoverage(db, space);
178
227
  for (const map of fresh) {
179
- for (const kind of COVERAGE_KINDS) {
180
- const has = kind === "wx" ? (address: number) => (map.bytes[address]! & (COVERAGE.ramWrite | COVERAGE.ramExecute)) === (COVERAGE.ramWrite | COVERAGE.ramExecute) : (address: number) => (map.bytes[address]! & KIND_BITS[kind]) !== 0;
181
- const known = union.get(kind)!;
182
- for (const range of rangesWhere((address) => known[address] === 0 && has(address))) {
183
- change.insertCoverage({ space, kind, start: range.start, end: range.end, origin: context.origin });
184
- known.fill(1, range.start, range.end + 1);
185
- result.ranges++;
186
- }
228
+ // Only a kind whose ranges differ from the earlier map of the path changes.
229
+ const wanted = mapRanges(map.bytes);
230
+ const rows = db.prepare("SELECT id, kind, ranges FROM current_coverage WHERE space = ? AND map = ?").all(space, map.name) as Array<{ id: string; kind: CoverageKind; ranges: string }>;
231
+ for (const row of rows) {
232
+ if (wanted.get(row.kind) === row.ranges) wanted.delete(row.kind);
233
+ else change.close("coverage", "id = ?", row.id);
187
234
  }
235
+ for (const [kind, ranges] of wanted) change.insertCoverage({ space, map: map.name, kind, ranges, origin: context.origin });
188
236
  }
237
+ const after = currentCoverage(db, space);
238
+ result.added = gained(before, after);
239
+ result.removed = gained(after, before);
189
240
  return result;
190
241
  });
191
242
  }
@@ -250,7 +301,7 @@ export function entryMemory(image: ProgramImage): Uint8Array {
250
301
 
251
302
  /**
252
303
  * The bytes for an analyzer: a PRG for one segment without an entry state,
253
- * else the 64 KiB with the entry-state pages (entryMemory). DXA, Ghidra and
304
+ * else the 64 KiB with the entry-state pages (entryMemory). DXA, the decompiler and
254
305
  * c64-source get the same bytes.
255
306
  */
256
307
  export function analyzedBytes(image: ProgramImage): { bytes: Buffer; kind: "prg" | "flat64k" } {
@@ -268,15 +319,12 @@ export function analyzedBytes(image: ProgramImage): { bytes: Buffer; kind: "prg"
268
319
  */
269
320
  export function programCoverage(db: DatabaseSync | undefined, space: Space = DEFAULT_SPACE): { map: Uint8Array; selfModified: Uint8Array } | undefined {
270
321
  if (db === undefined) return undefined;
271
- const rows = db.prepare("SELECT kind, start_address, end_address FROM current_coverage WHERE space = ?").all(space) as Array<{ kind: CoverageKind; start_address: number; end_address: number }>;
272
- if (rows.length === 0) return undefined;
322
+ const has = db.prepare("SELECT 1 FROM current_coverage WHERE space = ? LIMIT 1").get(space);
323
+ if (has === undefined) return undefined;
324
+ const union = currentCoverage(db, space);
273
325
  const map = new Uint8Array(SIZE);
274
- const selfModified = new Uint8Array(SIZE);
275
- for (const row of rows) {
276
- if (row.kind === "wx") selfModified.fill(1, row.start_address, row.end_address + 1);
277
- else for (let address = row.start_address; address <= row.end_address; address++) map[address]! |= KIND_BITS[row.kind];
278
- }
279
- return { map, selfModified };
326
+ for (const [kind, marks] of union) if (kind !== "wx") for (let address = 0; address < SIZE; address++) if (marks[address] === 1) map[address]! |= KIND_BITS[kind];
327
+ return { map, selfModified: union.get("wx")! };
280
328
  }
281
329
 
282
330
  /**
@@ -451,7 +451,7 @@ export function symbolNamed(db: DatabaseSync | undefined, name: string, space: S
451
451
  return row === undefined ? undefined : toSymbol(row);
452
452
  }
453
453
 
454
- /** The analyzer names at an address: one for each analyzer, in the order heuristic, Ghidra, DXA. */
454
+ /** The analyzer names at an address: one for each analyzer, in the order heuristic, decompiler, DXA. */
455
455
  export function analyzerNamesAt(db: DatabaseSync | undefined, address: number, space: Space = DEFAULT_SPACE): SymbolRow[] {
456
456
  if (db === undefined) return [];
457
457
  return (db.prepare(`SELECT ${SYMBOL_COLUMNS} FROM current_analyzer_names WHERE space = ? AND address = ?`).all(space, address) as Raw[]).map(toSymbol).sort(byAnalyzer);
@@ -464,10 +464,10 @@ export function analyzerNamed(db: DatabaseSync | undefined, name: string, space:
464
464
  }
465
465
 
466
466
  /** The analyzers in the order that their names are used when no other name exists. */
467
- export const ANALYZER_NAME_ORDER: readonly Origin[] = ["heuristic", "ghidra", "dxa"];
467
+ export const ANALYZER_NAME_ORDER: readonly Origin[] = ["heuristic", "decompiler", "dxa"];
468
468
  const byAnalyzer = (a: SymbolRow, b: SymbolRow) => a.address - b.address || ANALYZER_NAME_ORDER.indexOf(a.origin) - ANALYZER_NAME_ORDER.indexOf(b.origin);
469
469
 
470
- /** Current analyzer names in a range, in address order and then heuristic, Ghidra, DXA. */
470
+ /** Current analyzer names in a range, in address order and then heuristic, decompiler, DXA. */
471
471
  export function listAnalyzerNames(db: DatabaseSync | undefined, range: AddressRange = ALL, kind?: SymbolKind, origins?: OriginFilter, space: Space = DEFAULT_SPACE): SymbolRow[] {
472
472
  if (db === undefined) return [];
473
473
  return (db.prepare(`SELECT ${SYMBOL_COLUMNS} FROM current_analyzer_names WHERE space = ? AND address BETWEEN ? AND ?`).all(space, range.start, range.end) as Raw[])
@@ -8,12 +8,12 @@ import { REFERENCE_KINDS, type ReferenceKind } from "../c64.ts";
8
8
  import { OPERAND_SELECTS } from "./expression.ts";
9
9
 
10
10
  /** heuristic: 6502 idioms that the static analysis finds by pattern; an analyzer origin. */
11
- export const ORIGINS = ["user", "llm", "dxa", "ghidra", "heuristic"] as const;
11
+ export const ORIGINS = ["user", "llm", "dxa", "decompiler", "heuristic"] as const;
12
12
  export type Origin = (typeof ORIGINS)[number];
13
13
  /** The origins of semantic knowledge: what the user or the LLM decided. It wins over analyzer facts. */
14
14
  export const SEMANTIC_ORIGINS = ["user", "llm"] as const satisfies readonly Origin[];
15
15
  /** The analyzers: their facts and names give way to semantic knowledge. */
16
- export const ANALYZERS = ["dxa", "ghidra", "heuristic"] as const satisfies readonly Origin[];
16
+ export const ANALYZERS = ["dxa", "decompiler", "heuristic"] as const satisfies readonly Origin[];
17
17
  export type Analyzer = (typeof ANALYZERS)[number];
18
18
  export const isSemantic = (origin: string | undefined): boolean => (SEMANTIC_ORIGINS as readonly (string | undefined)[]).includes(origin);
19
19
  export const isAnalyzer = (origin: string | undefined): boolean => (ANALYZERS as readonly (string | undefined)[]).includes(origin);
@@ -176,7 +176,7 @@ function createSchema(db: DatabaseSync): void {
176
176
  address INTEGER NOT NULL CHECK (address BETWEEN 0 AND 65535),
177
177
  name TEXT NOT NULL CHECK (length(name) > 0),
178
178
  kind TEXT NOT NULL CHECK (kind IN (${list(SYMBOL_KINDS)})),
179
- origin TEXT NOT NULL CHECK (origin IN ('dxa', 'ghidra', 'heuristic')),
179
+ origin TEXT NOT NULL CHECK (origin IN ('dxa', 'decompiler', 'heuristic')),
180
180
  valid_from_revision TEXT NOT NULL REFERENCES revisions (id),
181
181
  valid_to_revision TEXT REFERENCES revisions (id)
182
182
  );
@@ -393,14 +393,14 @@ function createSchema(db: DatabaseSync): void {
393
393
  CREATE TABLE coverage (
394
394
  id TEXT PRIMARY KEY,
395
395
  space TEXT NOT NULL DEFAULT 'c64' CHECK (${SPACE_CHECK}),
396
+ map TEXT NOT NULL CHECK (length(map) > 0),
396
397
  kind TEXT NOT NULL CHECK (kind IN (${list(COVERAGE_KINDS)})),
397
- start_address INTEGER NOT NULL CHECK (start_address BETWEEN 0 AND 65535),
398
- end_address INTEGER NOT NULL CHECK (end_address BETWEEN start_address AND 65535),
398
+ ranges TEXT NOT NULL CHECK (length(ranges) >= 5),
399
399
  origin TEXT NOT NULL CHECK (origin IN ('user', 'llm')),
400
400
  valid_from_revision TEXT NOT NULL REFERENCES revisions (id),
401
401
  valid_to_revision TEXT REFERENCES revisions (id)
402
402
  );
403
- CREATE INDEX coverage_current ON coverage (space, kind) WHERE valid_to_revision IS NULL;
403
+ CREATE INDEX coverage_current ON coverage (space, map) WHERE valid_to_revision IS NULL;
404
404
  CREATE VIEW current_memory AS SELECT * FROM memory WHERE valid_to_revision IS NULL;
405
405
  CREATE VIEW current_release_memory AS SELECT * FROM release_memory WHERE valid_to_revision IS NULL;
406
406
  CREATE VIEW current_entries AS SELECT * FROM entries WHERE valid_to_revision IS NULL;
@@ -423,7 +423,7 @@ function createSchema(db: DatabaseSync): void {
423
423
  }
424
424
 
425
425
  /** The version of the index this build makes. An index with another version is emptied and made again. */
426
- export const INDEX_VERSION = 14;
426
+ export const INDEX_VERSION = 15;
427
427
 
428
428
  function indexVersion(db: DatabaseSync): number | undefined {
429
429
  const hasMeta = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'meta'").get();
@@ -9,6 +9,8 @@ import type { StartScreenMode } from "./schema.ts";
9
9
  /** The labels of the start screen in a generated loader: its wait for a key or a fire button, and the code after the wait. */
10
10
  export const START_SCREEN_WAIT = "loader_start_screen_wait";
11
11
  export const START_SCREEN_CONTINUE = "loader_start_screen_continue";
12
+ /** The label of the loader's jump to the entry, in ACME's symbol list. */
13
+ export const LOADER_JUMP = "c64_source_loader_jump";
12
14
 
13
15
  /** The fields of a start screen that the capture of a stage gives. */
14
16
  export interface StageScreen {
@@ -59,13 +59,18 @@ export function rowId(revision: string, order: number): string {
59
59
  * text, bytes as lowercase hex digits, or a JSON value that the index keeps as
60
60
  * JSON text.
61
61
  */
62
- type Format = "address" | "integer" | "text" | "hex" | "json";
62
+ type Format = "address" | "integer" | "text" | "hex" | "json" | "ranges";
63
+
64
+ /** Address ranges as text: "$1000-$1002 $1005", in address order, one space between them. */
65
+ const RANGES = /^\$[0-9a-f]{4}(?:-\$[0-9a-f]{4})?(?: \$[0-9a-f]{4}(?:-\$[0-9a-f]{4})?)*$/;
63
66
 
64
67
  interface Field {
65
68
  key: string;
66
69
  column: string;
67
70
  format: Format;
68
71
  optional?: boolean;
72
+ /** What to do when a line does not have this key: a key that an earlier toolkit version did not write. */
73
+ remedy?: string;
69
74
  }
70
75
 
71
76
  /** One fact table: its file, its fields in line order, and the column that sorts its lines after the space (an address, or a name). */
@@ -218,8 +223,23 @@ export const TABLES: readonly TableSpec[] = [
218
223
  sort: "address",
219
224
  fields: [space, field("entry", "address", "address"), field("state", "state", "json", true), field("stages", "stages", "json", true), origin],
220
225
  },
221
- // What the runs did: the union of the coverage maps as ranges of one kind each.
222
- { table: "coverage", file: "coverage.jsonl", sort: "start_address", fields: [space, field("kind", "kind", "text"), field("start", "start_address", "address"), field("end", "end_address", "address"), origin] },
226
+ // What the runs did: for each coverage map, by its project path, the ranges of each kind. The coverage of a space is the union of its maps.
227
+ {
228
+ table: "coverage",
229
+ file: "coverage.jsonl",
230
+ sort: "map",
231
+ fields: [
232
+ space,
233
+ {
234
+ ...field("map", "map", "text"),
235
+ remedy:
236
+ "The coverage of an earlier toolkit version does not keep the ranges of each map. Delete .c64-re-tools/knowledge/coverage.jsonl. Then put the coverage maps that you have into the project knowledge again.",
237
+ },
238
+ field("kind", "kind", "text"),
239
+ field("ranges", "ranges", "ranges"),
240
+ origin,
241
+ ],
242
+ },
223
243
  ];
224
244
 
225
245
  export const REVISIONS_FILE = "revisions.jsonl";
@@ -338,6 +358,8 @@ function parseLines(file: string, text: string): Array<{ line: number; value: Ra
338
358
 
339
359
  /** The column values of one line, checked against its fields. */
340
360
  function columnsOf(file: string, line: number, value: Raw, fields: readonly Field[], extra: readonly string[]): Raw {
361
+ // A line of an earlier format: the key that this format added is missing, and the remedy tells what to do.
362
+ for (const { key, remedy } of fields) if (remedy !== undefined && (value[key] === undefined || value[key] === null)) bad(file, line, `the key ${JSON.stringify(key)} is missing. ${remedy}`);
341
363
  const allowed = new Set([...fields.map((item) => item.key), ...extra]);
342
364
  for (const key of Object.keys(value)) if (!allowed.has(key)) bad(file, line, `the key ${JSON.stringify(key)} is not known.`);
343
365
  const columns: Raw = {};
@@ -355,6 +377,9 @@ function columnsOf(file: string, line: number, value: Raw, fields: readonly Fiel
355
377
  } else if (format === "hex") {
356
378
  if (typeof item !== "string" || !/^(?:[0-9a-f]{2})+$/.test(item)) bad(file, line, `${key} must be bytes as lowercase hex digits.`);
357
379
  columns[column] = item;
380
+ } else if (format === "ranges") {
381
+ if (typeof item !== "string" || !RANGES.test(item)) bad(file, line, `${key} must be address ranges such as "$1000-$1002 $1005".`);
382
+ columns[column] = item;
358
383
  } else if (format === "json") {
359
384
  if (typeof item !== "object") bad(file, line, `${key} must be a JSON object or list.`);
360
385
  columns[column] = JSON.stringify(item);
@@ -328,11 +328,11 @@ export class Change {
328
328
  .run(this.#rowId(), row.space, row.address, row.state, row.stages, row.origin, this.id());
329
329
  }
330
330
 
331
- /** One coverage range of one kind. */
332
- insertCoverage(row: { space: Space; kind: string; start: number; end: number; origin: Origin }): void {
331
+ /** The ranges of one kind of the coverage map at a project path, as text. */
332
+ insertCoverage(row: { space: Space; map: string; kind: string; ranges: string; origin: Origin }): void {
333
333
  this.#db
334
- .prepare("INSERT INTO coverage (id, space, kind, start_address, end_address, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?)")
335
- .run(this.#rowId(), row.space, row.kind, row.start, row.end, row.origin, this.id());
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());
336
336
  }
337
337
  }
338
338
 
@@ -1639,7 +1639,7 @@ const PROGRAM_TABLES = [
1639
1639
  ["memory", "space, address, bytes, origin"],
1640
1640
  ["release_memory", "space, label, address, bytes, origin"],
1641
1641
  ["entries", "space, address, state, stages, origin"],
1642
- ["coverage", "space, kind, start_address, end_address, origin"],
1642
+ ["coverage", "space, map, kind, ranges, origin"],
1643
1643
  ] as const;
1644
1644
 
1645
1645
  const KEYS = {
@@ -1770,7 +1770,7 @@ export function revert(db: DatabaseSync, context: WriteContext, request: { revis
1770
1770
  if (table === "memory") change.insertMemory(values);
1771
1771
  else if (table === "release_memory") change.insertReleaseMemory(values);
1772
1772
  else if (table === "entries") change.insertEntry(values);
1773
- else change.insertCoverage({ ...(values as { space: Space; kind: string; origin: Origin }), start: row.start_address as number, end: row.end_address as number });
1773
+ else change.insertCoverage(values);
1774
1774
  }
1775
1775
  }
1776
1776
  return { restoredRevision: restored };
@@ -176,7 +176,7 @@ export const c64CpuHistory = defineTool({
176
176
  },
177
177
  });
178
178
 
179
- /** The hits that a trace result gives inline; out gives all of them. */
179
+ /** The hits that a trace result gives inline; out gives all of them in the file, and none inline. */
180
180
  const TRACE_LISTED = 200;
181
181
 
182
182
  export const c64Trace = defineTool({
@@ -192,7 +192,7 @@ export const c64Trace = defineTool({
192
192
  "A read or write hit also gives the address that the instruction used, and value, the byte that it read or wrote. " +
193
193
  "At $D000-$DFFF only a load or a store gives value: a read after the access can give another byte. " +
194
194
  `The trace ends after frames frames (1 to ${MAX_TRACE_FRAMES}), at maxHits hits (at most ${MAX_TRACE_HITS}), or at a breakpoint, a watchpoint or a JAM. ` +
195
- `The result lists the first ${TRACE_LISTED} hits. With out, it writes all hits as JSON lines to that project file. ` +
195
+ `The result lists the first ${TRACE_LISTED} hits. With out, it writes all hits as JSON lines to that project file, and the result gives no hits. ` +
196
196
  "Each hit stops the machine for a short time. Thus a point with many hits in each frame makes the trace slow. Use a small range and a maxHits. " +
197
197
  "The machine is stopped after the trace.",
198
198
  inputSchema: z
@@ -209,23 +209,25 @@ export const c64Trace = defineTool({
209
209
  frames: z.number().int().min(0),
210
210
  pc: AddressOutput,
211
211
  count: z.number().int().min(0),
212
- hits: z.array(
213
- z.object({
214
- point: z.number().int().min(0),
215
- pc: AddressOutput,
216
- bytes: HexData,
217
- text: z.string(),
218
- a: Byte,
219
- x: Byte,
220
- y: Byte,
221
- sp: Byte,
222
- frame: z.number().int().min(0),
223
- rasterLine: z.number().int().min(0),
224
- rasterCycle: z.number().int().min(0),
225
- address: AddressOutput.optional(),
226
- value: Byte.optional(),
227
- }),
228
- ),
212
+ hits: z
213
+ .array(
214
+ z.object({
215
+ point: z.number().int().min(0),
216
+ pc: AddressOutput,
217
+ bytes: HexData,
218
+ text: z.string(),
219
+ a: Byte,
220
+ x: Byte,
221
+ y: Byte,
222
+ sp: Byte,
223
+ frame: z.number().int().min(0),
224
+ rasterLine: z.number().int().min(0),
225
+ rasterCycle: z.number().int().min(0),
226
+ address: AddressOutput.optional(),
227
+ value: Byte.optional(),
228
+ }),
229
+ )
230
+ .optional(),
229
231
  ...WrittenOutput,
230
232
  }),
231
233
  readOnly: false,
@@ -236,8 +238,8 @@ export const c64Trace = defineTool({
236
238
  if (ranges.some((point) => point.end < point.start)) throw new WireFailure("invalid-input", "A point end must not be before its start.");
237
239
  const traced = await session.trace({ points: ranges, ...request });
238
240
  const shown = traced.hits.map(({ address, ...hit }) => ({ ...hit, pc: formatC64Address(hit.pc), ...(address === undefined ? {} : { address: formatC64Address(address) }) }));
239
- const summary = { end: traced.end, frames: traced.frames, pc: formatC64Address(traced.pc), count: traced.hits.length, hits: shown.slice(0, TRACE_LISTED) };
240
- if (out === undefined) return summary;
241
+ const summary = { end: traced.end, frames: traced.frames, pc: formatC64Address(traced.pc), count: traced.hits.length };
242
+ if (out === undefined) return { ...summary, hits: shown.slice(0, TRACE_LISTED) };
241
243
  return { ...summary, ...writeOut(out, linesText(shown.map((hit) => JSON.stringify(hit))), project) };
242
244
  },
243
245
  });
@@ -186,7 +186,7 @@ export const c64Disassemble = defineTool({
186
186
  description:
187
187
  `Disassemble count instructions (1 to ${MAX_DISASSEMBLE}) from an address, as the bytes are in the live machine now. ` +
188
188
  "Use it to read code that a program changed or unpacked at run time. It includes the undocumented opcodes. " +
189
- `With out, it disassembles up to ${MAX_DISASSEMBLE_OUT} instructions, or to $ffff, and writes them as a listing to that project file. The result then gives the file in place of the instructions. ` +
189
+ `With out, it disassembles up to ${MAX_DISASSEMBLE_OUT} instructions, or to $ffff, and writes them as a listing to that project file. The result then gives the file in place of the instructions. A file name that ends in .json gets a JSON list of the instructions, as the result without out gives them. ` +
190
190
  "This does not change the run state of the machine.",
191
191
  inputSchema: z
192
192
  .object({
@@ -208,24 +208,27 @@ export const c64Disassemble = defineTool({
208
208
  const result = await session.disassemble(request);
209
209
  return { instructions: result.instructions.map((instruction) => ({ ...instruction, address: formatC64Address(instruction.address) })) };
210
210
  }
211
- const lines: string[] = [];
211
+ const instructions: Array<{ address: string; bytes: string; text: string }> = [];
212
212
  let address = request.address;
213
213
  // Ends at count, or where the disassembly would wrap past $ffff.
214
214
  let wrapped = false;
215
- while (!wrapped && lines.length < request.count && address <= 0xffff) {
216
- const { instructions } = await session.disassemble({ ...request, address, count: Math.min(MAX_DISASSEMBLE, request.count - lines.length) });
217
- if (instructions.length === 0) break;
218
- for (const instruction of instructions) {
219
- if (lines.length === request.count) break;
215
+ while (!wrapped && instructions.length < request.count && address <= 0xffff) {
216
+ const part = await session.disassemble({ ...request, address, count: Math.min(MAX_DISASSEMBLE, request.count - instructions.length) });
217
+ if (part.instructions.length === 0) break;
218
+ for (const instruction of part.instructions) {
219
+ if (instructions.length === request.count) break;
220
220
  if (instruction.address < address) {
221
221
  wrapped = true;
222
222
  break;
223
223
  }
224
- lines.push(`${formatC64Address(instruction.address)} ${spaced(instruction.bytes).padEnd(9)} ${instruction.text}`);
224
+ instructions.push({ ...instruction, address: formatC64Address(instruction.address) });
225
225
  address = instruction.address + instruction.bytes.length / 2;
226
226
  }
227
227
  }
228
- return { count: lines.length, ...writeOut(out, linesText(lines), project) };
228
+ const text = out.toLowerCase().endsWith(".json")
229
+ ? `${JSON.stringify(instructions, null, 1)}\n`
230
+ : linesText(instructions.map((instruction) => `${instruction.address} ${spaced(instruction.bytes).padEnd(9)} ${instruction.text}`));
231
+ return { count: instructions.length, ...writeOut(out, text, project) };
229
232
  },
230
233
  });
231
234
 
@@ -12,7 +12,7 @@ import type { SupervisedProcess } from "./processes.ts";
12
12
  import type { ToolContext } from "./run.ts";
13
13
 
14
14
  /** The command protocol that this module speaks; c64run --version and version name it. */
15
- export const C64RUN_PROTOCOL = 4;
15
+ export const C64RUN_PROTOCOL = 7;
16
16
 
17
17
  /** CPU cycles in one PAL frame: 312 lines of 63 cycles. */
18
18
  export const PAL_FRAME_CYCLES = 19_656;
@@ -22,15 +22,18 @@ const STOP_MS = 5_000;
22
22
  const COMMAND_MS = 30_000;
23
23
  /** The slowest run that a command limit allows for: c64run runs about 6 million cycles per second. */
24
24
  const SLOWEST_CYCLES_PER_SECOND = 1_000_000;
25
+ /** The argument of each run command that is the absolute tick it runs to at most: run <tick>, run-pc <pc> <tick> [<n>], run-reads <pc> <addr> <n> <tick>. */
26
+ const UNTIL_ARGUMENT: Record<string, number> = { run: 0, "run-pc": 1, "run-reads": 3 };
25
27
 
26
28
  /**
27
29
  * The time limit of a command, so that a core that hangs cannot keep the
28
- * script running. run, run-pc and run-reads end with the absolute tick that
29
- * they run to at most; the others answer at once.
30
+ * script running. A run command gets the time of the cycles up to the tick
31
+ * that it runs to at most; the others answer at once.
30
32
  */
31
33
  export function commandLimitMs(text: string): number {
32
34
  const [name, ...rest] = text.split(" ");
33
- const target = name === "run" || name === "run-pc" || name === "run-reads" ? Number(rest.at(-1)) : 0;
35
+ const at = UNTIL_ARGUMENT[name!];
36
+ const target = at === undefined ? 0 : Number(rest[at]);
34
37
  return COMMAND_MS + (Number.isFinite(target) ? (target * 1000) / SLOWEST_CYCLES_PER_SECOND : 0);
35
38
  }
36
39