@henols/c64-re-tools 2.6.0-rc.2 → 2.6.0-rc.20

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 (107) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-assembler/SKILL.md +28 -14
  3. package/skills/c64-assembler/scripts/assembler.ts +28 -15
  4. package/skills/c64-development/SKILL.md +4 -4
  5. package/skills/c64-docs/SKILL.md +9 -7
  6. package/skills/c64-docs/scripts/docs.ts +24 -11
  7. package/skills/c64-docs/scripts/lib/reference.ts +119 -33
  8. package/skills/c64-docs/scripts/lib/source-map.ts +23 -4
  9. package/skills/c64-knowledge/SKILL.md +67 -42
  10. package/skills/c64-knowledge/scripts/knowledge.ts +90 -67
  11. package/skills/c64-knowledge/scripts/lib/listing.ts +18 -3
  12. package/skills/c64-packer/SKILL.md +1 -1
  13. package/skills/c64-provenance/SKILL.md +11 -10
  14. package/skills/c64-provenance/scripts/lib/library.ts +16 -16
  15. package/skills/c64-provenance/scripts/provenance.ts +33 -23
  16. package/skills/c64-reverse-engineering/SKILL.md +17 -11
  17. package/skills/c64-source/SKILL.md +71 -47
  18. package/skills/c64-source/scripts/lib/export.ts +89 -34
  19. package/skills/c64-source/scripts/lib/loader.ts +79 -36
  20. package/skills/c64-source/scripts/lib/source.ts +38 -32
  21. package/skills/c64-source/scripts/lib/stage.ts +11 -5
  22. package/skills/c64-source/scripts/lib/start-screen.asm +4 -2
  23. package/skills/c64-source/scripts/source.ts +278 -145
  24. package/skills/c64-static-analysis/SKILL.md +29 -25
  25. package/skills/c64-static-analysis/scripts/lib/coverage.ts +2 -25
  26. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  27. package/skills/c64-static-analysis/scripts/lib/instructions.ts +26 -24
  28. package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
  29. package/skills/c64-static-analysis/scripts/static-analysis.ts +69 -67
  30. package/skills/c64-testing/SKILL.md +15 -5
  31. package/skills/c64-testing/references/recording-format.md +26 -5
  32. package/skills/c64-testing/references/scenario-format.md +11 -8
  33. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  34. package/skills/c64-testing/scripts/lib/play.ts +39 -41
  35. package/skills/c64-testing/scripts/lib/recording.ts +220 -46
  36. package/skills/c64-testing/scripts/lib/replay.ts +32 -6
  37. package/skills/c64-testing/scripts/lib/runs.ts +8 -3
  38. package/skills/c64-testing/scripts/lib/scenario.ts +18 -11
  39. package/skills/c64-testing/scripts/testing.ts +23 -2
  40. package/skills/c64-unpacker/SKILL.md +10 -5
  41. package/skills/c64-unpacker/scripts/lib/loads.ts +34 -13
  42. package/skills/c64-unpacker/scripts/lib/machine.ts +7 -3
  43. package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
  44. package/skills/c64-unpacker/scripts/unpacker.ts +43 -9
  45. package/skills/emulator/SKILL.md +7 -12
  46. package/src/build-name.ts +55 -0
  47. package/src/c64-keys.ts +98 -0
  48. package/src/c64.ts +22 -2
  49. package/src/cli/main.ts +3 -29
  50. package/src/host/main.ts +3 -3
  51. package/src/host/server.ts +3 -1
  52. package/src/host/tools/index.ts +2 -7
  53. package/src/host/vice/process.ts +34 -17
  54. package/src/host/vice/session.ts +138 -31
  55. package/src/host-client/steps.ts +21 -18
  56. package/src/host-client/tools.ts +2 -7
  57. package/src/host-client/vice-session.ts +7 -1
  58. package/src/knowledge/evidence.ts +66 -0
  59. package/src/knowledge/history.ts +5 -5
  60. package/src/knowledge/import.ts +12 -5
  61. package/src/knowledge/program.ts +123 -32
  62. package/src/knowledge/read.ts +36 -13
  63. package/src/knowledge/schema.ts +43 -17
  64. package/src/knowledge/start-screen.ts +70 -0
  65. package/src/knowledge/text.ts +33 -5
  66. package/src/knowledge/write.ts +75 -36
  67. package/src/mcp/inputs.ts +12 -0
  68. package/src/mcp/server.ts +1 -1
  69. package/src/mcp/tools/debug.ts +23 -21
  70. package/src/mcp/tools/input.ts +38 -5
  71. package/src/mcp/tools/machine.ts +3 -42
  72. package/src/mcp/tools/media.ts +1 -1
  73. package/src/mcp/tools/memory.ts +12 -9
  74. package/src/native/acme.ts +1 -1
  75. package/src/native/c64run.ts +7 -4
  76. package/src/native/decompiler/analyze.ts +98 -0
  77. package/src/native/decompiler/c64rt-wasm.ts +4 -0
  78. package/src/native/decompiler/language/c64rt_6510.sla +0 -0
  79. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  80. package/src/native/decompiler/pcode.ts +222 -0
  81. package/src/native/decompiler/walk.ts +205 -0
  82. package/src/native/decompiler/wasm.ts +98 -0
  83. package/src/native/discover.ts +3 -3
  84. package/src/native/dxa.ts +12 -1
  85. package/src/native/processes.ts +4 -4
  86. package/src/native/types.ts +27 -27
  87. package/src/opcodes.ts +1 -1
  88. package/src/platform.ts +30 -1
  89. package/src/project.ts +17 -4
  90. package/src/protocol/tools.ts +1 -45
  91. package/src/protocol/vice.ts +47 -0
  92. package/src/reference-pages.ts +64 -0
  93. package/src/script.ts +4 -4
  94. package/src/vsf.ts +98 -0
  95. package/tools/c64run.c +158 -15
  96. package/tools/install-container.sh +1 -2
  97. package/src/cli/status.ts +0 -127
  98. package/src/host/tools/status.ts +0 -47
  99. package/src/native/ghidra/analyze.ts +0 -87
  100. package/src/native/ghidra/index.ts +0 -170
  101. package/src/native/ghidra/scripts/C64Export.java +0 -274
  102. package/src/native/ghidra/scripts/C64Prepare.java +0 -66
  103. package/src/native/status.ts +0 -135
  104. package/tools/install-ghidra.sh +0 -40
  105. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  106. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  107. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
@@ -1,5 +1,5 @@
1
1
  // The c64-source script: generates ACME source from the program and the
2
- // knowledge and Ghidra's instructions, which it runs itself, and checks
2
+ // knowledge and the decompiler's instructions, which it runs itself, and checks
3
3
  // with ACME that the build of the base release assembles to the program byte
4
4
  // by byte. With --loader it also writes a loader that recreates the entry
5
5
  // state, simulates it, and checks it in the emulator. The default build may
@@ -11,30 +11,31 @@
11
11
 
12
12
  import { createHash } from "node:crypto";
13
13
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
14
- import { basename, join, relative, sep } from "node:path";
14
+ import { basename, dirname, join, relative, sep } from "node:path";
15
15
 
16
16
  import { isRefusal, Refusal } from "#src/errors.ts";
17
- import { type AddressRange, coverageSeedKinds, findHandoffs, formatC64Address, parseTokenized, textToPetscii } from "#src/c64.ts";
17
+ import { PACKAGE } from "#src/package.ts";
18
+ import { BUILD_DIRECTORY, buildName, symbolsPath } from "#src/build-name.ts";
19
+ import { type AddressRange, coverageSeedKinds, findHandoffs, formatC64Address, parseC64Address, parseTokenized, textToPetscii } from "#src/c64.ts";
18
20
  import { autostartLoaded, RUN_LIMIT_FRAMES } from "#src/host-client/autostart.ts";
19
21
  import { IO_RAM } from "#src/host-client/coverage.ts";
20
- import { readImage, type Image } from "#src/host-client/image.ts";
21
- import { readProjectFile } from "#src/host-client/transfer.ts";
22
22
  import { MAX_MEMORY_READ, WireFailure } from "#src/host-client/tools.ts";
23
23
  import { writeReported, type Written } from "#src/host-client/transfer.ts";
24
24
  import { ViceSessionClient } from "#src/host-client/vice-session.ts";
25
25
  import { conflicts } from "#src/knowledge/conflicts.ts";
26
26
  import { openForRead, withWrite } from "#src/knowledge/database.ts";
27
27
  import { identifiers } from "#src/knowledge/expression.ts";
28
- import { analyzedBytes, memoryRows, programCoverage, requireProgram, type ProgramImage } from "#src/knowledge/program.ts";
29
- import { ANALYZER_NAME_ORDER, baseValue, currentRevision, currentStartScreen, startScreenRanges, type StartScreenRow, listAnalyzerNames, listComments, listMacros, listMacroUses, listModules, listOperands, listPatches, listReferences, listRegions, listReleases, listSpaces, listSwitches, listSymbols, type ReleaseRow, type SymbolRow } from "#src/knowledge/read.ts";
30
- import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, LEFTOVERS_SWITCH, RELEASE_DEFINE, START_SCREEN_SWITCH, type Space } from "#src/knowledge/schema.ts";
28
+ import { analyzedBytes, memoryRows, programCoverage, releaseImage, requireProgram, type ProgramImage } from "#src/knowledge/program.ts";
29
+ import { ANALYZER_NAME_ORDER, baseValue, currentRevision, currentStartScreen, sourceRevision, startScreenRanges, type StartScreenRow, listAnalyzerNames, listComments, listMacros, listMacroUses, listModules, listOperands, listPatches, listReferences, listRegions, listReleases, listSpaces, listSwitches, listSymbols, type ReleaseRow, type SymbolRow } from "#src/knowledge/read.ts";
30
+ import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, LEFTOVER_FOLDER, LEFTOVERS_SWITCH, RELEASE_DEFINE, START_SCREEN_SWITCH, type Space } from "#src/knowledge/schema.ts";
31
31
  import { subtract, write } from "#src/knowledge/write.ts";
32
32
  import { assemble, symbolsFileText } from "#src/native/acme.ts";
33
- import { analyze } from "#src/native/ghidra/analyze.ts";
33
+ import { analyze } from "#src/native/decompiler/analyze.ts";
34
34
  import { localToolContext } from "#src/native/local.ts";
35
- import { GHIDRA_LIMITS, type AssembledSymbol, type Diagnostic } from "#src/native/types.ts";
36
- import { decode as decodeRegister, describeAddress, platformNames, platformNamesFor, romUseOfProgram } from "#src/platform.ts";
37
- import { ensureLocal, LOCAL_DIRECTORY, newProjectFolder, PROJECT_DIRECTORY, projectRoot, resolveProjectPath } from "#src/project.ts";
35
+ import { DECOMPILER_LIMITS, type AssembledSymbol, type Diagnostic } from "#src/native/types.ts";
36
+ import { decode as decodeRegister, describeAddress, platformNames, platformNamesFor, romRanges, romUseOfProgram } from "#src/platform.ts";
37
+ import { ensureLocal, generatedDirectory, LOCAL_DIRECTORY, newProjectFolder, PROJECT_DIRECTORY, projectRelative, projectRoot, resolveProjectPath } from "#src/project.ts";
38
+ import { generatedReferences } from "#src/reference-pages.ts";
38
39
  import { isoCet } from "#src/time.ts";
39
40
  import { zipFiles } from "#src/zip.ts";
40
41
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type Reply } from "#src/script.ts";
@@ -49,6 +50,7 @@ import {
49
50
  startScreenPlan,
50
51
  rasterLine,
51
52
  loaderState,
53
+ loaderSymbols,
52
54
  simulate,
53
55
  START_SCREEN_CODE,
54
56
  START_SCREEN_CONTINUE,
@@ -62,9 +64,10 @@ import {
62
64
  type StartScreenPlan,
63
65
  } from "./lib/loader.ts";
64
66
  import { instructionWith, OPCODES } from "#src/opcodes.ts";
67
+ import { capturedColourRam } from "#src/knowledge/start-screen.ts";
65
68
  import { planStage, STAGE_CODE_END, STAGE_FILE, STAGE_START, stageParts, stageText, type StageInput, type StagePart, type StagePlan } from "./lib/stage.ts";
66
69
  import { freeName, planDrops, readmeText, rewriteTest } from "./lib/export.ts";
67
- import { CONFIG_FILE, configText, configValues, entriesInData, entryOutsideImage, hasConfigFile, hasSwitchFile, layout, literalOperand, probeForms, render, switchesOf, type Layout, type PatchBlock, type Rendered, type SourceSwitch } from "./lib/source.ts";
70
+ import { CONFIG_FILE, configText, configValues, entriesInData, entryOutsideImage, hasConfigFile, hasSwitchFile, layout, literalOperand, probeForms, render, stagePatchText, switchesOf, type Layout, type PatchBlock, type Rendered, type SourceSwitch } from "./lib/source.ts";
68
71
 
69
72
  /** At most this many diagnostics or differences of one check. */
70
73
  const MAX_DIAGNOSTICS = 20;
@@ -91,8 +94,11 @@ function readKnowledge(space: Space, analyzerNames = false) {
91
94
  const second = listAnalyzerNames(db, undefined, undefined, undefined, space);
92
95
  const releases = listReleases(db, undefined, space);
93
96
  const base = releases.find((release) => release.base)?.label;
97
+ const startScreen = space === DEFAULT_SPACE ? currentStartScreen(db, space) : undefined;
94
98
  return {
95
99
  revision: currentRevision(db),
100
+ // The source and its loader hold the program of this space and the stage of its start screen: a change elsewhere does not change them.
101
+ sourceRevision: sourceRevision(db, space),
96
102
  program: requireProgram(db, space),
97
103
  // The coverage of the space: a run of the C64, or of a captured stage that coverage put into that space.
98
104
  coverage: programCoverage(db, space)?.map,
@@ -106,11 +112,12 @@ function readKnowledge(space: Space, analyzerNames = false) {
106
112
  operands: listOperands(db, undefined, undefined, space),
107
113
  patches: listPatches(db, undefined, undefined, undefined, space),
108
114
  switches: listSwitches(db, undefined, space).map((row): SourceSwitch => ({ name: row.name, kind: row.kind, default: row.default, base: baseValue(row, base), releases: row.releases, ...(row.comment === undefined ? {} : { comment: row.comment }) })),
109
- releases,
115
+ // Each release with its bytes: the check builds it and compares the build with them.
116
+ releases: releases.map((release) => ({ ...release, image: releaseImage(db, release.label, space)! })),
110
117
  macros: listMacros(db, undefined, space),
111
118
  macroUses: listMacroUses(db, undefined, undefined, undefined, space),
112
119
  // The start screen is of the C64 program: the loader shows it.
113
- startScreen: space === DEFAULT_SPACE ? currentStartScreen(db, space) : undefined,
120
+ startScreen,
114
121
  };
115
122
  } finally {
116
123
  db?.close();
@@ -122,7 +129,7 @@ type SourceKnowledge = ReturnType<typeof readKnowledge>;
122
129
 
123
130
  /**
124
131
  * The names of the user and the LLM, and for each address without one the
125
- * first analyzer name in the order heuristic, Ghidra, DXA. An analyzer
132
+ * first analyzer name in the order heuristic, decompiler, DXA. An analyzer
126
133
  * name that another address has already is left out. The analyzer names keep
127
134
  * their origin, so a platform name still wins over them.
128
135
  */
@@ -141,12 +148,20 @@ function withAnalyzerNames(symbols: SymbolRow[], second: SymbolRow[]): SymbolRow
141
148
  return [...symbols, ...added].sort((a, b) => a.address - b.address);
142
149
  }
143
150
 
151
+ /** Where the CPU sees ROM in the image (romRanges): the entry, the routines, the code regions and `entries` stay code. */
152
+ function romOf(image: ProgramImage, knowledge: Pick<SourceKnowledge, "routines" | "regions">, entries: readonly number[], coverage: Uint8Array | undefined): AddressRange[] {
153
+ const inImage = (address: number) => image.segments.some((segment) => address >= segment.start && address <= segment.end);
154
+ const code = knowledge.regions.filter((region) => CODE_REGION_TYPES.includes(region.type) || region.type === "dual-use").map((region) => region.start);
155
+ const known = [...(image.entry === undefined ? [] : [image.entry]), ...entries, ...knowledge.routines, ...code];
156
+ return romRanges(coverage, image.state, (address) => (inImage(address) ? image.byteAt(address) : undefined), known);
157
+ }
158
+
144
159
  /**
145
- * Ghidra's instruction starts and lengths inside the image, seeded from the
160
+ * The decompiler's instruction starts and lengths inside the image, seeded from the
146
161
  * entry, from knowledge of any origin, and from the coverage: a run's flow
147
162
  * starts, also after a JSR, so code that an analyzer does not reach by itself
148
163
  * is in the source. A program without a seed has no known code: it is data
149
- * only, and Ghidra does not run.
164
+ * only, and the decompiler does not run.
150
165
  */
151
166
  async function decode(image: ProgramImage, knowledge: Pick<SourceKnowledge, "routines" | "regions">, entries: number[], coverage: Uint8Array | undefined): Promise<{ instructions: Map<number, number>; dataOnly: boolean }> {
152
167
  const inImage = (address: number) => image.segments.some((segment) => address >= segment.start && address <= segment.end);
@@ -166,12 +181,14 @@ async function decode(image: ProgramImage, knowledge: Pick<SourceKnowledge, "rou
166
181
  const dataRanges = knowledge.regions
167
182
  .filter((region) => !CODE_REGION_TYPES.includes(region.type) && region.type !== "dual-use")
168
183
  .flatMap((region) => image.segments.filter((segment) => region.start <= segment.end && segment.start <= region.end).map((segment) => ({ start: Math.max(region.start, segment.start), end: Math.min(region.end, segment.end) })));
184
+ // A JSR into ROM runs the ROM: the RAM bytes of the image under it are data, not the code of the call.
185
+ for (const range of romOf(image, knowledge, entries, coverage)) if (!dataRanges.some((data) => range.start <= data.end && data.start <= range.end)) dataRanges.push(range);
169
186
  const { result } = await analyze(
170
187
  {
171
188
  imageKind: analyzedBytes(image).kind,
172
- entryPoints: entryPoints.slice(0, GHIDRA_LIMITS.entryPoints),
173
- codeStarts: flows.codeStarts.filter((address) => !seeds.has(address)).slice(0, GHIDRA_LIMITS.codeStarts),
174
- dataRanges: dataRanges.slice(0, GHIDRA_LIMITS.dataRanges),
189
+ entryPoints: entryPoints.slice(0, DECOMPILER_LIMITS.entryPoints),
190
+ codeStarts: flows.codeStarts.filter((address) => !seeds.has(address)).slice(0, DECOMPILER_LIMITS.codeStarts),
191
+ dataRanges: dataRanges.slice(0, DECOMPILER_LIMITS.dataRanges),
175
192
  labels: [],
176
193
  decompile: [],
177
194
  },
@@ -467,44 +484,32 @@ async function checkSwitch(row: SourceSwitch, patches: PatchBlock[], files: Arra
467
484
  };
468
485
  }
469
486
 
470
- /** What the build of a release gives against the bytes of its file. */
487
+ /** What the build of a release gives against the bytes of the release in the knowledge. */
471
488
  interface ReleaseCheck {
472
489
  label: string;
473
490
  base: boolean;
474
- file: string;
475
491
  define: string;
476
- result: "identical" | "different" | "layout differs" | "file changed" | "does not assemble";
477
- reason?: string;
492
+ result: "identical" | "different" | "does not assemble";
478
493
  segments?: SegmentCheck[];
494
+ /** The ranges of the program that the release does not have: the check does not compare them. */
495
+ notInRelease?: Array<{ start: string; end: string }>;
479
496
  diagnostics?: Diagnostic[];
480
497
  }
481
498
 
482
499
  /**
483
- * Builds a release with RELEASE_<label> and compares it with its file. A
484
- * release whose segments are not the segments of the program has moved code,
485
- * which patches cannot give: it is shown and does not fail the run.
500
+ * Builds a release with RELEASE_<label> and compares it with its bytes, in
501
+ * each segment of the release, as the build compare of the assembler does. A
502
+ * part of the program that the release does not have is listed, not compared.
486
503
  */
487
- async function checkRelease(release: ReleaseRow, files: Array<{ name: string; text: string }>, program: ProgramImage): Promise<ReleaseCheck> {
488
- const shown = { label: release.label, base: release.base, file: release.file, define: `--define ${RELEASE_DEFINE}${release.label}=1` };
489
- let image: Image;
490
- try {
491
- const bytes = readProjectFile(release.file).bytes;
492
- if (createHash("sha256").update(bytes).digest("hex") !== release.sha256) {
493
- return { ...shown, result: "file changed", reason: `The SHA-256 of ${release.file} is not the one that the knowledge has. Put back the file, or record the release again in the project knowledge.` };
494
- }
495
- image = readImage(release.file);
496
- } catch (error) {
497
- if (!(error instanceof Refusal || error instanceof WireFailure)) throw error;
498
- return { ...shown, result: "file changed", reason: error.message };
499
- }
500
- if (JSON.stringify(image.segments) !== JSON.stringify(program.segments)) {
501
- const segments = (list: readonly AddressRange[]) => list.map((segment) => `${formatC64Address(segment.start)}-${formatC64Address(segment.end)}`).join(", ");
502
- return { ...shown, result: "layout differs", reason: `The release has the segments ${segments(image.segments)}, and the program has ${segments(program.segments)}. Patches change bytes in place; they cannot move code.` };
503
- }
504
+ async function checkRelease(release: ReleaseRow & { image: Pick<ProgramImage, "segments" | "byteAt"> }, files: Array<{ name: string; text: string }>, program: ProgramImage): Promise<ReleaseCheck> {
505
+ const shown = { label: release.label, base: release.base, define: `--define ${RELEASE_DEFINE}${release.label}=1` };
506
+ const { image } = release;
507
+ const missing = program.segments.flatMap((segment) => subtract(segment, [...image.segments])).map((range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) }));
508
+ const notInRelease = missing.length === 0 ? {} : { notInRelease: missing };
504
509
  const built = await assembleFiles(files, "main.asm", { [`${RELEASE_DEFINE}${release.label}`]: 1 });
505
- if (built.program === undefined) return { ...shown, result: "does not assemble", diagnostics: built.diagnostics.slice(0, MAX_DIAGNOSTICS) };
510
+ if (built.program === undefined) return { ...shown, result: "does not assemble", diagnostics: built.diagnostics.slice(0, MAX_DIAGNOSTICS), ...notInRelease };
506
511
  const checked = check(built.program, built.start!, image);
507
- return { ...shown, result: checked.identical ? "identical" : "different", ...(checked.identical ? {} : { segments: checked.segments.filter((segment) => segment.result !== "identical") }) };
512
+ return { ...shown, result: checked.identical ? "identical" : "different", ...(checked.identical ? {} : { segments: checked.segments.filter((segment) => segment.result !== "identical") }), ...notInRelease };
508
513
  }
509
514
 
510
515
  /** Reads RAM in parts. */
@@ -544,7 +549,7 @@ interface LoaderRunPlan {
544
549
  /** The wait of the start screen and the code after it, when the loader has a start screen. */
545
550
  startScreen?: { wait: number; continue: number };
546
551
  /** The show stage of a start screen from a captured stage, which runs before the loader: its wait, the code after it, its VIC-II values and the bytes of the stage. */
547
- stage?: { name: string; wait: number; continue: number; screen: StartScreenPlan; parts: StagePart[]; frames: number };
552
+ stage?: { name: string; wait: number; continue: number; screen: StartScreenPlan; parts: StagePart[]; colourRam?: Uint8Array; frames: number };
548
553
  copierSource: number;
549
554
  fileByte: (address: number) => number;
550
555
  copierFrames: number;
@@ -567,11 +572,11 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, state:
567
572
  const port01 = `$${port.toString(16).padStart(2, "0")}`;
568
573
  return { verified: false, differences: [`The loader did not get to ${what}; it stopped at ${formatC64Address(pc)}.`], stop: { pc: formatC64Address(pc), port: port01, ...(cause === undefined ? {} : { cause }), history } };
569
574
  };
570
- // The start screen waits for a key or a fire button. The emulator cannot press a key of the keyboard matrix
571
- // on each VICE, so the check lets it wait, then sets the PC to the code after the wait.
575
+ // The start screen waits for a key or a fire button. Not each VICE can press a key of the keyboard matrix,
576
+ // so the check lets it wait, then sets the PC to the code after the wait.
572
577
  let screen: LoaderRun["startScreen"];
573
578
  const screenDifferences: string[] = [];
574
- const showScreen = async (at: { wait: number; continue: number }, wanted: StartScreenPlan, frames: number, copied: boolean, parts: readonly StagePart[] = []): Promise<LoaderRun | undefined> => {
579
+ const showScreen = async (at: { wait: number; continue: number }, wanted: StartScreenPlan, frames: number, copied: boolean, parts: readonly StagePart[] = [], colourRam?: Uint8Array): Promise<LoaderRun | undefined> => {
575
580
  const labels = { wait: formatC64Address(at.wait), continue: formatC64Address(at.continue) };
576
581
  const atWait = await client.runUntil({ target: { kind: "address", address: at.wait, space: "c64" }, timeoutFrames: frames });
577
582
  if (!atWait.reached) return await stopped(atWait.pc, copied, `its start screen at ${labels.wait}`, parts.length === 0);
@@ -591,6 +596,12 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, state:
591
596
  const wrong = part.body.findIndex((byte, offset) => ram[offset] !== byte);
592
597
  if (wrong >= 0) screenDifferences.push(`the stage has $${ram[wrong]!.toString(16).padStart(2, "0")} at ${formatC64Address(part.start + wrong)}, not $${part.body[wrong]!.toString(16).padStart(2, "0")}`);
593
598
  }
599
+ // The colour RAM of a captured stage: the first wrong colour.
600
+ if (colourRam !== undefined) {
601
+ const colours = Buffer.from((await client.ioRead(0xd800, colourRam.length)).data, "hex");
602
+ const wrong = colourRam.findIndex((value, offset) => (colours[offset]! & 0x0f) !== value);
603
+ if (wrong >= 0) screenDifferences.push(`the colour RAM has ${colours[wrong]! & 0x0f} at ${formatC64Address(0xd800 + wrong)}, not ${colourRam[wrong]}`);
604
+ }
594
605
  screen = { shown: screenDifferences.length === before, waits: !held.reached, ...labels, ...(run.stage === undefined ? {} : { stage: run.stage.name }) };
595
606
  if (held.reached) screenDifferences.push(`the start screen did not wait: it got to ${labels.continue} without a key or a fire button`);
596
607
  if (!held.reached) await client.registersSet("c64", { pc: at.continue });
@@ -598,7 +609,7 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, state:
598
609
  };
599
610
  // The show stage of a captured stage runs before the loader.
600
611
  if (run.stage !== undefined) {
601
- const stop = await showScreen(run.stage, run.stage.screen, run.stage.frames, false, run.stage.parts);
612
+ const stop = await showScreen(run.stage, run.stage.screen, run.stage.frames, false, run.stage.parts, run.stage.colourRam);
602
613
  if (stop !== undefined) return stop;
603
614
  }
604
615
  const copier = await client.runUntil({ target: { kind: "address", address: plan.copier, space: "c64" }, timeoutFrames: run.copierFrames });
@@ -687,73 +698,142 @@ function sourceMapText(rendered: Rendered, space: string, revision: string | nul
687
698
  return `${head},\n"labels": [\n${labels.join(",\n")}\n],\n"items": [\n${items.join(",\n")}\n]}\n`;
688
699
  }
689
700
 
690
- /** The folder in .c64-re-tools/local/ where the check of the loader runs the new loader.prg. */
701
+ /** The folder in .c64-re-tools/local/ where the check of the loader runs the new loader program. */
691
702
  const LOADER_CHECK_DIRECTORY = "loader-check";
692
703
 
693
- /** The files of the loader. Only a run with --loader writes them, so only such a run removes them. */
694
- const LOADER_FILES: ReadonlySet<string> = new Set(["loader.asm", "loader.prg", START_SCREEN_FILE, STAGE_FILE]);
704
+ /** The source files of the loader. Only a run with --loader writes them, so only such a run removes them. */
705
+ const LOADER_FILES: ReadonlySet<string> = new Set(["loader.asm", START_SCREEN_FILE, STAGE_FILE]);
695
706
 
696
- /** The start of the line of loader.asm that gives the knowledge revision of the loader. */
697
- const LOADER_REVISION = "Loader generated by c64-source from knowledge revision ";
707
+ /** The source files of the show stage. A run writes them only with a loader program whose check ran, so only such a run removes them. */
708
+ const STAGE_FILES: ReadonlySet<string> = new Set([START_SCREEN_FILE, STAGE_FILE]);
709
+
710
+ /** A loader program that generate wrote: its build name, as buildName gives it for loader.asm. */
711
+ const LOADER_PROGRAM = /^(clean|custom_[a-z0-9_]+|release_[A-Za-z0-9_]+)_loader\.prg$/;
712
+
713
+ /** The loader programs of earlier runs in the build folder, with their symbols files. */
714
+ function loaderPrograms(): string[] {
715
+ const directory = resolveProjectPath(BUILD_DIRECTORY);
716
+ if (!existsSync(directory)) return [];
717
+ return readdirSync(directory)
718
+ .filter((name) => LOADER_PROGRAM.test(name))
719
+ .flatMap((name) => [`${BUILD_DIRECTORY}/${name}`, symbolsPath(`${BUILD_DIRECTORY}/${name}`)])
720
+ .filter((path) => existsSync(resolveProjectPath(path)));
721
+ }
722
+
723
+ /** The line of loader.asm that gives the toolkit version and the newest knowledge revision of the spaces that the loader holds. */
724
+ const loaderLine = (revision: string) => `Loader generated by c64-source ${PACKAGE.version} from knowledge revision ${revision}.`;
725
+ const LOADER_LINE = /^; Loader generated by c64-source (\S+) from knowledge revision (\S+)\.$/;
698
726
 
699
727
  /**
700
728
  * The loader files of an earlier run that a run without --loader keeps, when
701
- * the generated loader.asm is of another knowledge revision: the loader can
702
- * then copy other bytes than the source has. Undefined when there is no
703
- * generated loader.asm, or it is of this revision.
729
+ * the generated loader.asm is of another knowledge revision or of another
730
+ * version of the toolkit: the loader can then copy other bytes than the source
731
+ * has. Undefined when there is no generated loader.asm, or it is of this
732
+ * revision and version.
704
733
  */
705
- function staleLoader(out: string, revision: string): { files: string[]; revision?: string } | undefined {
734
+ function staleLoader(out: string, revision: string): { files: string[]; revision?: string; version?: string } | undefined {
706
735
  const path = resolveProjectPath(`${out}/loader.asm`);
707
736
  if (!existsSync(path)) return undefined;
708
737
  const text = readFileSync(path, "utf8");
709
738
  if (!text.startsWith(GENERATED_MARK)) return undefined;
710
- const line = text.split(/\r?\n/).find((row) => row.startsWith(`; ${LOADER_REVISION}`));
711
- const old = line?.slice(`; ${LOADER_REVISION}`.length).replace(/\.$/, "");
712
- if (old === revision) return undefined;
713
- const files = [...LOADER_FILES].filter((name) => existsSync(resolveProjectPath(`${out}/${name}`))).map((name) => `${out}/${name}`);
714
- return { files, ...(old === undefined ? {} : { revision: old }) };
739
+ const found = text.split(/\r?\n/).map((row) => LOADER_LINE.exec(row)).find((match) => match !== null);
740
+ const version = found?.[1];
741
+ const old = found?.[2];
742
+ if (old === revision && version === PACKAGE.version) return undefined;
743
+ const files = [...[...LOADER_FILES].filter((name) => existsSync(resolveProjectPath(`${out}/${name}`))).map((name) => `${out}/${name}`), ...loaderPrograms()];
744
+ return { files, ...(old === undefined ? {} : { revision: old }), ...(version === undefined ? {} : { version }) };
745
+ }
746
+
747
+ /** The line of a leftover file that gives its range. */
748
+ const LEFTOVER_RANGE = /^; Leftovers (\$[0-9a-f]{4})-(\$[0-9a-f]{4}):/m;
749
+
750
+ /**
751
+ * The leftovers of the earlier run: the ranges of its generated leftover
752
+ * files in the leftovers folder of `out`. Undefined when `out` has no
753
+ * generated main.asm, so there was no earlier run to compare with.
754
+ */
755
+ function earlierLeftovers(out: string): AddressRange[] | undefined {
756
+ const root = resolveProjectPath(out);
757
+ const main = join(root, "main.asm");
758
+ if (!existsSync(main) || !readFileSync(main, "utf8").startsWith(GENERATED_MARK)) return undefined;
759
+ const directory = join(root, LEFTOVER_FOLDER);
760
+ if (!existsSync(directory)) return [];
761
+ return readdirSync(directory)
762
+ .filter((name) => /^leftover_[0-9a-f]{4}\.asm$/.test(name))
763
+ .flatMap((name) => {
764
+ const found = LEFTOVER_RANGE.exec(readFileSync(join(directory, name), "utf8"));
765
+ return found === null ? [] : [{ start: parseC64Address(found[1]!), end: parseC64Address(found[2]!) }];
766
+ });
767
+ }
768
+
769
+ /** The bytes of `ranges` that are not in `others`, as ranges in address order. */
770
+ function outside(ranges: readonly AddressRange[], others: readonly AddressRange[]): AddressRange[] {
771
+ return [...ranges].sort((a, b) => a.start - b.start).flatMap((range) => subtract(range, [...others]));
715
772
  }
716
773
 
717
774
  /**
718
775
  * Removes the generated .asm files of an earlier run that this run does not
719
- * write, and an earlier not_executed.json and source-map.json. An earlier
720
- * loader.asm stays unless this run has --loader: a source of the user can
721
- * include loader.asm. An earlier loader.prg always stays: only a new loader.prg
722
- * whose check ran replaces it. Other files stay. Gives the names it removed.
776
+ * write, and the reports of the earlier run (its source map and
777
+ * not_executed.json). An earlier loader.asm stays unless this run has
778
+ * --loader: a source of the user can include loader.asm. The files of a
779
+ * module are in `out` or in one folder of it: a folder that the run leaves
780
+ * empty goes too. A folder with a generated main.asm is the source of another
781
+ * space, and it stays. Other files stay. Gives the paths it removed.
723
782
  */
724
783
  function removeOldFiles(out: string, keep: ReadonlySet<string>, loaderRun: boolean): string[] {
725
- const directory = resolveProjectPath(out);
726
- if (!existsSync(directory)) return [];
727
784
  const removed: string[] = [];
728
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
729
- if (!entry.isFile()) continue;
730
- const name = entry.name;
731
- const path = join(directory, name);
732
- if (LOADER_FILES.has(name) && !loaderRun) continue;
733
- const old = name === NOT_EXECUTED_FILE || name === SOURCE_MAP_FILE || (name.endsWith(".asm") && !keep.has(name) && readFileSync(path, "utf8").startsWith(GENERATED_MARK));
734
- if (!old) continue;
785
+ const reports = generatedDirectory(projectRelative(out));
786
+ for (const name of [SOURCE_MAP_FILE, NOT_EXECUTED_FILE]) {
787
+ const path = resolveProjectPath(`${reports}/${name}`);
788
+ if (!existsSync(path)) continue;
735
789
  rmSync(path, { force: true });
736
- removed.push(name);
790
+ removed.push(`${reports}/${name}`);
737
791
  }
792
+ const root = resolveProjectPath(out);
793
+ if (!existsSync(root)) return removed;
794
+ /** Removes the old generated files of a folder ("" for `out` itself), and gives how many. */
795
+ const clean = (folder: string): number => {
796
+ const directory = folder === "" ? root : join(root, folder);
797
+ let count = 0;
798
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
799
+ const name = folder === "" ? entry.name : `${folder}/${entry.name}`;
800
+ if (entry.isDirectory() && folder === "") {
801
+ const main = join(root, name, "main.asm");
802
+ if (existsSync(main) && readFileSync(main, "utf8").startsWith(GENERATED_MARK)) continue;
803
+ // A folder of the user that held no generated file stays, also when it is empty.
804
+ if (clean(name) > 0 && readdirSync(join(root, name)).length === 0) rmSync(join(root, name), { recursive: true, force: true });
805
+ continue;
806
+ }
807
+ if (!entry.isFile()) continue;
808
+ const path = join(directory, entry.name);
809
+ if ((LOADER_FILES.has(name) && !loaderRun) || STAGE_FILES.has(name)) continue;
810
+ if (!name.endsWith(".asm") || keep.has(name) || !readFileSync(path, "utf8").startsWith(GENERATED_MARK)) continue;
811
+ rmSync(path, { force: true });
812
+ removed.push(`${out}/${name}`);
813
+ count++;
814
+ }
815
+ return count;
816
+ };
817
+ clean("");
738
818
  return removed;
739
819
  }
740
820
 
741
- /** The instructions that Ghidra decoded, and whether the program has known code. */
821
+ /** The instructions that the decompiler decoded, and whether the program has known code. */
742
822
  type DecodedProgram = Awaited<ReturnType<typeof decode>>;
743
823
 
744
824
  /** How buildSource makes and checks the source of a knowledge. */
745
825
  interface SourceOptions {
746
826
  space: Space;
747
- /** More entry points for Ghidra. */
827
+ /** More entry points for the decompiler. */
748
828
  entries: number[];
749
829
  header: string[];
750
830
  /** The first line of each file, or none. */
751
831
  mark?: string;
752
832
  /** The switch values of the build that must give the program. */
753
833
  values: ReadonlyMap<string, number>;
754
- /** The instructions of an earlier decode: then Ghidra does not run again. */
834
+ /** The instructions of an earlier decode: then the decompiler does not run again. */
755
835
  decoded?: DecodedProgram;
756
- /** Mark the code that no run executed. Without the marks, the coverage only gives the seeds of Ghidra and the ROM use. */
836
+ /** Mark the code that no run executed. Without the marks, the coverage only gives the seeds of the decompiler and the ROM use. */
757
837
  notExecutedMarks: boolean;
758
838
  /** With an entry state, the loader is planned too. */
759
839
  state?: EntryState;
@@ -793,7 +873,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
793
873
  operands: knowledge.operands,
794
874
  patches: knowledge.patches,
795
875
  switches: knowledge.switches,
796
- releases: knowledge.releases.map((release) => ({ label: release.label, file: release.file, base: release.base, ...(release.comment === undefined ? {} : { comment: release.comment }) })),
876
+ releases: knowledge.releases.map((release) => ({ label: release.label, base: release.base, ...(release.comment === undefined ? {} : { comment: release.comment }) })),
797
877
  macros: knowledge.macros,
798
878
  macroUses: knowledge.macroUses,
799
879
  startScreen: knowledge.startScreen !== undefined && options.exported !== true,
@@ -827,7 +907,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
827
907
 
828
908
  let loader: LoaderPlan | undefined;
829
909
  /** The build of main.asm that the loader loads: the switch values of the loader. */
830
- let loaderMain: { program: Buffer; start: number } | undefined;
910
+ let loaderMain: { program: Buffer; start: number; symbols: AssembledSymbol[] } | undefined;
831
911
  // An image without its entry has no program: the source is still written and checked, but the run fails.
832
912
  const missingEntry = entryOutsideImage(image.entry, image.segments);
833
913
  // A loader that cannot be planned does not stop the source: the source is written and checked, and the result says why.
@@ -839,7 +919,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
839
919
  else {
840
920
  const program = main.program;
841
921
  const start = main.start!;
842
- loaderMain = { program, start };
922
+ loaderMain = { program, start, symbols: main.symbols ?? [] };
843
923
  try {
844
924
  const entryName = laid.names.get(image.entry!);
845
925
  loader = planLoader({
@@ -934,18 +1014,18 @@ async function buildLoader(
934
1014
  * of the stage whose switch default is not its base value is in, as in the
935
1015
  * default build. Pages 0-3 are left out: the unpacker of Exomizer uses them.
936
1016
  */
937
- async function stageBytes(row: StartScreenRow): Promise<StagePart[]> {
1017
+ async function stageBytes(row: StartScreenRow): Promise<{ parts: StagePart[]; colourRam?: Uint8Array }> {
938
1018
  const stage = row.stage!;
939
1019
  const knowledge = readKnowledge(stage);
1020
+ const colourRam = row.colourRam === true ? capturedColourRam(knowledge.program.state) : undefined;
1021
+ if (row.colourRam === true && colourRam === undefined) throw new Refusal("not-found", `The start screen takes its colours from the colour RAM of the capture in ${stage}, and that capture has none. Capture the stage again while it shows the screen, and put it into the project knowledge with image --space ${stage}.`);
940
1022
  const image = knowledge.program;
941
1023
  const memory = Uint8Array.from(image.memory);
942
- const addresses = knowledge.symbols.map((symbol) => `${symbol.name} = ${formatC64Address(symbol.address)}`);
943
1024
  for (const patch of knowledge.patches) {
944
1025
  const owner = knowledge.switches.find((item) => item.name === patch.switch);
945
1026
  if (owner === undefined || owner.default === owner.base) continue;
946
1027
  const length = patch.end - patch.start + 1;
947
- const text = ["!cpu 6510", ...addresses, `* = ${formatC64Address(patch.start)}`, ...patch.code.split(/\r?\n/), `!fill ${length} - (* - ${formatC64Address(patch.start)}), $ea`].join("\n");
948
- const built = await assembleFiles([{ name: "patch.asm", text: `${text}\n` }], "patch.asm");
1028
+ const built = await assembleFiles([{ name: "patch.asm", text: stagePatchText(knowledge.symbols, patch) }], "patch.asm");
949
1029
  if (built.program === undefined || built.start !== patch.start || built.program.length - 2 !== length) {
950
1030
  throw new Refusal("invalid-input", `The patch of ${patch.switch} at ${formatC64Address(patch.start)}-${formatC64Address(patch.end)} in ${stage} does not assemble to ${length} bytes: ${built.diagnostics.map((diagnostic) => diagnostic.message).join("; ") || "it is longer than its range"}. Correct the patch in the project knowledge.`);
951
1031
  }
@@ -969,15 +1049,18 @@ async function stageBytes(row: StartScreenRow): Promise<StagePart[]> {
969
1049
  if (last !== undefined && range.start <= last.end + 1) last.end = Math.max(last.end, range.end);
970
1050
  else parts.push({ ...range });
971
1051
  }
972
- return parts.map((range) => ({ start: range.start, body: memory.slice(range.start, range.end + 1) }));
1052
+ return { parts: parts.map((range) => ({ start: range.start, body: memory.slice(range.start, range.end + 1) })), ...(colourRam === undefined ? {} : { colourRam }) };
973
1053
  }
974
1054
 
975
- /** What the show stage gives: loader.prg, the source of the stage, and what its check needs. */
1055
+ /** What the show stage gives: the loader program, the source of the stage, and what its check needs. */
976
1056
  interface BuiltStage {
977
1057
  program: Buffer;
978
1058
  text: string;
1059
+ /** The labels of the build of start_screen_stage.asm. */
1060
+ symbols: AssembledSymbol[];
979
1061
  plan: StagePlan;
980
1062
  parts: StagePart[];
1063
+ colourRam?: Uint8Array;
981
1064
  packed: PackedLoader;
982
1065
  wait: number;
983
1066
  continue: number;
@@ -990,7 +1073,7 @@ interface BuiltStage {
990
1073
  * is in memory before it starts. Refuses by name.
991
1074
  */
992
1075
  async function buildStage(files: Array<{ name: string; text: string }>, laid: Layout, program: PackedLoader, row: StartScreenRow, values: ReadonlyMap<string, number>, header: string[], mark: string): Promise<BuiltStage> {
993
- const stage = await stageBytes(row);
1076
+ const { parts: stage, colourRam } = await stageBytes(row);
994
1077
  // The packed program, as RUN would start it: its unpacker unpacks it over the start screen after the wait.
995
1078
  const inner: StagePart[] = [{ start: 0x0801, body: program.program.subarray(2) }];
996
1079
  const screen = startScreenPlan(row);
@@ -999,6 +1082,7 @@ async function buildStage(files: Array<{ name: string; text: string }>, laid: La
999
1082
  innerStart: 0x080d,
1000
1083
  innerPort: 0x37,
1001
1084
  stage,
1085
+ ...(colourRam === undefined ? {} : { colourRam }),
1002
1086
  row,
1003
1087
  plan: screen,
1004
1088
  settings: hasSwitchFile(laid) ? ['!source "switches.asm"'] : hasConfigFile(laid) ? ['!source "config.asm"'] : [],
@@ -1008,17 +1092,24 @@ async function buildStage(files: Array<{ name: string; text: string }>, laid: La
1008
1092
  const support = [...withValues(files, laid, values).filter((file) => file.name === CONFIG_FILE || file.name === "switches.asm"), { name: START_SCREEN_FILE, text: START_SCREEN_CODE }];
1009
1093
  const assembleStage = async (text: string) => {
1010
1094
  const built = await assembleFiles([...support, { name: STAGE_FILE, text }], STAGE_FILE);
1011
- if (built.program === undefined) throw new WireFailure("operation-failed", `${STAGE_FILE} does not assemble: ${built.diagnostics.map((diagnostic) => diagnostic.message).join("; ")}. This is a defect of the script.`);
1095
+ if (built.program === undefined) {
1096
+ // The source that failed stays readable: --out keeps the files of the last good run.
1097
+ ensureLocal(projectRoot());
1098
+ const kept = `${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/${LOADER_CHECK_DIRECTORY}/${STAGE_FILE}`;
1099
+ mkdirSync(dirname(resolveProjectPath(kept)), { recursive: true });
1100
+ writeFileSync(resolveProjectPath(kept), `${mark}\n${text}`);
1101
+ throw new WireFailure("operation-failed", `${STAGE_FILE} does not assemble: ${built.diagnostics.map((diagnostic) => diagnostic.message).join("; ")}. The source that failed is ${kept}. This is a defect of the script.`);
1102
+ }
1012
1103
  const labels = new Map((built.symbols ?? []).map((symbol) => [symbol.name, symbol.kind === "address" ? symbol.address : symbol.value]));
1013
1104
  const label = (name: string) => {
1014
1105
  const value = labels.get(name);
1015
1106
  if (value === undefined) throw new WireFailure("operation-failed", `The build of ${STAGE_FILE} has no ${name} label. This is a defect of the script.`);
1016
1107
  return value;
1017
1108
  };
1018
- return { program: built.program, label };
1109
+ return { program: built.program, symbols: built.symbols ?? [], label };
1019
1110
  };
1020
- // The size of the show code does not depend on its address: one build without a stash gives it.
1021
- const probe = await assembleStage(stageText(input, 0x1000, []));
1111
+ // The size of the show code does not depend on its address: one build without a stash and without the parts gives it.
1112
+ const probe = await assembleStage(stageText({ ...input, stage: [] }, 0x1000, []));
1022
1113
  input.codeSize = probe.label(STAGE_CODE_END) - probe.label(STAGE_START) - 2;
1023
1114
  const plan = planStage(input);
1024
1115
  const built = await assembleStage(plan.text);
@@ -1026,8 +1117,8 @@ async function buildStage(files: Array<{ name: string; text: string }>, laid: La
1026
1117
  const parts = stageParts(input, plan, built.program, built.label);
1027
1118
  const packed = await packParts(parts, plan.code, 0x37, "the loader and the start screen of the stage", "the show stage", localToolContext());
1028
1119
  const end = 0x0801 + packed.program.length - 3;
1029
- if (end > 0xcfff) throw new Refusal("invalid-input", `loader.prg with the start screen of ${row.stage} would end at ${formatC64Address(end)}, after $cfff: loading it would write the I/O area. Capture the stage with less memory, so that its program holds only the start screen and the routine of the call.`);
1030
- return { program: packed.program, text: `${mark}\n${plan.text}`, plan, parts: stage, packed, wait: built.label(START_SCREEN_WAIT), continue: built.label(START_SCREEN_CONTINUE), screen };
1120
+ if (end > 0xcfff) throw new Refusal("invalid-input", `The loader with the start screen of ${row.stage} would end at ${formatC64Address(end)}, after $cfff: loading it would write the I/O area. Capture the stage with less memory, so that its program holds only the start screen and the routine of the call.`);
1121
+ return { program: packed.program, text: `${mark}\n${plan.text}`, symbols: built.symbols, plan, parts: stage, ...(colourRam === undefined ? {} : { colourRam }), packed, wait: built.label(START_SCREEN_WAIT), continue: built.label(START_SCREEN_CONTINUE), screen };
1031
1122
  }
1032
1123
 
1033
1124
  /** The first line of each file that generate writes. */
@@ -1054,8 +1145,8 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1054
1145
  const given = existsSync(configPath) ? configValues(readFileSync(configPath, "utf8")) : new Map<string, 0 | 1>();
1055
1146
  const configNames = new Set([...knowledge.switches.map((row) => row.name), START_SCREEN_SWITCH, LEFTOVERS_SWITCH]);
1056
1147
  const loaderValues = new Map([...given].filter(([name]) => configNames.has(name)));
1057
- const header = [`Generated by c64-source from knowledge revision ${knowledge.revision}${space === DEFAULT_SPACE ? "" : ` in space ${space}`}.`, "Change names, comments, regions and modules in knowledge, then generate again."];
1058
- const loaderHeader = [`${LOADER_REVISION}${knowledge.revision}.`, "It copies the segments into place, sets the entry state and jumps to the entry."];
1148
+ const header = [`Generated by c64-source from knowledge revision ${knowledge.sourceRevision}${space === DEFAULT_SPACE ? "" : ` in space ${space}`}.`, "Change names, comments, regions and modules in knowledge, then generate again."];
1149
+ const loaderHeader = [loaderLine(knowledge.sourceRevision), "It copies the segments into place, sets the entry state and jumps to the entry."];
1059
1150
  const { romUse, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused } = await buildSource(knowledge, {
1060
1151
  space,
1061
1152
  entries,
@@ -1070,10 +1161,20 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1070
1161
  const configured = [...laid.switches, ...(laid.startScreen ? [{ name: START_SCREEN_SWITCH, default: 1 }] : []), ...(laid.leftovers.length > 0 ? [{ name: LEFTOVERS_SWITCH, default: 0 }] : [])];
1071
1162
  const kept = new Map(configured.flatMap((row) => (given.has(row.name) ? [[row.name, given.get(row.name)!] as const] : [])));
1072
1163
  const notDefault = configured.flatMap((row) => (kept.has(row.name) && kept.get(row.name) !== row.default ? [{ name: row.name, value: kept.get(row.name)!, default: row.default }] : []));
1073
- const removed = removeOldFiles(out, new Set(files.map((file) => file.name)), loaderWanted).map((name) => `${out}/${name}`);
1074
- const stale = loaderWanted || space !== DEFAULT_SPACE ? undefined : staleLoader(out, knowledge.revision);
1164
+ // The loader program has the name of its build: clean_loader with the defaults of config.asm.
1165
+ const loaderName = buildName("loader.asm", { values: kept, defaults: new Map(configured.map((row) => [row.name, row.default])) });
1166
+ // Read before the old files go: the leftovers of the earlier run, to tell what changed.
1167
+ const earlier = earlierLeftovers(out);
1168
+ const removed = removeOldFiles(out, new Set(files.map((file) => file.name)), loaderWanted);
1169
+ const stale = loaderWanted || space !== DEFAULT_SPACE ? undefined : staleLoader(out, knowledge.sourceRevision);
1075
1170
  const written: Written[] = withValues(files, laid, kept).map((file) => writeReported(`${out}/${file.name}`, file.text, { what: "--out" }));
1076
- written.push(writeReported(`${out}/${SOURCE_MAP_FILE}`, sourceMapText(rendered, space, knowledge.revision, files), { what: "--out" }));
1171
+ // The reports go to the local folder: the source folder holds only source files.
1172
+ const reports = generatedDirectory(projectRelative(out));
1173
+ written.push(writeReported(`${reports}/${SOURCE_MAP_FILE}`, sourceMapText(rendered, space, knowledge.sourceRevision, files)));
1174
+ // A reference that the project has from this source, made at an earlier revision: the new source makes it old.
1175
+ const staleReference = generatedReferences(projectRoot())
1176
+ .filter((reference) => reference.mapPath === `${reports}/${SOURCE_MAP_FILE}` && reference.revision !== knowledge.sourceRevision)
1177
+ .map((reference) => ({ folder: reference.folder, revision: reference.revision }));
1077
1178
  const showRange = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
1078
1179
  const inData = entriesInData(entries, knowledge.regions);
1079
1180
  if (rendered.notExecuted !== undefined) {
@@ -1086,19 +1187,24 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1086
1187
  });
1087
1188
  const files: Record<string, number> = {};
1088
1189
  for (const range of placed) if (range.file !== undefined) files[range.file] = (files[range.file] ?? 0) + 1;
1089
- const all = { revision: knowledge.revision, instructions: rendered.notExecuted.instructions, files, ranges: placed };
1090
- written.push(writeReported(`${out}/${NOT_EXECUTED_FILE}`, `${JSON.stringify(all, null, 2)}\n`, { what: "--out" }));
1190
+ const all = { revision: knowledge.sourceRevision, instructions: rendered.notExecuted.instructions, files, ranges: placed };
1191
+ written.push(writeReported(`${reports}/${NOT_EXECUTED_FILE}`, `${JSON.stringify(all, null, 2)}\n`));
1091
1192
  }
1193
+ // The leftovers that changed since the earlier run: the default build and the loader now leave out other bytes.
1194
+ const added = earlier === undefined ? [] : outside(laid.leftovers, earlier);
1195
+ const dropped = earlier === undefined ? [] : outside(earlier, laid.leftovers);
1196
+ const changed = added.length + dropped.length === 0 ? undefined : { added: added.map(showRange), removed: dropped.map(showRange) };
1092
1197
 
1093
1198
  const output: Record<string, unknown> = {
1094
1199
  out,
1095
1200
  files: written,
1096
- sourceMap: `${out}/${SOURCE_MAP_FILE}`,
1201
+ sourceMap: `${reports}/${SOURCE_MAP_FILE}`,
1097
1202
  // The values that config.asm keeps and that are not the default: a build of the source is not the default build.
1098
1203
  ...(notDefault.length === 0 ? {} : { config: { file: `${out}/${CONFIG_FILE}`, notDefault } }),
1099
1204
  revision: knowledge.revision,
1100
1205
  // A run without --loader keeps the loader of an earlier run: one of another revision is stale.
1101
1206
  ...(stale === undefined ? {} : { staleLoader: { ...stale, ...(image.state === undefined || image.entry === undefined ? { noEntryState: true } : {}) } }),
1207
+ ...(staleReference.length === 0 ? {} : { staleReference }),
1102
1208
  instructions: rendered.instructions,
1103
1209
  dataBytes: rendered.dataBytes,
1104
1210
  ...(rendered.undecodedBytes === 0 ? {} : { undecodedBytes: rendered.undecodedBytes }),
@@ -1117,15 +1223,17 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1117
1223
  ...(rendered.notExecuted === undefined
1118
1224
  ? {}
1119
1225
  : {
1120
- notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max, showRange, `${out}/${NOT_EXECUTED_FILE}`) },
1226
+ notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max, showRange, `a larger --max-listed, or read ${reports}/${NOT_EXECUTED_FILE}`) },
1121
1227
  }),
1122
1228
  ...(laid.unusedModules.length === 0 ? {} : { unusedModules: laid.unusedModules.map((module) => ({ start: formatC64Address(module.start), file: module.file })) }),
1123
1229
  // The bytes that nothing uses: in leftover files, which the default build and the loader leave out.
1124
1230
  ...(laid.leftovers.length === 0
1125
1231
  ? knowledge.coverage === undefined && space === DEFAULT_SPACE
1126
1232
  ? { leftovers: { bytes: 0, noCoverage: "The knowledge has no coverage, so no range is a leftover, and the default build and the loader have every byte of the program." } }
1127
- : {}
1128
- : { leftovers: { bytes: laid.leftovers.reduce((sum, range) => sum + range.end - range.start + 1, 0), ...listed(laid.leftovers, max, (range) => ({ ...showRange(range), bytes: range.end - range.start + 1, file: `leftover_${range.start.toString(16).padStart(4, "0")}.asm` })) } }),
1233
+ : changed === undefined
1234
+ ? {}
1235
+ : { leftovers: { bytes: 0, changed } }
1236
+ : { leftovers: { bytes: laid.leftovers.reduce((sum, range) => sum + range.end - range.start + 1, 0), ...listed(laid.leftovers, max, (range) => ({ ...showRange(range), bytes: range.end - range.start + 1, file: `${LEFTOVER_FOLDER}/leftover_${range.start.toString(16).padStart(4, "0")}.asm` })), ...(changed === undefined ? {} : { changed }) } }),
1129
1237
  ...(rendered.expressions.length === 0 && rendered.operandsAsNumbers.length === 0 ? {} : { operandExpressions: rendered.expressions.length }),
1130
1238
  ...(rendered.operandsAsNumbers.length === 0
1131
1239
  ? {}
@@ -1146,9 +1254,12 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1146
1254
  patchesNotWritten: listed(laid.patchesNotWritten, max, (item) => ({ start: formatC64Address(item.start), end: formatC64Address(item.end), switch: item.switch, reason: item.reason })),
1147
1255
  }),
1148
1256
  };
1149
- // A loader.prg of an earlier run stays when this run checks no new one: it can be a committed file.
1150
- const loaderPath = `${out}/loader.prg`;
1151
- const keptLoader = () => (existsSync(resolveProjectPath(loaderPath)) ? { kept: loaderPath } : {});
1257
+ // The loader program is a build: it goes to the build folder. A loader program of an earlier run stays when this run checks no new one.
1258
+ const loaderPath = `${BUILD_DIRECTORY}/${loaderName}.prg`;
1259
+ const keptLoader = () => {
1260
+ const earlier = loaderPrograms().filter((path) => path.endsWith(".prg"));
1261
+ return earlier.length === 0 ? {} : { kept: earlier };
1262
+ };
1152
1263
  const notVerified = (fields: Record<string, unknown>) => ({ verified: false, ...fields, ...keptLoader() });
1153
1264
  // The loader includes the source, so it is built only from a source that is identical to the image.
1154
1265
  const notBuilt = (reason: string) => (state === undefined ? {} : { loader: notVerified({ reason: loaderRefused ?? reason }) });
@@ -1181,7 +1292,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1181
1292
  const releases: ReleaseCheck[] = [];
1182
1293
  for (const release of knowledge.releases) releases.push(await checkRelease(release, files, image));
1183
1294
  if (releases.length > 0) output.releases = releases;
1184
- const releasesFailed = releases.some((item) => item.result !== "identical" && (item.base || item.result !== "layout differs"));
1295
+ const releasesFailed = releases.some((item) => item.result !== "identical");
1185
1296
  const sourceFailed = laid.patchesNotWritten.length > 0 || switches.some((item) => item.result !== "fits") || defaultFailed || releasesFailed;
1186
1297
  if (loaderRefused !== undefined) return { output: { ...output, loader: notVerified({ reason: loaderRefused }) }, removed, failed: true };
1187
1298
  if (loader === undefined || loaderMain === undefined || state === undefined) return { output, removed, failed: missingEntry !== undefined || sourceFailed };
@@ -1194,7 +1305,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1194
1305
  const fileByte = (address: number) => copierBuild[2 + address - (loader.packed?.start ?? 0x0801)]!;
1195
1306
  // A start screen of a captured stage: the show stage holds the packed program, as a cracktro holds the game.
1196
1307
  const stageRow = knowledge.startScreen?.stage === undefined ? undefined : knowledge.startScreen;
1197
- // The packed form: Exomizer packs the build of main.asm with the copier. Without Exomizer, or when its check fails, there is no new loader.prg.
1308
+ // The packed form: Exomizer packs the build of main.asm with the copier. Without Exomizer, or when its check fails, there is no new loader program.
1198
1309
  let packed: PackedLoader | undefined;
1199
1310
  if (loader.packed !== undefined) {
1200
1311
  try {
@@ -1214,12 +1325,12 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1214
1325
  }
1215
1326
  }
1216
1327
  const program = stage?.program ?? packed?.program ?? copierBuild;
1217
- // The check runs the new loader from a scratch file. Only a loader whose check ran goes to --out, so a check
1218
- // that cannot run (no host, or a host of another release) keeps the loader.prg of an earlier run.
1328
+ // The check runs the new loader from a scratch file. Only a loader whose check ran goes to the build folder, so a check
1329
+ // that cannot run (no host, or a host of another release) keeps the loader program of an earlier run.
1219
1330
  ensureLocal(projectRoot());
1220
1331
  const scratch = `${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/${LOADER_CHECK_DIRECTORY}`;
1221
1332
  mkdirSync(resolveProjectPath(scratch), { recursive: true });
1222
- const checkPath = `${scratch}/loader.prg`;
1333
+ const checkPath = `${scratch}/${loaderName}.prg`;
1223
1334
  writeFileSync(resolveProjectPath(checkPath), program);
1224
1335
  // The unpack runs before the copier, or before the show stage, which then starts the loader.
1225
1336
  const unpackFrames = (cycles: number | undefined) => (cycles === undefined ? LOADER_FRAMES : RUN_LIMIT_FRAMES + Math.ceil(cycles / PAL_FRAME_CYCLES));
@@ -1230,21 +1341,29 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1230
1341
  return part.body[address - part.start]!;
1231
1342
  };
1232
1343
  const screenParts = stage === undefined ? [] : startScreenRanges(stageRow!).map(({ range }) => ({ start: range.start, body: Uint8Array.from({ length: range.end - range.start + 1 }, (_, offset) => stageByte(range.start + offset)) }));
1233
- const stageRun = stage === undefined ? {} : { stage: { name: stageRow!.stage!, wait: stage.wait, continue: stage.continue, screen: stage.screen, parts: screenParts, frames: unpackFrames(stage.packed.cycles) + LOADER_FRAMES } };
1344
+ const stageRun = stage === undefined ? {} : { stage: { name: stageRow!.stage!, wait: stage.wait, continue: stage.continue, screen: stage.screen, parts: screenParts, ...(stage.colourRam === undefined ? {} : { colourRam: stage.colourRam }), frames: unpackFrames(stage.packed.cycles) + LOADER_FRAMES } };
1234
1345
  let ran: LoaderRun;
1235
1346
  try {
1236
1347
  ran = await runLoader(checkPath, program, loader, state, { jump, copierSource, fileByte, copierFrames, ...(startScreen === undefined ? {} : { startScreen }), ...stageRun }, expected);
1237
1348
  } catch (error) {
1238
1349
  if (!isRefusal(error)) throw error;
1239
- const what = existsSync(resolveProjectPath(loaderPath)) ? "kept the loader.prg of an earlier run" : "wrote no loader.prg";
1240
- return { output: { ...output, loader: notVerified({ reason: `The check of loader.prg did not run, so the script ${what}. ${error.message}` }) }, removed, failed: true };
1350
+ const what = loaderPrograms().length > 0 ? "kept the loader program of an earlier run" : "wrote no loader program";
1351
+ return { output: { ...output, loader: notVerified({ reason: `The check of ${loaderName}.prg did not run, so the script ${what}. ${error.message}` }) }, removed, failed: true };
1241
1352
  } finally {
1242
1353
  rmSync(resolveProjectPath(scratch), { recursive: true, force: true });
1243
1354
  }
1244
- written.push(writeReported(loaderPath, program, { what: "--out" }));
1355
+ // A loader program of an earlier run with another build name goes: config.asm has other values now.
1356
+ // The files of an earlier show stage go when this loader has no stage and this run did not write them.
1357
+ const stageFiles = stage === undefined ? [...STAGE_FILES].filter((name) => !files.some((file) => file.name === name)).map((name) => `${out}/${name}`).filter((path) => existsSync(resolveProjectPath(path)) && readFileSync(resolveProjectPath(path), "utf8").startsWith(GENERATED_MARK)) : [];
1358
+ for (const path of [...loaderPrograms().filter((item) => item !== loaderPath && item !== symbolsPath(loaderPath)), ...stageFiles]) {
1359
+ rmSync(resolveProjectPath(path), { force: true });
1360
+ removed.push(path);
1361
+ }
1362
+ written.push(writeReported(loaderPath, program), writeReported(symbolsPath(loaderPath), symbolsFileText(loaderSymbols(loaderMain.symbols, loaderBuilt.symbols, stage?.symbols ?? []))));
1245
1363
  if (stage !== undefined) written.push(writeReported(`${out}/${STAGE_FILE}`, stage.text, { what: "--out" }), writeReported(`${out}/${START_SCREEN_FILE}`, `${GENERATED_LINE}\n${START_SCREEN_CODE}`, { what: "--out" }));
1246
1364
  output.loader = {
1247
1365
  program: loaderPath,
1366
+ symbols: symbolsPath(loaderPath),
1248
1367
  ...(packed === undefined ? {} : { packed: { packedBytes: packed.packedBytes, unpackedBytes: packed.unpackedBytes } }),
1249
1368
  ...(stage === undefined
1250
1369
  ? {}
@@ -1276,15 +1395,21 @@ function exportValue(row: SourceSwitch): 0 | 1 {
1276
1395
 
1277
1396
  const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
1278
1397
 
1279
- /** The entry of a PRG without one in the knowledge: the address of the first SYS of its BASIC line, when the image holds it. */
1280
- function basicEntry(image: ProgramImage): number | undefined {
1398
+ /**
1399
+ * The BASIC line that starts a PRG: its bytes, and the address of its first
1400
+ * SYS when the image holds it (the entry of a PRG without one in the
1401
+ * knowledge). Undefined when the first segment holds no BASIC line with a SYS.
1402
+ */
1403
+ function basicStart(image: ProgramImage): { line: AddressRange; entry?: number } | undefined {
1281
1404
  const first = image.segments[0];
1282
1405
  if (first === undefined) return undefined;
1283
1406
  const tokenized = parseTokenized(Uint8Array.from([first.start & 0xff, first.start >> 8, ...image.memory.subarray(first.start, first.end + 1)]));
1284
1407
  if ("reason" in tokenized) return undefined;
1285
- const sys = findHandoffs(tokenized.lines).find((handoff) => handoff.kind === "sys" && "address" in handoff);
1286
- const address = sys !== undefined && "address" in sys ? sys.address : undefined;
1287
- return address !== undefined && image.segments.some((segment) => address >= segment.start && address <= segment.end) ? address : undefined;
1408
+ const sys = findHandoffs(tokenized.lines).find((handoff) => handoff.kind === "sys");
1409
+ if (sys === undefined) return undefined;
1410
+ const line = { start: first.start, end: Math.min(first.end, tokenized.basicEnd - 1) };
1411
+ const address = "address" in sys ? sys.address : undefined;
1412
+ return address !== undefined && image.segments.some((segment) => address >= segment.start && address <= segment.end) ? { line, entry: address } : { line };
1288
1413
  }
1289
1414
 
1290
1415
  /** The parts of a region outside the holes. A part that is not the whole region has no element size: its length need not be a multiple of it. */
@@ -1323,9 +1448,10 @@ function freeRanges(knowledge: SourceKnowledge, memory: Uint8Array, instructions
1323
1448
  for (const operand of knowledge.operands) {
1324
1449
  const names = operand.symbol !== undefined ? [operand.symbol] : identifiers(operand.expression ?? "");
1325
1450
  const targets = names.flatMap((item) => (addressOf.has(item) ? [(addressOf.get(item)! + (operand.symbol !== undefined ? operand.offset : 0)) & 0xffff] : []));
1326
- if (targets.length > 0) operandTargets.set(operand.address, targets);
1451
+ operandTargets.set(operand.address, targets);
1327
1452
  }
1328
- const entry = image.entry ?? basicEntry(image);
1453
+ const basic = basicStart(image);
1454
+ const entry = image.entry ?? basic?.entry;
1329
1455
  return planDrops({
1330
1456
  segments: image.segments,
1331
1457
  memory,
@@ -1335,6 +1461,8 @@ function freeRanges(knowledge: SourceKnowledge, memory: Uint8Array, instructions
1335
1461
  regions: effectiveRegions(knowledge.regions),
1336
1462
  references: knowledge.references,
1337
1463
  operandTargets,
1464
+ rom: romOf(image, knowledge, [], knowledge.coverage),
1465
+ ...(basic === undefined ? {} : { basic: basic.line }),
1338
1466
  changed: [...ranges.changed],
1339
1467
  keep: [...ranges.keep],
1340
1468
  drop: [...ranges.drop],
@@ -1354,9 +1482,12 @@ function leftoversOf(knowledge: SourceKnowledge, instructions: ReadonlyMap<numbe
1354
1482
  const addressOf = new Map(knowledge.symbols.map((symbol) => [symbol.name, symbol.address]));
1355
1483
  const screenParts = knowledge.startScreen === undefined || knowledge.startScreen.stage !== undefined ? [] : startScreenRanges(knowledge.startScreen).map((part) => part.range);
1356
1484
  const named = knowledge.patches.flatMap((patch) => patchTargets(patch.code, addressOf)).map((address) => ({ start: address, end: address }));
1357
- const keep = [...screenParts, ...kept, ...knowledge.macroUses, ...named].map((range) => ({ start: range.start, end: range.end })).filter(inImage);
1485
+ const keep = [...screenParts, ...kept, ...named].map((range) => ({ start: range.start, end: range.end })).filter(inImage);
1358
1486
  const changed = knowledge.patches.map((patch) => ({ start: patch.start, end: patch.end })).filter(inImage);
1359
- return freeRanges(knowledge, image.memory, instructions, { changed, keep, drop: [] }).free.map((range) => ({ start: range.start, end: range.end }));
1487
+ const free = freeRanges(knowledge, image.memory, instructions, { changed, keep, drop: [] }).free.map((range) => ({ start: range.start, end: range.end }));
1488
+ // A macro use in code that nothing uses goes with that code. A leftover never cuts a use in two: its edge stops at the use.
1489
+ const cut = (range: AddressRange) => knowledge.macroUses.filter((use) => use.start <= range.end && range.start <= use.end && (use.start < range.start || use.end > range.end));
1490
+ return free.flatMap((range) => subtract(range, cut(range)));
1360
1491
  }
1361
1492
 
1362
1493
  /** Every file in a folder with its path in it, with / between the parts, in path order. `skip` leaves out a folder by its path. */
@@ -1564,7 +1695,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1564
1695
  ),
1565
1696
  );
1566
1697
  for (const file of exported.files) files.push(put(`src/${file.name}`, file.text));
1567
- files.push(put(`baseline/${name}.prg`, baseline.program), put(`baseline/${name}.json`, symbolsFileText(shownSymbols)));
1698
+ files.push(put(`baseline/${name}.prg`, baseline.program), put(symbolsPath(`baseline/${name}.prg`), symbolsFileText(shownSymbols)));
1568
1699
  for (const test of tests) files.push(put(test.file, test.text));
1569
1700
  ensureLocal(to);
1570
1701
  const folder = basename(to);
@@ -1578,7 +1709,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1578
1709
  to: fromProject(to),
1579
1710
  zip: zipWritten,
1580
1711
  source: { project: basename(project), revision: knowledge.revision },
1581
- files: listed(files.map((file) => ({ ...file, out: fromProject(join(to, file.out)) })), max, (file) => file, "the folder of the new project"),
1712
+ files: listed(files.map((file) => ({ ...file, out: fromProject(join(to, file.out)) })), max, (file) => file, "a larger --max-listed, or list the folder of the new project"),
1582
1713
  switches,
1583
1714
  check: exportCheck,
1584
1715
  ...(loaderOutput === undefined ? {} : { loader: loaderOutput }),
@@ -1639,9 +1770,9 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
1639
1770
  steps.push("Read the reason of each item in patchesNotWritten, and the result of each switch and of the default build. Correct the patches and the switches in the project knowledge.");
1640
1771
  again = true;
1641
1772
  }
1642
- const releases = body.releases as Array<{ result: string; base: boolean }> | undefined;
1643
- if (releases?.some((item) => item.result !== "identical" && (item.base || item.result !== "layout differs")) === true) {
1644
- steps.push("Read the result of each release. Put back a changed file, or record a switch and a patch in the project knowledge for each difference.");
1773
+ const releases = body.releases as Array<{ result: string }> | undefined;
1774
+ if (releases?.some((item) => item.result !== "identical") === true) {
1775
+ steps.push("Read the result of each release. Record a switch and a patch in the project knowledge for each difference.");
1645
1776
  again = true;
1646
1777
  }
1647
1778
  if ((body.loader as { verified?: boolean } | undefined)?.verified === false) steps.push("The loader is not verified. Read loader.reason, loader.differences and loader.stop.");
@@ -1660,15 +1791,17 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
1660
1791
  }
1661
1792
  if ([body.asBytes, body.operandsAsNumbers, body.macrosAsInstructions, body.patchesNotWritten].some(isCut)) steps.push("To see all items of a list, give a larger --max-listed.");
1662
1793
  const staleLoader = body.staleLoader as { noEntryState?: boolean } | undefined;
1663
- if (steps.length === 0 && staleLoader === undefined) return reply(body, { hint: "Read the source. Record names, comments, regions and modules in the project knowledge. Then generate again." });
1794
+ // The reference is made from the source: it is the step after this run, also when the run has no finding.
1795
+ const reference = body.staleReference === undefined ? "" : " The reference pages in staleReference are from an earlier revision of this source. Generate the reference pages again from this source.";
1796
+ if (steps.length === 0 && staleLoader === undefined) return reply(body, { hint: `Read the source. Record names, comments, regions and modules in the project knowledge. Then generate again.${reference}` });
1664
1797
  if (again) steps.push("Then generate again.");
1665
1798
  // The run with --loader writes the loader again, so it is the next action also for the other findings.
1666
1799
  const loaderAgain = staleLoader !== undefined && staleLoader.noEntryState !== true;
1667
1800
  if (staleLoader !== undefined) {
1668
- steps.push("The loader files in staleLoader.files are of another knowledge revision, and the run kept them.");
1801
+ steps.push("The loader files in staleLoader.files are of another knowledge revision or toolkit version, and the run kept them.");
1669
1802
  steps.push(loaderAgain ? "To write the loader of this revision, generate with --loader." : "The knowledge has no entry state, so --loader cannot write them again. Remove them when the build does not use them.");
1670
1803
  }
1671
- return reply(body, { hint: steps.join(" "), ...(again || loaderAgain ? { nextAction: generateAgain(call, call.flag("loader") || loaderAgain) } : {}) });
1804
+ return reply(body, { hint: `${steps.join(" ")}${reference}`, ...(again || loaderAgain ? { nextAction: generateAgain(call, call.flag("loader") || loaderAgain) } : {}) });
1672
1805
  }
1673
1806
 
1674
1807
  /** The hint of an export result: the action for a failed stage, or the next steps for the new project. */
@@ -1696,16 +1829,16 @@ await runScript({
1696
1829
  commands: [
1697
1830
  {
1698
1831
  name: "generate",
1699
- summary: "Writes the source files, source-map.json and not_executed.json, and checks them. result is PASS when every check passes, else FAIL.",
1832
+ summary: "Writes the source files to --out and checks them. The source map and not_executed.json go to .c64-re-tools/local/generated/<dir>/. result is PASS when every check passes, else FAIL.",
1700
1833
  options: {
1701
1834
  out: { ...OPTIONS.out, output: "folder", value: "<dir>", help: "the folder for the source files, relative to the project folder", required: true },
1702
1835
  entry: { ...OPTIONS.entry, multiple: true, help: "an address where code starts. The entry of the program, the routines and the code regions of the knowledge are entry points too" },
1703
- space: { ...OPTIONS.space, help: "the knowledge space of the program: c64 (the default), drive8, or bank0 to bank255. --loader is for c64 only" },
1704
- loader: { kind: "flag", help: "also write loader.asm and loader.prg: the loader copies the segments into place, sets the entry state of the knowledge, and jumps to the entry. It is checked in the emulator. The loader leaves out the leftovers. When the check cannot run, the script keeps the loader.prg of an earlier run" },
1836
+ space: { ...OPTIONS.space, help: "the knowledge space of the program: c64 (the default), drive8, loading, or bank0 to bank255. --loader is for c64 only" },
1837
+ loader: { kind: "flag", help: "also write loader.asm, and write the loader program to build/<build>_loader.prg (build/clean_loader.prg with the defaults of config.asm), with its symbols in build/symbols/: the loader copies the segments into place, sets the entry state of the knowledge, and jumps to the entry. It is checked in the emulator. The loader leaves out the leftovers. When the check cannot run, the script keeps the loader program of an earlier run" },
1705
1838
  "analyzer-names": { kind: "flag", help: "name an address that has no name of the user or the LLM, and no platform name, with its analyzer name" },
1706
1839
  "max-listed": OPTIONS["max-listed"],
1707
1840
  },
1708
- notes: "The program, its entry state and the coverage come from the knowledge: put them into the project knowledge first. Code that no imported run executed is marked and listed, and <dir>/not_executed.json has all of its ranges. Without --analyzer-names, an address without a name gets a name of the source, for example l_17e2.",
1841
+ notes: "The program, its entry state and the coverage come from the knowledge: put them into the project knowledge first. Code that no imported run executed is marked and listed, and .c64-re-tools/local/generated/<dir>/not_executed.json has all of its ranges. Without --analyzer-names, an address without a name gets a name of the source, for example l_17e2.",
1709
1842
  run: async (call) => {
1710
1843
  const { output, failed, removed } = await generate(call);
1711
1844
  // A file of an earlier run that this run removed and did not write again.
@@ -1724,7 +1857,7 @@ await runScript({
1724
1857
  drop: { ...OPTIONS.range, multiple: true, help: "a range that becomes free: code that the entry does not reach (see unreachableExecuted), or data. Nothing that stays may go to it or read it" },
1725
1858
  "max-listed": OPTIONS["max-listed"],
1726
1859
  },
1727
- notes: "Fixes, trainers and cheats are in, protection and crack changes are out, and a change keeps its default. Code becomes free only when no run executed it and nothing reaches it; data only when no run touched it and nothing names it. Charset, sprite, bitmap and screen data stay unless --drop names them. Addresses do not move: a free range is $00 with a label free_xxxx. The export needs coverage in the knowledge to make ranges free by itself.",
1860
+ notes: "Fixes, trainers and cheats are in, protection and crack changes are out, and a change keeps its default. Code becomes free only when no run executed it and nothing reaches it; data only when no run touched it and nothing names it. Charset, sprite, bitmap and screen data, and data in them, stay unless --drop names them. Addresses do not move: a free range is $00 with a label free_xxxx. The export needs coverage in the knowledge to make ranges free by itself.",
1728
1861
  run: async (call) => exportReply(await exportProject(call)),
1729
1862
  },
1730
1863
  ],