@henols/c64-re-tools 2.3.0-rc.5 → 2.3.0

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 (61) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +149 -78
  3. package/skills/c64-assembler/scripts/assembler.ts +18 -11
  4. package/skills/c64-basic/SKILL.md +90 -52
  5. package/skills/c64-basic/scripts/basic.ts +15 -6
  6. package/skills/c64-development/SKILL.md +46 -73
  7. package/skills/c64-disk/SKILL.md +145 -73
  8. package/skills/c64-disk/scripts/disk.ts +11 -6
  9. package/skills/c64-docs/SKILL.md +199 -118
  10. package/skills/c64-docs/references/page-types.md +3 -3
  11. package/skills/c64-docs/references/style.md +9 -13
  12. package/skills/c64-docs/scripts/docs.ts +39 -15
  13. package/skills/c64-docs/scripts/lib/links.ts +1 -1
  14. package/skills/c64-docs/scripts/lib/reference.ts +2 -2
  15. package/skills/c64-docs/scripts/lib/source-map.ts +2 -2
  16. package/skills/c64-export/SKILL.md +21 -45
  17. package/skills/c64-knowledge/SKILL.md +489 -233
  18. package/skills/c64-knowledge/scripts/knowledge.ts +31 -26
  19. package/skills/c64-memory-map/SKILL.md +131 -65
  20. package/skills/c64-memory-map/scripts/memory-map.ts +19 -11
  21. package/skills/c64-packer/SKILL.md +120 -72
  22. package/skills/c64-packer/scripts/packer.ts +10 -3
  23. package/skills/c64-provenance/SKILL.md +301 -173
  24. package/skills/c64-provenance/scripts/lib/library.ts +6 -6
  25. package/skills/c64-provenance/scripts/provenance.ts +85 -36
  26. package/skills/c64-reverse-engineering/SKILL.md +55 -72
  27. package/skills/c64-source/SKILL.md +316 -224
  28. package/skills/c64-source/scripts/lib/export.ts +9 -14
  29. package/skills/c64-source/scripts/lib/loader.ts +5 -5
  30. package/skills/c64-source/scripts/lib/source.ts +5 -5
  31. package/skills/c64-source/scripts/source.ts +106 -21
  32. package/skills/c64-static-analysis/SKILL.md +188 -112
  33. package/skills/c64-static-analysis/scripts/static-analysis.ts +29 -9
  34. package/skills/c64-testing/SKILL.md +272 -166
  35. package/skills/c64-testing/references/recording-format.md +11 -12
  36. package/skills/c64-testing/references/scenario-format.md +20 -5
  37. package/skills/c64-testing/scripts/lib/diff-files.ts +8 -8
  38. package/skills/c64-testing/scripts/lib/recording.ts +7 -7
  39. package/skills/c64-testing/scripts/lib/replay.ts +7 -7
  40. package/skills/c64-testing/scripts/lib/runs.ts +6 -7
  41. package/skills/c64-testing/scripts/lib/scenario.ts +12 -6
  42. package/skills/c64-testing/scripts/testing.ts +35 -15
  43. package/skills/c64-unpacker/SKILL.md +273 -127
  44. package/skills/c64-unpacker/scripts/lib/loads.ts +3 -3
  45. package/skills/c64-unpacker/scripts/unpacker.ts +70 -11
  46. package/skills/emulator/SKILL.md +12 -12
  47. package/src/errors.ts +22 -2
  48. package/src/host/vice/session.ts +1 -1
  49. package/src/host-client/entry-state.ts +1 -1
  50. package/src/host-client/image.ts +3 -3
  51. package/src/host-client/steps.ts +1 -1
  52. package/src/knowledge/expression.ts +1 -1
  53. package/src/knowledge/names.ts +2 -3
  54. package/src/knowledge/program.ts +2 -3
  55. package/src/knowledge/write.ts +2 -2
  56. package/src/mcp/inputs.ts +1 -1
  57. package/src/mcp/tools/input.ts +1 -1
  58. package/src/mcp/tools/media.ts +1 -1
  59. package/src/native/exomizer.ts +2 -2
  60. package/src/project.ts +2 -2
  61. package/src/script.ts +164 -75
@@ -405,7 +405,7 @@ export interface ReadmeInput {
405
405
  tests: { written: ReadonlyArray<{ file: string; kind: "scenario" | "run" }>; leftOut: ReadonlyArray<{ file: string; reason: string }> };
406
406
  }
407
407
 
408
- /** The README of the new project: the commands first, then the free ranges, the files and where the program comes from. */
408
+ /** The README of the new project: the build and the tests first, then the free ranges, the files and where the program comes from. */
409
409
  export function readmeText(input: ReadmeInput): string {
410
410
  const { name } = input;
411
411
  const lines = [
@@ -415,15 +415,11 @@ export function readmeText(input: ReadmeInput): string {
415
415
  "",
416
416
  "## Build",
417
417
  "",
418
- "With the c64-assembler skill:",
419
- "",
420
- "```",
421
- ...(input.entryFile === "main.asm"
422
- ? [`assembler.ts build src main.asm --out build/${name}.prg --out-symbols build/${name}.json --compare`]
423
- : [`assembler.ts build src ${input.entryFile} --out build/${name}.prg --out-symbols build/${name}.json`, `assembler.ts build src main.asm --out .c64-re-tools/local/program.prg --compare`]),
424
- "```",
425
- "",
426
- "`--compare` checks that the source gives the program in the knowledge. After a change to the source, it gives FAIL: that is correct.",
418
+ `Assemble \`src/${input.entryFile}\` to \`build/${name}.prg\`, with its symbols in \`build/${name}.json\`.`,
419
+ input.entryFile === "main.asm"
420
+ ? "Compare the build with the program in the project knowledge: the source must give that program."
421
+ : "Assemble `src/main.asm` to `.c64-re-tools/local/program.prg`, and compare it with the program in the project knowledge: the source must give that program.",
422
+ "After a change to the source, the compare gives FAIL: that is correct.",
427
423
  "",
428
424
  "With ACME only, from the folder `src`:",
429
425
  "",
@@ -434,11 +430,10 @@ export function readmeText(input: ReadmeInput): string {
434
430
  "## Test",
435
431
  "",
436
432
  ];
437
- if (input.tests.written.length === 0) lines.push("No tests came with the program. Write run files with `expect` steps in `tests/` (c64-development skill).");
433
+ if (input.tests.written.length === 0) lines.push("No tests came with the program. Write run files with `expect` steps in `tests/`.");
438
434
  else {
439
- lines.push(`Build first. A scenario compares \`build/${name}.prg\` with \`baseline/${name}.prg\`, the exported program. A run file runs \`build/${name}.prg\`. Use the c64-testing skill:`, "", "```");
440
- for (const test of input.tests.written) lines.push(test.kind === "run" ? `testing.ts run ${test.file} --out .c64-re-tools/local/runs/${test.file.replace(/^tests\//, "").replace(/\.json$/, "")}` : `testing.ts test ${test.file}`);
441
- lines.push("```");
435
+ lines.push(`Build first. A scenario compares \`build/${name}.prg\` with \`baseline/${name}.prg\`, the exported program. A run file runs \`build/${name}.prg\`. Run each test:`, "");
436
+ for (const test of input.tests.written) lines.push(test.kind === "run" ? `- \`${test.file}\`: run the run file, with its results in \`.c64-re-tools/local/runs/${test.file.replace(/^tests\//, "").replace(/\.json$/, "")}\`.` : `- \`${test.file}\`: run the scenario.`);
442
437
  }
443
438
  lines.push("", "## Free ranges", "");
444
439
  if (input.free.length === 0) lines.push("None: the export dropped nothing.");
@@ -69,12 +69,12 @@ const FLAG_BITS = { n: 0x80, v: 0x40, d: 0x08, i: 0x04, z: 0x02, c: 0x01 } as co
69
69
 
70
70
  /**
71
71
  * The entry state that the loader recreates: the shared entry state of the
72
- * c64-unpacker capture, with the flags as PLP reads them, the VIC-II and the CIAs.
72
+ * program capture, with the flags as PLP reads them, the VIC-II and the CIAs.
73
73
  */
74
74
  export function loaderState(value: unknown, where: string): EntryState {
75
75
  const state = parseEntryState(value, where);
76
76
  const fail = (what: string): never => {
77
- throw new Refusal("invalid-input", `${where} is not an entry state of a c64-unpacker capture: ${what}. Capture the program again with c64-unpacker capture or loads.`);
77
+ throw new Refusal("invalid-input", `${where} is not an entry state of a program capture: ${what}. Capture the program again at its entry point.`);
78
78
  };
79
79
  let flags = 0x20;
80
80
  for (const [name, bit] of Object.entries(FLAG_BITS)) if (state.flags[name as keyof typeof FLAG_BITS]) flags |= bit;
@@ -119,7 +119,7 @@ export interface LoaderPlan {
119
119
  */
120
120
  export function loaderLimits(plan: { cia?: CiaPlan }): string[] {
121
121
  if (plan.cia === undefined) {
122
- return ["The entry state has no CIA values, so the loader does not set the CIA timers. Capture the program again with c64-unpacker to get them."];
122
+ return ["The entry state has no CIA values, so the loader does not set the CIA timers. Capture the program again at its entry point to get them."];
123
123
  }
124
124
  return plan.cia.limits;
125
125
  }
@@ -448,7 +448,7 @@ export function planLoader(input: LoaderInput): LoaderPlan {
448
448
  if (end > LOAD_LIMIT) return planPacked(input, blocks, cia, codeSize, `The plain loader would end ${end > 0xffff ? "past $ffff" : `at ${formatC64Address(end)}`}, after ${formatC64Address(LOAD_LIMIT)}: loading it would write the I/O area.`);
449
449
  // The CIA part takes room from the copy table in the copier's two pages.
450
450
  const maxCopies = Math.min(MAX_COPIES, Math.floor((COPIER_LIMIT - codeSize - 2) / COPY_ENTRY));
451
- if (plain.length > maxCopies) throw new WireFailure("invalid-input", `The loader needs ${plain.length} copies; it can do at most ${maxCopies}. Join segments in the unpacker capture (--range) or write the loader by hand.`);
451
+ if (plain.length > maxCopies) throw new WireFailure("invalid-input", `The loader needs ${plain.length} copies; it can do at most ${maxCopies}. Capture the program again with fewer segments, or write the loader by hand.`);
452
452
 
453
453
  const order = copyOrder(plain);
454
454
  if (order === undefined) {
@@ -566,7 +566,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
566
566
  const stackByte = 0x0100 + state.sp;
567
567
  const lines: string[] = [
568
568
  ...input.header.map((line) => `; ${line}`),
569
- "; The image is too large for one loader file, so this is the packed form. c64-packer packs the",
569
+ "; The image is too large for one loader file, so this is the packed form. Exomizer packs the",
570
570
  `; build of main.asm and the build of this file into loader.prg, with --entry '${formatC64Address(copier)}' and --exit-memory '$34'.`,
571
571
  "; The unpacker of Exomizer uses the zero page and $0334-$03ff, so the copier writes pages $0002-$03ff after the unpack.",
572
572
  "",
@@ -273,7 +273,7 @@ export function entriesInData<R extends { start: number; end: number; type: Regi
273
273
  /** Why an image without its entry fails: the image does not hold the program. Undefined when the entry is in a segment, or the image has no entry. */
274
274
  export function entryOutsideImage(entry: number | undefined, segments: readonly AddressRange[]): string | undefined {
275
275
  if (entry === undefined || segments.some((segment) => entry >= segment.start && entry <= segment.end)) return undefined;
276
- return `The entry ${formatC64Address(entry)} is in no segment of the image: the image does not hold the program. Capture it again with c64-unpacker loads or capture.`;
276
+ return `The entry ${formatC64Address(entry)} is in no segment of the image: the image does not hold the program. Capture the program again, so that a segment holds the entry.`;
277
277
  }
278
278
 
279
279
  /** Splits the segments into pieces at module starts and lays out instructions and data. */
@@ -434,7 +434,7 @@ export function layout(input: SourceInput): Layout {
434
434
  }
435
435
  const missing = [...new Set(use.args.flatMap((arg) => identifiers(arg)))].filter((name) => !byName.has(name));
436
436
  if (missing.length > 0) {
437
- fallBack(unknownNames(missing, "Name the address with knowledge.ts rename, or give other args with knowledge.ts use."));
437
+ fallBack(unknownNames(missing, "Name the address in the project knowledge, or record the macro use again with other args."));
438
438
  continue;
439
439
  }
440
440
  candidates.push({ use, items: run as InstructionItem[] });
@@ -453,7 +453,7 @@ export function layout(input: SourceInput): Layout {
453
453
  }
454
454
  const missing = identifiers(expression).filter((name) => !byName.has(name));
455
455
  if (missing.length > 0) {
456
- operandsAsNumbers.push({ address: operand.address, expression, reason: unknownNames(missing, "Name the address with knowledge.ts rename, or write the operand again with knowledge.ts operand.") });
456
+ operandsAsNumbers.push({ address: operand.address, expression, reason: unknownNames(missing, "Name the address in the project knowledge, or record the operand expression again.") });
457
457
  continue;
458
458
  }
459
459
  // An immediate operand builds the address of a name; any other operand uses the address as the instruction does.
@@ -501,7 +501,7 @@ export function layout(input: SourceInput): Layout {
501
501
  const known = symbols.get(address);
502
502
  if (known !== undefined) {
503
503
  const problem = labelProblem(known);
504
- if (problem !== undefined) throw new WireFailure("invalid-input", `The symbol ${known} at ${formatC64Address(address)}: ${problem} Rename the symbol with c64-knowledge.`);
504
+ if (problem !== undefined) throw new WireFailure("invalid-input", `The symbol ${known} at ${formatC64Address(address)}: ${problem} Rename the symbol in the project knowledge.`);
505
505
  names.set(address, known);
506
506
  if (inImage(address)) namedLabels++;
507
507
  continue;
@@ -902,7 +902,7 @@ export function configText(layout: Pick<Layout, "switches" | "patches">, values:
902
902
  function switchesText(layout: Layout): string {
903
903
  const out = [
904
904
  "; The releases of the knowledge. config.asm holds the value of each switch.",
905
- `; Build a release with -D${RELEASE_DEFINE}<label>=1 (c64-assembler --release <label>):`,
905
+ `; Build a release with -D${RELEASE_DEFINE}<label>=1 (the build option --release <label>):`,
906
906
  "; then each switch has the value of that release, and the build does not read config.asm.",
907
907
  ];
908
908
  for (const release of layout.releases) {
@@ -36,7 +36,7 @@ import { decode as decodeRegister, describeAddress, platformNames, platformNames
36
36
  import { ensureLocal, LOCAL_DIRECTORY, newProjectFolder, PROJECT_DIRECTORY, projectRoot, resolveProjectPath } from "#src/project.ts";
37
37
  import { isoCet } from "#src/time.ts";
38
38
  import { zipFiles } from "#src/zip.ts";
39
- import { listed, OPTIONS, runScript, UsageError, type Call } from "#src/script.ts";
39
+ import { listed, OPTIONS, reply, runScript, UsageError, type Call, type Reply } from "#src/script.ts";
40
40
  import { knowledgeNames } from "#src/knowledge/names.ts";
41
41
  import { COPIER_SOURCE, LOADER_JUMP, loaderLimits, packLoader, planLoader, rasterLine, loaderState, simulate, stopCause, VIC_DISPLAY_REGISTERS, type EntryState, type LoaderPlan, type PackedLoader } from "./lib/loader.ts";
42
42
  import { instructionWith, OPCODES } from "#src/opcodes.ts";
@@ -50,7 +50,7 @@ const ROUNDS = 6;
50
50
  const PROBE_BASE = 0x1000;
51
51
  const PROBE_SLOT = 4;
52
52
  /** Why a source has no instructions when the knowledge has no code. */
53
- const DATA_ONLY = "The knowledge has no entry, routine, code region or executed address in this space. Thus the source has only data. For instructions, give --entry, or classify the code with knowledge.ts classify, then generate again.";
53
+ const DATA_ONLY = "The knowledge has no entry, routine, code region or executed address in this space. Thus the source has only data. For instructions, give --entry, or record a code region in the project knowledge. Then generate again.";
54
54
 
55
55
  /** The copies of a full 64 KiB take about 140 frames. */
56
56
  const LOADER_FRAMES = 1500;
@@ -63,7 +63,7 @@ function readKnowledge(space: Space, analyzerNames = false) {
63
63
  try {
64
64
  // With conflicts from a git merge, the source would depend on which of two rows comes first.
65
65
  const found = conflicts(db).length;
66
- if (found > 0) throw new Refusal("conflict", `The knowledge has ${found} conflict${found === 1 ? "" : "s"} from a git merge. Nothing was generated. Run c64-knowledge's knowledge.ts merge, then generate again.`);
66
+ if (found > 0) throw new Refusal("conflict", `The knowledge has ${found} conflict${found === 1 ? "" : "s"} from a git merge. Merge the open changes of the project knowledge. Then run the command again.`);
67
67
  const symbols = listSymbols(db, undefined, undefined, undefined, space);
68
68
  const second = listAnalyzerNames(db, undefined, undefined, undefined, space);
69
69
  const releases = listReleases(db, undefined, space);
@@ -465,7 +465,7 @@ async function checkRelease(release: ReleaseRow, files: Array<{ name: string; te
465
465
  try {
466
466
  const bytes = readProjectFile(release.file).bytes;
467
467
  if (createHash("sha256").update(bytes).digest("hex") !== release.sha256) {
468
- return { ...shown, result: "file changed", reason: `The SHA-256 of ${release.file} is not the one that the knowledge has. Record the release again (knowledge.ts release), or put back the file.` };
468
+ 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.` };
469
469
  }
470
470
  image = readImage(release.file);
471
471
  } catch (error) {
@@ -752,16 +752,16 @@ async function buildLoader(files: Array<{ name: string; text: string }>, laid: L
752
752
  return false;
753
753
  });
754
754
  if (loaderBuilt.start !== (loader.packed?.start ?? 0x0801) || loaderBuilt.start + program.length - 3 !== loader.end || wrongPacking !== undefined) {
755
- throw new WireFailure("operation-failed", `The assembled loader does not have the planned layout${wrongPacking === undefined ? "" : ` (${wrongPacking.what})`}. This is a defect of the c64-source script.`);
755
+ 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.`);
756
756
  }
757
757
  const symbolValue = (name: string) => {
758
758
  const symbol = loaderBuilt.symbols?.find((item) => item.name === name);
759
- if (symbol === undefined) throw new WireFailure("operation-failed", `The assembled loader has no ${name} label. This is a defect of the c64-source script.`);
759
+ if (symbol === undefined) throw new WireFailure("operation-failed", `The assembled loader has no ${name} label. This is a defect of the script.`);
760
760
  return symbol.kind === "address" ? symbol.address : symbol.value;
761
761
  };
762
762
  const jump = symbolValue(LOADER_JUMP);
763
763
  const wrong = simulate(memory, loader.copies, expected);
764
- if (wrong !== undefined) throw new WireFailure("operation-failed", `The simulated loader writes a wrong byte at ${formatC64Address(wrong)}. This is a defect of the c64-source script.`);
764
+ 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.`);
765
765
  return { program, symbols: loaderBuilt.symbols ?? [], jump, copierSource: symbolValue(COPIER_SOURCE), expected };
766
766
  }
767
767
 
@@ -778,7 +778,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
778
778
  const knowledge = readKnowledge(space, call.flag("analyzer-names"));
779
779
  const image = knowledge.program;
780
780
  if (loaderWanted && (image.state === undefined || image.entry === undefined)) {
781
- throw new Refusal("not-found", "--loader needs the entry and the entry state of a c64-unpacker capture in the knowledge: put the capture in with knowledge.ts image <image.json>");
781
+ throw new Refusal("not-found", "The knowledge has no entry and no entry state, and --loader needs them. Capture the unpacked program at its entry point, and put the capture into the project knowledge. Then generate again.");
782
782
  }
783
783
  // Read the entry state before the long steps, so a bad state stops the run at once.
784
784
  const state = loaderWanted ? loaderState(image.state, "the entry state of the knowledge") : undefined;
@@ -1019,13 +1019,12 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1019
1019
  // 1. The source of the knowledge must give the base release byte for byte, with every patch in it.
1020
1020
  const baseValues = new Map(knowledge.switches.map((row) => [row.name, row.base]));
1021
1021
  const original = await buildSource(knowledge, { space: DEFAULT_SPACE, entries: [], header: [], values: baseValues, notExecutedMarks: false });
1022
- const fix = "Run source.ts generate, correct the knowledge until generate gives PASS, then export again.";
1023
- if (original.built.program === undefined) return { result: "FAIL", stage: "original", reason: `The source of the knowledge does not assemble. ${fix}`, diagnostics: original.built.diagnostics.slice(0, MAX_DIAGNOSTICS) };
1022
+ if (original.built.program === undefined) return { result: "FAIL", stage: "original", reason: "The source of the knowledge does not assemble.", diagnostics: original.built.diagnostics.slice(0, MAX_DIAGNOSTICS) };
1024
1023
  const checked = check(original.built.program, original.built.start!, image);
1025
- if (!checked.identical) return { result: "FAIL", stage: "original", reason: `The source of the knowledge does not assemble to the program. ${fix}`, check: checked };
1024
+ if (!checked.identical) return { result: "FAIL", stage: "original", reason: "The source of the knowledge does not assemble to the program.", check: checked };
1026
1025
  if (original.missingEntry !== undefined) return { result: "FAIL", stage: "original", reason: original.missingEntry };
1027
1026
  if (original.laid.patchesNotWritten.length > 0) {
1028
- return { result: "FAIL", stage: "original", reason: `The source cannot write every patch. ${fix}`, patchesNotWritten: listed(original.laid.patchesNotWritten, max, (item) => ({ ...shownRange(item), switch: item.switch, reason: item.reason })) };
1027
+ return { result: "FAIL", stage: "original", reason: "The source cannot write every patch.", patchesNotWritten: listed(original.laid.patchesNotWritten, max, (item) => ({ ...shownRange(item), switch: item.switch, reason: item.reason })) };
1029
1028
  }
1030
1029
 
1031
1030
  // 2. Each switch at its export value. Two alternatives of one range cannot both be in.
@@ -1033,7 +1032,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1033
1032
  for (const patch of original.laid.patches.values()) {
1034
1033
  const both = patch.alternatives.filter((alternative) => values.get(alternative.switch) !== alternative.base);
1035
1034
  if (both.length > 1) {
1036
- throw new Refusal("invalid-input", `The switches ${both.map((item) => item.switch).join(" and ")} change ${formatC64Address(patch.start)}-${formatC64Address(patch.end)} in different ways, and the export puts both in. Give all but one of them the kind change with --default and the value of the base release (knowledge.ts switch), then export again.`);
1035
+ throw new Refusal("invalid-input", `The switches ${both.map((item) => item.switch).join(" and ")} change ${formatC64Address(patch.start)}-${formatC64Address(patch.end)} in different ways, and the export puts both in. In the project knowledge, give all but one of them the kind change, with the default of the base release. Then export again.`);
1037
1036
  }
1038
1037
  }
1039
1038
  const withPatches = switchesOf(original.laid);
@@ -1042,7 +1041,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1042
1041
  const baked = await assembleFiles(withValues(original.files, original.laid, values), "main.asm");
1043
1042
  const bakedCheck = compareBuilds(baked, patchesIn, { program: original.built.program, start: original.built.start! });
1044
1043
  const switches = knowledge.switches.map((row) => ({ name: row.name, kind: row.kind, base: row.base, value: values.get(row.name)! }));
1045
- if (bakedCheck.result !== "fits" || baked.program === undefined) return { result: "FAIL", stage: "switches", reason: "The build with the export values of the switches does not fit. Build each switch alone with source.ts generate and correct its patches.", switches, build: bakedCheck };
1044
+ if (bakedCheck.result !== "fits" || baked.program === undefined) return { result: "FAIL", stage: "switches", reason: "The build with the export values of the switches does not fit.", switches, build: bakedCheck };
1046
1045
 
1047
1046
  // 3. The baked image: the bytes of that build in the segments of the program.
1048
1047
  const memory = Uint8Array.from(image.memory);
@@ -1130,9 +1129,9 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1130
1129
  notExecutedMarks: false,
1131
1130
  ...(state === undefined ? {} : { state, loaderHeader: [`The loader of ${name}.`, "It copies the segments into place, sets the entry state and jumps to the entry."] }),
1132
1131
  });
1133
- if (exported.built.program === undefined) return { result: "FAIL", stage: "export", reason: "The source of the export does not assemble. This is a defect of the c64-source script.", diagnostics: exported.built.diagnostics.slice(0, MAX_DIAGNOSTICS) };
1132
+ if (exported.built.program === undefined) return { result: "FAIL", stage: "export", reason: "The source of the export does not assemble. This is a defect of the script.", diagnostics: exported.built.diagnostics.slice(0, MAX_DIAGNOSTICS) };
1134
1133
  const exportCheck = check(exported.built.program, exported.built.start!, derived.program);
1135
- if (!exportCheck.identical) return { result: "FAIL", stage: "export", reason: "The source of the export does not assemble to the exported program. This is a defect of the c64-source script.", check: exportCheck };
1134
+ if (!exportCheck.identical) return { result: "FAIL", stage: "export", reason: "The source of the export does not assemble to the exported program. This is a defect of the script.", check: exportCheck };
1136
1135
 
1137
1136
  // 6. The loader of a capture: planned and simulated. The tests of the new project run it.
1138
1137
  let baseline = { program: exported.built.program, symbols: exported.built.symbols ?? [], entryFile: "main.asm" };
@@ -1141,7 +1140,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1141
1140
  if (exported.loader === undefined) return { result: "FAIL", stage: "loader", reason: exported.loaderRefused ?? "The loader could not be planned." };
1142
1141
  if (exported.loader.packed !== undefined) return { result: "FAIL", stage: "loader", reason: "The program is too large for one loader file, and export does not make the packed form of the loader." };
1143
1142
  const loaderBuilt = await buildLoader(exported.files, exported.laid, exported.loader, derived.program, state, new Map());
1144
- if ("diagnostics" in loaderBuilt) return { result: "FAIL", stage: "loader", reason: "loader.asm does not assemble. This is a defect of the c64-source script.", diagnostics: loaderBuilt.diagnostics };
1143
+ if ("diagnostics" in loaderBuilt) return { result: "FAIL", stage: "loader", reason: "loader.asm does not assemble. This is a defect of the script.", diagnostics: loaderBuilt.diagnostics };
1145
1144
  baseline = { program: loaderBuilt.program, symbols: loaderBuilt.symbols, entryFile: "loader.asm" };
1146
1145
  loaderOutput = {
1147
1146
  copies: exported.loader.copies.map((copy) => ({ what: copy.what, to: `${formatC64Address(copy.target.start)}-${formatC64Address(copy.target.end)}` })),
@@ -1219,6 +1218,92 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1219
1218
  };
1220
1219
  }
1221
1220
 
1221
+ /** True when a list of a body (from listed) is cut at --max-listed. */
1222
+ function isCut(list: unknown): boolean {
1223
+ return typeof list === "object" && list !== null && "rest" in list;
1224
+ }
1225
+
1226
+ /** The same generate command line again, for the run after a change of the knowledge. */
1227
+ function generateAgain(call: Call): string {
1228
+ const max = call.count("max-listed")!;
1229
+ return call.next(
1230
+ "generate",
1231
+ "--out",
1232
+ call.string("out")!,
1233
+ ...call.addresses("entry").flatMap((entry) => ["--entry", formatC64Address(entry)]),
1234
+ ...(call.space === DEFAULT_SPACE ? [] : ["--space", call.space]),
1235
+ ...(call.flag("loader") ? ["--loader"] : []),
1236
+ ...(call.flag("analyzer-names") ? ["--analyzer-names"] : []),
1237
+ ...(max === OPTIONS["max-listed"].default ? [] : ["--max-listed", String(max)]),
1238
+ );
1239
+ }
1240
+
1241
+ /**
1242
+ * The hint of a generate result: the action for each finding. When a change
1243
+ * of the knowledge corrects a finding, nextAction is the same generate command.
1244
+ */
1245
+ function generateReply(call: Call, body: Record<string, unknown>): Reply {
1246
+ const steps: string[] = [];
1247
+ let again = false;
1248
+ const check = body.check as { identical: boolean; diagnostics?: unknown[] } | undefined;
1249
+ if (check?.diagnostics !== undefined) {
1250
+ steps.push("ACME does not assemble the source. Read check.diagnostics, and correct the name or the patch code in the project knowledge that ACME refuses.");
1251
+ again = true;
1252
+ } else if (check !== undefined && !check.identical) {
1253
+ steps.push("The source does not assemble to the program. This is a defect of the script. Give the result to the user.");
1254
+ }
1255
+ if (body.entryOutside !== undefined) {
1256
+ steps.push("The entry is in no segment of the program. Capture the program again, so that a segment holds the entry, and put the capture into the project knowledge.");
1257
+ again = true;
1258
+ }
1259
+ const switches = body.switches as Array<{ result: string }> | undefined;
1260
+ const defaultBuild = body.default as { result: string } | undefined;
1261
+ if (body.patchesNotWritten !== undefined || switches?.some((item) => item.result !== "fits") === true || (defaultBuild !== undefined && defaultBuild.result !== "fits")) {
1262
+ 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.");
1263
+ again = true;
1264
+ }
1265
+ const releases = body.releases as Array<{ result: string; base: boolean }> | undefined;
1266
+ if (releases?.some((item) => item.result !== "identical" && (item.base || item.result !== "layout differs")) === true) {
1267
+ 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.");
1268
+ again = true;
1269
+ }
1270
+ if ((body.loader as { verified?: boolean } | undefined)?.verified === false) steps.push("The loader is not verified. Read loader.reason, loader.differences and loader.stop.");
1271
+ if (body.dataOnly !== undefined) {
1272
+ steps.push("The source has only data. If the space has code, give --entry, or record a code region in the project knowledge.");
1273
+ again = true;
1274
+ }
1275
+ if (body.entriesInData !== undefined) {
1276
+ steps.push("An --entry is in a data region, and the source does not decode it. If the entry is code, record a code region at the entry in the project knowledge.");
1277
+ again = true;
1278
+ }
1279
+ if (body.operandsAsNumbers !== undefined || body.macrosAsInstructions !== undefined) {
1280
+ steps.push("Read the reason of each item in operandsAsNumbers and macrosAsInstructions. Correct the operand expression or the macro use in the project knowledge.");
1281
+ again = true;
1282
+ }
1283
+ 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.");
1284
+ if (steps.length === 0) return reply(body, { hint: "Read the source. Record names, comments, regions and modules in the project knowledge. Then generate again." });
1285
+ if (again) steps.push("Then generate again.");
1286
+ return reply(body, { hint: steps.join(" "), ...(again ? { nextAction: generateAgain(call) } : {}) });
1287
+ }
1288
+
1289
+ /** The hint of an export result: the action for a failed stage, or the next steps for the new project. */
1290
+ function exportReply(body: Record<string, unknown>): Reply {
1291
+ if (body.result === "FAIL") {
1292
+ const hints: Record<string, string> = {
1293
+ original: "Run generate, and correct the project knowledge until generate gives PASS. Then export again.",
1294
+ switches: "Run generate. It builds each switch alone. Correct the patches in the project knowledge until each switch fits. Then export again.",
1295
+ export: "This is a defect of the script. Give the result to the user.",
1296
+ loader: "Read reason, and give it to the user.",
1297
+ };
1298
+ return reply(body, { hint: hints[String(body.stage)] });
1299
+ }
1300
+ const steps = ["Build and test the new project as its README.md tells."];
1301
+ if (body.noCoverage !== undefined) steps.push("To make unused code and data free, put the coverage of a run into the project knowledge. Then remove the new folder and its zip file, and export again.");
1302
+ if (((body.unreachableExecuted as { count: number } | undefined)?.count ?? 0) > 0) steps.push("To make the code in unreachableExecuted free, remove the new folder and its zip file. Then export again with the drop value of the code.");
1303
+ if ([body.free, body.unreachableExecuted, body.operandsAsNumbers, body.macrosAsInstructions, (body.tests as { leftOut?: unknown } | undefined)?.leftOut].some(isCut)) steps.push("To see all items of a list, give a larger --max-listed.");
1304
+ return reply(body, { hint: steps.join(" ") });
1305
+ }
1306
+
1222
1307
  await runScript({
1223
1308
  name: "source",
1224
1309
  summary: "Generates ACME source from the program and the knowledge, and checks with ACME that it assembles to the program byte by byte.",
@@ -1229,19 +1314,19 @@ await runScript({
1229
1314
  summary: "Writes the source files, source-map.json and not_executed.json, and checks them. result is PASS when every check passes, else FAIL.",
1230
1315
  options: {
1231
1316
  out: { ...OPTIONS.out, output: "folder", value: "<dir>", help: "the folder for the source files, relative to the project folder", required: true },
1232
- entry: { ...OPTIONS.entry, multiple: true, help: "an entry point for Ghidra" },
1317
+ 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" },
1233
1318
  space: { ...OPTIONS.space, help: "the knowledge space of the program: c64 (the default), drive8, or bank0 to bank255. The coverage and --loader are for c64 only" },
1234
1319
  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" },
1235
1320
  "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" },
1236
1321
  "max-listed": OPTIONS["max-listed"],
1237
1322
  },
1238
- notes: "The program, its entry state and the coverage come from the knowledge: put them in with knowledge.ts image and coverage of the c64-knowledge skill. 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.",
1323
+ 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.",
1239
1324
  run: async (call) => {
1240
1325
  const { output, failed, removed } = await generate(call);
1241
1326
  // A file of an earlier run that this run removed and did not write again.
1242
1327
  const written = new Set((output.files as Written[]).map((file) => file.out));
1243
1328
  const gone = removed.filter((path) => !written.has(path));
1244
- return { result: failed ? "FAIL" : "PASS", ...output, ...(gone.length === 0 ? {} : { removed: gone }) };
1329
+ return generateReply(call, { result: failed ? "FAIL" : "PASS", ...output, ...(gone.length === 0 ? {} : { removed: gone }) });
1245
1330
  },
1246
1331
  },
1247
1332
  {
@@ -1255,7 +1340,7 @@ await runScript({
1255
1340
  "max-listed": OPTIONS["max-listed"],
1256
1341
  },
1257
1342
  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.",
1258
- run: (call) => exportProject(call),
1343
+ run: async (call) => exportReply(await exportProject(call)),
1259
1344
  },
1260
1345
  ],
1261
1346
  });