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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +1 -1
  3. package/skills/c64-assembler/scripts/assembler.ts +78 -24
  4. package/skills/c64-docs/scripts/docs.ts +31 -10
  5. package/skills/c64-knowledge/SKILL.md +4 -3
  6. package/skills/c64-knowledge/scripts/knowledge.ts +31 -12
  7. package/skills/c64-packer/scripts/packer.ts +9 -2
  8. package/skills/c64-provenance/SKILL.md +1 -1
  9. package/skills/c64-provenance/scripts/lib/runtime.ts +5 -16
  10. package/skills/c64-source/references/loader.md +8 -7
  11. package/skills/c64-source/scripts/lib/loader.ts +4 -111
  12. package/skills/c64-source/scripts/source.ts +49 -78
  13. package/skills/c64-static-analysis/SKILL.md +2 -2
  14. package/skills/c64-static-analysis/scripts/lib/coverage.ts +56 -4
  15. package/skills/c64-static-analysis/scripts/static-analysis.ts +32 -21
  16. package/skills/c64-testing/SKILL.md +6 -0
  17. package/skills/c64-testing/scripts/lib/play.ts +8 -7
  18. package/skills/c64-testing/scripts/lib/recording.ts +218 -12
  19. package/skills/c64-testing/scripts/lib/replay.ts +7 -3
  20. package/skills/c64-testing/scripts/lib/runs.ts +5 -1
  21. package/skills/c64-testing/scripts/lib/scenario.ts +4 -0
  22. package/skills/c64-testing/scripts/testing.ts +24 -11
  23. package/skills/c64-unpacker/SKILL.md +6 -4
  24. package/skills/c64-unpacker/scripts/lib/loads.ts +4 -2
  25. package/skills/c64-unpacker/scripts/lib/machine.ts +128 -5
  26. package/skills/c64-unpacker/scripts/lib/stages.ts +5 -1
  27. package/skills/c64-unpacker/scripts/unpacker.ts +13 -12
  28. package/skills/emulator/SKILL.md +2 -2
  29. package/src/host/vice/adapter.ts +2 -1
  30. package/src/host-client/image.ts +33 -4
  31. package/src/host-client/tools.ts +1 -1
  32. package/src/host-client/transfer.ts +48 -26
  33. package/src/host-client/vice-session.ts +15 -0
  34. package/src/knowledge/database.ts +72 -19
  35. package/src/knowledge/import.ts +31 -8
  36. package/src/knowledge/names.ts +2 -2
  37. package/src/knowledge/program.ts +67 -7
  38. package/src/knowledge/schema.ts +6 -0
  39. package/src/knowledge/start-screen.ts +55 -2
  40. package/src/knowledge/write.ts +18 -12
  41. package/src/loader.ts +101 -33
  42. package/src/mcp/output.ts +13 -12
  43. package/src/mcp/server.ts +33 -22
  44. package/src/mcp/tools/debug.ts +21 -24
  45. package/src/mcp/tools/media.ts +27 -27
  46. package/src/mcp/tools/memory.ts +13 -17
  47. package/src/mcp/tools/video.ts +10 -12
  48. package/src/native/c64run.ts +39 -1
  49. package/src/native/decompiler/analyze.ts +1 -1
  50. package/src/native/dxa.ts +2 -2
  51. package/src/native/types.ts +26 -7
  52. package/src/program-code.ts +4 -2
  53. package/src/project.ts +224 -71
  54. package/src/protocol/vice.ts +5 -3
  55. package/src/script.ts +60 -15
  56. package/{skills/c64-source/scripts/lib → src}/stage.ts +142 -11
  57. package/tools/c64run.c +18 -5
@@ -19,12 +19,12 @@ import { readFileSync } from "node:fs";
19
19
  import { fileURLToPath } from "node:url";
20
20
 
21
21
  import { COPIER_LINE } from "#src/build-name.ts";
22
- import { type AddressRange, formatC64Address, formatC64Byte, formatC64Range, hexWord, rangesOverlap, subtract, underRom } from "#src/c64.ts";
22
+ import { type AddressRange, formatC64Address, formatC64Byte, formatC64Range, rangesOverlap, subtract, underRom } from "#src/c64.ts";
23
23
  import { Refusal } from "#src/errors.ts";
24
24
  import { parseEntryState } from "#src/host-client/entry-state.ts";
25
- import { isRomFont, startScreenRanges, type StartScreenRow } from "#src/knowledge/read.ts";
26
- import { capturedColourRam, LOADER_JUMP } from "#src/knowledge/start-screen.ts";
27
- import { COPIER_SOURCE } from "#src/loader.ts";
25
+ import { startScreenRanges, type StartScreenRow } from "#src/knowledge/read.ts";
26
+ import { capturedColourRam, LOADER_JUMP, START_SCREEN_FILE, startScreenPlan, startScreenValues, type StartScreenPlan } from "#src/knowledge/start-screen.ts";
27
+ import { blockLabel, COPIER_SOURCE, largestFree, type Piece, placePieces, settingsLines } from "#src/loader.ts";
28
28
  import { romUseOfPort } from "#src/platform.ts";
29
29
  import { WireFailure } from "#src/host-client/tools.ts";
30
30
 
@@ -145,61 +145,11 @@ export function loaderLimits(plan: { cia?: CiaPlan; colourLimit?: string }): str
145
145
  return [...cia, ...(plan.colourLimit === undefined ? [] : [plan.colourLimit])];
146
146
  }
147
147
 
148
- /** The file of the start screen in the generated source. */
149
- export const START_SCREEN_FILE = "start_screen.asm";
150
148
  /** The code of the start screen: the same for each program. loader.asm sets its values. */
151
149
  export const START_SCREEN_CODE = readFileSync(fileURLToPath(new URL("./start-screen.asm", import.meta.url)), "utf8");
152
150
  /** The bytes of the start screen code for each colour mode: none, one colour, a copy of 1000 bytes. */
153
151
  export const START_SCREEN_SIZES = [197, 216, 226] as const;
154
152
 
155
- /** The VIC-II values of a start screen, as the start screen code sets them. */
156
- export interface StartScreenPlan {
157
- d011: number;
158
- d016: number;
159
- d018: number;
160
- /** The VIC bank: 0 for $0000-$3fff to 3 for $c000-$ffff. */
161
- bank: number;
162
- border: number;
163
- background: number;
164
- /** 0: no colour RAM (hires), 1: one colour, 2: a copy of 1000 bytes. */
165
- colourMode: 0 | 1 | 2;
166
- }
167
-
168
- /** The VIC-II values that show a start screen of the knowledge. */
169
- export function startScreenPlan(row: StartScreenRow): StartScreenPlan {
170
- const bank = row.screen >> 14;
171
- const base = (row.bitmap === undefined ? ((row.charset! & 0x3fff) >> 11) << 1 : ((row.bitmap & 0x3fff) >> 13) << 3) | 0x01;
172
- return {
173
- d011: row.mode === "text" ? 0x1b : 0x3b,
174
- d016: row.mode === "multicolour" ? 0x18 : 0x08,
175
- d018: (((row.screen & 0x3fff) >> 10) << 4) | base,
176
- bank,
177
- border: row.border,
178
- background: row.background,
179
- colourMode: row.colours !== undefined || row.colourRam === true ? 2 : row.colour !== undefined ? 1 : 0,
180
- };
181
- }
182
-
183
- /** The lines of loader.asm that give the start screen code its values. */
184
- export function startScreenValues(row: StartScreenRow, plan: StartScreenPlan): string[] {
185
- const value = (name: string, number: number, comment?: string) => `c64_source_ss_${name} = ${formatC64Byte(number)}${comment === undefined ? "" : ` ; ${comment}`}`;
186
- const font = row.charset !== undefined && isRomFont(row.charset) ? " (the character ROM)" : "";
187
- const what = [`screen ${formatC64Address(row.screen)}`, ...(row.bitmap === undefined ? [] : [`bitmap ${formatC64Address(row.bitmap)}`]), ...(row.charset === undefined ? [] : [`charset ${formatC64Address(row.charset)}${font}`])];
188
- return [
189
- `; The start screen: ${row.mode}, ${what.join(", ")}.${row.comment === undefined ? "" : ` ${row.comment.replace(/\s*\r?\n\s*/g, " ")}`}`,
190
- value("d011", plan.d011),
191
- value("d016", plan.d016),
192
- value("d018", plan.d018),
193
- value("bank", 3 - plan.bank, `VIC bank ${formatC64Address(plan.bank << 14)}-${formatC64Address((plan.bank << 14) + 0x3fff)}`),
194
- value("border", plan.border),
195
- value("background", plan.background),
196
- value("colour_mode", plan.colourMode),
197
- value("colour", row.colour ?? 0),
198
- // The colour RAM of a captured stage is in the show code: STAGE_COLOURS in stage.ts.
199
- `c64_source_ss_colours = ${row.colourRam === true ? "c64_source_stage_colours" : formatC64Address(row.colours ?? 0)}`,
200
- ];
201
- }
202
-
203
153
  /** The copier lines that include the start screen code, in a zone of its own. */
204
154
  const START_SCREEN_LINES = ["!zone c64_source_start_screen {", `!source "${START_SCREEN_FILE}"`, "}"];
205
155
 
@@ -475,14 +425,6 @@ function checkStartScreen(input: LoaderInput): StartScreenPlan | undefined {
475
425
  return startScreenPlan(row);
476
426
  }
477
427
 
478
- /** The settings that loader.asm and the show stage include: switches.asm, else config.asm for a start screen, else none. */
479
- export function settingsLines(input: Pick<LoaderInput, "switches" | "config">): string[] {
480
- if (input.switches === true) return ['!source "switches.asm"'];
481
- return input.config === true ? ['!source "config.asm"'] : [];
482
- }
483
-
484
- /** The label of a block: its first byte and the byte after it in the loader file, and its first address where it runs. */
485
- const blockLabel = (start: number, part: "from" | "end" | "to") => `loader_${part}_${hexWord(start)}`;
486
428
  const plus = (label: string, offset: number) => (offset === 0 ? label : `${label}+${offset}`);
487
429
 
488
430
  /** A block of the loader: a segment with its files, or bytes of pages 0-3. */
@@ -698,14 +640,6 @@ export function copierAreas(port: readonly [number, number]): AddressRange[] {
698
640
  if (rom.basic) return [{ start: 0x0400, end: 0x9fff }, { start: 0xc000, end: 0xcfff }];
699
641
  return [{ start: 0x0400, end: 0xcfff }, ...(rom.kernal ? [] : [{ start: 0xe000, end: BELOW_VECTORS }])];
700
642
  }
701
- /** The free ranges that a refusal names. */
702
- const SHOWN_FREE = 8;
703
-
704
- /** The largest free ranges with their sizes, for a refusal: at most SHOWN_FREE of them, or none. */
705
- export function largestFree(ranges: readonly AddressRange[]): string {
706
- const shown = [...ranges].sort((a, b) => b.end - b.start - (a.end - a.start)).slice(0, SHOWN_FREE);
707
- return shown.length === 0 ? "none" : shown.map((range) => `${formatC64Range(range)} (${range.end - range.start + 1} bytes)`).join(", ");
708
- }
709
643
 
710
644
  /**
711
645
  * The packed form of the loader, for an image too large for one loader file:
@@ -811,47 +745,6 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
811
745
  };
812
746
  }
813
747
 
814
- /** A piece of pages 0-3 in the packed form: its target and where the copier reads it. */
815
- export interface Piece {
816
- what: string;
817
- target: AddressRange;
818
- at: number;
819
- bytes: (address: number) => number;
820
- }
821
-
822
- /**
823
- * Puts the parts of pages 0-3 into the free ranges, in their order: each time
824
- * into the nearest range that holds the rest, else into the largest range.
825
- * A part that does not fit in one range is split, and each piece is a copy.
826
- * Undefined when the ranges are too small.
827
- */
828
- export function placePieces(ranges: AddressRange[], low: ReadonlyArray<{ what: string; range: AddressRange; bytes: (address: number) => number }>, distance: (range: AddressRange) => number): Piece[] | undefined {
829
- const left = ranges.map((range) => ({ ...range }));
830
- const pieces: Piece[] = [];
831
- let rest = low.reduce((sum, block) => sum + block.range.end - block.range.start + 1, 0);
832
- const length = (range: AddressRange) => range.end - range.start + 1;
833
- let target: AddressRange | undefined;
834
- for (const block of low) {
835
- let next = block.range.start;
836
- while (next <= block.range.end) {
837
- if (target === undefined || target.start > target.end) {
838
- const open = left.filter((range) => range.start <= range.end);
839
- if (open.length === 0) return undefined;
840
- const holding = open.filter((range) => length(range) >= rest).sort((a, b) => distance(a) - distance(b));
841
- target = holding[0] ?? open.sort((a, b) => length(b) - length(a))[0]!;
842
- }
843
- const count = Math.min(block.range.end - next + 1, length(target));
844
- const part = { start: next, end: next + count - 1 };
845
- const cut = part.start !== block.range.start || part.end !== block.range.end;
846
- pieces.push({ what: cut ? `${block.what}, bytes ${formatC64Range(part)}` : block.what, target: part, at: target.start, bytes: block.bytes });
847
- target.start += count;
848
- next += count;
849
- rest -= count;
850
- }
851
- }
852
- return pieces;
853
- }
854
-
855
748
  /**
856
749
  * Where the packed form puts its copier and the pieces of pages 0-3: the copier
857
750
  * in one range of copierFree, a free page of the plain copier first, else the start of a
@@ -27,7 +27,7 @@ import { conflicts } from "#src/knowledge/conflicts.ts";
27
27
  import { withRead, withWrite } from "#src/knowledge/database.ts";
28
28
  import { identifiers } from "#src/knowledge/expression.ts";
29
29
  import { clipped, codeKnowledge, effectiveRegions } from "#src/knowledge/code-reach.ts";
30
- import { memoryRows, releaseImage, type ProgramImage } from "#src/knowledge/program.ts";
30
+ import { memoryRows, releaseImage, type ProgramImage, startScreenKey } from "#src/knowledge/program.ts";
31
31
  import { ANALYZER_NAME_ORDER, baseValue, currentRevision, sourceRevision, startScreenRanges, type StartScreenRow, listAnalyzerNames, listComments, listMacros, listMacroUses, listModules, listReleases, listSpaces, listSwitches, type ReleaseRow, type SymbolRow } from "#src/knowledge/read.ts";
32
32
  import { DEFAULT_SPACE, LEFTOVER_FOLDER, LEFTOVERS_SWITCH, RELEASE_DEFINE, START_SCREEN_SWITCH, type Space } from "#src/knowledge/schema.ts";
33
33
  import { write } from "#src/knowledge/write.ts";
@@ -35,7 +35,7 @@ import { assemble, symbolsFileText } from "#src/native/acme.ts";
35
35
  import { PAL_FRAME_CYCLES } from "#src/native/c64run.ts";
36
36
  import { decodeProgram, leftoverInput, reachInput } from "#src/program-code.ts";
37
37
  import { localToolContext } from "#src/native/local.ts";
38
- import type { AssembledSymbol, Diagnostic } from "#src/native/types.ts";
38
+ import { type AssembledSymbol, type Diagnostic, requiredLabel, symbolValues } from "#src/native/types.ts";
39
39
  import { decode as decodeRegister, describeAddress, platformNames, platformNamesFor, romUseOfProgram } from "#src/platform.ts";
40
40
  import { ensureLocal, generatedDirectory, LOCAL_DIRECTORY, newProjectFolder, PROJECT_DIRECTORY, projectRelative, projectRoot, resolveProjectPath } from "#src/project.ts";
41
41
  import { generatedReferences } from "#src/reference-pages.ts";
@@ -43,26 +43,22 @@ import { isoCet } from "#src/time.ts";
43
43
  import { zipFiles } from "#src/zip.ts";
44
44
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type Reply } from "#src/script.ts";
45
45
  import { knowledgeNames } from "#src/knowledge/names.ts";
46
- import { COPIER_SOURCE, leftoverRange, loaderSymbols, packLoader, packParts, type PackedLoader } from "#src/loader.ts";
46
+ import { COPIER_SOURCE, leftoverRange, loaderSymbols, packLoader, type PackedLoader, settingsLines } from "#src/loader.ts";
47
47
  import {
48
48
  loaderLimits,
49
49
  planLoader,
50
- startScreenPlan,
51
50
  rasterLine,
52
51
  loaderState,
53
- settingsLines,
54
52
  simulate,
55
53
  START_SCREEN_CODE,
56
- START_SCREEN_FILE,
57
54
  stopCause,
58
55
  VIC_DISPLAY_REGISTERS,
59
56
  type EntryState,
60
57
  type LoaderPlan,
61
- type StartScreenPlan,
62
58
  } from "./lib/loader.ts";
63
59
  import { instructionWith, OPCODES } from "#src/opcodes.ts";
64
- import { capturedColourRam, LOADER_JUMP, START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
65
- import { planStage, STAGE_CODE_END, STAGE_FILE, STAGE_START, stageParts, stageText, type StageInput, type StagePart, type StagePlan } from "./lib/stage.ts";
60
+ import { capturedColourRam, LOADER_JUMP, START_SCREEN_CONTINUE, START_SCREEN_FILE, START_SCREEN_WAIT, startScreenLabels, type StartScreenPlan } from "#src/knowledge/start-screen.ts";
61
+ import { packStage, type PackedStage, STAGE_FILE, type StageBytes, type StagePart } from "#src/stage.ts";
66
62
  import { freeName, planDrops, readmeText, rewriteTest } from "./lib/export.ts";
67
63
  import type { UnresolvedFlow } from "#src/knowledge/separate.ts";
68
64
  import { configText, entriesInData, entryOutsideImage, hasConfigFile, hasSwitchFile, layout, literalOperand, probeForms, render, stagePatchText, switchesOf, type Layout, type PatchBlock, type Rendered, type SourceSwitch } from "./lib/source.ts";
@@ -244,7 +240,7 @@ async function probeUses(laid: Layout, rendered: Rendered, image: ProgramImage):
244
240
  for (const [start, reason] of refused) blamed.set(start, reason);
245
241
  continue;
246
242
  }
247
- const ends = new Map((built.symbols ?? []).map((symbol) => [symbol.name, symbol.kind === "address" ? symbol.address : symbol.value]));
243
+ const ends = symbolValues(built.symbols ?? []);
248
244
  let offset = 2 + PROBE_BASE - built.start!;
249
245
  uses.forEach((use, index) => {
250
246
  const length = ends.get(`probe_end_${index}`)! - use.start;
@@ -620,6 +616,9 @@ const LOADER_FILES: ReadonlySet<string> = new Set(["loader.asm", START_SCREEN_FI
620
616
  /** 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. */
621
617
  const STAGE_FILES: ReadonlySet<string> = new Set([START_SCREEN_FILE, STAGE_FILE]);
622
618
 
619
+ /** The loader program of the defaults of config.asm: the default build of a source with a loader. */
620
+ const DEFAULT_LOADER = `${BUILD_DIRECTORY}/${buildName("loader.asm", { values: new Map(), defaults: new Map() })}.prg`;
621
+
623
622
  /** A loader program that generate wrote: its build name, as buildName gives it for loader.asm. */
624
623
  const LOADER_PROGRAM = /^(clean|custom_[a-z0-9_]+|release_[A-Za-z0-9_]+)_loader\.prg$/;
625
624
 
@@ -902,16 +901,13 @@ async function buildLoader(
902
901
  if (loaderBuilt.start !== (loader.packed?.start ?? 0x0801) || loaderBuilt.start + program.length - 3 !== loader.end || wrongPacking !== undefined) {
903
902
  throw new WireFailure("operation-failed", `The assembled loader does not have the planned layout${wrongPacking === undefined ? "" : ` (${wrongPacking.what})`}. This is a defect of the script.`);
904
903
  }
905
- const symbolValue = (name: string) => {
906
- const symbol = loaderBuilt.symbols?.find((item) => item.name === name);
907
- if (symbol === undefined) throw new WireFailure("operation-failed", `The assembled loader has no ${name} label. This is a defect of the script.`);
908
- return symbol.kind === "address" ? symbol.address : symbol.value;
909
- };
910
- const jump = symbolValue(LOADER_JUMP);
904
+ const labels = symbolValues(loaderBuilt.symbols ?? []);
905
+ const labelValue = (name: string) => requiredLabel(labels, name, "The assembled loader");
906
+ const jump = labelValue(LOADER_JUMP);
911
907
  const wrong = simulate(memory, loader.copies, expected);
912
908
  if (wrong !== undefined) throw new WireFailure("operation-failed", `The simulated loader writes a wrong byte at ${formatC64Address(wrong)}. This is a defect of the script.`);
913
- const startScreen = loader.startScreen === undefined ? undefined : { wait: symbolValue(START_SCREEN_WAIT), continue: symbolValue(START_SCREEN_CONTINUE) };
914
- return { program, symbols: loaderBuilt.symbols ?? [], jump, copierSource: symbolValue(COPIER_SOURCE), expected, ...(startScreen === undefined ? {} : { startScreen }) };
909
+ const startScreen = loader.startScreen === undefined ? undefined : { wait: labelValue(START_SCREEN_WAIT), continue: labelValue(START_SCREEN_CONTINUE) };
910
+ return { program, symbols: loaderBuilt.symbols ?? [], jump, copierSource: labelValue(COPIER_SOURCE), expected, ...(startScreen === undefined ? {} : { startScreen }) };
915
911
  }
916
912
 
917
913
  /**
@@ -921,7 +917,7 @@ async function buildLoader(
921
917
  * of the stage whose switch default is not its base value is in, as in the
922
918
  * default build. Pages 0-3 are left out: the unpacker of Exomizer uses them.
923
919
  */
924
- async function stageBytes(row: StartScreenRow): Promise<{ parts: StagePart[]; colourRam?: Uint8Array }> {
920
+ async function stageBytes(row: StartScreenRow): Promise<StageBytes> {
925
921
  const stage = row.stage!;
926
922
  const knowledge = readKnowledge(stage);
927
923
  const colourRam = row.colourRam === true ? capturedColourRam(knowledge.program.state) : undefined;
@@ -955,42 +951,16 @@ async function stageBytes(row: StartScreenRow): Promise<{ parts: StagePart[]; co
955
951
  }
956
952
 
957
953
  /** What the show stage gives: the loader program, the source of the stage, and what its check needs. */
958
- interface BuiltStage {
959
- program: Buffer;
960
- text: string;
961
- /** The labels of the build of start_screen_stage.asm. */
962
- symbols: AssembledSymbol[];
963
- plan: StagePlan;
964
- parts: StagePart[];
965
- colourRam?: Uint8Array;
966
- packed: PackedLoader;
967
- wait: number;
968
- continue: number;
969
- screen: StartScreenPlan;
970
- }
954
+ type BuiltStage = PackedStage & StageBytes;
971
955
 
972
956
  /**
973
- * Builds the show stage of a start screen from a captured stage: plans it,
974
- * assembles start_screen_stage.asm and packs it with the loader as the loader
975
- * is in memory before it starts. Refuses by name.
957
+ * Builds the show stage of a start screen from a captured stage around the
958
+ * packed program, with the bytes of the stage from the knowledge. A text of
959
+ * start_screen_stage.asm that does not assemble goes to the local folder.
960
+ * Refuses by name.
976
961
  */
977
962
  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> {
978
- const { parts: stage, colourRam } = await stageBytes(row);
979
- // The packed program, as RUN would start it: its unpacker unpacks it over the start screen after the wait.
980
- const inner: StagePart[] = [{ start: 0x0801, body: program.program.subarray(2) }];
981
- const screen = startScreenPlan(row);
982
- const input: StageInput = {
983
- inner,
984
- innerStart: 0x080d,
985
- innerPort: 0x37,
986
- stage,
987
- ...(colourRam === undefined ? {} : { colourRam }),
988
- row,
989
- plan: screen,
990
- settings: settingsLines({ switches: hasSwitchFile(laid), config: hasConfigFile(laid) }),
991
- header,
992
- codeSize: 0,
993
- };
963
+ const stage = await stageBytes(row);
994
964
  const support = [...withValues(files, laid, values).filter((file) => file.name === CONFIG_FILE || file.name === "switches.asm"), { name: START_SCREEN_FILE, text: START_SCREEN_CODE }];
995
965
  const assembleStage = async (text: string) => {
996
966
  const built = await assembleFiles([...support, { name: STAGE_FILE, text }], STAGE_FILE);
@@ -1002,25 +972,13 @@ async function buildStage(files: Array<{ name: string; text: string }>, laid: La
1002
972
  writeFileSync(resolveProjectPath(kept), `${mark}\n${text}`);
1003
973
  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.`);
1004
974
  }
1005
- const labels = new Map((built.symbols ?? []).map((symbol) => [symbol.name, symbol.kind === "address" ? symbol.address : symbol.value]));
1006
- const label = (name: string) => {
1007
- const value = labels.get(name);
1008
- if (value === undefined) throw new WireFailure("operation-failed", `The build of ${STAGE_FILE} has no ${name} label. This is a defect of the script.`);
1009
- return value;
1010
- };
1011
- return { program: built.program, symbols: built.symbols ?? [], label };
975
+ return { program: built.program, symbols: built.symbols ?? [] };
1012
976
  };
1013
- // The size of the show code does not depend on its address: one build without a stash and without the parts gives it.
1014
- const probe = await assembleStage(stageText({ ...input, stage: [] }, 0x1000, []));
1015
- input.codeSize = probe.label(STAGE_CODE_END) - probe.label(STAGE_START) - 2;
1016
- const plan = planStage(input);
1017
- const built = await assembleStage(plan.text);
1018
- if (built.label(STAGE_START) !== plan.code || built.label(STAGE_CODE_END) - plan.code !== input.codeSize + 6 * plan.stash.length + 2) throw new WireFailure("operation-failed", `The build of ${STAGE_FILE} does not have the planned layout. This is a defect of the script.`);
1019
- const parts = stageParts(input, plan, built.program, built.label);
1020
- const packed = await packParts(parts, plan.code, 0x37, "the loader and the start screen of the stage", "the show stage", localToolContext());
1021
- const end = 0x0801 + packed.program.length - 3;
1022
- 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.`);
1023
- 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 };
977
+ const settings = settingsLines({ switches: hasSwitchFile(laid), config: hasConfigFile(laid) });
978
+ // The key of the start screen goes into the file: a build with other switch values uses its bytes only for that start screen.
979
+ const key = withRead((db) => startScreenKey(db, row));
980
+ const built = await packStage(program.program, stage, row, { settings, header, key }, assembleStage, localToolContext());
981
+ return { ...built, text: `${mark}\n${built.text}`, ...stage };
1024
982
  }
1025
983
 
1026
984
  /** An operand expression that the source writes as a number, as a result lists it. */
@@ -1240,7 +1198,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1240
1198
  return { output: { ...output, loader: notVerified({ reason: `The show stage of the start screen from ${stageRow.stage} cannot be built. ${error.message}` }) }, removed, failed: true };
1241
1199
  }
1242
1200
  }
1243
- const program = stage?.program ?? packed?.program ?? copierBuild;
1201
+ const program = stage?.packed.program ?? packed?.program ?? copierBuild;
1244
1202
  // The check runs the new loader from a scratch file. Only a loader whose check ran goes to the build folder, so a check
1245
1203
  // that cannot run (no host, or a host of another release) keeps the loader program of an earlier run.
1246
1204
  ensureLocal(projectRoot());
@@ -1250,17 +1208,21 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1250
1208
  writeFileSync(resolveProjectPath(checkPath), program);
1251
1209
  // The unpack runs before the copier, or before the show stage, which then starts the loader.
1252
1210
  const unpackFrames = (cycles: number | undefined) => (cycles === undefined ? LOADER_FRAMES : RUN_LIMIT_FRAMES + Math.ceil(cycles / PAL_FRAME_CYCLES));
1253
- const copierFrames = packed === undefined ? RUN_LIMIT_FRAMES : unpackFrames(packed.cycles);
1211
+ // A build with START_SCREEN = 0 or LEFTOVERS = 1 has the labels of the start screen, but goes on at once: the check waits only for a start screen that shows.
1212
+ const shows = (symbols: readonly AssembledSymbol[]) => startScreenLabels(symbolValues(symbols)) !== undefined;
1213
+ const stageShown = stage !== undefined && shows(stage.symbols);
1214
+ // A show stage that goes on at once unpacks the loader right after its own unpack.
1215
+ const copierFrames = (packed === undefined ? RUN_LIMIT_FRAMES : unpackFrames(packed.cycles)) + (stage === undefined || stageShown ? 0 : unpackFrames(stage.packed.cycles));
1254
1216
  // The check compares the bytes of the screen of the stage: a routine of the stage can change its other bytes.
1255
1217
  const stageByte = (address: number) => {
1256
1218
  const part = stage!.parts.find((item) => address >= item.start && address < item.start + item.body.length)!;
1257
1219
  return part.body[address - part.start]!;
1258
1220
  };
1259
1221
  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)) }));
1260
- 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 } };
1222
+ const stageRun = stage === undefined || !stageShown ? {} : { 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 } };
1261
1223
  let ran: LoaderRun;
1262
1224
  try {
1263
- ran = await runLoader(checkPath, program, loader, state, { jump, copierSource, fileByte, copierFrames, ...(startScreen === undefined ? {} : { startScreen }), ...stageRun }, expected);
1225
+ ran = await runLoader(checkPath, program, loader, state, { jump, copierSource, fileByte, copierFrames, ...(startScreen === undefined || !shows(loaderBuilt.symbols) ? {} : { startScreen }), ...stageRun }, expected);
1264
1226
  } catch (error) {
1265
1227
  if (!isRefusal(error)) throw error;
1266
1228
  const what = loaderPrograms().length > 0 ? "kept the loader program of an earlier run" : "wrote no loader program";
@@ -1505,7 +1467,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1505
1467
  // 7. The tests of the project, changed for the new project.
1506
1468
  const testsFolder = join(project, "tests");
1507
1469
  const testFiles = existsSync(testsFolder) ? readdirSync(testsFolder, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name).sort() : [];
1508
- const symbolMap = new Map(shownSymbols.map((symbol) => [symbol.name, symbol.kind === "address" ? symbol.address : symbol.value]));
1470
+ const symbolMap = symbolValues(shownSymbols);
1509
1471
  const tests: Array<{ file: string; kind: "scenario" | "run"; text: string }> = [];
1510
1472
  const testsLeftOut: Array<{ file: string; reason: string }> = [];
1511
1473
  for (const file of testFiles) {
@@ -1640,9 +1602,18 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
1640
1602
  }
1641
1603
  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.");
1642
1604
  const staleLoader = body.staleLoader as { noEntryState?: boolean } | undefined;
1643
- // The reference is made from the source: it is the step after this run, also when the run has no finding.
1644
- 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.";
1645
- 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}` });
1605
+ // The default loader program goes when config.asm has other values, and the replays of the default build need it.
1606
+ const loaderGone = body.config !== undefined && ((body.removed as string[] | undefined) ?? []).includes(DEFAULT_LOADER);
1607
+ // The notes after the steps. The reference is made from the source: it is the step after this run, also when the run has no finding.
1608
+ const notes = [
1609
+ ...(loaderGone
1610
+ ? [`The run removed the default loader program ${DEFAULT_LOADER}, because config.asm does not have the default switch values (config.notDefault). To make it again, set the defaults in config.asm, and generate with --loader. To get the loader program of other switch values without a change to the source, build main.asm with the build option --switch.`]
1611
+ : []),
1612
+ ...(body.staleReference === undefined ? [] : ["The reference pages in staleReference are from an earlier revision of this source. Generate the reference pages again from this source."]),
1613
+ ]
1614
+ .map((note) => ` ${note}`)
1615
+ .join("");
1616
+ 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.${notes}` });
1646
1617
  if (again) steps.push("Then generate again.");
1647
1618
  // The run with --loader writes the loader again, so it is the next action also for the other findings.
1648
1619
  const loaderAgain = staleLoader !== undefined && staleLoader.noEntryState !== true;
@@ -1650,7 +1621,7 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
1650
1621
  steps.push("The loader files in staleLoader.files are of another knowledge revision or toolkit version, and the run kept them.");
1651
1622
  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.");
1652
1623
  }
1653
- return reply(body, { hint: `${steps.join(" ")}${reference}`, ...(again || loaderAgain ? { nextAction: generateAgain(call, call.flag("loader") || loaderAgain) } : {}) });
1624
+ return reply(body, { hint: `${steps.join(" ")}${notes}`, ...(again || loaderAgain ? { nextAction: generateAgain(call, call.flag("loader") || loaderAgain) } : {}) });
1654
1625
  }
1655
1626
 
1656
1627
  /** The hint of an export result: the action for a failed stage, or the next steps for the new project. */
@@ -102,7 +102,7 @@ The script records only structure: code and data regions, analyzer names, and th
102
102
 
103
103
  - `analyzer`: `dxa` or `decompiler`. `analyzerVersion` gives the version of the analyzer when the analyzer tells it. `space` is in `body` only for a space that is not `c64`.
104
104
  - `revision`: the revision of the findings, or `null` when the knowledge did not change.
105
- - `changes`: for analyzer names (`names`), `regions` and `references`, the counts `added`, `changed`, `retired`, `unchanged` and `suppressed`. `suppressed` counts the findings that the script did not record, because the user or the LLM removed a fact at that place. `references.inData` counts the references that start in a data region of the user, the LLM or an idiom. The analyzer decoded these data bytes as code. `regions.onExecutedCode` counts the data findings on code that a run executed and that the project knowledge holds as code. The script does not record these findings, and they are not conflicts.
105
+ - `changes`: for analyzer names (`names`), `regions` and `references`, the counts `added`, `changed`, `retired`, `unchanged` and `suppressed`. `suppressed` counts the findings that the script did not record, because the user or the LLM removed a fact at that place. `references.inData` counts the references that start in a data region of the user, the LLM or an idiom. The analyzer decoded these data bytes as code. `regions.onExecutedCode` and `names.onExecutedCode` count the data findings on code that a run executed and that the project knowledge holds as code. The script does not record these findings, and they are not conflicts.
106
106
  - `conflicts`: each place where the analyzer and the project knowledge disagree. `problem` tells the disagreement. A conflict of code and data also gives these facts about its range:
107
107
  - `access`: only with coverage. `executed` counts the instructions in the range that a run executed. `read` and `written` count the bytes that a run read and wrote.
108
108
  - `references`: the references of the project knowledge into the range from outside it, each with `from` and `kind`.
@@ -160,7 +160,7 @@ Each item of `seeds.refused` and `coverageGaps` has a `reason`. `at` gives the i
160
160
  | `not-decodable` | No instruction decodes at the address. Correct the entry point or the routine. |
161
161
  | `not-reached` | Only in `coverageGaps`: no flow and no seed reached the start. Give it with `--entry`, or record a routine there. |
162
162
 
163
- A start in a `dual-use` region is a known overlap, for example a BIT skip. It is not a gap.
163
+ A start in a `dual-use` region is a known overlap, for example a BIT skip. It is not a gap. `seeds.refused` does not list a seed that the analysis refused because of a known overlap.
164
164
 
165
165
  #### The candidates
166
166
 
@@ -1,13 +1,13 @@
1
1
  // Runtime evidence for static analysis: the coverage as entry points,
2
- // user/LLM code regions and JMP tables as entry points, and the check that
3
- // shows analyzer data over executed code.
2
+ // user/LLM code regions, JMP tables and jump and call targets as entry
3
+ // points, and the check that shows analyzer data over executed code.
4
4
 
5
5
  import type { DatabaseSync } from "node:sqlite";
6
6
 
7
- import { COVERAGE } from "#src/c64.ts";
7
+ import { type AddressRange, COVERAGE, inRanges } from "#src/c64.ts";
8
8
  import type { RefusedSeed, RefusedSeedReason } from "#src/native/types.ts";
9
9
  import { listReferences, listRegions, type RegionRow } from "#src/knowledge/read.ts";
10
- import { CODE_REGION_TYPES, DEFAULT_SPACE, isAnalyzer, isSemantic, type Analyzer, type Space } from "#src/knowledge/schema.ts";
10
+ import { CODE_REGION_TYPES, DEFAULT_SPACE, INSTRUCTION_REGION_TYPES, isAnalyzer, isSemantic, type Analyzer, type Space } from "#src/knowledge/schema.ts";
11
11
 
12
12
  /** The byte at an address of the analyzed image, or undefined outside it. */
13
13
  export type ImageByte = (address: number) => number | undefined;
@@ -34,6 +34,43 @@ export function codeEntries(db: DatabaseSync | undefined, image: ImageByte, spac
34
34
  return entries;
35
35
  }
36
36
 
37
+ /** The classes of an address for referenceTargets, as bits of a 64 KiB map. */
38
+ const CODE = 1;
39
+ const SEMANTIC_DATA = 2;
40
+ const NO_TARGET = 4;
41
+
42
+ /**
43
+ * The targets of the jump and call references from code in the knowledge,
44
+ * inside the image: entry points for DXA. DXA drops code that it
45
+ * reaches on one route only when another route runs into an instruction, for
46
+ * example into the operand of a BIT skip; which code it drops changes with
47
+ * the seeds. A target in a data range would make that range code, and DXA
48
+ * cannot decode both instructions of a dual-use region: such targets are left out.
49
+ * `dualUse` adds the dual-use regions that this run found and that the knowledge
50
+ * does not have yet. The references of the analyzer that runs are left out: fed back, a wrong
51
+ * decode would seed itself, and a re-analysis could not retire it. A
52
+ * reference from a data region of the user or the LLM is left out too: their
53
+ * regions win over the code region of an analyzer.
54
+ */
55
+ export function referenceTargets(db: DatabaseSync | undefined, analyzer: Analyzer, image: ImageByte, ranges: { data: readonly AddressRange[]; dualUse: readonly AddressRange[] }, space: Space = DEFAULT_SPACE): number[] {
56
+ const map = new Uint8Array(0x10000);
57
+ const mark = (range: AddressRange, bit: number) => {
58
+ for (let address = range.start; address <= range.end; address++) map[address]! |= bit;
59
+ };
60
+ for (const region of listRegions(db, undefined, undefined, undefined, space)) {
61
+ if (INSTRUCTION_REGION_TYPES.includes(region.type)) mark(region, CODE);
62
+ else if (isSemantic(region.origin)) mark(region, SEMANTIC_DATA);
63
+ if (region.type === "dual-use") mark(region, NO_TARGET);
64
+ }
65
+ for (const range of [...ranges.data, ...ranges.dualUse]) mark(range, NO_TARGET);
66
+ const targets = new Set<number>();
67
+ for (const reference of listReferences(db, undefined, undefined, undefined, space)) {
68
+ if (reference.kind !== "jump" && reference.kind !== "call") continue;
69
+ if (reference.origin !== analyzer && (map[reference.from]! & (CODE | SEMANTIC_DATA)) === CODE) targets.add(reference.to);
70
+ }
71
+ return [...targets].filter((address) => image(address) !== undefined && (map[address]! & NO_TARGET) === 0).sort((a, b) => a - b);
72
+ }
73
+
37
74
  /** Analyzer data regions that hold executed instruction starts: the coverage shows code there. */
38
75
  export function coverageConflicts(db: DatabaseSync | undefined, map: Uint8Array): Array<{ region: RegionRow; executed: number }> {
39
76
  const conflicts: Array<{ region: RegionRow; executed: number }> = [];
@@ -68,6 +105,21 @@ export function writtenNotExecuted(db: DatabaseSync | undefined, analyzer: Analy
68
105
  return found;
69
106
  }
70
107
 
108
+ /**
109
+ * The refused seeds without the known overlaps. An instruction that starts
110
+ * inside another instruction, in a dual-use region, is a known overlap, for
111
+ * example the second instruction of a BIT skip: one list of instructions cannot
112
+ * hold both, so the analysis refuses the seed of one of them. That seed is not
113
+ * a fault of the knowledge.
114
+ */
115
+ export function withoutOverlaps(refused: readonly RefusedSeed[], dualUse: readonly AddressRange[]): RefusedSeed[] {
116
+ const inner = (seed: RefusedSeed) => (seed.reason === "inside-instruction" ? seed.address : seed.reason === "into-instruction" ? seed.at : undefined);
117
+ return refused.filter((seed) => {
118
+ const start = inner(seed);
119
+ return start === undefined || !inRanges(dualUse, start);
120
+ });
121
+ }
122
+
71
123
  /** Why an executed instruction start has no decoded instruction. */
72
124
  export interface GapReason {
73
125
  address: number;