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

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 +23 -38
  3. package/skills/c64-assembler/scripts/assembler.ts +114 -16
  4. package/skills/c64-basic/SKILL.md +11 -31
  5. package/skills/c64-basic/scripts/basic.ts +4 -1
  6. package/skills/c64-development/SKILL.md +2 -2
  7. package/skills/c64-disk/SKILL.md +11 -32
  8. package/skills/c64-docs/SKILL.md +27 -45
  9. package/skills/c64-docs/references/page-types.md +20 -18
  10. package/skills/c64-docs/references/style.md +10 -4
  11. package/skills/c64-docs/scripts/docs.ts +13 -2
  12. package/skills/c64-docs/scripts/lib/reference.ts +47 -5
  13. package/skills/c64-knowledge/SKILL.md +138 -267
  14. package/skills/c64-knowledge/references/batches.md +48 -0
  15. package/skills/c64-knowledge/references/coverage.md +29 -0
  16. package/skills/c64-knowledge/references/source-knowledge.md +72 -0
  17. package/skills/c64-knowledge/references/start-screen.md +44 -0
  18. package/skills/c64-knowledge/scripts/knowledge.ts +266 -61
  19. package/skills/c64-knowledge/scripts/lib/check.ts +133 -0
  20. package/skills/c64-knowledge/scripts/lib/listing.ts +72 -8
  21. package/skills/c64-memory-map/SKILL.md +11 -32
  22. package/skills/c64-packer/SKILL.md +11 -31
  23. package/skills/c64-provenance/SKILL.md +40 -62
  24. package/skills/c64-provenance/scripts/lib/leftovers.ts +8 -3
  25. package/skills/c64-provenance/scripts/provenance.ts +64 -55
  26. package/skills/c64-reverse-engineering/SKILL.md +20 -47
  27. package/skills/c64-reverse-engineering/references/comment-check.md +42 -0
  28. package/skills/c64-reverse-engineering/references/versions.md +47 -0
  29. package/skills/c64-source/SKILL.md +43 -237
  30. package/skills/c64-source/references/export.md +50 -0
  31. package/skills/c64-source/references/loader.md +78 -0
  32. package/skills/c64-source/references/source-format.md +46 -0
  33. package/skills/c64-source/scripts/lib/export.ts +20 -7
  34. package/skills/c64-source/scripts/lib/loader.ts +4 -82
  35. package/skills/c64-source/scripts/source.ts +48 -51
  36. package/skills/c64-static-analysis/SKILL.md +51 -52
  37. package/skills/c64-static-analysis/scripts/lib/coverage.ts +55 -2
  38. package/skills/c64-static-analysis/scripts/lib/idioms.ts +28 -9
  39. package/skills/c64-static-analysis/scripts/static-analysis.ts +69 -15
  40. package/skills/c64-testing/SKILL.md +72 -58
  41. package/skills/c64-testing/references/recording-format.md +5 -80
  42. package/skills/c64-testing/references/scenario-format.md +4 -12
  43. package/skills/c64-testing/scripts/lib/play.ts +16 -8
  44. package/skills/c64-testing/scripts/lib/recording.ts +74 -9
  45. package/skills/c64-testing/scripts/lib/replay.ts +4 -0
  46. package/skills/c64-testing/scripts/lib/runs.ts +112 -1
  47. package/skills/c64-testing/scripts/lib/scenario.ts +12 -6
  48. package/skills/c64-testing/scripts/lib/start-screen.ts +27 -0
  49. package/skills/c64-testing/scripts/testing.ts +34 -13
  50. package/skills/c64-unpacker/SKILL.md +10 -30
  51. package/skills/emulator/SKILL.md +7 -36
  52. package/src/build-name.ts +12 -1
  53. package/src/knowledge/history.ts +8 -0
  54. package/src/knowledge/program.ts +73 -1
  55. package/src/knowledge/read.ts +46 -2
  56. package/src/knowledge/recording-files.ts +32 -0
  57. package/src/knowledge/schema.ts +3 -1
  58. package/src/knowledge/separate.ts +90 -3
  59. package/src/knowledge/start-screen.ts +99 -17
  60. package/src/knowledge/text.ts +2 -1
  61. package/src/knowledge/write.ts +15 -8
  62. package/src/loader.ts +167 -0
  63. package/src/native/decompiler/analyze.ts +7 -6
  64. package/src/native/decompiler/walk.ts +32 -2
  65. package/src/native/dxa.ts +4 -4
  66. package/src/native/types.ts +32 -4
  67. package/src/script.ts +87 -17
  68. package/skills/c64-export/SKILL.md +0 -63
@@ -114,11 +114,18 @@ export interface SwitchRow {
114
114
  revision: string;
115
115
  }
116
116
 
117
- /** A release of the program, and whether its bytes are the program of the knowledge. The bytes of another release are in release_memory. */
117
+ /**
118
+ * A release of the program, and whether its bytes are the program of the
119
+ * knowledge. The bytes of another release are in release_memory. `file` and
120
+ * `sha256` are the file that recorded the release and its SHA-256; a release
121
+ * of an earlier toolkit version has neither.
122
+ */
118
123
  export interface ReleaseRow {
119
124
  space: Space;
120
125
  label: string;
121
126
  base: boolean;
127
+ file?: string;
128
+ sha256?: string;
122
129
  comment?: string;
123
130
  origin: Extract<Origin, "user" | "llm">;
124
131
  revision: string;
@@ -199,7 +206,7 @@ export const MODULE_COLUMNS = "space, start_address, file, title, origin, valid_
199
206
  export const OPERAND_COLUMNS = "space, address, selector, symbol, offset, expression, origin, valid_from_revision";
200
207
  export const PATCH_COLUMNS = "space, start_address, end_address, switch_name, code, comment, origin, valid_from_revision";
201
208
  export const SWITCH_COLUMNS = "space, name, kind, default_value, releases, comment, origin, valid_from_revision";
202
- export const RELEASE_COLUMNS = "space, label, base, comment, origin, valid_from_revision";
209
+ export const RELEASE_COLUMNS = "space, label, base, file, sha256, comment, origin, valid_from_revision";
203
210
  export const MACRO_COLUMNS = "space, name, params, body, comment, origin, valid_from_revision";
204
211
  export const MACRO_USE_COLUMNS = "space, start_address, end_address, macro, args, origin, valid_from_revision";
205
212
  export const START_SCREEN_COLUMNS = "space, mode, screen, bitmap, charset, colours, colour, border, background, stage, call_address, colour_ram, comment, origin, valid_from_revision";
@@ -306,6 +313,8 @@ export function toRelease(row: Raw): ReleaseRow {
306
313
  origin: row.origin as ReleaseRow["origin"],
307
314
  revision: row.valid_from_revision as string,
308
315
  };
316
+ if (row.file !== null && row.file !== undefined) release.file = row.file as string;
317
+ if (row.sha256 !== null && row.sha256 !== undefined) release.sha256 = row.sha256 as string;
309
318
  if (row.comment !== null && row.comment !== undefined) release.comment = row.comment as string;
310
319
  return release;
311
320
  }
@@ -706,6 +715,41 @@ export function listReferences(db: DatabaseSync | undefined, range: AddressRange
706
715
  .filter((reference) => (kind === undefined || reference.kind === kind) && kept(origins)(reference));
707
716
  }
708
717
 
718
+ /** Where a reference goes, seen from a range: into it from outside, out of it, or with both ends inside it. */
719
+ export const REFERENCE_DIRECTIONS = ["in", "out", "inside"] as const;
720
+ export type ReferenceDirection = (typeof REFERENCE_DIRECTIONS)[number];
721
+
722
+ /** True for a reference that goes in the direction, seen from the range. */
723
+ export function goes(range: AddressRange, direction: ReferenceDirection): (row: Pick<ReferenceRow, "from" | "to">) => boolean {
724
+ const inside = (address: number) => address >= range.start && address <= range.end;
725
+ if (direction === "in") return (row) => inside(row.to) && !inside(row.from);
726
+ if (direction === "out") return (row) => inside(row.from) && !inside(row.to);
727
+ return (row) => inside(row.from) && inside(row.to);
728
+ }
729
+
730
+ /** The references counted by kind, and by target with the target that most references go to first. */
731
+ export function referenceCounts(rows: readonly ReferenceRow[]): { byKind: Partial<Record<ReferenceKind, number>>; byTarget: Array<{ to: number; count: number }> } {
732
+ const byKind: Partial<Record<ReferenceKind, number>> = {};
733
+ const targets = new Map<number, number>();
734
+ for (const row of rows) {
735
+ byKind[row.kind] = (byKind[row.kind] ?? 0) + 1;
736
+ targets.set(row.to, (targets.get(row.to) ?? 0) + 1);
737
+ }
738
+ const byTarget = [...targets].map(([to, count]) => ({ to, count })).sort((a, b) => b.count - a.count || a.to - b.to);
739
+ return { byKind, byTarget };
740
+ }
741
+
742
+ /** The regions counted by type, with their bytes in the range. */
743
+ export function regionCounts(rows: readonly RegionRow[], range: AddressRange = ALL): Partial<Record<RegionType, { count: number; bytes: number }>> {
744
+ const counts: Partial<Record<RegionType, { count: number; bytes: number }>> = {};
745
+ for (const row of rows) {
746
+ const item = (counts[row.type] ??= { count: 0, bytes: 0 });
747
+ item.count++;
748
+ item.bytes += Math.min(row.end, range.end) - Math.max(row.start, range.start) + 1;
749
+ }
750
+ return counts;
751
+ }
752
+
709
753
  /** Current suppressions whose place lies in the range: a reference by its source or target. */
710
754
  export function listSuppressions(db: DatabaseSync | undefined, range: AddressRange = ALL, space: Space = DEFAULT_SPACE): SuppressionRow[] {
711
755
  if (db === undefined) return [];
@@ -0,0 +1,32 @@
1
+ // The files of a recording folder: the record of a session writes them, and the
2
+ // knowledge takes the coverage map of the folder. They are here, so the
3
+ // script that records and the script that keeps the knowledge share one list.
4
+
5
+ import { existsSync, statSync } from "node:fs";
6
+ import { join } from "node:path";
7
+
8
+ import { Refusal } from "../errors.ts";
9
+ import { projectRoot, resolveReadFile } from "../project.ts";
10
+
11
+ export const RECORDING_FILES = { recording: "recording.json", reads: "reads.txt", coverage: "coverage.bin" } as const;
12
+
13
+ /**
14
+ * The coverage map that a path names: the path itself, or for a recording
15
+ * folder the coverage map in it (<folder>/coverage.bin). The knowledge names a
16
+ * map by this path, so a new recording into the same folder replaces the map.
17
+ * A path that is no folder, or that does not exist, is given back as it is:
18
+ * the read of the map refuses it.
19
+ */
20
+ export function coverageMapOf(path: string, root = projectRoot()): string {
21
+ let real: string;
22
+ try {
23
+ real = resolveReadFile(path, root);
24
+ } catch {
25
+ return path;
26
+ }
27
+ if (!statSync(real).isDirectory()) return path;
28
+ if (!existsSync(join(real, RECORDING_FILES.coverage)) || !existsSync(join(real, RECORDING_FILES.recording))) {
29
+ throw new Refusal("not-found", `${path} is a folder that holds no recording. Give a coverage map, or a folder that a record of a session wrote.`);
30
+ }
31
+ return `${path.replace(/\/+$/, "")}/${RECORDING_FILES.coverage}`;
32
+ }
@@ -302,6 +302,8 @@ function createSchema(db: DatabaseSync): void {
302
302
  space TEXT NOT NULL DEFAULT 'c64' CHECK (${SPACE_CHECK}),
303
303
  label TEXT NOT NULL CHECK (length(label) > 0),
304
304
  base INTEGER NOT NULL CHECK (base IN (0, 1)),
305
+ file TEXT CHECK (file IS NULL OR length(file) > 0),
306
+ sha256 TEXT CHECK (sha256 IS NULL OR length(sha256) = 64),
305
307
  comment TEXT CHECK (comment IS NULL OR length(comment) > 0),
306
308
  origin TEXT NOT NULL CHECK (origin IN ('user', 'llm')),
307
309
  valid_from_revision TEXT NOT NULL REFERENCES revisions (id),
@@ -423,7 +425,7 @@ function createSchema(db: DatabaseSync): void {
423
425
  }
424
426
 
425
427
  /** The version of the index this build makes. An index with another version is emptied and made again. */
426
- export const INDEX_VERSION = 15;
428
+ export const INDEX_VERSION = 16;
427
429
 
428
430
  function indexVersion(db: DatabaseSync): number | undefined {
429
431
  const hasMeta = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'meta'").get();
@@ -3,7 +3,9 @@
3
3
  // region of knowledge, whether call and jump references or the run on from
4
4
  // its last instruction reach it from a root (the entry, and the NMI, RESET
5
5
  // and IRQ vectors at $fffa-$ffff when the image holds them); and what the program reads
6
- // or executes outside the image. Evidence only: nothing here decides which
6
+ // or executes outside the image. A region that nothing reaches is unknown, not
7
+ // dead, while the program has a flow whose targets the knowledge does not give,
8
+ // or when no coverage shows what ran. Evidence only: nothing here decides which
7
9
  // bytes the publisher shipped.
8
10
 
9
11
  import { type AddressRange, COVERAGE, executedRamCode, instructionLength } from "../c64.ts";
@@ -21,6 +23,8 @@ export interface SeparationInput {
21
23
  coverage?: Uint8Array;
22
24
  codeRegions: Array<AddressRange & { type: string }>;
23
25
  references: Array<{ from: number; to: number; kind: string }>;
26
+ /** The instructions with a reference of the user or the LLM from them: the LLM recorded the targets of their flows. */
27
+ resolvedSites?: ReadonlySet<number>;
24
28
  /** More roots after the entry and the hardware vectors, for example code that a run executed. */
25
29
  roots?: Root[];
26
30
  }
@@ -37,6 +41,18 @@ export interface CodeRegionEvidence extends AddressRange {
37
41
  reachable?: boolean;
38
42
  /** Absent without coverage. */
39
43
  executed?: boolean;
44
+ /** Not reached and not executed, but an unresolved flow can go there, or no coverage shows that it did not run. */
45
+ unknown?: true;
46
+ }
47
+
48
+ /**
49
+ * A flow whose targets the knowledge does not give: a JMP (indirect) through
50
+ * a vector that a run wrote or that is not in the image, or a JMP or JSR whose
51
+ * address bytes a run wrote.
52
+ */
53
+ export interface UnresolvedFlow {
54
+ at: number;
55
+ kind: "indirect-jump" | "written-operand";
40
56
  }
41
57
 
42
58
  /** An address where the reachability starts, and why: the entry, a hardware vector in the image, or a root that the caller gives. */
@@ -57,6 +73,8 @@ export interface Separation {
57
73
  * pieces of code with gaps of up to two operand bytes.
58
74
  */
59
75
  outside: { read: AddressRange[]; executed: AddressRange[]; generated: AddressRange[] };
76
+ /** The unresolved flows of the code regions: while one exists, an unreached code region is unknown. */
77
+ unresolved: UnresolvedFlow[];
60
78
  }
61
79
 
62
80
  const SYSTEM_PAGES_END = 0x03ff;
@@ -97,6 +115,73 @@ export function fallThrough(region: AddressRange, memory: Uint8Array): number |
97
115
  return NO_FALL_THROUGH.has(memory[last]!) || at > 0xffff ? undefined : at;
98
116
  }
99
117
 
118
+ /** The instruction starts of code regions: each region runs from its start, one instruction after the other. */
119
+ export function regionStarts(regions: readonly AddressRange[], memory: Uint8Array): number[] {
120
+ const starts: number[] = [];
121
+ for (const region of regions) for (let at = region.start; at <= region.end; at += instructionLength(memory[at]!)) starts.push(at);
122
+ return starts.sort((a, b) => a - b);
123
+ }
124
+
125
+ /**
126
+ * The vectors that the program sets with its own immediates: an LDA, LDX or
127
+ * LDY # and a store to N, and the same to N + 1, in one run of instructions.
128
+ * A JMP (N) then goes where those immediates point, which the flows of the
129
+ * stores give.
130
+ */
131
+ export function immediateVectors(starts: readonly number[], memory: Uint8Array): Set<number> {
132
+ const stored = new Set<number>();
133
+ let registers: { a?: number | undefined; x?: number | undefined; y?: number | undefined } = {};
134
+ let previousEnd = -2;
135
+ for (const at of [...starts].sort((a, b) => a - b)) {
136
+ if (at > previousEnd + 1) registers = {};
137
+ const opcode = memory[at]!;
138
+ const length = instructionLength(opcode);
139
+ previousEnd = at + length - 1;
140
+ const operand = length === 3 ? memory[at + 1]! | (memory[(at + 2) & 0xffff]! << 8) : memory[(at + 1) & 0xffff]!;
141
+ const store = (value: number | undefined) => {
142
+ if (value !== undefined) stored.add(operand);
143
+ };
144
+ switch (opcode) {
145
+ case 0xa9: registers.a = operand; break;
146
+ case 0xa2: registers.x = operand; break;
147
+ case 0xa0: registers.y = operand; break;
148
+ case 0x85: case 0x8d: store(registers.a); break;
149
+ case 0x86: case 0x8e: store(registers.x); break;
150
+ case 0x84: case 0x8c: store(registers.y); break;
151
+ case 0xaa: registers.x = registers.a; break;
152
+ case 0xa8: registers.y = registers.a; break;
153
+ case 0x8a: registers.a = registers.x; break;
154
+ case 0x98: registers.a = registers.y; break;
155
+ default: registers = {};
156
+ }
157
+ if (NO_FALL_THROUGH.has(opcode)) registers = {};
158
+ }
159
+ return new Set([...stored].filter((address) => stored.has((address + 1) & 0xffff)));
160
+ }
161
+
162
+ /**
163
+ * The unresolved flows of the instructions at `starts`. A flow is resolved
164
+ * when a reference of the user or the LLM goes from it. An indirect jump is
165
+ * also resolved when the program's own immediates set its vector, or when the
166
+ * vector is in the image and no run wrote it.
167
+ */
168
+ export function unresolvedFlows(input: { starts: readonly number[]; memory: Uint8Array; inImage: (address: number) => boolean; coverage?: Uint8Array | undefined; resolvedSites?: ReadonlySet<number> | undefined }): UnresolvedFlow[] {
169
+ const written = (address: number) => input.coverage !== undefined && (input.coverage[address & 0xffff]! & COVERAGE.ramWrite) !== 0;
170
+ const vectors = immediateVectors(input.starts, input.memory);
171
+ const flows: UnresolvedFlow[] = [];
172
+ for (const at of input.starts) {
173
+ if (input.resolvedSites?.has(at) === true) continue;
174
+ const opcode = input.memory[at]!;
175
+ if (opcode === 0x6c) {
176
+ const vector = input.memory[(at + 1) & 0xffff]! | (input.memory[(at + 2) & 0xffff]! << 8);
177
+ if (vectors.has(vector)) continue;
178
+ if (input.inImage(vector) && input.inImage((vector + 1) & 0xffff) && !written(vector) && !written(vector + 1)) continue;
179
+ flows.push({ at, kind: "indirect-jump" });
180
+ } else if ((opcode === 0x4c || opcode === 0x20) && (written(at + 1) || written(at + 2))) flows.push({ at, kind: "written-operand" });
181
+ }
182
+ return flows;
183
+ }
184
+
100
185
  /** The most instructions outside the code regions that the run on from a region goes through, for example an instruction in a dual-use region. */
101
186
  const MAX_RUN_ON = 16;
102
187
 
@@ -190,13 +275,15 @@ export function separate(input: SeparationInput): Separation {
190
275
  queue.push(to);
191
276
  }
192
277
  }
278
+ const unresolved = unresolvedFlows({ starts: regionStarts(regions, input.memory), memory: input.memory, inImage, coverage: input.coverage, resolvedSites: input.resolvedSites });
193
279
  const codeRegions = regions.map((region, index): CodeRegionEvidence => {
194
280
  let ran: boolean | undefined;
195
281
  if (input.coverage !== undefined) {
196
282
  ran = false;
197
283
  for (let address = region.start; address <= region.end && !ran; address++) ran = executed[address] === 1;
198
284
  }
199
- return { start: region.start, end: region.end, type: region.type, ...(roots.length === 0 ? {} : { reachable: reached.has(index) }), ...(ran === undefined ? {} : { executed: ran }) };
285
+ const unreached = roots.length > 0 && !reached.has(index) && ran !== true;
286
+ return { start: region.start, end: region.end, type: region.type, ...(roots.length === 0 ? {} : { reachable: reached.has(index) }), ...(ran === undefined ? {} : { executed: ran }), ...(unreached && (unresolved.length > 0 || input.coverage === undefined) ? { unknown: true as const } : {}) };
200
287
  });
201
288
 
202
289
  const read: number[] = [];
@@ -216,5 +303,5 @@ export function separate(input: SeparationInput): Separation {
216
303
  for (let address = from + 1; address < to; address++) if (inImage(address)) return false;
217
304
  return true;
218
305
  };
219
- return { roots, ranges, codeRegions, outside: { read: merge(read), executed: merge(ranOutside), generated: merge(generated, 2, outsideImage) } };
306
+ return { roots, ranges, codeRegions, outside: { read: merge(read), executed: merge(ranOutside), generated: merge(generated, 2, outsideImage) }, unresolved };
220
307
  }
@@ -4,7 +4,7 @@
4
4
  // stage needs no address from the user.
5
5
 
6
6
  import { Refusal } from "../errors.ts";
7
- import type { StartScreenMode } from "./schema.ts";
7
+ import { LEFTOVERS_SWITCH, START_SCREEN_SWITCH, type StartScreenMode } from "./schema.ts";
8
8
 
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";
@@ -12,6 +12,21 @@ export const START_SCREEN_CONTINUE = "loader_start_screen_continue";
12
12
  /** The label of the loader's jump to the entry, in ACME's symbol list. */
13
13
  export const LOADER_JUMP = "c64_source_loader_jump";
14
14
 
15
+ /**
16
+ * The wait and the code after the wait of the start screen that a build shows,
17
+ * from the symbols of the build; undefined when the build shows none. A build
18
+ * with START_SCREEN = 0 or LEFTOVERS = 1 has both labels but skips the screen
19
+ * (the start screen code of the generated source). A symbol file without the
20
+ * constants is a build with the default values: the screen is on.
21
+ */
22
+ export function startScreenLabels(symbols: ReadonlyMap<string, number>): { wait: number; continue: number } | undefined {
23
+ const wait = symbols.get(START_SCREEN_WAIT);
24
+ const resume = symbols.get(START_SCREEN_CONTINUE);
25
+ if (wait === undefined || resume === undefined) return undefined;
26
+ if ((symbols.get(START_SCREEN_SWITCH) ?? 1) === 0 || (symbols.get(LEFTOVERS_SWITCH) ?? 0) !== 0) return undefined;
27
+ return { wait, continue: resume };
28
+ }
29
+
15
30
  /** The fields of a start screen that the capture of a stage gives. */
16
31
  export interface StageScreen {
17
32
  mode: StartScreenMode;
@@ -37,34 +52,101 @@ export function capturedColourRam(state: Record<string, unknown> | undefined): U
37
52
  return bytes === undefined || bytes.length !== 1000 ? undefined : Uint8Array.from(bytes, (value) => value & 0x0f);
38
53
  }
39
54
 
55
+ /** How a refusal names the capture: the program that has no entry state, the capture, and how to capture it again. */
56
+ interface Named {
57
+ program: string;
58
+ capture: string;
59
+ again: string;
60
+ }
61
+
40
62
  /**
41
- * The start screen that the capture of a stage shows: its mode, its screen,
42
- * its bitmap or charset, its colours and the colour RAM. Refuses by name when
43
- * the capture does not show a start screen that the loader can show.
63
+ * The screen that the VIC-II of an entry state shows: its mode, its screen, its
64
+ * bitmap or charset and its colours of the border and the background, from the
65
+ * VIC-II registers and the VIC bank of CIA 2. Refuses by name when the capture
66
+ * does not show a screen that the loader can show.
44
67
  */
45
- export function startScreenOfStage(state: Record<string, unknown> | undefined, stage: string): StageScreen {
46
- const again = `Capture the stage again while it shows the screen, and put the capture into the project knowledge with image --space ${stage}.`;
68
+ function vicScreen(state: Record<string, unknown> | undefined, named: Named): Omit<StageScreen, "colourRam"> {
47
69
  const vic = ioBytes(state, "vic");
48
70
  const cia2 = ioBytes(state, "cia2");
49
- if (state === undefined || vic === undefined || vic.length < 0x2f || cia2 === undefined) throw new Refusal("not-found", `The program in ${stage} has no entry state with the VIC-II and CIA 2. ${again}`);
71
+ 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}`);
50
72
  const [d011, d016, d018] = [vic[0x11]!, vic[0x16]!, vic[0x18]!];
51
- if ((d011 & 0x10) === 0) throw new Refusal("invalid-input", `The capture in ${stage} has the display off ($d011 = $${d011.toString(16).padStart(2, "0")}). ${again}`);
52
- if ((d011 & 0x40) !== 0) throw new Refusal("invalid-input", `The capture in ${stage} shows a screen in the extended colour mode, which a start screen does not have.`);
73
+ if ((d011 & 0x10) === 0) throw new Refusal("invalid-input", `${named.capture} has the display off ($d011 = $${d011.toString(16).padStart(2, "0")}). ${named.again}`);
74
+ if ((d011 & 0x40) !== 0) throw new Refusal("invalid-input", `${named.capture} shows a screen in the extended colour mode, which a start screen does not have.`);
53
75
  const bitmap = (d011 & 0x20) !== 0;
54
76
  const multicolour = (d016 & 0x10) !== 0;
55
- if (!bitmap && multicolour) throw new Refusal("invalid-input", `The capture in ${stage} shows a multicolour text screen, which a start screen does not have.`);
77
+ if (!bitmap && multicolour) throw new Refusal("invalid-input", `${named.capture} shows a multicolour text screen, which a start screen does not have.`);
56
78
  const bank = (3 - (cia2[0]! & 0x03)) << 14;
57
- const mode: StartScreenMode = bitmap ? (multicolour ? "multicolour" : "hires") : "text";
58
- const screen = bank + ((d018 >> 4) & 0x0f) * 0x400;
59
- const colourRam = mode === "hires" ? undefined : capturedColourRam(state);
60
- if (mode !== "hires" && colourRam === undefined) throw new Refusal("not-found", `The capture in ${stage} has no colour RAM: it is from an older version. ${again}`);
61
79
  return {
62
- mode,
63
- screen,
80
+ mode: bitmap ? (multicolour ? "multicolour" : "hires") : "text",
81
+ screen: bank + ((d018 >> 4) & 0x0f) * 0x400,
64
82
  ...(bitmap ? { bitmap: bank + ((d018 >> 3) & 1) * 0x2000 } : { charset: bank + ((d018 >> 1) & 7) * 0x800 }),
65
83
  border: vic[0x20]! & 0x0f,
66
84
  background: vic[0x21]! & 0x0f,
67
- ...(colourRam === undefined ? {} : { colourRam: true as const }),
68
85
  };
69
86
  }
70
87
 
88
+ /**
89
+ * The start screen that the capture of a stage shows: its mode, its screen,
90
+ * its bitmap or charset, its colours and the colour RAM. Refuses by name when
91
+ * the capture does not show a start screen that the loader can show.
92
+ */
93
+ export function startScreenOfStage(state: Record<string, unknown> | undefined, stage: string): StageScreen {
94
+ const again = `Capture the stage again while it shows the screen, and put the capture into the project knowledge with image --space ${stage}.`;
95
+ const shown = vicScreen(state, { program: `The program in ${stage}`, capture: `The capture in ${stage}`, again });
96
+ const colourRam = shown.mode === "hires" ? undefined : capturedColourRam(state);
97
+ if (shown.mode !== "hires" && colourRam === undefined) throw new Refusal("not-found", `The capture in ${stage} has no colour RAM: it is from an older version. ${again}`);
98
+ return { ...shown, ...(colourRam === undefined ? {} : { colourRam: true as const }) };
99
+ }
100
+
101
+ /** The bytes of the colour RAM. */
102
+ const COLOURS = 1000;
103
+
104
+ /**
105
+ * The first address of the program from $0400 where 1000 bytes hold the
106
+ * colours (the low 4 bits of each byte), outside $d000-$dfff, where the loader
107
+ * sees the I/O area. Undefined when the program has no such bytes.
108
+ */
109
+ export function findColours(colours: Uint8Array, byteAt: (address: number) => number | undefined): number | undefined {
110
+ for (let start = 0x0400; start + COLOURS - 1 <= 0xffff; start++) {
111
+ if (start <= 0xdfff && start + COLOURS - 1 >= 0xd000) continue;
112
+ let offset = 0;
113
+ while (offset < COLOURS) {
114
+ const byte = byteAt(start + offset);
115
+ if (byte === undefined || (byte & 0x0f) !== colours[offset]) break;
116
+ offset++;
117
+ }
118
+ if (offset === COLOURS) return start;
119
+ }
120
+ return undefined;
121
+ }
122
+
123
+ const CAPTURE_AGAIN = "Capture the program again while it shows the screen. Then give the image.json of that capture.";
124
+
125
+ /**
126
+ * The start screen in the program that a capture of the program shows: the
127
+ * mode, the addresses and the border and background colours from the VIC-II
128
+ * and CIA 2 of the capture. Refuses by name when the capture does not show a
129
+ * start screen that the loader can show.
130
+ */
131
+ export function startScreenOfCapture(state: Record<string, unknown> | undefined, path: string): Omit<StageScreen, "colourRam"> {
132
+ return vicScreen(state, { program: `The capture ${path}`, capture: `The capture ${path}`, again: CAPTURE_AGAIN });
133
+ }
134
+
135
+ /**
136
+ * The colour RAM of a capture as the program gives it: one colour, or the
137
+ * address of 1000 bytes that the program has (findColours). Refuses with the
138
+ * reason when the program cannot give the colours.
139
+ */
140
+ export function coloursOfCapture(state: Record<string, unknown> | undefined, path: string, byteAt: (address: number) => number | undefined): { colour: number } | { colours: number } {
141
+ const colours = capturedColourRam(state);
142
+ if (colours === undefined) throw new Refusal("not-found", `The capture ${path} has no colour RAM: it is from an older version. ${CAPTURE_AGAIN}`);
143
+ if (colours.every((colour) => colour === colours[0])) return { colour: colours[0]! };
144
+ const found = findColours(colours, byteAt);
145
+ if (found === undefined) {
146
+ throw new Refusal(
147
+ "not-found",
148
+ `The colour RAM of the capture ${path} has more than one colour, and the program of the knowledge has no 1000 bytes with these colours from $0400, outside $d000-$dfff. Thus the loader cannot set the colours. If a stage of the loading shows the screen, record the start screen of that stage.`,
149
+ );
150
+ }
151
+ return { colours: found };
152
+ }
@@ -172,11 +172,12 @@ export const TABLES: readonly TableSpec[] = [
172
172
  ],
173
173
  },
174
174
  // The releases of the program, and the one whose bytes are the program. The bytes of the other releases are in release_memory.jsonl.
175
+ // file and sha256 are the file that recorded the release and its SHA-256; a release of an earlier toolkit version has neither.
175
176
  {
176
177
  table: "releases",
177
178
  file: "releases.jsonl",
178
179
  sort: "label",
179
- fields: [space, field("label", "label", "text"), field("base", "base", "integer"), field("comment", "comment", "text", true), origin],
180
+ fields: [space, field("label", "label", "text"), field("base", "base", "integer"), field("file", "file", "text", true), field("sha256", "sha256", "text", true), field("comment", "comment", "text", true), origin],
180
181
  },
181
182
  {
182
183
  table: "macros",
@@ -281,8 +281,8 @@ export class Change {
281
281
 
282
282
  insertRelease(row: Omit<ReleaseRow, "revision">): void {
283
283
  this.#db
284
- .prepare("INSERT INTO releases (id, space, label, base, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?)")
285
- .run(this.#rowId(), row.space, row.label, row.base ? 1 : 0, row.comment ?? null, row.origin, this.id());
284
+ .prepare("INSERT INTO releases (id, space, label, base, file, sha256, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
285
+ .run(this.#rowId(), row.space, row.label, row.base ? 1 : 0, row.file ?? null, row.sha256 ?? null, row.comment ?? null, row.origin, this.id());
286
286
  }
287
287
 
288
288
  /** Bytes of a release other than the base release, as a memory row of the program holds them. */
@@ -1032,9 +1032,10 @@ function unswitchStep(db: DatabaseSync, change: Change, _origin: Origin, request
1032
1032
  /**
1033
1033
  * A release. `rows` are the bytes of a release other than the base release,
1034
1034
  * as memoryRows gives them: the address of each row and its bytes as hex. The
1035
- * base release has no bytes of its own: its bytes are the program.
1035
+ * base release has no bytes of its own: its bytes are the program. `file` and
1036
+ * `sha256` are the project file that the bytes come from and its SHA-256.
1036
1037
  */
1037
- type ReleaseRequest = InSpace & { label: string; base?: boolean; comment?: string; rows?: ReadonlyMap<number, string> };
1038
+ type ReleaseRequest = InSpace & { label: string; base?: boolean; file?: string; sha256?: string; comment?: string; rows?: ReadonlyMap<number, string> };
1038
1039
 
1039
1040
  function checkRelease(request: ReleaseRequest): void {
1040
1041
  checkSpace(request);
@@ -1046,6 +1047,8 @@ function checkRelease(request: ReleaseRequest): void {
1046
1047
  throw new Refusal("invalid-input", `The bytes of a release at ${formatC64Address(address & 0xffff)} are not a memory row.`);
1047
1048
  }
1048
1049
  }
1050
+ if (request.file !== undefined && (typeof request.file !== "string" || request.file.length === 0)) throw new Refusal("invalid-input", "The file of a release is a project path.");
1051
+ if (request.sha256 !== undefined && (typeof request.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(request.sha256))) throw new Refusal("invalid-input", "The SHA-256 of a release file is 64 lowercase hex digits.");
1049
1052
  checkCommentText(request.comment, "A release comment");
1050
1053
  }
1051
1054
 
@@ -1054,12 +1057,16 @@ function releaseStep(db: DatabaseSync, change: Change, origin: Origin, request:
1054
1057
  const existing = releaseLabeled(db, request.label, space);
1055
1058
  const base = request.base ?? existing?.base ?? false;
1056
1059
  const comment = request.comment === undefined ? existing?.comment : request.comment.trim();
1060
+ // A release that is recorded again without its file keeps the file that it has.
1061
+ const file = request.file ?? existing?.file;
1062
+ const sha256 = request.file === undefined ? existing?.sha256 : request.sha256;
1063
+ const sameFile = existing?.file === file && existing?.sha256 === sha256;
1057
1064
  const held = db.prepare("SELECT id, address, bytes FROM current_release_memory WHERE space = ? AND label = ?").all(space, request.label) as Array<{ id: string; address: number; bytes: string }>;
1058
1065
  // A release without new bytes keeps its bytes. The base release has none: its bytes are the program.
1059
1066
  const wanted = base ? new Map<number, string>() : (request.rows ?? new Map(held.map((row) => [row.address, row.bytes])));
1060
1067
  if (!base && wanted.size === 0) throw new Refusal("invalid-input", `The release ${request.label} has no bytes. Give the file of the release.`);
1061
1068
  const sameBytes = held.length === wanted.size && held.every((row) => wanted.get(row.address) === row.bytes);
1062
- if (existing !== undefined && existing.base === base && existing.comment === comment && sameBytes && !confirms(existing.origin, origin)) return { current: existing };
1069
+ if (existing !== undefined && existing.base === base && existing.comment === comment && sameFile && sameBytes && !confirms(existing.origin, origin)) return { current: existing };
1063
1070
  const other = baseLabel(db, space);
1064
1071
  if (base && other !== undefined && other !== request.label) throw new Refusal("conflict", `The release ${other} is the base release. A space has one base release.`);
1065
1072
  // Every switch takes its base value from the base release: it cannot change under them.
@@ -1069,9 +1076,9 @@ function releaseStep(db: DatabaseSync, change: Change, origin: Origin, request:
1069
1076
  }
1070
1077
  const symbol = symbolNamed(db, `${RELEASE_DEFINE}${request.label}`, space);
1071
1078
  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.`);
1072
- if (existing === undefined || existing.base !== base || existing.comment !== comment || confirms(existing.origin, origin)) {
1079
+ if (existing === undefined || existing.base !== base || existing.comment !== comment || !sameFile || confirms(existing.origin, origin)) {
1073
1080
  if (existing !== undefined) change.close("releases", "space = ? AND label = ?", space, request.label);
1074
- change.insertRelease({ space, label: request.label, base, ...(comment === undefined ? {} : { comment }), origin: origin as ReleaseRow["origin"] });
1081
+ change.insertRelease({ space, label: request.label, base, ...(file === undefined ? {} : { file }), ...(sha256 === undefined ? {} : { sha256 }), ...(comment === undefined ? {} : { comment }), origin: origin as ReleaseRow["origin"] });
1075
1082
  }
1076
1083
  // Only the rows that changed: a changed byte changes one short line of the text.
1077
1084
  const kept = new Set<number>();
@@ -1667,7 +1674,7 @@ const KEYS = {
1667
1674
  releases: {
1668
1675
  columns: RELEASE_COLUMNS,
1669
1676
  map: toRelease,
1670
- key: (row: ReleaseRow) => `${row.space}|${row.label}|${row.base}|${row.comment ?? ""}|${row.origin}`,
1677
+ key: (row: ReleaseRow) => `${row.space}|${row.label}|${row.base}|${row.file ?? ""}|${row.sha256 ?? ""}|${row.comment ?? ""}|${row.origin}`,
1671
1678
  },
1672
1679
  start_screens: {
1673
1680
  columns: START_SCREEN_COLUMNS,