@henols/c64-re-tools 2.2.1 → 2.3.0-rc.2

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 (43) hide show
  1. package/README.md +4 -3
  2. package/package.json +1 -1
  3. package/skills/c64-assembler/SKILL.md +4 -3
  4. package/skills/c64-assembler/scripts/assembler.ts +1 -1
  5. package/skills/c64-basic/SKILL.md +3 -3
  6. package/skills/c64-development/SKILL.md +9 -9
  7. package/skills/c64-disk/SKILL.md +2 -2
  8. package/skills/c64-docs/SKILL.md +2 -2
  9. package/skills/c64-knowledge/SKILL.md +1 -1
  10. package/skills/c64-memory-map/SKILL.md +2 -2
  11. package/skills/c64-packer/SKILL.md +109 -0
  12. package/skills/c64-packer/scripts/packer.ts +95 -0
  13. package/skills/c64-provenance/SKILL.md +18 -5
  14. package/skills/c64-provenance/scripts/lib/compare.ts +144 -16
  15. package/skills/c64-provenance/scripts/provenance.ts +37 -8
  16. package/skills/c64-reverse-engineering/SKILL.md +3 -3
  17. package/skills/c64-source/SKILL.md +23 -2
  18. package/skills/c64-source/scripts/lib/loader.ts +281 -43
  19. package/skills/c64-source/scripts/source.ts +37 -9
  20. package/skills/c64-static-analysis/SKILL.md +3 -3
  21. package/skills/c64-testing/SKILL.md +4 -4
  22. package/skills/c64-testing/scripts/lib/play.ts +4 -4
  23. package/skills/c64-testing/scripts/testing.ts +1 -1
  24. package/skills/c64-unpacker/SKILL.md +8 -8
  25. package/skills/c64-unpacker/scripts/lib/loads.ts +17 -4
  26. package/skills/c64-unpacker/scripts/unpacker.ts +15 -3
  27. package/skills/emulator/SKILL.md +137 -0
  28. package/src/cli/main.ts +1 -1
  29. package/{skills/c64-assembler/scripts/lib → src}/compare.ts +21 -3
  30. package/src/host-client/coverage.ts +26 -0
  31. package/src/mcp/output.ts +4 -4
  32. package/src/mcp/server.ts +7 -2
  33. package/src/mcp/tools/debug.ts +6 -3
  34. package/src/mcp/tools/execution.ts +1 -0
  35. package/src/mcp/tools/input.ts +1 -0
  36. package/src/mcp/tools/machine.ts +1 -1
  37. package/src/mcp/tools/media.ts +4 -2
  38. package/src/native/discover.ts +8 -0
  39. package/src/native/exomizer.ts +90 -0
  40. package/src/native/status.ts +3 -2
  41. package/tools/install-container.sh +2 -1
  42. package/tools/install-exomizer.sh +70 -0
  43. package/skills/c64-emulator/SKILL.md +0 -160
@@ -2,8 +2,10 @@
2
2
  // has bytes in one or more segments: a PRG at its load address plus an
3
3
  // optional shift, or the segments of an unpacker image. The comparison
4
4
  // covers the addresses where every release has bytes, and reports where the
5
- // releases differ and which releases agree there. It never decides which
6
- // bytes are original: that needs evidence beyond one comparison.
5
+ // releases differ and which releases agree there. For two releases with
6
+ // moved code, align maps the bytes of one to the other in blocks of equal
7
+ // bytes. It never decides which bytes are original: that needs evidence
8
+ // beyond one comparison.
7
9
 
8
10
  import { type AddressRange, formatC64Address } from "#src/c64.ts";
9
11
 
@@ -53,9 +55,13 @@ export function identicalShare(identical: number, differing: number): number {
53
55
 
54
56
  /** The ranges where every release has bytes, inside from..to. */
55
57
  export function commonRanges(releases: Release[], from = 0x0000, to = 0xffff): AddressRange[] {
58
+ return rangesOf(Array.from({ length: to - from + 1 }, (_, offset) => from + offset).filter((address) => releases.every((release) => covers(release, address))));
59
+ }
60
+
61
+ /** Consecutive addresses in order as ranges. */
62
+ function rangesOf(addresses: number[]): AddressRange[] {
56
63
  const ranges: AddressRange[] = [];
57
- for (let address = from; address <= to; address++) {
58
- if (!releases.every((release) => covers(release, address))) continue;
64
+ for (const address of addresses) {
59
65
  const last = ranges.at(-1);
60
66
  if (last !== undefined && last.end + 1 === address) last.end = address;
61
67
  else ranges.push({ start: address, end: address });
@@ -102,6 +108,24 @@ function addressesOf(release: Release): number[] {
102
108
  return release.segments.flatMap((segment) => Array.from({ length: segment.end - segment.start + 1 }, (_, offset) => segment.start + offset));
103
109
  }
104
110
 
111
+ /** The length of the byte sequences that find equal bytes in two releases. */
112
+ const WINDOW = 8;
113
+
114
+ const windowKey = (release: Release, addresses: number[], at: number) => String.fromCharCode(...addresses.slice(at, at + WINDOW).map((address) => release.byteAt(address)));
115
+
116
+ /** The addresses where each 8-byte sequence of `addresses` starts, at most 8 for each sequence. */
117
+ function indexWindows(release: Release, addresses: number[]): Map<string, number[]> {
118
+ const positions = new Map<string, number[]>();
119
+ for (let at = 0; at + WINDOW <= addresses.length; at++) {
120
+ const key = windowKey(release, addresses, at);
121
+ const found = positions.get(key);
122
+ // Very common sequences (fill bytes) say nothing about the alignment.
123
+ if (found === undefined) positions.set(key, [addresses[at]!]);
124
+ else if (found.length < 8) found.push(addresses[at]!);
125
+ }
126
+ return positions;
127
+ }
128
+
105
129
  /** Most shifts that suggestShifts gives: data that did not move can outvote code that did. */
106
130
  export const MAX_SUGGESTED_SHIFTS = 3;
107
131
 
@@ -111,21 +135,11 @@ export const MAX_SUGGESTED_SHIFTS = 3;
111
135
  * less than a tenth of the best one's votes is chance. Empty when nothing matches.
112
136
  */
113
137
  export function suggestShifts(base: Release, other: Release): Array<{ shift: number; matches: number }> {
114
- const WINDOW = 8;
115
- const key = (release: Release, addresses: number[], at: number) =>
116
- String.fromCharCode(...addresses.slice(at, at + WINDOW).map((address) => release.byteAt(address)));
117
- const baseAddresses = addressesOf(base);
138
+ const positions = indexWindows(base, addressesOf(base));
118
139
  const otherAddresses = addressesOf(other);
119
- const positions = new Map<string, number[]>();
120
- for (let at = 0; at + WINDOW <= baseAddresses.length; at++) {
121
- const found = positions.get(key(base, baseAddresses, at));
122
- // Very common sequences (fill bytes) say nothing about the alignment.
123
- if (found === undefined) positions.set(key(base, baseAddresses, at), [baseAddresses[at]!]);
124
- else if (found.length < 8) found.push(baseAddresses[at]!);
125
- }
126
140
  const votes = new Map<number, number>();
127
141
  for (let at = 0; at + WINDOW <= otherAddresses.length; at++) {
128
- for (const address of positions.get(key(other, otherAddresses, at)) ?? []) {
142
+ for (const address of positions.get(windowKey(other, otherAddresses, at)) ?? []) {
129
143
  const shift = address - otherAddresses[at]!;
130
144
  votes.set(shift, (votes.get(shift) ?? 0) + 1);
131
145
  }
@@ -134,6 +148,120 @@ export function suggestShifts(base: Release, other: Release): Array<{ shift: num
134
148
  return ranked.filter((found) => found.matches * 10 >= ranked[0]!.matches).slice(0, MAX_SUGGESTED_SHIFTS);
135
149
  }
136
150
 
151
+ export interface Block {
152
+ a: AddressRange;
153
+ b: AddressRange;
154
+ /** The address in b minus the address in a. */
155
+ shift: number;
156
+ bytes: number;
157
+ }
158
+
159
+ export interface Alignment {
160
+ /** In the order of their addresses in a. */
161
+ blocks: Block[];
162
+ /** The bytes of a that no block holds: removed in b. */
163
+ onlyInA: AddressRange[];
164
+ /** The bytes of b that no block holds: inserted in b. */
165
+ onlyInB: AddressRange[];
166
+ /** The share of the bytes of a and b in the range that a block holds, as identicalShare gives it. */
167
+ alignedShare: number;
168
+ }
169
+
170
+ /**
171
+ * Maps the bytes of `a` to the bytes of `b` in blocks of equal bytes, at least
172
+ * `minBlock` long, for releases with added code and moved data, where no one
173
+ * shift fits. Only the bytes inside `range` and the segments count. Each
174
+ * address of a that no block holds yet gets the longest block through it:
175
+ * from each address of b with the same 8 bytes, and from the shift of the
176
+ * block before. Then the longest blocks are kept with no byte of a or b in two
177
+ * blocks; a block that overlaps a kept one keeps its free parts. Blocks can
178
+ * cross: moved code changes the order.
179
+ */
180
+ export function align(a: Release, b: Release, range: AddressRange, minBlock: number): Alignment {
181
+ const inRange = (address: number) => address >= range.start && address <= range.end;
182
+ const aAddresses = addressesOf(a).filter(inRange);
183
+ const bAddresses = addressesOf(b).filter(inRange);
184
+ // -1 where the release has no byte; an index outside $0000-$ffff gives undefined.
185
+ const bytesOf = (release: Release, addresses: number[]) => {
186
+ const bytes = new Int16Array(0x10000).fill(-1);
187
+ for (const address of addresses) bytes[address] = release.byteAt(address);
188
+ return bytes;
189
+ };
190
+ const bytesA = bytesOf(a, aAddresses);
191
+ const bytesB = bytesOf(b, bAddresses);
192
+ const equal = (x: number, y: number) => {
193
+ const value = bytesA[x];
194
+ return value !== undefined && value >= 0 && value === bytesB[y];
195
+ };
196
+
197
+ type Found = { a: number; b: number; bytes: number };
198
+ const index = indexWindows(b, bAddresses);
199
+ const found: Found[] = [];
200
+ let covered = -1;
201
+ let lastShift: number | undefined;
202
+ for (let at = 0; at < aAddresses.length; at++) {
203
+ const p = aAddresses[at]!;
204
+ if (p <= covered) continue;
205
+ const candidates = at + WINDOW <= aAddresses.length ? [...(index.get(windowKey(a, aAddresses, at)) ?? [])] : [];
206
+ if (lastShift !== undefined) candidates.push(p + lastShift);
207
+ let best: Found | undefined;
208
+ for (const q of candidates) {
209
+ if (!equal(p, q)) continue;
210
+ let back = 0;
211
+ while (equal(p - back - 1, q - back - 1)) back++;
212
+ let forward = 1;
213
+ while (equal(p + forward, q + forward)) forward++;
214
+ if (best === undefined || back + forward > best.bytes) best = { a: p - back, b: q - back, bytes: back + forward };
215
+ }
216
+ if (best === undefined || best.bytes < minBlock) continue;
217
+ found.push(best);
218
+ covered = best.a + best.bytes - 1;
219
+ lastShift = best.b - best.a;
220
+ }
221
+
222
+ // The longest first; a piece that is left of an overlapping block goes back in its place in that order.
223
+ const before = (x: Found, y: Found) => y.bytes - x.bytes || Math.abs(x.b - x.a) - Math.abs(y.b - y.a) || x.a - y.a;
224
+ const queue = found.sort(before);
225
+ const usedA = new Uint8Array(0x10000);
226
+ const usedB = new Uint8Array(0x10000);
227
+ const kept: Found[] = [];
228
+ for (let next = 0; next < queue.length; next++) {
229
+ const block = queue[next]!;
230
+ const pieces: Found[] = [];
231
+ let start: number | undefined;
232
+ for (let offset = 0; offset <= block.bytes; offset++) {
233
+ if (offset < block.bytes && usedA[block.a + offset] === 0 && usedB[block.b + offset] === 0) start ??= offset;
234
+ else if (start !== undefined) {
235
+ pieces.push({ a: block.a + start, b: block.b + start, bytes: offset - start });
236
+ start = undefined;
237
+ }
238
+ }
239
+ if (pieces.length === 1 && pieces[0]!.bytes === block.bytes) {
240
+ kept.push(block);
241
+ usedA.fill(1, block.a, block.a + block.bytes);
242
+ usedB.fill(1, block.b, block.b + block.bytes);
243
+ continue;
244
+ }
245
+ for (const piece of pieces.filter((item) => item.bytes >= minBlock)) {
246
+ let place = next + 1;
247
+ while (place < queue.length && before(queue[place]!, piece) <= 0) place++;
248
+ queue.splice(place, 0, piece);
249
+ }
250
+ }
251
+
252
+ const alignedBytes = kept.reduce((sum, block) => sum + block.bytes, 0);
253
+ const onlyInA = rangesOf(aAddresses.filter((address) => usedA[address] === 0));
254
+ const onlyInB = rangesOf(bAddresses.filter((address) => usedB[address] === 0));
255
+ return {
256
+ blocks: kept
257
+ .sort((x, y) => x.a - y.a)
258
+ .map((block) => ({ a: { start: block.a, end: block.a + block.bytes - 1 }, b: { start: block.b, end: block.b + block.bytes - 1 }, shift: block.b - block.a, bytes: block.bytes })),
259
+ onlyInA,
260
+ onlyInB,
261
+ alignedShare: identicalShare(2 * alignedBytes, aAddresses.length + bAddresses.length - 2 * alignedBytes),
262
+ };
263
+ }
264
+
137
265
  export type ShiftSuggestion = { release: number; shift: number; matchingSequences: number } | { release: number; matchingSequences: number; reason: string };
138
266
 
139
267
  /**
@@ -43,7 +43,7 @@ import { platformNames } from "#src/platform.ts";
43
43
  import { projectRoot } from "#src/project.ts";
44
44
  import { knowledgeAt, knowledgeNames } from "#src/knowledge/names.ts";
45
45
  import { listed, OPTIONS, runScript, UsageError, type Call, type CommandSpec } from "#src/script.ts";
46
- import { compareReleases, identicalShare, shiftSuggestion, suggestShifts, type Release } from "./lib/compare.ts";
46
+ import { align, compareReleases, identicalShare, shiftSuggestion, suggestShifts, type Release } from "./lib/compare.ts";
47
47
  import { findRoutine, libraryFolder, readLibrary, routineFrom, saveRoutine, suggest } from "./lib/library.ts";
48
48
  import { watchRelease, type Start } from "./lib/runtime.ts";
49
49
  import { findLeftovers } from "./lib/leftovers.ts";
@@ -100,7 +100,10 @@ function readRelease(name: string, shift: number): LoadedRelease {
100
100
  };
101
101
  }
102
102
 
103
- /** compare: the releases byte by byte, and with --frames the first access of each difference in each release. */
103
+ /** Most blocks and ranges that a list of --align shows. */
104
+ const MAX_ALIGNED = 64;
105
+
106
+ /** compare: the releases byte by byte, with --align a map of two releases in blocks, and with --frames the first access of each difference in each release. */
104
107
  async function compare(call: Call): Promise<unknown> {
105
108
  const positionals = call.subjects;
106
109
  if (positionals.length < 2) throw new UsageError("compare needs two or more releases");
@@ -117,12 +120,40 @@ async function compare(call: Call): Promise<unknown> {
117
120
  const frames = call.count("frames");
118
121
  const stepsFile = call.string("steps");
119
122
  if (stepsFile !== undefined && frames === undefined) throw new UsageError("--steps works only with --frames");
123
+ const aligned = call.flag("align");
124
+ const minBlock = call.count("min-block");
125
+ if (minBlock !== undefined && !aligned) throw new UsageError("--min-block works only with --align");
126
+ if (aligned) {
127
+ if (shifts.size > 0) throw new UsageError("--align does not work with --shift: --align finds the shift of each block itself. Remove --shift");
128
+ if (frames !== undefined) throw new UsageError("--align does not work with --frames: --align gives no differences to run. Run --frames without --align");
129
+ if (positionals.length !== 2) throw new UsageError(`--align maps two releases, not ${positionals.length}. Give two releases`);
130
+ }
120
131
  const steps: ActionStep[] = stepsFile === undefined ? [] : readActionSteps(stepsFile, "--steps", knowledgeAt());
121
132
  const loaded = positionals.map((path, index) => readRelease(path, shifts.get(index + 1) ?? 0));
122
133
  const releases = loaded.map((item) => item.release);
123
134
  const range = call.range("range");
124
135
  const comparison = compareReleases(releases, range === undefined ? {} : { from: range.start, to: range.end });
125
136
  const share = identicalShare(comparison.identicalBytes, comparison.differingBytes);
137
+ const show = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
138
+ const compared = {
139
+ releases: loaded.map((item) => ({ name: item.release.name, shift: item.shift, segments: item.release.segments.map(show) })),
140
+ common: comparison.common.map(show),
141
+ identicalBytes: comparison.identicalBytes,
142
+ differingBytes: comparison.differingBytes,
143
+ identicalShare: share,
144
+ };
145
+ if (aligned) {
146
+ // Code added and data moved: one shift for the release cannot fit, so each block of equal bytes gets its own.
147
+ const alignment = align(releases[0]!, releases[1]!, range ?? { start: 0x0000, end: 0xffff }, minBlock ?? 16);
148
+ const capped = <T>(name: string, items: T[]) => ({ [name]: items.slice(0, MAX_ALIGNED), ...(items.length > MAX_ALIGNED ? { [`more${name[0]!.toUpperCase()}${name.slice(1)}`]: items.length - MAX_ALIGNED } : {}) });
149
+ return {
150
+ ...compared,
151
+ alignedShare: alignment.alignedShare,
152
+ ...capped("blocks", alignment.blocks.map((block) => ({ a: show(block.a), b: show(block.b), shift: block.shift, bytes: block.bytes }))),
153
+ ...capped("onlyInA", alignment.onlyInA.map(show)),
154
+ ...capped("onlyInB", alignment.onlyInB.map(show)),
155
+ };
156
+ }
126
157
  // A poor match at the load addresses can mean that the releases are placed differently.
127
158
  // Each release gets its best shifts: data that stayed can outvote code that moved, so one is not enough.
128
159
  const applied = loaded.map((item) => item.shift);
@@ -165,11 +196,7 @@ async function compare(call: Call): Promise<unknown> {
165
196
  }
166
197
 
167
198
  return {
168
- releases: loaded.map((item) => ({ name: item.release.name, shift: item.shift, segments: item.release.segments.map((segment) => ({ start: formatC64Address(segment.start), end: formatC64Address(segment.end) })) })),
169
- common: comparison.common.map((range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) })),
170
- identicalBytes: comparison.identicalBytes,
171
- differingBytes: comparison.differingBytes,
172
- identicalShare: share,
199
+ ...compared,
173
200
  differences: comparison.differences.map((difference, index) => ({
174
201
  start: formatC64Address(difference.start),
175
202
  end: formatC64Address(difference.end),
@@ -460,7 +487,7 @@ const LIBRARY = { kind: "text", value: "<folder>", required: true, help: "the li
460
487
  const COMMANDS: CommandSpec[] = [
461
488
  {
462
489
  name: "compare",
463
- summary: "Compares releases byte by byte, in their common ranges, and suggests shifts when they are placed differently.",
490
+ summary: "Compares releases byte by byte, in their common ranges, and suggests shifts when they are placed differently. With --align, maps two releases with moved code in blocks of equal bytes, each with its own shift.",
464
491
  subjects: [{ name: "<release>", help: "knowledge (the program in the knowledge), a PRG at its load address, or an image.json of the c64-unpacker skill with the entry_state.json beside it. Two or more", list: true }],
465
492
  options: {
466
493
  shift: {
@@ -472,6 +499,8 @@ const COMMANDS: CommandSpec[] = [
472
499
  example: (given) => `2:${given !== undefined && /^-\d+$/.test(given) ? given : "-256"}`,
473
500
  },
474
501
  range: { ...OPTIONS.range, help: "compare only the addresses from start to end" },
502
+ align: { kind: "flag", help: "map the first release to the second in blocks of equal bytes, each with its own shift, for releases with added code and moved data. Two releases; not with --shift or --frames" },
503
+ "min-block": { kind: "count", value: "<n>", min: 8, max: 0x10000, help: "with --align: the fewest bytes in a block (default 16)" },
475
504
  frames: { ...OPTIONS.frames, max: MAX_EXECUTION_COUNT, help: "run each release in its own emulator for n frames, and give each listed difference its first access and whether it changed" },
476
505
  steps: { ...OPTIONS.steps, help: "with --frames: action steps (JSON) to run before the frames" },
477
506
  },
@@ -72,7 +72,7 @@ Select the path for the scope:
72
72
  | The files on a disk image, or a file to extract | c64-disk |
73
73
  | A BASIC program, and where it starts machine code | c64-basic |
74
74
  | A program that can be packed or crunched | c64-unpacker |
75
- | What the program does at run time: values, input, timing, screen | c64-emulator |
75
+ | What the program does at run time: values, input, timing, screen | emulator |
76
76
  | The routines, code, data and references of the program | c64-static-analysis |
77
77
  | The platform meaning of an address or a register | c64-memory-map |
78
78
  | Differences between releases of the program | c64-provenance `compare`, then c64-knowledge `release`, `switch` and `patch` |
@@ -96,7 +96,7 @@ Do the stages in this sequence. Go to the next stage only when its exit check is
96
96
  | 2. Get | c64-disk: list the disk. Extract the start file into `original/`. | The start file is in the project. |
97
97
  | 3. Start | c64-basic: find the SYS address of the BASIC start. | You have the entry address. |
98
98
  | 4. Unpack | c64-unpacker: examine the program with `unpacker.ts inspect`, `trace` and `stages`. Capture a packed program with `unpacker.ts capture` into `.c64-re-tools/local/`. When a segment is the data of a cracktro and the program does not read it, capture again with `--exclude` for that range. Then c64-knowledge: put the capture, or the PRG of a program without a packer, into the knowledge with `knowledge.ts image`. | `program` of c64-knowledge shows the segments and the entry. |
99
- | 5. Run | First record: ask the user to play each part that the scope names, with `testing.ts record --play` of c64-testing. Tell the user which parts. Record a part yourself only when the sessions of the user do not have it. Put the recordings in `tests/recordings/`. Then use c64-emulator and `testing.ts run` of c64-testing for the parts that a recording cannot have. Write a coverage map for each part into `.c64-re-tools/local/`. Then c64-knowledge: add the maps and the `coverage.bin` of each recording with `knowledge.ts coverage`. | `program` of c64-knowledge lists a coverage map for each part that the scope names. |
99
+ | 5. Run | First record: ask the user to play each part that the scope names, with `testing.ts record --play` of c64-testing. Tell the user which parts. Record a part yourself only when the sessions of the user do not have it. Put the recordings in `tests/recordings/`. Then use the emulator skill and `testing.ts run` of c64-testing for the parts that a recording cannot have. Write a coverage map for each part into `.c64-re-tools/local/`. Then c64-knowledge: add the maps and the `coverage.bin` of each recording with `knowledge.ts coverage`. | `program` of c64-knowledge lists a coverage map for each part that the scope names. |
100
100
  | 6. Analyze | c64-static-analysis: `static-analysis.ts analyze`. It reads the program and the coverage from the knowledge. | No coverage conflict is open. |
101
101
  | 7. Name | c64-provenance: if the workspace has a library, find its routines with `provenance.ts match` and apply the batch. Then c64-knowledge and c64-memory-map: name each routine in the scope and give it a comment. Record the modules. When the scope has hundreds of routines, ask the user which routines to name. The source gives the other routines an `l_xxxx` label. | Each routine that the user selected has a name and a comment. |
102
102
  | 8. Releases and switches | c64-knowledge: record the base release with `knowledge.ts release <label> --file original/<file> --base`. For a capture, copy its folder to `original/<label>/` first, because git ignores `.c64-re-tools/local/`. Record each other release. c64-provenance: compare the releases with `provenance.ts compare`, and find leftovers with `provenance.ts leftovers`. c64-knowledge: record a switch for each copy protection, trainer, cheat, crack change and correction, and a patch for each of its ranges. Record each leftover as a region with a comment. | `knowledge.ts switches` lists each switch. Each difference between the releases is in a patch, or the answer gives it as an exception. |
@@ -179,7 +179,7 @@ A clear answer for the scope, with the durable conclusions in the project knowle
179
179
  - A tool gives a wrong result, and the exit check of a stage cannot be true. Tell the user the defect and the evidence, and wait for the user. Do not make a workaround, for example a change to a generated file. When the user accepts an exception, give the defect and the exception in the answer of stage 12.
180
180
  - If the evidence does not support a conclusion, keep the unknown and get more evidence. Do not make up a meaning.
181
181
  - Before you replace current knowledge from the user or the LLM, read its history and the evidence for it.
182
- - A conflict from the static analysis: find the correct answer at run time with the c64-emulator skill.
182
+ - A conflict from the static analysis: find the correct answer at run time with the emulator skill.
183
183
  - A test that is INCONCLUSIVE does not show a defect. Find why the test could not compare.
184
184
 
185
185
  ## Handoffs
@@ -140,6 +140,26 @@ The script simulates the copies first. Then it runs `loader.prg` in the emulator
140
140
 
141
141
  The entry state is the state of the base release. Thus the script builds and checks `loader.prg` with the switch values of the base release. For a loader of the default build, build `loader.asm` with the c64-assembler skill and no option.
142
142
 
143
+ ### The packed loader
144
+
145
+ A loader file that loads into $d000 or higher writes the I/O area. When the image is too large for one loader file, `loader.asm` has the packed form. The packed form needs Exomizer. It has these differences:
146
+
147
+ - `loader.asm` holds only the copier and the bytes below $0400: pages $0002-$03ff of the entry state and the parts of segments there. The copier is in one free range, at `loader.copier`. The bytes below $0400 go into free ranges. When one range is too small, they go into more ranges, and each piece is a copy. Between these ranges, `loader.asm` holds the bytes of the image. The segments at $0400 and higher are not in `loader.asm`.
148
+ - The script packs the build of `main.asm` from $0400 and the build of `loader.asm` into `loader.prg` with Exomizer. Where the two builds overlap, the bytes of `loader.asm` are in `loader.prg`.
149
+ - `10 SYS` starts the unpacker. The unpacker writes all bytes, also at $d000-$dfff. Then it jumps to the copier with all RAM visible ($01 = $34).
150
+ - The unpacker uses the zero page and $0334-$03ff. Thus the copier writes pages $0002-$03ff after the unpack. Then it does steps 4 to 6.
151
+ - The jump to the entry uses the address of the entry, not its label. The build of `loader.asm` does not include `main.asm`.
152
+
153
+ The script checks the unpack in the emulator of Exomizer. All bytes of the two builds must be correct, and the unpacker must jump to the copier. Then the script runs `loader.prg` in the emulator, as for the plain loader. `loader.packed` gives `packedBytes` and `unpackedBytes`.
154
+
155
+ To make the packed loader for other switch values, do these steps:
156
+
157
+ 1. Build the program with the c64-assembler skill: `assembler.ts build src main.asm --out build/main.prg`.
158
+ 2. Build the copier with the c64-assembler skill: `assembler.ts build src loader.asm --out build/copier.prg`.
159
+ 3. Pack the two files with the c64-packer skill: `packer.ts pack build/main.prg build/copier.prg --entry '$c000' --exit-memory '$34' --out build/loader.prg`. The comment at the start of `loader.asm` gives the `--entry` value.
160
+
161
+ These commands do not work when a segment starts below $0400. Then the build of `main.asm` has bytes in the area of the unpacker. They also do not work when a patch is between the ranges of `loader.asm`, because there `loader.asm` has the bytes of the image. In these cases, use `generate --loader` for the base release.
162
+
143
163
  ## Export for a new application
144
164
 
145
165
  `export` writes the program of the knowledge as the start of a new program: a new project folder and a zip file of it. A person changes the source of the new project directly. The c64-export skill gives the full procedure.
@@ -255,7 +275,7 @@ Do not store:
255
275
  - `switches`: the build of each switch that has patches. Each item has `kind`, `default`, `base`, the `define` for the c64-assembler skill and the patches. `result` is the result of the build with the switch at the value that is not `base`. `fits` tells that the build is good, and `changedBytes` counts the changed bytes. `overflow` tells that the code of a patch is longer than its range. `changes outside` gives the first byte outside the ranges that changed. `does not assemble` gives the diagnostics of ACME. `insideNames` lists the labels inside a patch. Code that writes to one of these labels changes the patch when the switch is on.
256
276
  - `default`: the default build. `in` lists the switches whose patches are in. `result` and `changedBytes` are as in `switches`.
257
277
  - `releases`: the build of each release. Each item has `label`, `base`, `file`, the `define` and the `result`. `identical` tells that the build gives the bytes of the file. `different` gives the segments that differ. `layout differs` tells that the release has other segments than the program: patches cannot move code, so this result does not fail the run. `file changed` tells that the file is not the file that the knowledge recorded. `does not assemble` gives the diagnostics of ACME.
258
- - `loader`: the program, the copies in their order, the copier page, `stackByte`, `verified` and `differences`. `limits` lists the CIA values that the loader cannot set. An entry state from an old capture has no CIA values. Then `limits` tells you to capture the program again. When the script cannot make the loader, `loader` has `verified: false` and a `reason`. The loader includes the source. Thus a source that does not assemble to the program also stops the loader.
278
+ - `loader`: the program, the copies in their order, the copier page, `stackByte`, `verified` and `differences`. A packed loader also has `packed` with `packedBytes` and `unpackedBytes`. `limits` lists the CIA values that the loader cannot set. An entry state from an old capture has no CIA values. Then `limits` tells you to capture the program again. When the script cannot make the loader, `loader` has `verified: false` and a `reason`. The loader includes the source. Thus a source that does not assemble to the program also stops the loader.
259
279
 
260
280
  `result` is `PASS` when the source is identical and the emulator check of the loader passes. `result` is `FAIL` for a failed check and for an entry in no segment. These also give `FAIL`:
261
281
 
@@ -282,8 +302,9 @@ Do not store:
282
302
  - `dataOnly`: this is not a failure. If the space has code, give `--entry` or classify the code with the c64-knowledge skill. Then generate again.
283
303
  - `entriesInData`: an analyzer region of data hides the code at the entry. If the entry is code, record a code region at the entry with the c64-knowledge skill, for example `classify '$0500-$05ff' code`. A region of the user or the LLM replaces the analyzer region. Then generate again.
284
304
  - `loader.verified: false` with a `reason`: the script did not make the loader. The script still writes and checks the source. When no copy order or no free pages exist, or the loader needs too many copies, the reason gives the ranges. Capture the program again with fewer segments, or write the loader by hand.
305
+ - `loader.verified: false` with a `reason` about the packed form: the image is too large for one loader file. If the reason tells that Exomizer is not installed, stop the task. Give the message to the user. If the free ranges are too small for the copier and the bytes below $0400, the reason gives the largest free ranges. Write the loader by hand. If the unpack check of Exomizer fails, give the reason to the user.
285
306
  - `loader.verified: false` with `differences`: the loader ran, and `differences` gives the bytes and registers that are not equal.
286
- - `loader.verified: false` with `stop`: the loader did not get to its copier or to its jump. `stop` gives the address where it stopped and `port`, the value of $01. `history` gives the last 16 instructions. `cause` gives the first byte of the copier that is not equal to its byte in the loader file. If the copier ran, `cause` can also give the first byte that a copy did not write correctly.
307
+ - `loader.verified: false` with `stop`: the loader did not get to its copier or to its jump. `stop` gives the address where it stopped and `port`, the value of $01. `history` gives the last 16 instructions. `cause` gives the first byte of the copier that is not equal to its byte in the loader file. For a packed loader, `cause` gives the first byte of the copier that the unpack did not write. If the copier ran, `cause` can also give the first byte that a copy did not write correctly.
287
308
  - `export` with `stage: "original"`: the source of the knowledge does not pass. Run `generate`, and correct the knowledge until `generate` gives PASS.
288
309
  - `export` with `stage: "switches"`: the build with the export values changes bytes outside the patches, or a patch does not fit. Read `build`. Correct the patches.
289
310
  - `export` refuses two switches that change one range: the export puts both alternatives in. Give all but one of them the kind `change` and the default of the base release with `switch` of the c64-knowledge skill.