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

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 (67) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +1 -1
  3. package/skills/c64-assembler/scripts/assembler.ts +78 -24
  4. package/skills/c64-docs/scripts/docs.ts +31 -10
  5. package/skills/c64-knowledge/SKILL.md +11 -7
  6. package/skills/c64-knowledge/references/batches.md +2 -1
  7. package/skills/c64-knowledge/references/source-knowledge.md +1 -1
  8. package/skills/c64-knowledge/scripts/knowledge.ts +46 -29
  9. package/skills/c64-packer/scripts/packer.ts +9 -2
  10. package/skills/c64-provenance/SKILL.md +2 -2
  11. package/skills/c64-provenance/scripts/lib/runtime.ts +45 -10
  12. package/skills/c64-provenance/scripts/provenance.ts +10 -3
  13. package/skills/c64-source/references/loader.md +8 -7
  14. package/skills/c64-source/scripts/lib/loader.ts +4 -111
  15. package/skills/c64-source/scripts/lib/source.ts +3 -1
  16. package/skills/c64-source/scripts/source.ts +49 -78
  17. package/skills/c64-static-analysis/SKILL.md +2 -2
  18. package/skills/c64-static-analysis/scripts/lib/coverage.ts +56 -4
  19. package/skills/c64-static-analysis/scripts/lib/idioms.ts +92 -42
  20. package/skills/c64-static-analysis/scripts/static-analysis.ts +32 -21
  21. package/skills/c64-testing/SKILL.md +7 -0
  22. package/skills/c64-testing/scripts/lib/play.ts +8 -7
  23. package/skills/c64-testing/scripts/lib/recording.ts +278 -27
  24. package/skills/c64-testing/scripts/lib/replay.ts +9 -8
  25. package/skills/c64-testing/scripts/lib/runs.ts +5 -1
  26. package/skills/c64-testing/scripts/lib/scenario.ts +4 -0
  27. package/skills/c64-testing/scripts/testing.ts +30 -11
  28. package/skills/c64-unpacker/SKILL.md +13 -11
  29. package/skills/c64-unpacker/scripts/lib/loads.ts +10 -5
  30. package/skills/c64-unpacker/scripts/lib/machine.ts +163 -3
  31. package/skills/c64-unpacker/scripts/lib/stages.ts +13 -6
  32. package/skills/c64-unpacker/scripts/unpacker.ts +34 -15
  33. package/skills/emulator/SKILL.md +2 -2
  34. package/src/c64.ts +21 -0
  35. package/src/host/vice/adapter.ts +2 -1
  36. package/src/host/vice/chips.ts +6 -9
  37. package/src/host/vice/session.ts +2 -2
  38. package/src/host-client/image.ts +40 -4
  39. package/src/host-client/tools.ts +1 -1
  40. package/src/host-client/transfer.ts +48 -26
  41. package/src/host-client/vice-session.ts +15 -0
  42. package/src/knowledge/database.ts +72 -19
  43. package/src/knowledge/import.ts +32 -7
  44. package/src/knowledge/join.ts +50 -2
  45. package/src/knowledge/names.ts +2 -2
  46. package/src/knowledge/program.ts +103 -24
  47. package/src/knowledge/schema.ts +6 -0
  48. package/src/knowledge/start-screen.ts +57 -7
  49. package/src/knowledge/write.ts +20 -13
  50. package/src/loader.ts +101 -33
  51. package/src/mcp/output.ts +13 -12
  52. package/src/mcp/server.ts +33 -22
  53. package/src/mcp/tools/debug.ts +21 -24
  54. package/src/mcp/tools/media.ts +27 -27
  55. package/src/mcp/tools/memory.ts +13 -17
  56. package/src/mcp/tools/video.ts +10 -12
  57. package/src/native/c64run.ts +39 -1
  58. package/src/native/decompiler/analyze.ts +1 -1
  59. package/src/native/dxa.ts +2 -2
  60. package/src/native/types.ts +26 -7
  61. package/src/opcodes.ts +5 -0
  62. package/src/program-code.ts +4 -2
  63. package/src/project.ts +224 -71
  64. package/src/protocol/vice.ts +5 -3
  65. package/src/script.ts +60 -15
  66. package/{skills/c64-source/scripts/lib → src}/stage.ts +142 -11
  67. package/tools/c64run.c +18 -5
@@ -4,7 +4,10 @@
4
4
  // there; at an address that no batch owns, the first batch in the order given
5
5
  // wins. A name that a batch gave to an address, and that the join replaced
6
6
  // with the name of another batch, is replaced in that batch's operand
7
- // expressions and macro args too. The join writes no knowledge.
7
+ // expressions, macro args, patch code and macro bodies too. In the comment
8
+ // texts of the batch, and after a ; in its code, the name is replaced as a
9
+ // whole word only when no English word can be the name: "the score" stays
10
+ // prose. The join writes no knowledge.
8
11
 
9
12
  import { replaceIdentifiers } from "./expression.ts";
10
13
  import { spaceOf } from "./schema.ts";
@@ -46,6 +49,13 @@ export interface JoinResult {
46
49
 
47
50
  type Op<K extends BatchOperation["op"]> = Extract<BatchOperation, { op: K }>;
48
51
 
52
+ /** A name as a whole word of a comment: a word after a letter, a digit, _, . or $ is part of another word or a number. */
53
+ const WORD = /(?<![A-Za-z0-9_.$])\.?[A-Za-z_][A-Za-z0-9_]*/g;
54
+ /** A name that no English word is: with a dot first (a local label), an underscore, a digit, or a capital letter after a small one. */
55
+ const NO_WORD = /^\.|[_0-9]|[a-z][A-Z]/;
56
+ /** A string or a character of ACME, also one that the line ends before its quote: its text holds no name. */
57
+ const QUOTED = /("(?:\\.|[^"\\])*"?|'(?:\\.|[^'\\])*'?)/;
58
+
49
59
  /** The value of a keyed write as text, to compare and report it. */
50
60
  function valueOf(op: BatchOperation): string {
51
61
  switch (op.op) {
@@ -134,6 +144,35 @@ export function joinBatches(batches: readonly Batch[]): JoinResult {
134
144
  return text;
135
145
  }
136
146
  };
147
+ /** The comment text of a batch with each name that it lost and that no English word is. */
148
+ const followWords = (batch: Batch, space: string, text: string) => {
149
+ const map = renamedIn.get(batch)!;
150
+ return map.size === 0 ? text : text.replace(WORD, (word) => (NO_WORD.test(word) ? (map.get(`${space}|${word}`) ?? word) : word));
151
+ };
152
+ /** ACME code of a batch with each name that it lost, outside strings and `kept` (the params of a macro), and its comments after a ; as followWords gives them. */
153
+ const followCode = (batch: Batch, space: string, code: string, kept: readonly string[] = []) => {
154
+ const map = renamedIn.get(batch)!;
155
+ if (map.size === 0) return code;
156
+ const name = (word: string) => (kept.includes(word) ? word : (map.get(`${space}|${word}`) ?? word));
157
+ return code
158
+ .split("\n")
159
+ .map((line) => {
160
+ // The parts at odd indexes are strings. A ; outside a string starts the comment of the line.
161
+ let comment = false;
162
+ return line
163
+ .split(QUOTED)
164
+ .map((part, index) => {
165
+ if (comment) return followWords(batch, space, part);
166
+ if (index % 2 === 1) return part;
167
+ const at = part.indexOf(";");
168
+ if (at === -1) return part.replace(WORD, name);
169
+ comment = true;
170
+ return part.slice(0, at).replace(WORD, name) + followWords(batch, space, part.slice(at));
171
+ })
172
+ .join("");
173
+ })
174
+ .join("\n");
175
+ };
137
176
 
138
177
  const comments = choose("comment", "comment", (write) => `${spaceOf(write)}|${write.address}|${write.placement}`, (write) => write.address);
139
178
  const operands = choose("operand", "operand", (write) => `${spaceOf(write)}|${write.address}`, (write) => write.address);
@@ -191,19 +230,28 @@ export function joinBatches(batches: readonly Batch[]): JoinResult {
191
230
  case "use":
192
231
  if (once(write)) rest.push({ ...write, args: (write.args ?? []).map((arg) => follow(batch, spaceOf(write), arg)) });
193
232
  break;
233
+ case "patch":
234
+ if (once(write)) rest.push({ ...write, code: followCode(batch, spaceOf(write), write.code), ...(write.comment === undefined ? {} : { comment: followWords(batch, spaceOf(write), write.comment) }) });
235
+ break;
194
236
  default:
195
237
  if (once(write)) rest.push(write);
196
238
  }
197
239
  }
198
240
  }
199
241
  const kept = <T extends { batch: Batch; write: BatchOperation }>(map: Map<string, T>) => [...map.values()].map(({ write }) => write);
242
+ const commentWrites = [...comments.values()].map(({ batch, write }) => ({ ...write, text: followWords(batch, spaceOf(write), write.text) }));
243
+ const macroWrites = [...macros.values()].map(({ batch, write }) => ({
244
+ ...write,
245
+ body: followCode(batch, spaceOf(write), write.body, write.params),
246
+ ...(write.comment === undefined ? {} : { comment: followWords(batch, spaceOf(write), write.comment) }),
247
+ }));
200
248
  const operandWrites = [...operands.values()].map(({ batch, write }) => ({
201
249
  ...write,
202
250
  ...(write.symbol === undefined ? {} : { symbol: follow(batch, spaceOf(write), write.symbol) }),
203
251
  ...(write.expression === undefined ? {} : { expression: follow(batch, spaceOf(write), write.expression) }),
204
252
  }));
205
253
  return {
206
- ops: [...removals, ...foreignRegions, ...ownRegions, ...kept(names), ...kept(comments), ...kept(modules), ...references, ...kept(macros), ...operandWrites, ...rest],
254
+ ops: [...removals, ...foreignRegions, ...ownRegions, ...kept(names), ...commentWrites, ...kept(modules), ...references, ...macroWrites, ...operandWrites, ...rest],
207
255
  choices,
208
256
  clashes,
209
257
  repeated,
@@ -10,7 +10,7 @@ import { Refusal } from "../errors.ts";
10
10
  import { projectRoot } from "../project.ts";
11
11
  import { withRead } from "./database.ts";
12
12
  import { analyzerNamed, listAnalyzerNames, listSymbols, symbolNamed } from "./read.ts";
13
- import { DEFAULT_SPACE, type Space, type SymbolKind } from "./schema.ts";
13
+ import { DEFAULT_SPACE, inSpace, type Space, type SymbolKind } from "./schema.ts";
14
14
 
15
15
  /** The address of a name in a space. Refuses a name that no symbol and no analyzer has, and an analyzer name at two addresses. */
16
16
  export function addressOfName(db: DatabaseSync | undefined, name: string, space: Space = DEFAULT_SPACE): number {
@@ -19,7 +19,7 @@ export function addressOfName(db: DatabaseSync | undefined, name: string, space:
19
19
  const rows = analyzerNamed(db, name, space);
20
20
  const addresses = [...new Set(rows.map((row) => row.address))];
21
21
  if (addresses.length === 1) return addresses[0]!;
22
- const where = space === DEFAULT_SPACE ? "" : ` in ${space}`;
22
+ const where = inSpace(space);
23
23
  if (addresses.length > 1) throw new Refusal("invalid-input", `the analyzers give ${name} to ${rows.map((row) => `${formatC64Address(row.address)} (${row.origin})`).join(" and ")}${where}. Give the address.`);
24
24
  throw new Refusal("not-found", `${name} is not a name in the knowledge${where}. Give a $ address, or a symbol or an analyzer name of the project knowledge${where}.`);
25
25
  }
@@ -3,12 +3,14 @@
3
3
  // capture and the coverage maps are imported one time; every later step reads
4
4
  // them here, so a project needs no image or coverage files to be made again.
5
5
 
6
+ import { createHash } from "node:crypto";
6
7
  import type { DatabaseSync } from "node:sqlite";
7
8
 
8
9
  import { Refusal } from "../errors.ts";
9
- import { type AddressRange, COVERAGE, formatC64Address, formatC64Byte, formatC64Range, inRanges, prgOf, rangesWhere } from "../c64.ts";
10
- import { COVERAGE_KINDS, DEFAULT_SPACE, MEMORY_ROW, type CoverageKind, type Space } from "./schema.ts";
11
- import { coverageRuns } from "./read.ts";
10
+ import { type AddressRange, COVERAGE, formatC64Address, formatC64Byte, formatC64Range, inRanges, mergeRanges, prgOf, rangesWhere } from "../c64.ts";
11
+ import { COVERAGE_KINDS, DEFAULT_SPACE, inSpace, MEMORY_ROW, type CoverageKind, type Space } from "./schema.ts";
12
+ import { baseValue, coverageRuns, listPatches, listReleases, listSwitches, type StartScreenRow } from "./read.ts";
13
+ import { capturedColourRam } from "./start-screen.ts";
12
14
  import { sha256 } from "./text.ts";
13
15
  import { checkAddress, checkSpace, write, type Evidence, type OperandImage, type WriteContext } from "./write.ts";
14
16
 
@@ -180,6 +182,28 @@ function gained(before: Map<CoverageKind, Uint8Array>, after: Map<CoverageKind,
180
182
  return count;
181
183
  }
182
184
 
185
+ /** True at each address that a run executed: in RAM, in a ROM or in the I/O area. */
186
+ function executedIn(maps: Map<CoverageKind, Uint8Array>): (address: number) => boolean {
187
+ const executes = (["x", "rom-x", "io-x"] as const).map((kind) => maps.get(kind)!);
188
+ return (address) => executes.some((map) => map[address] === 1);
189
+ }
190
+
191
+ /** What one import did to the coverage of a space. */
192
+ export interface CoverageImport {
193
+ space: Space;
194
+ imported: string[];
195
+ replaced: string[];
196
+ known: string[];
197
+ /** The ranges of accesses that the coverage gained and lost, of all kinds. */
198
+ added: number;
199
+ removed: number;
200
+ /** At an address: gained when the runs now execute it and did not before, lost when they no longer execute it, else undefined. */
201
+ executeChange: (address: number) => ExecuteChange | undefined;
202
+ }
203
+
204
+ /** How an import changed what the runs execute at an address. */
205
+ export type ExecuteChange = "gained" | "lost";
206
+
183
207
  /**
184
208
  * Puts coverage maps into the coverage of a space. The knowledge keeps the
185
209
  * ranges of each map by its project path; the coverage of the space is the
@@ -193,7 +217,7 @@ export function addCoverage(
193
217
  db: DatabaseSync,
194
218
  context: WriteContext,
195
219
  request: { space?: Space; maps: CoverageMap[] },
196
- ): { revision: string | null; current: { space: Space; imported: string[]; replaced: string[]; known: string[]; added: number; removed: number } } {
220
+ ): { revision: string | null; current: CoverageImport } {
197
221
  checkSpace(request);
198
222
  const space = request.space ?? DEFAULT_SPACE;
199
223
  for (const map of request.maps) {
@@ -210,7 +234,15 @@ export function addCoverage(
210
234
  const fresh = hashed.filter((map) => !isKnown(map));
211
235
  const evidence: Evidence[] = [...(context.evidence ?? []), ...fresh.map((map): Evidence => ({ kind: "coverage", ref: map.name, sha256: map.sha256, ...(space === DEFAULT_SPACE ? {} : { space }) }))];
212
236
  return write(db, { ...context, evidence }, "coverage", (change) => {
213
- 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 };
237
+ const result: CoverageImport = {
238
+ space,
239
+ imported: fresh.map((map) => map.name),
240
+ replaced: fresh.filter((map) => latest.has(map.name) && latest.get(map.name) !== map.sha256).map((map) => map.name),
241
+ known: hashed.filter((map) => !fresh.includes(map)).map((map) => map.name),
242
+ added: 0,
243
+ removed: 0,
244
+ executeChange: () => undefined,
245
+ };
214
246
  if (fresh.length === 0) return result;
215
247
  // A revision for each import, also when the coverage does not change: the maps are its evidence.
216
248
  change.id();
@@ -228,6 +260,12 @@ export function addCoverage(
228
260
  const after = currentCoverage(db, space);
229
261
  result.added = gained(before, after);
230
262
  result.removed = gained(after, before);
263
+ // One value for each address: a lookup of a comment costs one read, also for many short ranges.
264
+ const was = executedIn(before);
265
+ const is = executedIn(after);
266
+ const changes = new Uint8Array(SIZE);
267
+ for (let address = 0; address < SIZE; address++) if (was(address) !== is(address)) changes[address] = is(address) ? 1 : 2;
268
+ result.executeChange = (address) => (changes[address] === 1 ? "gained" : changes[address] === 2 ? "lost" : undefined);
231
269
  return result;
232
270
  });
233
271
  }
@@ -281,19 +319,28 @@ export function coverageAccess(db: DatabaseSync | undefined, space: Space = DEFA
281
319
  };
282
320
  }
283
321
 
284
- /** The bytes of memory rows in address order, in 64 KiB, and the ranges that they fill: rows that touch are one range. */
322
+ /** The bytes of memory rows in 64 KiB, and the ranges that they fill: rows that touch are one range (mergeRanges). */
285
323
  function rowsImage(rows: ReadonlyArray<{ address: number; bytes: string }>): { segments: AddressRange[]; memory: Uint8Array } {
286
324
  const memory = new Uint8Array(SIZE);
287
- const segments: AddressRange[] = [];
288
- for (const row of rows) {
325
+ const ranges = rows.map((row) => {
289
326
  const bytes = Buffer.from(row.bytes, "hex");
290
327
  memory.set(bytes, row.address);
291
- const end = row.address + bytes.length - 1;
292
- const last = segments.at(-1);
293
- if (last !== undefined && last.end + 1 === row.address) last.end = end;
294
- else segments.push({ start: row.address, end });
295
- }
296
- return { segments, memory };
328
+ return { start: row.address, end: row.address + bytes.length - 1 };
329
+ });
330
+ return { segments: mergeRanges(ranges), memory };
331
+ }
332
+
333
+ /**
334
+ * True when an image holds the program of the knowledge: the same ranges and
335
+ * the same byte at each address. The knowledge keeps segments that touch as
336
+ * one range (rowsImage), so the segments of the image are joined in the same
337
+ * way before the compare.
338
+ */
339
+ export function isProgram(program: Pick<ProgramImage, "segments" | "byteAt">, image: Pick<ProgramImage, "segments" | "byteAt">): boolean {
340
+ return JSON.stringify(mergeRanges(image.segments)) === JSON.stringify(program.segments) && program.segments.every((segment) => {
341
+ for (let address = segment.start; address <= segment.end; address++) if (program.byteAt(address) !== image.byteAt(address)) return false;
342
+ return true;
343
+ });
297
344
  }
298
345
 
299
346
  /** The program of a space, or undefined when the knowledge has no bytes for it. */
@@ -312,12 +359,16 @@ export function programImage(db: DatabaseSync | undefined, space: Space = DEFAUL
312
359
  return image;
313
360
  }
314
361
 
362
+ /** The entry of the program of a space, without its bytes; undefined when the knowledge has none. */
363
+ export function programEntry(db: DatabaseSync | undefined, space: Space = DEFAULT_SPACE): number | undefined {
364
+ return (db?.prepare("SELECT address FROM current_entries WHERE space = ?").get(space) as { address: number } | undefined)?.address;
365
+ }
366
+
315
367
  /** The program of a space for a tool; refused with the way to put it in when the knowledge has none. */
316
368
  export function requireProgram(db: DatabaseSync | undefined, space: Space = DEFAULT_SPACE): ProgramImage {
317
369
  const image = programImage(db, space);
318
370
  if (image !== undefined) return image;
319
- const where = space === DEFAULT_SPACE ? "" : ` in ${space}`;
320
- throw new Refusal("not-found", `The knowledge has no program${where}. Put the program into the project knowledge${where}: a PRG, or the image.json of a capture.`);
371
+ throw new Refusal("not-found", `The knowledge has no program${inSpace(space)}. Put the program into the project knowledge${inSpace(space)}: a PRG, or the image.json of a capture.`);
321
372
  }
322
373
 
323
374
  /** The pages of an entry state: $0000-$03ff as the capture wrote them, 256 bytes as hex for each page. */
@@ -327,21 +378,26 @@ const STATE_PAGES = ["$0000", "$0100", "$0200", "$0300"] as const;
327
378
  * The memory that the program has at its entry: the segments, and below them
328
379
  * $0002-$03ff of the entry state (the zero page, the stack and the system
329
380
  * pages hold code and data that the loader left). $0000 and $0001 are the
330
- * CPU port, not memory. A segment byte wins over a state byte.
381
+ * CPU port, not memory. A segment byte wins over a state byte. `segments`
382
+ * are the ranges that hold these bytes, and `fromState` the ranges of the
383
+ * state pages in them: none when the state has no page. The analyzers read
384
+ * this memory, and the listing of the knowledge shows it.
331
385
  */
332
- function entryMemory(image: ProgramImage): Uint8Array {
386
+ export function entryMemory(image: ProgramImage): Pick<ProgramImage, "segments" | "memory" | "byteAt"> & { fromState: AddressRange[] } {
333
387
  const memory = new Uint8Array(image.memory);
388
+ const fromState: AddressRange[] = [];
334
389
  const pages = image.state?.pages;
335
- if (typeof pages !== "object" || pages === null) return memory;
336
390
  STATE_PAGES.forEach((page, index) => {
337
- const hex = (pages as Record<string, unknown>)[page];
391
+ const hex = typeof pages === "object" && pages !== null ? (pages as Record<string, unknown>)[page] : undefined;
338
392
  if (typeof hex !== "string" || !/^(?:[0-9a-fA-F]{2}){1,256}$/.test(hex)) return;
339
- Buffer.from(hex, "hex").forEach((byte, offset) => {
393
+ const bytes = Buffer.from(hex, "hex");
394
+ bytes.forEach((byte, offset) => {
340
395
  const address = index * 0x100 + offset;
341
396
  if (address >= 2 && !inRanges(image.segments, address)) memory[address] = byte;
342
397
  });
398
+ if (index * 0x100 + bytes.length > 2) fromState.push({ start: Math.max(index * 0x100, 2), end: index * 0x100 + bytes.length - 1 });
343
399
  });
344
- return memory;
400
+ return { segments: mergeRanges([...image.segments, ...fromState]), fromState: mergeRanges(fromState), memory, byteAt: (address) => memory[address]! };
345
401
  }
346
402
 
347
403
  /**
@@ -354,7 +410,30 @@ export function analyzedBytes(image: ProgramImage): { bytes: Buffer; kind: "prg"
354
410
  const [segment] = image.segments;
355
411
  return { bytes: prgOf(segment!.start, image.memory.subarray(segment!.start, segment!.end + 1)), kind: "prg" };
356
412
  }
357
- return { bytes: Buffer.from(entryMemory(image)), kind: "flat64k" };
413
+ return { bytes: Buffer.from(entryMemory(image).memory), kind: "flat64k" };
414
+ }
415
+
416
+ /**
417
+ * The key of a start screen of a captured stage: a hash of what the bytes of
418
+ * its show stage are made from. These are the fields of the start screen (not
419
+ * its comment), the bytes of the program of the stage, the code of each patch
420
+ * there whose switch default is not its base value, the colour RAM of the
421
+ * capture when the start screen takes its colours from it, and with a call
422
+ * the coverage of the stage. A name, a comment or a module of the stage does
423
+ * not change it. Another key means that a show stage of the source is not of
424
+ * this start screen.
425
+ */
426
+ export function startScreenKey(db: DatabaseSync | undefined, row: StartScreenRow): string {
427
+ const stage = row.stage!;
428
+ const hash = createHash("sha256").update(JSON.stringify([row.space, row.mode, row.screen, row.bitmap, row.charset, row.colours, row.colour, row.border, row.background, stage, row.call, row.colourRam]));
429
+ const image = programImage(db, stage);
430
+ for (const segment of image?.segments ?? []) hash.update(JSON.stringify([segment.start, segment.end])).update(image!.memory.subarray(segment.start, segment.end + 1));
431
+ const base = listReleases(db, undefined, stage).find((release) => release.base)?.label;
432
+ const changed = new Set(listSwitches(db, undefined, stage).filter((item) => item.default !== baseValue(item, base)).map((item) => item.name));
433
+ hash.update(JSON.stringify(listPatches(db, undefined, undefined, undefined, stage).filter((patch) => changed.has(patch.switch)).map((patch) => [patch.start, patch.end, patch.code])));
434
+ if (row.colourRam === true) hash.update(capturedColourRam(image?.state) ?? new Uint8Array());
435
+ if (row.call !== undefined) hash.update(programCoverage(db, stage)?.map ?? new Uint8Array());
436
+ return hash.digest("hex").slice(0, 16);
358
437
  }
359
438
 
360
439
  /**
@@ -415,7 +494,7 @@ const PATCH_LINE_BYTES = 8;
415
494
  export function releaseCode(db: DatabaseSync | undefined, label: string, start: number, end: number, space: Space = DEFAULT_SPACE): string {
416
495
  const range = formatC64Range({ start, end });
417
496
  const release = db?.prepare("SELECT base FROM current_releases WHERE space = ? AND label = ?").get(space, label) as { base: number } | undefined;
418
- if (release === undefined) throw new Refusal("not-found", `There is no release ${label}${space === DEFAULT_SPACE ? "" : ` in ${space}`}. Record it first with its file.`);
497
+ if (release === undefined) throw new Refusal("not-found", `There is no release ${label}${inSpace(space)}. Record it first with its file.`);
419
498
  if (release.base === 1) throw new Refusal("invalid-input", `${label} is the base release: its bytes are the program, and a patch holds the bytes of the other state. Give the release that has the other bytes in ${range}.`);
420
499
  const image = releaseImage(db, label, space)!;
421
500
  for (let address = start; address <= end; address++) {
@@ -132,6 +132,12 @@ export const DEFAULT_SPACE: Space = "c64";
132
132
  /** The space of a request: the C64 when it names none. */
133
133
  export const spaceOf = (request: { space?: Space }): Space => request.space ?? DEFAULT_SPACE;
134
134
 
135
+ /** A space other than the C64 in a message: " in <space>". */
136
+ export const inSpace = (space: Space): string => (space === DEFAULT_SPACE ? "" : ` in ${space}`);
137
+
138
+ /** The option of a command for a space other than the C64 in a message: " --space <space>". */
139
+ export const spaceOption = (space: Space): string => (space === DEFAULT_SPACE ? "" : ` --space ${space}`);
140
+
135
141
  /** The order of the spaces: the C64, the drive, the loading, then the banks by number. */
136
142
  export const spaceOrder = (space: Space): number => (space === "c64" ? -3 : space === "drive8" ? -2 : space === "loading" ? -1 : Number(space.slice(4)));
137
143
  const SPACE_CHECK = "space IN ('c64', 'drive8', 'loading') OR space GLOB 'bank[0-9]' OR space GLOB 'bank[1-9][0-9]' OR space GLOB 'bank[12][0-9][0-9]'";
@@ -1,12 +1,65 @@
1
1
  // The start screen of a captured stage, from the entry state of its capture:
2
2
  // the VIC-II registers and the VIC bank give the mode and the addresses, and
3
3
  // the colour RAM of the capture gives the colours. Thus the start screen of a
4
- // stage needs no address from the user.
4
+ // stage needs no address from the user. Also the values that the start screen
5
+ // code of a generated loader gets from a start screen of the knowledge.
5
6
 
6
- import { d018Offsets, formatC64Byte, vicBankBase } from "../c64.ts";
7
+ import { formatC64Address, formatC64Byte, vicScreenMemory } from "../c64.ts";
7
8
  import { Refusal } from "../errors.ts";
9
+ import { isRomFont, type StartScreenRow } from "./read.ts";
8
10
  import { LEFTOVERS_SWITCH, START_SCREEN_SWITCH, type StartScreenMode } from "./schema.ts";
9
11
 
12
+ /** The file of the start screen code in the generated source. */
13
+ export const START_SCREEN_FILE = "start_screen.asm";
14
+
15
+ /** The VIC-II values of a start screen, as the start screen code sets them. */
16
+ export interface StartScreenPlan {
17
+ d011: number;
18
+ d016: number;
19
+ d018: number;
20
+ /** The VIC bank: 0 for $0000-$3fff to 3 for $c000-$ffff. */
21
+ bank: number;
22
+ border: number;
23
+ background: number;
24
+ /** 0: no colour RAM (hires), 1: one colour, 2: a copy of 1000 bytes. */
25
+ colourMode: 0 | 1 | 2;
26
+ }
27
+
28
+ /** The VIC-II values that show a start screen of the knowledge. */
29
+ export function startScreenPlan(row: StartScreenRow): StartScreenPlan {
30
+ const bank = row.screen >> 14;
31
+ const base = (row.bitmap === undefined ? ((row.charset! & 0x3fff) >> 11) << 1 : ((row.bitmap & 0x3fff) >> 13) << 3) | 0x01;
32
+ return {
33
+ d011: row.mode === "text" ? 0x1b : 0x3b,
34
+ d016: row.mode === "multicolour" ? 0x18 : 0x08,
35
+ d018: (((row.screen & 0x3fff) >> 10) << 4) | base,
36
+ bank,
37
+ border: row.border,
38
+ background: row.background,
39
+ colourMode: row.colours !== undefined || row.colourRam === true ? 2 : row.colour !== undefined ? 1 : 0,
40
+ };
41
+ }
42
+
43
+ /** The lines of loader.asm or of the show stage that give the start screen code its values. */
44
+ export function startScreenValues(row: StartScreenRow, plan: StartScreenPlan): string[] {
45
+ const value = (name: string, number: number, comment?: string) => `c64_source_ss_${name} = ${formatC64Byte(number)}${comment === undefined ? "" : ` ; ${comment}`}`;
46
+ const font = row.charset !== undefined && isRomFont(row.charset) ? " (the character ROM)" : "";
47
+ const what = [`screen ${formatC64Address(row.screen)}`, ...(row.bitmap === undefined ? [] : [`bitmap ${formatC64Address(row.bitmap)}`]), ...(row.charset === undefined ? [] : [`charset ${formatC64Address(row.charset)}${font}`])];
48
+ return [
49
+ `; The start screen: ${row.mode}, ${what.join(", ")}.${row.comment === undefined ? "" : ` ${row.comment.replace(/\s*\r?\n\s*/g, " ")}`}`,
50
+ value("d011", plan.d011),
51
+ value("d016", plan.d016),
52
+ value("d018", plan.d018),
53
+ value("bank", 3 - plan.bank, `VIC bank ${formatC64Address(plan.bank << 14)}-${formatC64Address((plan.bank << 14) + 0x3fff)}`),
54
+ value("border", plan.border),
55
+ value("background", plan.background),
56
+ value("colour_mode", plan.colourMode),
57
+ value("colour", row.colour ?? 0),
58
+ // The colour RAM of a captured stage is in the show code: STAGE_COLOURS in src/stage.ts.
59
+ `c64_source_ss_colours = ${row.colourRam === true ? "c64_source_stage_colours" : formatC64Address(row.colours ?? 0)}`,
60
+ ];
61
+ }
62
+
10
63
  /** 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. */
11
64
  export const START_SCREEN_WAIT = "loader_start_screen_wait";
12
65
  export const START_SCREEN_CONTINUE = "loader_start_screen_continue";
@@ -70,18 +123,15 @@ function vicScreen(state: Record<string, unknown> | undefined, named: Named): Om
70
123
  const vic = ioBytes(state, "vic");
71
124
  const cia2 = ioBytes(state, "cia2");
72
125
  if (state === undefined || vic === undefined || vic.length < 0x2f || cia2 === undefined) throw new Refusal("not-found", `${named.program} has no entry state with the VIC-II and CIA 2. ${named.again}`);
73
- const [d011, d016, d018] = [vic[0x11]!, vic[0x16]!, vic[0x18]!];
126
+ const [d011, d016] = [vic[0x11]!, vic[0x16]!];
74
127
  if ((d011 & 0x10) === 0) throw new Refusal("invalid-input", `${named.capture} has the display off ($d011 = ${formatC64Byte(d011)}). ${named.again}`);
75
128
  if ((d011 & 0x40) !== 0) throw new Refusal("invalid-input", `${named.capture} shows a screen in the extended colour mode, which a start screen does not have.`);
76
129
  const bitmap = (d011 & 0x20) !== 0;
77
130
  const multicolour = (d016 & 0x10) !== 0;
78
131
  if (!bitmap && multicolour) throw new Refusal("invalid-input", `${named.capture} shows a multicolour text screen, which a start screen does not have.`);
79
- const bank = vicBankBase(cia2[0]!, cia2[2]);
80
- const offsets = d018Offsets(d018);
81
132
  return {
82
133
  mode: bitmap ? (multicolour ? "multicolour" : "hires") : "text",
83
- screen: bank + offsets.screen,
84
- ...(bitmap ? { bitmap: bank + offsets.bitmap } : { charset: bank + offsets.characters }),
134
+ ...vicScreenMemory(vic, cia2),
85
135
  border: vic[0x20]! & 0x0f,
86
136
  background: vic[0x21]! & 0x0f,
87
137
  };
@@ -52,7 +52,7 @@ import {
52
52
  type SwitchRow,
53
53
  type SymbolRow,
54
54
  } from "./read.ts";
55
- import { CODE_REGION_TYPES, COMMENT_PLACEMENTS, EVIDENCE_KINDS, MAX_ELEMENT, MEMORY_ROW, MODULE_FILE, DEFAULT_SPACE, spaceOf, GENERATED_FILES, GENERATED_FOLDERS, isGeneratedFile, isSemantic, MACRO_NAME, MACRO_PARAM, OFF_KINDS, RELEASE_DEFINE, RELEASE_LABEL, LEFTOVERS_SWITCH, START_SCREEN_MODES, START_SCREEN_SWITCH, SWITCH_KINDS, SWITCH_NAME, NO_ELEMENT_TYPES, POINTER_KIND, REGION_TYPES, SYMBOL_KINDS, type CommentPlacement, type EvidenceKind, type Origin, type RegionType, type Space, type StartScreenMode, type SwitchKind, type SymbolKind } from "./schema.ts";
55
+ import { CODE_REGION_TYPES, COMMENT_PLACEMENTS, EVIDENCE_KINDS, MAX_ELEMENT, MEMORY_ROW, MODULE_FILE, DEFAULT_SPACE, spaceOf, inSpace, spaceOption, GENERATED_FILES, GENERATED_FOLDERS, isGeneratedFile, isSemantic, MACRO_NAME, MACRO_PARAM, OFF_KINDS, RELEASE_DEFINE, RELEASE_LABEL, LEFTOVERS_SWITCH, START_SCREEN_MODES, START_SCREEN_SWITCH, SWITCH_KINDS, SWITCH_NAME, NO_ELEMENT_TYPES, POINTER_KIND, REGION_TYPES, SYMBOL_KINDS, type CommentPlacement, type EvidenceKind, type Origin, type RegionType, type Space, type StartScreenMode, type SwitchKind, type SymbolKind } from "./schema.ts";
56
56
  import { newRevisionId, rowId, sqlName, TABLES, tableSpec } from "./text.ts";
57
57
 
58
58
  type Raw = Record<string, unknown>;
@@ -94,8 +94,10 @@ export interface WriteResult<T, P = never> {
94
94
  }
95
95
 
96
96
  const MAX_COMMENT = 4000;
97
- /** The most characters of patch code and of a macro body. */
97
+ /** The most characters of a macro body, and of the code of a patch of a small range. */
98
98
  const MAX_CODE = 8000;
99
+ /** The most characters of patch code for each byte of its range, when that is more than MAX_CODE: the bytes of a release as !byte lines (releaseCode) need less than 5. */
100
+ const CODE_PER_BYTE = 8;
99
101
  /** The most parameters of a macro. */
100
102
  const MAX_PARAMS = 16;
101
103
  const MAX_EVIDENCE_REF = 1000;
@@ -813,7 +815,11 @@ function checkSwitchName(name: unknown, what = "A switch name"): void {
813
815
  function checkPatch(request: PatchRequest): void {
814
816
  checkRange(request);
815
817
  checkSwitchName(request.switch, "The switch of a patch");
816
- if (typeof request.code !== "string" || request.code.length > MAX_CODE) throw new Refusal("invalid-input", `Patch code has at most ${MAX_CODE} characters; empty code fills the range with NOP.`);
818
+ // The limit grows with the range: the bytes of a release fit a patch of any range.
819
+ const limit = Math.max(MAX_CODE, CODE_PER_BYTE * (request.end - request.start + 1));
820
+ if (typeof request.code !== "string" || request.code.length > limit) {
821
+ throw new Refusal("invalid-input", `The patch code of ${formatC64Range(request)} has at most ${limit} characters: ${MAX_CODE}, or ${CODE_PER_BYTE} for each byte of the range when that is more. Make the code shorter. Empty code fills the range with NOP.`);
822
+ }
817
823
  checkBraces(request.code, "The patch code");
818
824
  checkCommentText(request.comment, "A patch comment");
819
825
  }
@@ -870,7 +876,7 @@ function patchStep(db: DatabaseSync, change: Change, request: PatchRequest, cont
870
876
  throw new Refusal("invalid-input", `The patch code is at least ${least} bytes, and the range ${range} has ${length}. Make the code shorter, or make the range larger.`);
871
877
  }
872
878
  const owner = switchNamed(db, request.switch, space);
873
- if (owner === undefined) throw new Refusal("not-found", `There is no switch ${request.switch}. Write it first (switch ${request.switch} --kind <kind> --releases <labels>).`);
879
+ if (owner === undefined) throw new Refusal("not-found", `There is no switch ${request.switch}${inSpace(space)}. Write it first (switch ${request.switch} --kind <kind> --releases <labels>${spaceOption(space)}).`);
874
880
  // A write at the start of a patch of the same switch changes that patch. Another switch can have the same range: an alternative.
875
881
  const mine = (row: PatchRow) => row.start === request.start && row.switch === request.switch;
876
882
  const other = patchesOverlapping(db, request.start, request.end, space).find((row) => !mine(row) && (row.start !== request.start || row.end !== request.end || row.switch === request.switch));
@@ -962,10 +968,10 @@ function defaultOf(request: SwitchRequest, existing: SwitchRow | undefined): 0 |
962
968
  function switchStep(db: DatabaseSync, change: Change, request: SwitchRequest, context: StepContext): Step<SwitchRow, SwitchRow> {
963
969
  const space = spaceOf(request);
964
970
  const base = baseLabel(db, space);
965
- if (base === undefined) throw new Refusal("not-found", "The knowledge has no base release. Record the release whose bytes are the program first (release <label> --file <file> --base).");
971
+ if (base === undefined) throw new Refusal("not-found", `The knowledge has no base release${inSpace(space)}. Record the release whose bytes are the program${inSpace(space)} first (release <label> --file <file> --base${spaceOption(space)}).`);
966
972
  const existing = switchNamed(db, request.name, space);
967
973
  const releases = [...new Set(request.releases ?? existing?.releases ?? [])].sort();
968
- for (const label of releases) if (releaseLabeled(db, label, space) === undefined) throw new Refusal("not-found", `There is no release ${label}. Record it first (release ${label} --file <file>).`);
974
+ for (const label of releases) if (releaseLabeled(db, label, space) === undefined) throw new Refusal("not-found", `There is no release ${label}${inSpace(space)}. Record it first (release ${label} --file <file>${spaceOption(space)}).`);
969
975
  const value = defaultOf(request, existing);
970
976
  const comment = request.comment === undefined ? existing?.comment : request.comment.trim();
971
977
  const origin = context.origin as SwitchRow["origin"];
@@ -1003,7 +1009,8 @@ function unswitchStep(db: DatabaseSync, change: Change, request: InSpace & { nam
1003
1009
  * A release. `rows` are the bytes of a release other than the base release,
1004
1010
  * as memoryRows gives them: the address of each row and its bytes as hex. The
1005
1011
  * base release has no bytes of its own: its bytes are the program. `file` and
1006
- * `sha256` are the project file that the bytes come from and its SHA-256.
1012
+ * `sha256` are the project file of the release and its SHA-256: the PRG that
1013
+ * the bytes come from, or for a capture the program file that the capture ran.
1007
1014
  */
1008
1015
  type ReleaseRequest = InSpace & { label: string; base?: boolean; file?: string; sha256?: string; comment?: string; rows?: ReadonlyMap<number, string> };
1009
1016
 
@@ -1038,11 +1045,11 @@ function releaseStep(db: DatabaseSync, change: Change, request: ReleaseRequest,
1038
1045
  const sameBytes = held.length === wanted.size && held.every((row) => wanted.get(row.address) === row.bytes);
1039
1046
  if (existing !== undefined && existing.base === base && existing.comment === comment && sameFile && sameBytes && !confirms(existing.origin, origin)) return { current: existing };
1040
1047
  const other = baseLabel(db, space);
1041
- if (base && other !== undefined && other !== request.label) throw new Refusal("conflict", `The release ${other} is the base release. A space has one base release.`);
1048
+ if (base && other !== undefined && other !== request.label) throw new Refusal("conflict", `The release ${other} is the base release${inSpace(space)}. A space has one base release.`);
1042
1049
  // Every switch takes its base value from the base release: it cannot change under them.
1043
1050
  if ((existing?.base ?? false) !== base) {
1044
1051
  const switches = listSwitches(db, undefined, space);
1045
- if (switches.length > 0) throw new Refusal("conflict", `The base release decides the state of the program for the switches ${switches.map((row) => row.name).join(", ")}. Remove them first (unswitch) to change the base release.`);
1052
+ if (switches.length > 0) throw new Refusal("conflict", `The base release decides the state of the program for the switches ${switches.map((row) => row.name).join(", ")}. Remove them first (unswitch${spaceOption(space)}) to change the base release${inSpace(space)}.`);
1046
1053
  }
1047
1054
  const symbol = symbolNamed(db, `${RELEASE_DEFINE}${request.label}`, space);
1048
1055
  if (symbol !== undefined) throw new Refusal("conflict", `The build of the release defines ${RELEASE_DEFINE}${request.label}, and that is the name of the symbol at ${formatC64Address(symbol.address)}. Give the release another label.`);
@@ -1064,7 +1071,7 @@ function releaseStep(db: DatabaseSync, change: Change, request: ReleaseRequest,
1064
1071
  function unreleaseStep(db: DatabaseSync, change: Change, request: InSpace & { label: string }): Step<null> {
1065
1072
  const space = spaceOf(request);
1066
1073
  const existing = releaseLabeled(db, request.label, space);
1067
- if (existing === undefined) throw new Refusal("not-found", `There is no release ${request.label}.`);
1074
+ if (existing === undefined) throw new Refusal("not-found", `There is no release ${request.label}${inSpace(space)}.`);
1068
1075
  const switches = listSwitches(db, undefined, space).filter((row) => existing.base || row.releases.includes(request.label));
1069
1076
  if (switches.length > 0) {
1070
1077
  const why = existing.base ? "decides the state of the program for" : "is named by";
@@ -1522,10 +1529,10 @@ export function revert(db: DatabaseSync, context: WriteContext, request: { revis
1522
1529
  // The coverage maps that the knowledge has follow the revert, also when no coverage range changes.
1523
1530
  const maps = (runs: CoverageRun[]) => JSON.stringify(runs.filter((run) => only === undefined || run.space === only).map((run) => [run.name, run.sha256, run.space, run.revision]));
1524
1531
  if (maps(coverageRuns(db, restored)) !== maps(coverageRuns(db))) change.id();
1525
- const inSpace = only === undefined ? "" : " AND space = ?";
1532
+ const spaceWhere = only === undefined ? "" : " AND space = ?";
1526
1533
  const spaceArgs = only === undefined ? [] : [only];
1527
- const at = `valid_from_revision <= ? AND (valid_to_revision IS NULL OR valid_to_revision > ?)${inSpace}`;
1528
- const current = `valid_to_revision IS NULL${inSpace}`;
1534
+ const at = `valid_from_revision <= ? AND (valid_to_revision IS NULL OR valid_to_revision > ?)${spaceWhere}`;
1535
+ const current = `valid_to_revision IS NULL${spaceWhere}`;
1529
1536
  // A row is the same when all its values are the same.
1530
1537
  for (const spec of TABLES) {
1531
1538
  const columns = spec.fields.map((field) => field.column);