@henols/c64-re-tools 2.6.0-rc.3 → 2.6.0-rc.5

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 (37) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +26 -12
  3. package/skills/c64-assembler/scripts/assembler.ts +25 -13
  4. package/skills/c64-development/SKILL.md +1 -1
  5. package/skills/c64-docs/SKILL.md +4 -4
  6. package/skills/c64-docs/scripts/docs.ts +3 -3
  7. package/skills/c64-docs/scripts/lib/reference.ts +3 -3
  8. package/skills/c64-docs/scripts/lib/source-map.ts +9 -4
  9. package/skills/c64-knowledge/SKILL.md +25 -16
  10. package/skills/c64-knowledge/scripts/knowledge.ts +26 -41
  11. package/skills/c64-packer/SKILL.md +1 -1
  12. package/skills/c64-provenance/SKILL.md +11 -10
  13. package/skills/c64-provenance/scripts/lib/library.ts +16 -16
  14. package/skills/c64-provenance/scripts/provenance.ts +33 -23
  15. package/skills/c64-reverse-engineering/SKILL.md +6 -6
  16. package/skills/c64-source/SKILL.md +46 -39
  17. package/skills/c64-source/scripts/lib/export.ts +5 -4
  18. package/skills/c64-source/scripts/lib/loader.ts +6 -6
  19. package/skills/c64-source/scripts/lib/source.ts +11 -24
  20. package/skills/c64-source/scripts/lib/stage.ts +2 -2
  21. package/skills/c64-source/scripts/source.ts +135 -68
  22. package/skills/c64-static-analysis/SKILL.md +4 -4
  23. package/skills/c64-static-analysis/scripts/static-analysis.ts +26 -33
  24. package/skills/c64-testing/SKILL.md +1 -1
  25. package/skills/c64-testing/references/scenario-format.md +1 -1
  26. package/skills/c64-unpacker/SKILL.md +2 -0
  27. package/skills/c64-unpacker/scripts/lib/loads.ts +33 -12
  28. package/skills/c64-unpacker/scripts/unpacker.ts +5 -3
  29. package/src/build-name.ts +50 -0
  30. package/src/host/vice/session.ts +6 -1
  31. package/src/knowledge/program.ts +44 -1
  32. package/src/knowledge/read.ts +3 -7
  33. package/src/knowledge/schema.ts +27 -8
  34. package/src/knowledge/text.ts +4 -2
  35. package/src/knowledge/write.ts +47 -14
  36. package/src/native/acme.ts +1 -1
  37. package/src/project.ts +13 -1
@@ -14,27 +14,26 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync
14
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 { BUILD_DIRECTORY, buildName, symbolsPath } from "#src/build-name.ts";
18
+ import { type AddressRange, coverageSeedKinds, findHandoffs, formatC64Address, parseC64Address, parseTokenized, textToPetscii } from "#src/c64.ts";
18
19
  import { autostartLoaded, RUN_LIMIT_FRAMES } from "#src/host-client/autostart.ts";
19
20
  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
21
  import { MAX_MEMORY_READ, WireFailure } from "#src/host-client/tools.ts";
23
22
  import { writeReported, type Written } from "#src/host-client/transfer.ts";
24
23
  import { ViceSessionClient } from "#src/host-client/vice-session.ts";
25
24
  import { conflicts } from "#src/knowledge/conflicts.ts";
26
25
  import { openForRead, withWrite } from "#src/knowledge/database.ts";
27
26
  import { identifiers } from "#src/knowledge/expression.ts";
28
- import { analyzedBytes, memoryRows, programCoverage, requireProgram, type ProgramImage } from "#src/knowledge/program.ts";
27
+ import { analyzedBytes, memoryRows, programCoverage, releaseImage, requireProgram, type ProgramImage } from "#src/knowledge/program.ts";
29
28
  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";
29
+ import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, LEFTOVER_FOLDER, LEFTOVERS_SWITCH, RELEASE_DEFINE, START_SCREEN_SWITCH, type Space } from "#src/knowledge/schema.ts";
31
30
  import { subtract, write } from "#src/knowledge/write.ts";
32
31
  import { assemble, symbolsFileText } from "#src/native/acme.ts";
33
32
  import { analyze } from "#src/native/ghidra/analyze.ts";
34
33
  import { localToolContext } from "#src/native/local.ts";
35
34
  import { GHIDRA_LIMITS, type AssembledSymbol, type Diagnostic } from "#src/native/types.ts";
36
35
  import { decode as decodeRegister, describeAddress, platformNames, platformNamesFor, romRanges, romUseOfProgram } from "#src/platform.ts";
37
- import { ensureLocal, LOCAL_DIRECTORY, newProjectFolder, PROJECT_DIRECTORY, projectRoot, resolveProjectPath } from "#src/project.ts";
36
+ import { ensureLocal, generatedDirectory, LOCAL_DIRECTORY, newProjectFolder, PROJECT_DIRECTORY, projectRelative, projectRoot, resolveProjectPath } from "#src/project.ts";
38
37
  import { isoCet } from "#src/time.ts";
39
38
  import { zipFiles } from "#src/zip.ts";
40
39
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type Reply } from "#src/script.ts";
@@ -108,7 +107,8 @@ function readKnowledge(space: Space, analyzerNames = false) {
108
107
  operands: listOperands(db, undefined, undefined, space),
109
108
  patches: listPatches(db, undefined, undefined, undefined, space),
110
109
  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 }) })),
111
- releases,
110
+ // Each release with its bytes: the check builds it and compares the build with them.
111
+ releases: releases.map((release) => ({ ...release, image: releaseImage(db, release.label, space)! })),
112
112
  macros: listMacros(db, undefined, space),
113
113
  macroUses: listMacroUses(db, undefined, undefined, undefined, space),
114
114
  // The start screen is of the C64 program: the loader shows it.
@@ -479,36 +479,25 @@ async function checkSwitch(row: SourceSwitch, patches: PatchBlock[], files: Arra
479
479
  };
480
480
  }
481
481
 
482
- /** What the build of a release gives against the bytes of its file. */
482
+ /** What the build of a release gives against the bytes of the release in the knowledge. */
483
483
  interface ReleaseCheck {
484
484
  label: string;
485
485
  base: boolean;
486
- file: string;
487
486
  define: string;
488
- result: "identical" | "different" | "layout differs" | "file changed" | "does not assemble";
487
+ result: "identical" | "different" | "layout differs" | "does not assemble";
489
488
  reason?: string;
490
489
  segments?: SegmentCheck[];
491
490
  diagnostics?: Diagnostic[];
492
491
  }
493
492
 
494
493
  /**
495
- * Builds a release with RELEASE_<label> and compares it with its file. A
494
+ * Builds a release with RELEASE_<label> and compares it with its bytes. A
496
495
  * release whose segments are not the segments of the program has moved code,
497
496
  * which patches cannot give: it is shown and does not fail the run.
498
497
  */
499
- async function checkRelease(release: ReleaseRow, files: Array<{ name: string; text: string }>, program: ProgramImage): Promise<ReleaseCheck> {
500
- const shown = { label: release.label, base: release.base, file: release.file, define: `--define ${RELEASE_DEFINE}${release.label}=1` };
501
- let image: Image;
502
- try {
503
- const bytes = readProjectFile(release.file).bytes;
504
- if (createHash("sha256").update(bytes).digest("hex") !== release.sha256) {
505
- 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.` };
506
- }
507
- image = readImage(release.file);
508
- } catch (error) {
509
- if (!(error instanceof Refusal || error instanceof WireFailure)) throw error;
510
- return { ...shown, result: "file changed", reason: error.message };
511
- }
498
+ async function checkRelease(release: ReleaseRow & { image: Pick<ProgramImage, "segments" | "byteAt"> }, files: Array<{ name: string; text: string }>, program: ProgramImage): Promise<ReleaseCheck> {
499
+ const shown = { label: release.label, base: release.base, define: `--define ${RELEASE_DEFINE}${release.label}=1` };
500
+ const { image } = release;
512
501
  if (JSON.stringify(image.segments) !== JSON.stringify(program.segments)) {
513
502
  const segments = (list: readonly AddressRange[]) => list.map((segment) => `${formatC64Address(segment.start)}-${formatC64Address(segment.end)}`).join(", ");
514
503
  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.` };
@@ -705,14 +694,24 @@ function sourceMapText(rendered: Rendered, space: string, revision: string | nul
705
694
  return `${head},\n"labels": [\n${labels.join(",\n")}\n],\n"items": [\n${items.join(",\n")}\n]}\n`;
706
695
  }
707
696
 
708
- /** The folder in .c64-re-tools/local/ where the check of the loader runs the new loader.prg. */
697
+ /** The folder in .c64-re-tools/local/ where the check of the loader runs the new loader program. */
709
698
  const LOADER_CHECK_DIRECTORY = "loader-check";
710
699
 
711
- /** The symbols file of loader.prg: the labels of each build that it holds. */
712
- const LOADER_SYMBOLS_FILE = "loader.json";
700
+ /** The source files of the loader. Only a run with --loader writes them, so only such a run removes them. */
701
+ const LOADER_FILES: ReadonlySet<string> = new Set(["loader.asm", START_SCREEN_FILE, STAGE_FILE]);
702
+
703
+ /** A loader program that generate wrote: its build name, as buildName gives it for loader.asm. */
704
+ const LOADER_PROGRAM = /^(clean|custom_[a-z0-9_]+|release_[A-Za-z0-9_]+)_loader\.prg$/;
713
705
 
714
- /** The files of the loader. Only a run with --loader writes them, so only such a run removes them. */
715
- const LOADER_FILES: ReadonlySet<string> = new Set(["loader.asm", "loader.prg", LOADER_SYMBOLS_FILE, START_SCREEN_FILE, STAGE_FILE]);
706
+ /** The loader programs of earlier runs in the build folder, with their symbols files. */
707
+ function loaderPrograms(): string[] {
708
+ const directory = resolveProjectPath(BUILD_DIRECTORY);
709
+ if (!existsSync(directory)) return [];
710
+ return readdirSync(directory)
711
+ .filter((name) => LOADER_PROGRAM.test(name))
712
+ .flatMap((name) => [`${BUILD_DIRECTORY}/${name}`, symbolsPath(`${BUILD_DIRECTORY}/${name}`)])
713
+ .filter((path) => existsSync(resolveProjectPath(path)));
714
+ }
716
715
 
717
716
  /** The start of the line of loader.asm that gives the knowledge revision of the loader. */
718
717
  const LOADER_REVISION = "Loader generated by c64-source from knowledge revision ";
@@ -731,31 +730,78 @@ function staleLoader(out: string, revision: string): { files: string[]; revision
731
730
  const line = text.split(/\r?\n/).find((row) => row.startsWith(`; ${LOADER_REVISION}`));
732
731
  const old = line?.slice(`; ${LOADER_REVISION}`.length).replace(/\.$/, "");
733
732
  if (old === revision) return undefined;
734
- const files = [...LOADER_FILES].filter((name) => existsSync(resolveProjectPath(`${out}/${name}`))).map((name) => `${out}/${name}`);
733
+ const files = [...[...LOADER_FILES].filter((name) => existsSync(resolveProjectPath(`${out}/${name}`))).map((name) => `${out}/${name}`), ...loaderPrograms()];
735
734
  return { files, ...(old === undefined ? {} : { revision: old }) };
736
735
  }
737
736
 
737
+ /** The line of a leftover file that gives its range. */
738
+ const LEFTOVER_RANGE = /^; Leftovers (\$[0-9a-f]{4})-(\$[0-9a-f]{4}):/m;
739
+
740
+ /**
741
+ * The leftovers of the earlier run: the ranges of its generated leftover
742
+ * files in the leftovers folder of `out`. Undefined when `out` has no
743
+ * generated main.asm, so there was no earlier run to compare with.
744
+ */
745
+ function earlierLeftovers(out: string): AddressRange[] | undefined {
746
+ const root = resolveProjectPath(out);
747
+ const main = join(root, "main.asm");
748
+ if (!existsSync(main) || !readFileSync(main, "utf8").startsWith(GENERATED_MARK)) return undefined;
749
+ const directory = join(root, LEFTOVER_FOLDER);
750
+ if (!existsSync(directory)) return [];
751
+ return readdirSync(directory)
752
+ .filter((name) => /^leftover_[0-9a-f]{4}\.asm$/.test(name))
753
+ .flatMap((name) => {
754
+ const found = LEFTOVER_RANGE.exec(readFileSync(join(directory, name), "utf8"));
755
+ return found === null ? [] : [{ start: parseC64Address(found[1]!), end: parseC64Address(found[2]!) }];
756
+ });
757
+ }
758
+
759
+ /** The bytes of `ranges` that are not in `others`, as ranges in address order. */
760
+ function outside(ranges: readonly AddressRange[], others: readonly AddressRange[]): AddressRange[] {
761
+ return [...ranges].sort((a, b) => a.start - b.start).flatMap((range) => subtract(range, [...others]));
762
+ }
763
+
738
764
  /**
739
765
  * Removes the generated .asm files of an earlier run that this run does not
740
- * write, and an earlier not_executed.json and source-map.json. An earlier
741
- * loader.asm stays unless this run has --loader: a source of the user can
742
- * include loader.asm. An earlier loader.prg always stays: only a new loader.prg
743
- * whose check ran replaces it. Other files stay. Gives the names it removed.
766
+ * write, and the reports of the earlier run (its source map and
767
+ * not_executed.json). An earlier loader.asm stays unless this run has
768
+ * --loader: a source of the user can include loader.asm. The files of a
769
+ * module are in `out` or in one folder of it: a folder that the run leaves
770
+ * empty goes too. Other files stay. Gives the paths it removed.
744
771
  */
745
772
  function removeOldFiles(out: string, keep: ReadonlySet<string>, loaderRun: boolean): string[] {
746
- const directory = resolveProjectPath(out);
747
- if (!existsSync(directory)) return [];
748
773
  const removed: string[] = [];
749
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
750
- if (!entry.isFile()) continue;
751
- const name = entry.name;
752
- const path = join(directory, name);
753
- if (LOADER_FILES.has(name) && !loaderRun) continue;
754
- const old = name === NOT_EXECUTED_FILE || name === SOURCE_MAP_FILE || (name.endsWith(".asm") && !keep.has(name) && readFileSync(path, "utf8").startsWith(GENERATED_MARK));
755
- if (!old) continue;
774
+ const reports = generatedDirectory(projectRelative(out));
775
+ for (const name of [SOURCE_MAP_FILE, NOT_EXECUTED_FILE]) {
776
+ const path = resolveProjectPath(`${reports}/${name}`);
777
+ if (!existsSync(path)) continue;
756
778
  rmSync(path, { force: true });
757
- removed.push(name);
779
+ removed.push(`${reports}/${name}`);
758
780
  }
781
+ const root = resolveProjectPath(out);
782
+ if (!existsSync(root)) return removed;
783
+ /** Removes the old generated files of a folder ("" for `out` itself), and gives how many. */
784
+ const clean = (folder: string): number => {
785
+ const directory = folder === "" ? root : join(root, folder);
786
+ let count = 0;
787
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
788
+ const name = folder === "" ? entry.name : `${folder}/${entry.name}`;
789
+ if (entry.isDirectory() && folder === "") {
790
+ // A folder of the user that held no generated file stays, also when it is empty.
791
+ if (clean(name) > 0 && readdirSync(join(root, name)).length === 0) rmSync(join(root, name), { recursive: true, force: true });
792
+ continue;
793
+ }
794
+ if (!entry.isFile()) continue;
795
+ const path = join(directory, entry.name);
796
+ if (LOADER_FILES.has(name) && !loaderRun) continue;
797
+ if (!name.endsWith(".asm") || keep.has(name) || !readFileSync(path, "utf8").startsWith(GENERATED_MARK)) continue;
798
+ rmSync(path, { force: true });
799
+ removed.push(`${out}/${name}`);
800
+ count++;
801
+ }
802
+ return count;
803
+ };
804
+ clean("");
759
805
  return removed;
760
806
  }
761
807
 
@@ -814,7 +860,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
814
860
  operands: knowledge.operands,
815
861
  patches: knowledge.patches,
816
862
  switches: knowledge.switches,
817
- releases: knowledge.releases.map((release) => ({ label: release.label, file: release.file, base: release.base, ...(release.comment === undefined ? {} : { comment: release.comment }) })),
863
+ releases: knowledge.releases.map((release) => ({ label: release.label, base: release.base, ...(release.comment === undefined ? {} : { comment: release.comment }) })),
818
864
  macros: knowledge.macros,
819
865
  macroUses: knowledge.macroUses,
820
866
  startScreen: knowledge.startScreen !== undefined && options.exported !== true,
@@ -995,7 +1041,7 @@ async function stageBytes(row: StartScreenRow): Promise<{ parts: StagePart[]; co
995
1041
  return { parts: parts.map((range) => ({ start: range.start, body: memory.slice(range.start, range.end + 1) })), ...(colourRam === undefined ? {} : { colourRam }) };
996
1042
  }
997
1043
 
998
- /** What the show stage gives: loader.prg, the source of the stage, and what its check needs. */
1044
+ /** What the show stage gives: the loader program, the source of the stage, and what its check needs. */
999
1045
  interface BuiltStage {
1000
1046
  program: Buffer;
1001
1047
  text: string;
@@ -1060,7 +1106,7 @@ async function buildStage(files: Array<{ name: string; text: string }>, laid: La
1060
1106
  const parts = stageParts(input, plan, built.program, built.label);
1061
1107
  const packed = await packParts(parts, plan.code, 0x37, "the loader and the start screen of the stage", "the show stage", localToolContext());
1062
1108
  const end = 0x0801 + packed.program.length - 3;
1063
- 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.`);
1109
+ 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.`);
1064
1110
  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 };
1065
1111
  }
1066
1112
 
@@ -1104,10 +1150,16 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1104
1150
  const configured = [...laid.switches, ...(laid.startScreen ? [{ name: START_SCREEN_SWITCH, default: 1 }] : []), ...(laid.leftovers.length > 0 ? [{ name: LEFTOVERS_SWITCH, default: 0 }] : [])];
1105
1151
  const kept = new Map(configured.flatMap((row) => (given.has(row.name) ? [[row.name, given.get(row.name)!] as const] : [])));
1106
1152
  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 }] : []));
1107
- const removed = removeOldFiles(out, new Set(files.map((file) => file.name)), loaderWanted).map((name) => `${out}/${name}`);
1153
+ // The loader program has the name of its build: clean_loader with the defaults of config.asm.
1154
+ const loaderName = buildName("loader.asm", { values: kept, defaults: new Map(configured.map((row) => [row.name, row.default])) });
1155
+ // Read before the old files go: the leftovers of the earlier run, to tell what changed.
1156
+ const earlier = earlierLeftovers(out);
1157
+ const removed = removeOldFiles(out, new Set(files.map((file) => file.name)), loaderWanted);
1108
1158
  const stale = loaderWanted || space !== DEFAULT_SPACE ? undefined : staleLoader(out, knowledge.revision);
1109
1159
  const written: Written[] = withValues(files, laid, kept).map((file) => writeReported(`${out}/${file.name}`, file.text, { what: "--out" }));
1110
- written.push(writeReported(`${out}/${SOURCE_MAP_FILE}`, sourceMapText(rendered, space, knowledge.revision, files), { what: "--out" }));
1160
+ // The reports go to the local folder: the source folder holds only source files.
1161
+ const reports = generatedDirectory(projectRelative(out));
1162
+ written.push(writeReported(`${reports}/${SOURCE_MAP_FILE}`, sourceMapText(rendered, space, knowledge.revision, files)));
1111
1163
  const showRange = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
1112
1164
  const inData = entriesInData(entries, knowledge.regions);
1113
1165
  if (rendered.notExecuted !== undefined) {
@@ -1121,13 +1173,17 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1121
1173
  const files: Record<string, number> = {};
1122
1174
  for (const range of placed) if (range.file !== undefined) files[range.file] = (files[range.file] ?? 0) + 1;
1123
1175
  const all = { revision: knowledge.revision, instructions: rendered.notExecuted.instructions, files, ranges: placed };
1124
- written.push(writeReported(`${out}/${NOT_EXECUTED_FILE}`, `${JSON.stringify(all, null, 2)}\n`, { what: "--out" }));
1176
+ written.push(writeReported(`${reports}/${NOT_EXECUTED_FILE}`, `${JSON.stringify(all, null, 2)}\n`));
1125
1177
  }
1178
+ // The leftovers that changed since the earlier run: the default build and the loader now leave out other bytes.
1179
+ const added = earlier === undefined ? [] : outside(laid.leftovers, earlier);
1180
+ const dropped = earlier === undefined ? [] : outside(earlier, laid.leftovers);
1181
+ const changed = added.length + dropped.length === 0 ? undefined : { added: added.map(showRange), removed: dropped.map(showRange) };
1126
1182
 
1127
1183
  const output: Record<string, unknown> = {
1128
1184
  out,
1129
1185
  files: written,
1130
- sourceMap: `${out}/${SOURCE_MAP_FILE}`,
1186
+ sourceMap: `${reports}/${SOURCE_MAP_FILE}`,
1131
1187
  // The values that config.asm keeps and that are not the default: a build of the source is not the default build.
1132
1188
  ...(notDefault.length === 0 ? {} : { config: { file: `${out}/${CONFIG_FILE}`, notDefault } }),
1133
1189
  revision: knowledge.revision,
@@ -1151,15 +1207,17 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1151
1207
  ...(rendered.notExecuted === undefined
1152
1208
  ? {}
1153
1209
  : {
1154
- notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max, showRange, `${out}/${NOT_EXECUTED_FILE}`) },
1210
+ notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max, showRange, `${reports}/${NOT_EXECUTED_FILE}`) },
1155
1211
  }),
1156
1212
  ...(laid.unusedModules.length === 0 ? {} : { unusedModules: laid.unusedModules.map((module) => ({ start: formatC64Address(module.start), file: module.file })) }),
1157
1213
  // The bytes that nothing uses: in leftover files, which the default build and the loader leave out.
1158
1214
  ...(laid.leftovers.length === 0
1159
1215
  ? knowledge.coverage === undefined && space === DEFAULT_SPACE
1160
1216
  ? { 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." } }
1161
- : {}
1162
- : { 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` })) } }),
1217
+ : changed === undefined
1218
+ ? {}
1219
+ : { leftovers: { bytes: 0, changed } }
1220
+ : { 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 }) } }),
1163
1221
  ...(rendered.expressions.length === 0 && rendered.operandsAsNumbers.length === 0 ? {} : { operandExpressions: rendered.expressions.length }),
1164
1222
  ...(rendered.operandsAsNumbers.length === 0
1165
1223
  ? {}
@@ -1180,9 +1238,12 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1180
1238
  patchesNotWritten: listed(laid.patchesNotWritten, max, (item) => ({ start: formatC64Address(item.start), end: formatC64Address(item.end), switch: item.switch, reason: item.reason })),
1181
1239
  }),
1182
1240
  };
1183
- // A loader.prg of an earlier run stays when this run checks no new one: it can be a committed file.
1184
- const loaderPath = `${out}/loader.prg`;
1185
- const keptLoader = () => (existsSync(resolveProjectPath(loaderPath)) ? { kept: loaderPath } : {});
1241
+ // 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.
1242
+ const loaderPath = `${BUILD_DIRECTORY}/${loaderName}.prg`;
1243
+ const keptLoader = () => {
1244
+ const earlier = loaderPrograms().filter((path) => path.endsWith(".prg"));
1245
+ return earlier.length === 0 ? {} : { kept: earlier };
1246
+ };
1186
1247
  const notVerified = (fields: Record<string, unknown>) => ({ verified: false, ...fields, ...keptLoader() });
1187
1248
  // The loader includes the source, so it is built only from a source that is identical to the image.
1188
1249
  const notBuilt = (reason: string) => (state === undefined ? {} : { loader: notVerified({ reason: loaderRefused ?? reason }) });
@@ -1228,7 +1289,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1228
1289
  const fileByte = (address: number) => copierBuild[2 + address - (loader.packed?.start ?? 0x0801)]!;
1229
1290
  // A start screen of a captured stage: the show stage holds the packed program, as a cracktro holds the game.
1230
1291
  const stageRow = knowledge.startScreen?.stage === undefined ? undefined : knowledge.startScreen;
1231
- // 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.
1292
+ // 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.
1232
1293
  let packed: PackedLoader | undefined;
1233
1294
  if (loader.packed !== undefined) {
1234
1295
  try {
@@ -1248,12 +1309,12 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1248
1309
  }
1249
1310
  }
1250
1311
  const program = stage?.program ?? packed?.program ?? copierBuild;
1251
- // The check runs the new loader from a scratch file. Only a loader whose check ran goes to --out, so a check
1252
- // that cannot run (no host, or a host of another release) keeps the loader.prg of an earlier run.
1312
+ // The check runs the new loader from a scratch file. Only a loader whose check ran goes to the build folder, so a check
1313
+ // that cannot run (no host, or a host of another release) keeps the loader program of an earlier run.
1253
1314
  ensureLocal(projectRoot());
1254
1315
  const scratch = `${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/${LOADER_CHECK_DIRECTORY}`;
1255
1316
  mkdirSync(resolveProjectPath(scratch), { recursive: true });
1256
- const checkPath = `${scratch}/loader.prg`;
1317
+ const checkPath = `${scratch}/${loaderName}.prg`;
1257
1318
  writeFileSync(resolveProjectPath(checkPath), program);
1258
1319
  // The unpack runs before the copier, or before the show stage, which then starts the loader.
1259
1320
  const unpackFrames = (cycles: number | undefined) => (cycles === undefined ? LOADER_FRAMES : RUN_LIMIT_FRAMES + Math.ceil(cycles / PAL_FRAME_CYCLES));
@@ -1270,15 +1331,21 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1270
1331
  ran = await runLoader(checkPath, program, loader, state, { jump, copierSource, fileByte, copierFrames, ...(startScreen === undefined ? {} : { startScreen }), ...stageRun }, expected);
1271
1332
  } catch (error) {
1272
1333
  if (!isRefusal(error)) throw error;
1273
- const what = existsSync(resolveProjectPath(loaderPath)) ? "kept the loader.prg of an earlier run" : "wrote no loader.prg";
1274
- return { output: { ...output, loader: notVerified({ reason: `The check of loader.prg did not run, so the script ${what}. ${error.message}` }) }, removed, failed: true };
1334
+ const what = loaderPrograms().length > 0 ? "kept the loader program of an earlier run" : "wrote no loader program";
1335
+ return { output: { ...output, loader: notVerified({ reason: `The check of ${loaderName}.prg did not run, so the script ${what}. ${error.message}` }) }, removed, failed: true };
1275
1336
  } finally {
1276
1337
  rmSync(resolveProjectPath(scratch), { recursive: true, force: true });
1277
1338
  }
1278
- written.push(writeReported(loaderPath, program, { what: "--out" }), writeReported(`${out}/${LOADER_SYMBOLS_FILE}`, symbolsFileText(loaderSymbols(loaderMain.symbols, loaderBuilt.symbols, stage?.symbols ?? [])), { what: "--out" }));
1339
+ // A loader program of an earlier run with another build name goes: config.asm has other values now.
1340
+ for (const path of loaderPrograms().filter((item) => item !== loaderPath && item !== symbolsPath(loaderPath))) {
1341
+ rmSync(resolveProjectPath(path), { force: true });
1342
+ removed.push(path);
1343
+ }
1344
+ written.push(writeReported(loaderPath, program), writeReported(symbolsPath(loaderPath), symbolsFileText(loaderSymbols(loaderMain.symbols, loaderBuilt.symbols, stage?.symbols ?? []))));
1279
1345
  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" }));
1280
1346
  output.loader = {
1281
1347
  program: loaderPath,
1348
+ symbols: symbolsPath(loaderPath),
1282
1349
  ...(packed === undefined ? {} : { packed: { packedBytes: packed.packedBytes, unpackedBytes: packed.unpackedBytes } }),
1283
1350
  ...(stage === undefined
1284
1351
  ? {}
@@ -1607,7 +1674,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
1607
1674
  ),
1608
1675
  );
1609
1676
  for (const file of exported.files) files.push(put(`src/${file.name}`, file.text));
1610
- files.push(put(`baseline/${name}.prg`, baseline.program), put(`baseline/${name}.json`, symbolsFileText(shownSymbols)));
1677
+ files.push(put(`baseline/${name}.prg`, baseline.program), put(symbolsPath(`baseline/${name}.prg`), symbolsFileText(shownSymbols)));
1611
1678
  for (const test of tests) files.push(put(test.file, test.text));
1612
1679
  ensureLocal(to);
1613
1680
  const folder = basename(to);
@@ -1739,16 +1806,16 @@ await runScript({
1739
1806
  commands: [
1740
1807
  {
1741
1808
  name: "generate",
1742
- summary: "Writes the source files, source-map.json and not_executed.json, and checks them. result is PASS when every check passes, else FAIL.",
1809
+ 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.",
1743
1810
  options: {
1744
1811
  out: { ...OPTIONS.out, output: "folder", value: "<dir>", help: "the folder for the source files, relative to the project folder", required: true },
1745
1812
  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" },
1746
1813
  space: { ...OPTIONS.space, help: "the knowledge space of the program: c64 (the default), drive8, loading, or bank0 to bank255. --loader is for c64 only" },
1747
- 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" },
1814
+ 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" },
1748
1815
  "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" },
1749
1816
  "max-listed": OPTIONS["max-listed"],
1750
1817
  },
1751
- 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.",
1818
+ 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.",
1752
1819
  run: async (call) => {
1753
1820
  const { output, failed, removed } = await generate(call);
1754
1821
  // A file of an earlier run that this run removed and did not write again.
@@ -29,7 +29,7 @@ To get the command list, run the script with no arguments.
29
29
  | Get C-like code of a routine | `analyze --entry '$080d' --decompile '$0818'` |
30
30
  | Get each instruction as JSON | `analyze --entry '$080d' --out-instructions .c64-re-tools/local/instructions.json` |
31
31
  | Analyze drive code or a cartridge bank | `analyze --space drive8` |
32
- | Get the macro candidates as a batch of changes | `analyze --out-macro-batch .c64-re-tools/local/macros.json` |
32
+ | Write the macro candidates to the project knowledge | `analyze --apply-macros` |
33
33
  | Get more items in each list | `analyze --max-listed 500` |
34
34
 
35
35
  ---
@@ -86,7 +86,7 @@ Each flag applies only to the commands in the table. On another command, the scr
86
86
  | `--max-listed <n>` | `analyze` | List at most `n` items in each list. `0` lists no items. The counts stay complete. The default is 50. |
87
87
  | `--out-listing <file>` | `analyze` | DXA only. Write the disassembly listing to this project file. There is no default. |
88
88
  | `--out-instructions <file>` | `analyze` | Ghidra only. Write each instruction to this project file as JSON. There is no default. |
89
- | `--out-macro-batch <file>` | `analyze` | Write the macro candidates to this project file as a batch of changes to the project knowledge. There is no default. |
89
+ | `--apply-macros` | `analyze` | Write the macro candidates and their macros to the project knowledge as one revision of the LLM. Off by default. |
90
90
 
91
91
  ---
92
92
 
@@ -127,7 +127,7 @@ The `hint` gives each of these cases:
127
127
 
128
128
  - `conflicts` is not empty. Find the correct answer in the emulator. Then correct the project knowledge.
129
129
  - `coverageConflicts` is not empty. Classify each range as code in the project knowledge, or as `dual-use` when its bytes are also data. For many ranges, write all classifications in one batch of changes.
130
- - The batch of `--out-macro-batch` has changes. Apply the changes in the batch file to the project knowledge. Then generate the source again.
130
+ - `macros` has candidates, and the run had no `--apply-macros`. Examine the candidates. To write them to the project knowledge, run the analysis again with `--apply-macros`. Then generate the source again.
131
131
  - A list is cut. Give a larger `--max-listed`. The project knowledge has all `labels` and `functions` as analyzer names.
132
132
 
133
133
  There is no `nextAction`.
@@ -140,7 +140,7 @@ The script does not record the candidates. Examine each candidate and decide.
140
140
  - `selfModified`: opcodes that the program wrote and then executed. The write and the execution must be in one coverage file. A coverage file does not record the order. Thus a candidate can also be code that ran first, and that the program then wrote over. To prevent this, save one coverage file for each part of the program, for example the intro, the game, or a loader that copies code. Clear the memory map between the parts.
141
141
  - `pointers`: code that makes an address from immediates. A `vector` or a `zero-page pointer` candidate stores a low byte (`low`) and a high byte (`high`) to a vector or to a zero-page pair. A `sprite pointer` candidate stores an immediate (`at`) to a sprite pointer of the screen at `$0400` in VIC bank 0. For each correct candidate, record a low and a high operand expression to its `target` in the project knowledge. Then a rebuild can move the target.
142
142
  - `pitfalls`: code that a C64 runs in a different way than it reads. For `raster-bit-8`, the instruction at `at` reads `$D011`, and the instruction at `store` writes the value back. The write can move the raster interrupt to line 256 or later. On PAL, past line 311, the interrupt never comes. Where the code must not keep bit 7, add a comment and test the program.
143
- - `macros`: runs of instructions that one macro line can replace, for example `+inc16 ptr`. Each candidate has `macro`, `start`, `end`, `args` and `text`. The macros are `inc16`, `dec16`, `add16_8`, `add16`, `sub16`, `set16`, `mov16` and `wait_line`. An arg is a name of the user or the LLM, or a platform name of a ROM that the program uses. `known` counts the uses that the project knowledge has. `leftOut` counts the candidates with a label inside, or with a patch or a use over them. With `--out-macro-batch`, `batch` gives the file and the count of changes (`writes`). The batch holds the macros that the project knowledge does not have, and the uses. `otherMacros` names each macro that the project knowledge has with another body. The batch does not have the uses of that macro.
143
+ - `macros`: runs of instructions that one macro line can replace, for example `+inc16 ptr`. Each candidate has `macro`, `start`, `end`, `args` and `text`. The macros are `inc16`, `dec16`, `add16_8`, `add16`, `sub16`, `set16`, `mov16` and `wait_line`. An arg is a name of the user or the LLM, or a platform name of a ROM that the program uses. `known` counts the uses that the project knowledge has. `leftOut` counts the candidates with a label inside, or with a patch or a use over them. With `--apply-macros`, `revision` gives the revision of the writes, and `writes` counts them. The writes hold the macros that the project knowledge does not have, and the uses. `otherMacros` names each macro that the project knowledge has with another body. The writes do not have the uses of that macro.
144
144
 
145
145
  #### Which facts the analysis replaces
146
146
 
@@ -13,7 +13,8 @@ import { analyze as analyzeWithGhidra } from "#src/native/ghidra/analyze.ts";
13
13
  import { localToolContext } from "#src/native/local.ts";
14
14
  import { GHIDRA_LIMITS } from "#src/native/types.ts";
15
15
  import { openForRead, withWrite } from "#src/knowledge/database.ts";
16
- import { analyzedBytes, programCoverage, requireProgram } from "#src/knowledge/program.ts";
16
+ import { analyzedBytes, operandImages, programCoverage, requireProgram } from "#src/knowledge/program.ts";
17
+ import { applyBatch, type BatchOperation } from "#src/knowledge/write.ts";
17
18
  import { importFindings, runProvenance, type ImportConflict, type ImportContext, type ImportResult, type NormalizedFindings } from "#src/knowledge/import.ts";
18
19
  import { currentRevision, listMacros, listMacroUses, listPatches, listReferences, listRegions, listSymbols } from "#src/knowledge/read.ts";
19
20
  import { DEFAULT_SPACE, SEMANTIC_ORIGINS, type Analyzer } from "#src/knowledge/schema.ts";
@@ -32,14 +33,15 @@ const ALL_NAMES = "a larger --max-listed. The project knowledge has all of them
32
33
 
33
34
  /**
34
35
  * The result with a hint for what the agent does next: conflicts to examine,
35
- * analyzer data over executed code to classify, and a macro batch to apply.
36
+ * analyzer data over executed code to classify, and macro candidates to write.
36
37
  * The envelope adds the sentence for a cut list.
37
38
  */
38
- function withHint(body: Record<string, unknown>, conflicts: number, coverageConflicts: number, batch: { out: string; writes: number } | undefined) {
39
+ function withHint(body: Record<string, unknown>, conflicts: number, coverageConflicts: number, macros: { candidates: number; applied: boolean; revision: string | null | undefined }) {
39
40
  const hints: string[] = [];
40
41
  if (conflicts > 0) hints.push("The analysis and the project knowledge disagree at each place in conflicts. Find the correct answer in the emulator. Then correct the project knowledge.");
41
42
  if (coverageConflicts > 0) hints.push("The coverage shows executed code in each range of coverageConflicts. Classify each range as code, or as dual-use when its bytes are also data, in the project knowledge.");
42
- if (batch !== undefined && batch.writes > 0) hints.push(`Apply the changes in ${batch.out} to the project knowledge. Then generate the source again.`);
43
+ if (typeof macros.revision === "string") hints.push("The project knowledge has the macro candidates now. Generate the source again.");
44
+ else if (!macros.applied && macros.candidates > 0) hints.push("Examine idioms.candidates.macros. To write them to the project knowledge, run the analysis again with --apply-macros.");
43
45
  if (hints.length === 0) return body;
44
46
  return reply(body, { hint: hints.join(" ") });
45
47
  }
@@ -73,11 +75,11 @@ function showMacro(candidate: MacroCandidate) {
73
75
  * the ROMs that the program uses, as c64-source names them. A candidate is left out when
74
76
  * a name or a reference target is inside it, or a patch or a use overlaps it:
75
77
  * c64-source would write its instructions. The same use in the knowledge is
76
- * known. With `batchPath`, the candidates go to an apply batch with the
77
- * macros they need; a macro of the catalogue that the knowledge has with
78
- * another body leaves its candidates out of the batch.
78
+ * known. The writes are the candidates with the macros they need. A macro of
79
+ * the catalogue that the knowledge has with another body leaves its
80
+ * candidates out of the writes.
79
81
  */
80
- function macroCandidates(space: string, byteAt: ImageByte, batchPath: string | undefined, romUse: RomUse) {
82
+ function macroCandidates(space: string, byteAt: ImageByte, romUse: RomUse) {
81
83
  const db = openForRead();
82
84
  try {
83
85
  // The platform names that c64-source uses: a name of a ROM that the program does not use is no arg.
@@ -98,33 +100,20 @@ function macroCandidates(space: string, byteAt: ImageByte, batchPath: string | u
98
100
  else if ([...named].some((address) => address > candidate.start && address <= candidate.end) || patches.some((patch) => overlaps(patch, candidate)) || uses.some((use) => overlaps(use, candidate))) leftOut++;
99
101
  else candidates.push(candidate);
100
102
  }
101
- if (batchPath === undefined) return { candidates, known, leftOut };
102
- // A macro of the catalogue goes into the batch unless the knowledge has it; with another body, its uses stay out.
103
+ // A macro of the catalogue goes into the writes unless the knowledge has it; with another body, its uses stay out.
103
104
  const macros = new Map(listMacros(db, undefined, space).map((macro) => [macro.name, macro]));
104
- const batch: Array<Record<string, unknown>> = [];
105
- const batched: MacroCandidate[] = [];
105
+ const writes: BatchOperation[] = [];
106
106
  const other = new Set<string>();
107
107
  for (const idiom of CATALOGUE.filter((item) => candidates.some((candidate) => candidate.macro === item.name))) {
108
108
  const existing = macros.get(idiom.name);
109
- if (existing === undefined) batch.push({ op: "macro", name: idiom.name, params: idiom.params, body: idiom.body, comment: idiom.comment, ...(space === DEFAULT_SPACE ? {} : { space }) });
109
+ if (existing === undefined) writes.push({ op: "macro", space, name: idiom.name, params: [...idiom.params], body: idiom.body, comment: idiom.comment });
110
110
  else if (existing.params.join(",") !== idiom.params.join(",") || existing.body !== idiom.body) other.add(idiom.name);
111
111
  }
112
112
  for (const candidate of candidates) {
113
113
  if (other.has(candidate.macro)) continue;
114
- batched.push(candidate);
115
- batch.push({ op: "use", start: formatC64Address(candidate.start), end: formatC64Address(candidate.end), macro: candidate.macro, args: candidate.args, ...(space === DEFAULT_SPACE ? {} : { space }) });
114
+ writes.push({ op: "use", space, start: candidate.start, end: candidate.end, macro: candidate.macro, args: candidate.args });
116
115
  }
117
- const written = batch.length > 0 ? writeReported(batchPath, `${JSON.stringify(batch, null, 1)}\n`, { what: "--out-macro-batch" }) : { out: batchPath };
118
- return {
119
- candidates,
120
- known,
121
- leftOut,
122
- batch: {
123
- ...written,
124
- writes: batch.length,
125
- ...(other.size === 0 ? {} : { otherMacros: [...other].map((name) => `The knowledge has another macro ${name}: its candidates are not in the batch.`) }),
126
- },
127
- };
116
+ return { candidates, known, leftOut, writes, otherMacros: [...other].map((name) => `The knowledge has another macro ${name}: its candidates are not written.`) };
128
117
  } finally {
129
118
  db?.close();
130
119
  }
@@ -194,7 +183,7 @@ async function analyze(call: Call): Promise<unknown> {
194
183
  const analyzer = call.string("analyzer") as "dxa" | "ghidra";
195
184
  const listingPath = call.string("out-listing");
196
185
  const instructionsPath = call.string("out-instructions");
197
- const batchPath = call.string("out-macro-batch");
186
+ const applyMacros = call.flag("apply-macros");
198
187
  if (analyzer === "dxa" && decompile.length > 0) throw new UsageError("--decompile works only with --analyzer ghidra");
199
188
  if (analyzer === "ghidra" && listingPath !== undefined) throw new UsageError("--out-listing works only with --analyzer dxa");
200
189
  if (analyzer === "dxa" && instructionsPath !== undefined) throw new UsageError("--out-instructions works only with --analyzer ghidra");
@@ -241,7 +230,10 @@ async function analyze(call: Call): Promise<unknown> {
241
230
  const idiomsResult = () => {
242
231
  const imported = withWrite((db) => importFindings(db, { ...idioms.findings, space }, { description: "Idioms in the program" }));
243
232
  // The macro candidates read the code regions after both imports.
244
- const macros = macroCandidates(space, byteAt, batchPath, romUseOfProgram(coverage, program.state));
233
+ const macros = macroCandidates(space, byteAt, romUseOfProgram(coverage, program.state));
234
+ // With --apply-macros, the candidates and their macros are a third revision of the LLM.
235
+ const platformNamed = new Map(platformNames().map((entry) => [entry.name, entry.address]));
236
+ const written = applyMacros && macros.writes.length > 0 ? withWrite((db) => applyBatch(db, { origin: "llm", description: "Macro candidates in the program", image: operandImages(db, platformNamed) }, macros.writes)) : undefined;
245
237
  // Platform pitfalls are C64 facts: drive code and banks get none. Pitfalls and pointers read the code regions after both imports.
246
238
  const codeDb = openForRead();
247
239
  const code = listRegions(codeDb, undefined, "code", undefined, space);
@@ -264,10 +256,11 @@ async function analyze(call: Call): Promise<unknown> {
264
256
  pointers: listed(pointers, max, showPointer, "a larger --max-listed"),
265
257
  pitfalls: listed(pitfalls, max, showPitfall, "a larger --max-listed"),
266
258
  macros: {
267
- ...listed(macros.candidates, max, showMacro, "a larger --max-listed, or --out-macro-batch <file>"),
259
+ ...listed(macros.candidates, max, showMacro, "a larger --max-listed"),
268
260
  ...(macros.known === 0 ? {} : { known: macros.known }),
269
261
  ...(macros.leftOut === 0 ? {} : { leftOut: macros.leftOut }),
270
- ...(macros.batch === undefined ? {} : { batch: macros.batch }),
262
+ ...(written === undefined ? {} : { revision: written.revision, writes: macros.writes.length }),
263
+ ...(macros.otherMacros.length === 0 ? {} : { otherMacros: macros.otherMacros }),
271
264
  },
272
265
  },
273
266
  },
@@ -315,7 +308,7 @@ async function analyze(call: Call): Promise<unknown> {
315
308
  labels: listed(result.labels, max, (label) => ({ address: formatC64Address(label.address), name: label.name }), ALL_NAMES),
316
309
  ...(written === undefined ? {} : { listing: written }),
317
310
  };
318
- return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, found.idioms.candidates.macros.batch);
311
+ return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision });
319
312
  }
320
313
 
321
314
  const { result } = await analyzeWithGhidra({ imageKind, ...seeds, codeStarts, decompile }, bytes, localToolContext());
@@ -349,7 +342,7 @@ async function analyze(call: Call): Promise<unknown> {
349
342
  ? {}
350
343
  : { notDecompiled: result.notDecompiled!.map((item) => ({ entry: formatC64Address(item.entry), reason: withRemedy(item.reason) })) }),
351
344
  };
352
- return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, found.idioms.candidates.macros.batch);
345
+ return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision });
353
346
  }
354
347
 
355
348
  await runScript({
@@ -368,7 +361,7 @@ await runScript({
368
361
  "max-listed": { ...OPTIONS["max-listed"], help: "list at most n labels, functions or candidates (default 50, 0 for none). The counts are always given, and the knowledge has all labels and functions" },
369
362
  "out-listing": { kind: "path", output: "file", value: "<file>", help: "dxa: write the disassembly listing to this project file" },
370
363
  "out-instructions": { kind: "path", output: "file", value: "<file>", help: "ghidra: write every instruction (address, bytes, mnemonic, mode, operand, target, executed) to this project file as JSON" },
371
- "out-macro-batch": { kind: "path", output: "file", value: "<file>", help: "write the macro candidates (the macros and their uses) to this project file as a batch of changes to the project knowledge" },
364
+ "apply-macros": { kind: "flag", help: "write the macro candidates (the macros and their uses) to the project knowledge as one revision of the LLM" },
372
365
  },
373
366
  notes: "The program and the coverage come from the project knowledge: put them into the project knowledge first. The executed code of the coverage gives entry points. Routine symbols in the knowledge are entry points too. Ghidra needs at least one entry point. DXA finds the SYS of a BASIC start by itself.",
374
367
  run: analyze,
@@ -30,7 +30,7 @@ To get the command list, run the script with no arguments.
30
30
  | Record a play session of a person on the original | `record tests/record/start.json --out tests/recordings/play1 --play --joystick 1` |
31
31
  | Record a session from steps only | `record tests/record/rooms.json --out tests/recordings/rooms` |
32
32
  | Make sure that a recording replays on the original | `replay tests/recordings/rooms` |
33
- | Compare the rebuild with a recording | `replay tests/recordings/rooms --checkpoint main_loop --state room --state lives --pin random_ptr:2 --rebuild build/game.prg --symbols build/game.json --out .c64-re-tools/local/results/rooms` |
33
+ | Compare the rebuild with a recording | `replay tests/recordings/rooms --checkpoint main_loop --state room --state lives --pin random_ptr:2 --rebuild build/clean.prg --symbols build/symbols/clean.json --out .c64-re-tools/local/results/rooms` |
34
34
  | Find what changed between two snapshot files | `diff .c64-re-tools/local/runs/rooms/before.vsf .c64-re-tools/local/runs/rooms/after.vsf` |
35
35
  | Find what changed between two observations of runs | `diff .c64-re-tools/local/runs/rooms/results.json:room0 .c64-re-tools/local/runs/rooms/results.json:room3` |
36
36
  | Find what changed between two memory files of runs | `diff .c64-re-tools/local/runs/a/all.bin .c64-re-tools/local/runs/b/all.bin --gap 4` |
@@ -8,7 +8,7 @@ A scenario is one JSON object in a project file.
8
8
  {
9
9
  "name": "player moves left",
10
10
  "original": { "program": "original/game.prg", "symbols": "knowledge" },
11
- "rebuild": { "program": "build/game.prg", "symbols": "build/game.json" },
11
+ "rebuild": { "program": "build/clean.prg", "symbols": "build/symbols/clean.json" },
12
12
  "steps": [
13
13
  { "frames": 150 },
14
14
  { "load": true },