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

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 (87) hide show
  1. package/package.json +2 -2
  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 +2 -2
  5. package/skills/c64-docs/SKILL.md +4 -4
  6. package/skills/c64-docs/scripts/docs.ts +7 -7
  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 +29 -20
  10. package/skills/c64-knowledge/scripts/knowledge.ts +33 -39
  11. package/skills/c64-knowledge/scripts/lib/listing.ts +18 -3
  12. package/skills/c64-packer/SKILL.md +1 -1
  13. package/skills/c64-provenance/SKILL.md +11 -10
  14. package/skills/c64-provenance/scripts/lib/library.ts +16 -16
  15. package/skills/c64-provenance/scripts/provenance.ts +33 -23
  16. package/skills/c64-reverse-engineering/SKILL.md +16 -10
  17. package/skills/c64-source/SKILL.md +60 -42
  18. package/skills/c64-source/scripts/lib/export.ts +76 -32
  19. package/skills/c64-source/scripts/lib/loader.ts +26 -7
  20. package/skills/c64-source/scripts/lib/source.ts +21 -24
  21. package/skills/c64-source/scripts/lib/stage.ts +6 -5
  22. package/skills/c64-source/scripts/source.ts +213 -106
  23. package/skills/c64-static-analysis/SKILL.md +7 -5
  24. package/skills/c64-static-analysis/scripts/lib/coverage.ts +2 -25
  25. package/skills/c64-static-analysis/scripts/lib/instructions.ts +22 -20
  26. package/skills/c64-static-analysis/scripts/static-analysis.ts +36 -43
  27. package/skills/c64-testing/SKILL.md +5 -2
  28. package/skills/c64-testing/references/recording-format.md +18 -3
  29. package/skills/c64-testing/references/scenario-format.md +7 -6
  30. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  31. package/skills/c64-testing/scripts/lib/play.ts +39 -41
  32. package/skills/c64-testing/scripts/lib/recording.ts +46 -37
  33. package/skills/c64-testing/scripts/lib/replay.ts +1 -1
  34. package/skills/c64-testing/scripts/lib/runs.ts +2 -2
  35. package/skills/c64-testing/scripts/lib/scenario.ts +17 -10
  36. package/skills/c64-unpacker/SKILL.md +4 -1
  37. package/skills/c64-unpacker/scripts/lib/loads.ts +34 -13
  38. package/skills/c64-unpacker/scripts/unpacker.ts +5 -3
  39. package/skills/emulator/SKILL.md +7 -12
  40. package/src/build-name.ts +50 -0
  41. package/src/c64-keys.ts +98 -0
  42. package/src/c64.ts +20 -0
  43. package/src/cli/main.ts +3 -29
  44. package/src/host/main.ts +1 -1
  45. package/src/host/tools/index.ts +1 -6
  46. package/src/host/vice/session.ts +88 -9
  47. package/src/host-client/steps.ts +17 -17
  48. package/src/host-client/tools.ts +2 -7
  49. package/src/host-client/vice-session.ts +7 -1
  50. package/src/knowledge/program.ts +44 -1
  51. package/src/knowledge/read.ts +28 -8
  52. package/src/knowledge/schema.ts +33 -9
  53. package/src/knowledge/start-screen.ts +4 -0
  54. package/src/knowledge/text.ts +4 -2
  55. package/src/knowledge/write.ts +59 -25
  56. package/src/mcp/inputs.ts +12 -0
  57. package/src/mcp/server.ts +1 -1
  58. package/src/mcp/tools/input.ts +38 -5
  59. package/src/mcp/tools/machine.ts +3 -42
  60. package/src/mcp/tools/media.ts +1 -1
  61. package/src/native/acme.ts +1 -1
  62. package/src/native/c64run.ts +1 -1
  63. package/src/native/discover.ts +3 -3
  64. package/src/native/dxa.ts +12 -1
  65. package/src/native/ghidra/analyze.ts +74 -63
  66. package/src/native/ghidra/c64rt-wasm.ts +4 -0
  67. package/src/native/ghidra/language/c64rt_6510.sla +0 -0
  68. package/src/native/ghidra/pcode.ts +222 -0
  69. package/src/native/ghidra/walk.ts +205 -0
  70. package/src/native/ghidra/wasm.ts +98 -0
  71. package/src/native/processes.ts +4 -4
  72. package/src/native/types.ts +2 -2
  73. package/src/platform.ts +30 -1
  74. package/src/project.ts +17 -4
  75. package/src/protocol/tools.ts +1 -45
  76. package/src/protocol/vice.ts +47 -0
  77. package/src/script.ts +1 -1
  78. package/src/vsf.ts +98 -0
  79. package/tools/c64run.c +9 -12
  80. package/tools/install-container.sh +1 -2
  81. package/src/cli/status.ts +0 -127
  82. package/src/host/tools/status.ts +0 -47
  83. package/src/native/ghidra/index.ts +0 -170
  84. package/src/native/ghidra/scripts/C64Export.java +0 -274
  85. package/src/native/ghidra/scripts/C64Prepare.java +0 -66
  86. package/src/native/status.ts +0 -135
  87. package/tools/install-ghidra.sh +0 -40
@@ -17,7 +17,7 @@ import { operandText } from "#src/knowledge/expression.ts";
17
17
  import { historyAt, historyNamed, historyOfMacro, historyOfSwitch, revision, revisionNote, revisions, type HistoryEntry } from "#src/knowledge/history.ts";
18
18
  import { joinBatches, type Batch, type JoinChoice, type JoinClash } from "#src/knowledge/join.ts";
19
19
  import { knowledgeNames } from "#src/knowledge/names.ts";
20
- import { addCoverage, programCoverage, programImage, requireProgram, setImage, type ImageRequest } from "#src/knowledge/program.ts";
20
+ import { addCoverage, memoryRows, operandImages as programImages, programCoverage, programImage, requireProgram, setImage, type ImageRequest } from "#src/knowledge/program.ts";
21
21
  import { startScreenOfStage } from "#src/knowledge/start-screen.ts";
22
22
  import {
23
23
  analyzerNamesAt,
@@ -159,8 +159,6 @@ const switchRow = (row: SwitchRow, base?: string, patches?: readonly PatchRow[])
159
159
  const release = (row: ReleaseRow) => ({
160
160
  ...spaceOf(row),
161
161
  label: row.label,
162
- file: row.file,
163
- sha256: row.sha256,
164
162
  base: row.base,
165
163
  define: `--define ${RELEASE_DEFINE}${row.label}=1`,
166
164
  ...(row.comment === undefined ? {} : { comment: row.comment }),
@@ -273,8 +271,10 @@ function listingSource(db: DatabaseSync | undefined, space: string): ListingSour
273
271
  const coverage = programCoverage(db, space)?.map;
274
272
  const inside = (at: number) => image.segments.some((segment) => at >= segment.start && at <= segment.end);
275
273
  const platform = new Map(space === DEFAULT_SPACE ? platformNames().map((entry) => [entry.address, entry.name]) : []);
274
+ const entries = space === DEFAULT_SPACE ? platformNames().filter((entry) => entry.end > entry.address) : [];
276
275
  return {
277
276
  byteAt: (at) => (inside(at) ? image.byteAt(at) : undefined),
277
+ entryStart: (at) => (inside(at) ? undefined : entries.find((entry) => at > entry.address && at <= entry.end)?.address),
278
278
  // A user or LLM name, else the platform name; an analyzer name in symbols (knowledge from an older version) gives way to it.
279
279
  nameOf: (at) => {
280
280
  const own = symbolAt(db, at, space);
@@ -361,15 +361,9 @@ function imageRequest(path: string, space: string): ImageRequest {
361
361
  return request;
362
362
  }
363
363
 
364
- /**
365
- * The program in the knowledge that operand, patch and macro use writes
366
- * are checked against, with the platform names. A byte outside
367
- * the segments of the program is not in it.
368
- */
369
- function operandImage(db: DatabaseSync, space: string): OperandImage {
370
- const image = requireProgram(db, space);
371
- const inside = (at: number) => image.segments.some((segment) => at >= segment.start && at <= segment.end);
372
- return { byteAt: (at) => (inside(at) ? image.byteAt(at) : undefined), platform: new Map(platformNames().map((entry) => [entry.name, entry.address])) };
364
+ /** The programs that operand, patch and macro use writes are checked against, with the platform names. */
365
+ function operandImages(db: DatabaseSync): (space: string) => OperandImage {
366
+ return programImages(db, new Map(platformNames().map((entry) => [entry.name, entry.address])));
373
367
  }
374
368
 
375
369
  /** An offset: a whole number in decimal or $ hex, with an optional minus sign. */
@@ -812,7 +806,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
812
806
  request.symbol = call.string(select)!;
813
807
  if (offset !== undefined) request.offset = offsetOf(offset, "--offset");
814
808
  }
815
- return (db) => shown(setOperand(db, { ...context, image: operandImage(db, call.space) }, request), "operand", operand);
809
+ return (db) => shown(setOperand(db, { ...context, image: operandImages(db) }, request), "operand", operand);
816
810
  },
817
811
  ),
818
812
  writeCommand({ name: "unoperand", summary: "Removes the operand expression at an address.", subjects: [ADDRESS] }, (call) => {
@@ -839,7 +833,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
839
833
  if ((code === undefined) === !call.flag("nop")) throw new UsageError("patch needs exactly one of --code, --code-file or --nop.");
840
834
  const commentText = call.string("comment");
841
835
  const request = { space: call.space, ...call.parseRange(call.subject(0), "<range>"), switch: call.subject(1), code: code ?? "", ...(commentText === undefined ? {} : { comment: commentText }) };
842
- return (db) => shown(setPatch(db, { ...context, image: operandImage(db, call.space) }, request), "patch", patch);
836
+ return (db) => shown(setPatch(db, { ...context, image: operandImages(db) }, request), "patch", patch);
843
837
  },
844
838
  ),
845
839
  writeCommand(
@@ -883,7 +877,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
883
877
  ...(commentText === undefined ? {} : { comment: commentText }),
884
878
  };
885
879
  return (db) => {
886
- const result = setSwitch(db, { ...context, image: operandImage(db, call.space) }, request);
880
+ const result = setSwitch(db, { ...context, image: operandImages(db) }, request);
887
881
  const base = listReleases(db, undefined, call.space).find((row) => row.base)?.label;
888
882
  return shown(result, "switch", (row: SwitchRow) => switchRow(row, base));
889
883
  };
@@ -897,27 +891,23 @@ const WRITE_COMMANDS: CommandSpec[] = [
897
891
  writeCommand(
898
892
  {
899
893
  name: "release",
900
- summary: "Records a release of the program: its PRG or the image.json of its capture in the project. The base release is the one whose bytes are the program of the knowledge.",
894
+ summary: "Records a release of the program from its PRG or the image.json of its capture: the knowledge keeps the bytes of the release. The base release is the one whose bytes are the program of the knowledge.",
901
895
  subjects: [{ name: "<label>", help: "the release label, for example ORIGINAL or FIRESTAR" }],
902
896
  options: {
903
- file: { kind: "path", value: "<file>", help: "the PRG or image.json of the release, in a folder that git keeps", required: true },
897
+ file: { kind: "path", value: "<file>", help: "the PRG or image.json of the release. After the write, the knowledge does not need the file", required: true },
904
898
  base: { kind: "flag", help: "this release is the program of the knowledge: its segments and bytes must be the same" },
905
899
  comment: { kind: "text", value: "<text>", help: "what the release is, for example the group and the date" },
906
900
  },
907
- notes: "The build of a release defines RELEASE_<label>=1: each switch then has the value of that release. The check of the generated source builds each release and compares it with the bytes of its file.",
901
+ notes: "The build of a release defines RELEASE_<label>=1: each switch then has the value of that release. The check of the generated source builds each release and compares it with the bytes of the release in the knowledge.",
908
902
  },
909
903
  (call) => {
910
904
  const context = contextOf(call);
911
905
  const file = knowledgePath(call.string("file")!, "--file");
912
- const root = projectRoot();
913
- if (isInside(join(root, PROJECT_DIRECTORY, LOCAL_DIRECTORY), resolveProjectPath(file, root))) {
914
- throw new UsageError(`--file ${file} is in ${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/, which git ignores. Move the release to a folder that git keeps, for example original/.`);
915
- }
916
906
  const image = readImage(file);
917
- const sha256 = createHash("sha256").update(readProjectFile(file).bytes).digest("hex");
918
907
  const commentText = call.string("comment");
919
908
  const base = call.flag("base");
920
- const request = { space: call.space, label: call.subject(0), file, sha256, ...(base ? { base } : {}), ...(commentText === undefined ? {} : { comment: commentText }) };
909
+ // The base release has no bytes of its own: its bytes are the program.
910
+ const request = { space: call.space, label: call.subject(0), ...(base ? { base } : { rows: memoryRows(image.segments, image.byteAt) }), ...(commentText === undefined ? {} : { comment: commentText }) };
921
911
  return (db) => {
922
912
  if (base) {
923
913
  const program = requireProgram(db, call.space);
@@ -927,7 +917,8 @@ const WRITE_COMMANDS: CommandSpec[] = [
927
917
  });
928
918
  if (!same) throw new Refusal("invalid-input", `The bytes of ${file} are not the program of the knowledge. Give --base only to the release whose file image put into the knowledge.`);
929
919
  }
930
- return shown(setRelease(db, context, request), "release", release);
920
+ const bytes = image.segments.reduce((sum, segment) => sum + segment.end - segment.start + 1, 0);
921
+ return { ...shown(setRelease(db, context, request), "release", release), bytes };
931
922
  };
932
923
  },
933
924
  ),
@@ -1042,7 +1033,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
1042
1033
  const context = contextOf(call);
1043
1034
  const request = { space: call.space, ...call.parseRange(call.subject(0), "<range>"), macro: call.subject(1), args: commaList(call.string("args") ?? "") };
1044
1035
  return (db) => {
1045
- const result = setMacroUse(db, { ...context, image: operandImage(db, call.space) }, request);
1036
+ const result = setMacroUse(db, { ...context, image: operandImages(db) }, request);
1046
1037
  return { revision: result.revision, use: macroUse(result.current), ...(result.previous === undefined ? {} : { previous: macroUse(result.previous) }) };
1047
1038
  };
1048
1039
  },
@@ -1126,23 +1117,25 @@ const WRITE_COMMANDS: CommandSpec[] = [
1126
1117
  }
1127
1118
  if (!Array.isArray(parsed)) throw new Refusal("invalid-input", `The batch ${path} is not a JSON list of writes. Give a list such as [{"op": "rename", "address": "$2100", "name": "update_player"}].`);
1128
1119
  const operations = parsed.map((item, index) => batchOperation(call, item, `write ${index + 1}`));
1129
- const checked = operations.some((operation) => operation.op === "operand" || operation.op === "patch" || operation.op === "use");
1130
- return (db) => {
1131
- const applied = applyBatch(db, checked ? { ...context, image: operandImage(db, call.space) } : context, operations);
1132
- // replaced: each write that replaced a row of another origin, with that row as previous gives it for one write.
1133
- const replaced = applied.steps.flatMap((step, index) => (step.previous === undefined ? [] : [{ write: index + 1, op: operations[index]!.op, previous: shownPrevious(step.previous) }]));
1134
- return { revision: applied.revision, writes: applied.steps.length, replaced };
1135
- };
1120
+ return (db) => applied(db, context, operations);
1136
1121
  },
1137
1122
  ),
1138
1123
  ];
1139
1124
 
1140
- /** join: the batches of agents that worked in parallel, as one batch for apply. It writes no knowledge. */
1125
+ /** Applies the writes of a batch as one revision, and gives the revision, the count and each row of another origin that a write replaced. */
1126
+ function applied(db: DatabaseSync, context: WriteContext, operations: BatchOperation[]) {
1127
+ const result = applyBatch(db, { ...context, image: operandImages(db) }, operations);
1128
+ // replaced: each write that replaced a row of another origin, with that row as previous gives it for one write.
1129
+ const replaced = result.steps.flatMap((step, index) => (step.previous === undefined ? [] : [{ write: index + 1, op: operations[index]!.op, previous: shownPrevious(step.previous) }]));
1130
+ return { revision: result.revision, writes: result.steps.length, replaced };
1131
+ }
1132
+
1133
+ /** join: the batches of agents that worked in parallel, as one list of writes. With --apply, it writes them as one revision. */
1141
1134
  const JOIN: CommandSpec = {
1142
1135
  name: "join",
1143
- summary: "Joins the batches of agents that worked in parallel into one batch for apply. It writes no knowledge.",
1136
+ summary: "Joins the batches of agents that worked in parallel into one list of writes, and shows it. With --apply, it writes the list as one revision, or nothing when one write is refused.",
1144
1137
  subjects: [{ name: "<batch>", help: 'a batch: a list of writes, or {"owner": {"start": "$1000", "end": "$1fff"}, "ops": [...]}', list: true }],
1145
- options: { ...SPACE, out: { ...OPTIONS.out, output: "file", value: "<file>", help: "the joined batch, relative to the project folder", required: true } },
1138
+ options: { ...WRITE, apply: { kind: "flag", help: "write the joined writes to the project knowledge as one revision. Without it, the result only shows them" }, ...LIST },
1146
1139
  notes: "At an address in the owner range of a batch, its name, comment, operand and module win, and its regions come last. One name or one module file at two addresses writes nothing.",
1147
1140
  run: (call) => {
1148
1141
  if (call.subjects.length < 2) throw new UsageError("join needs two or more batch files.");
@@ -1179,9 +1172,10 @@ const JOIN: CommandSpec = {
1179
1172
  const clash = (item: JoinClash) => `${item.what} ${item.value} at ${item.places.map((place) => `${formatC64Address(place.address)} (${place.file})`).join(" and ")}${item.space === DEFAULT_SPACE ? "" : ` in ${item.space}`}`;
1180
1173
  throw new Refusal("conflict", `The batches give one ${joined.clashes.map(clash).join(", one ")}. Nothing was written. Give each name and each module file one address in the batches, then join again.`);
1181
1174
  }
1182
- const out = call.string("out")!;
1183
- const body = { writes: joined.ops.length, repeated: joined.repeated, choices: joined.choices.map(choice), ...writeReported(out, `${JSON.stringify(joined.ops.map(batchJson), null, 1)}\n`, { what: "--out" }) };
1184
- return reply(body, { hint: "Examine each item of choices. Then apply the joined batch.", nextAction: call.next("apply", out) });
1175
+ const shown = { repeated: joined.repeated, choices: joined.choices.map(choice) };
1176
+ if (call.flag("apply")) return { ...withWrite((db) => applied(db, contextOf(call), joined.ops)), ...shown };
1177
+ const body = { writes: listed(joined.ops.map(batchJson), call.count("max-listed")!, (write) => write, MORE), ...shown };
1178
+ return reply(body, { hint: "Examine each item of choices and writes. Then nextAction writes them to the project knowledge as one revision.", nextAction: call.next("join", ...call.subjects, "--apply") });
1185
1179
  },
1186
1180
  };
1187
1181
 
@@ -11,6 +11,8 @@ export interface ListingSource {
11
11
  byteAt: (address: number) => number | undefined;
12
12
  /** The name of an address: a symbol, else a platform name. */
13
13
  nameOf: (address: number) => string | undefined;
14
+ /** The start of the platform entry of more bytes that holds an address outside the image (NMINV for its high byte), or undefined. */
15
+ entryStart?: (address: number) => number | undefined;
14
16
  /** The analyzer names of an address, for reference. */
15
17
  secondNames: (address: number) => string[];
16
18
  /** The knowledge regions, in address order. */
@@ -52,9 +54,22 @@ function accessOf(coverage: Uint8Array | undefined, start: number, length: numbe
52
54
  return text === "" ? "-" : text;
53
55
  }
54
56
 
57
+ /**
58
+ * The name of an operand target, as c64-source writes it: its own name, else
59
+ * name+offset inside a named data region, or inside a platform entry of more bytes.
60
+ */
61
+ function targetName(target: number, source: ListingSource): string | undefined {
62
+ const own = source.nameOf(target);
63
+ if (own !== undefined) return own;
64
+ const region = source.regions.find((row) => target > row.start && target <= row.end && !CODE.has(row.type) && row.type !== "dual-use");
65
+ const start = region?.start ?? source.entryStart?.(target);
66
+ const name = start === undefined ? undefined : source.nameOf(start);
67
+ return name === undefined ? undefined : `${name}+${target - start!}`;
68
+ }
69
+
55
70
  /** The operand value of an instruction as an expression: the name of its target where one exists, else the number. Empty for no operand. */
56
- function operandOf(mode: Mode, address: number, low: number, high: number, nameOf: ListingSource["nameOf"]): string {
57
- const named = (target: number, digits: 2 | 4) => nameOf(target) ?? (digits === 2 ? formatC64Byte(target) : formatC64Address(target));
71
+ function operandOf(mode: Mode, address: number, low: number, high: number, source: ListingSource): string {
72
+ const named = (target: number, digits: 2 | 4) => targetName(target, source) ?? (digits === 2 ? formatC64Byte(target) : formatC64Address(target));
58
73
  if (mode === "imp") return "";
59
74
  if (mode === "imm") return formatC64Byte(low);
60
75
  if (mode === "rel") return named((address + 2 + (low < 0x80 ? low : low - 0x100)) & 0xffff, 4);
@@ -108,7 +123,7 @@ export function listing(source: ListingSource, start: number, end: number): List
108
123
  const bytes = Array.from({ length: length - 1 }, (_, offset) => source.byteAt(address + 1 + offset));
109
124
  if (address + length - 1 <= region.end && bytes.every((value) => value !== undefined)) {
110
125
  // The operand expression of the knowledge in the syntax of the addressing mode, as c64-source writes it.
111
- const operand = source.operand(address) ?? operandOf(opcode.mode, address, bytes[0] ?? 0, bytes[1] ?? 0, source.nameOf);
126
+ const operand = source.operand(address) ?? operandOf(opcode.mode, address, bytes[0] ?? 0, bytes[1] ?? 0, source);
112
127
  if (address >= start) lines.push(line(address, length, instructionWith(byte, operand)));
113
128
  address += length;
114
129
  continue;
@@ -25,7 +25,7 @@ To get the command list, run the script with no arguments.
25
25
  |---|---|
26
26
  | Pack a BASIC program at `$0801` that starts with `SYS` | `pack build/game.prg --out build/game-packed.prg` |
27
27
  | Pack a program that starts at a known address | `pack build/main.prg --entry '$0400' --out build/release.prg` |
28
- | Merge more PRG files into one packed program | `pack build/loader.prg build/main.prg --entry '$0400' --out build/release.prg` |
28
+ | Merge more PRG files into one packed program | `pack build/clean_loader.prg build/clean.prg --entry '$0400' --out build/clean_packed.prg` |
29
29
  | Start the program with RAM in place of the BASIC and KERNAL ROMs | `pack build/game.prg --exit-memory '$35' --out build/game-packed.prg` |
30
30
 
31
31
  ---
@@ -34,7 +34,7 @@ To get the command list, run the script with no arguments.
34
34
  | Save a module of the program as a routine of the library | `routine '$1000' --library ../library` |
35
35
  | Save a range of the program as a routine with a name | `routine '$1000-$1026' --name play --library ../library` |
36
36
  | Find the routines of the library in the program | `match --library ../library` |
37
- | Write the names of the found routines as a batch of changes | `match --library ../library --out .c64-re-tools/local/match.json` |
37
+ | Write the names of the found routines to the project knowledge | `match --library ../library --apply` |
38
38
 
39
39
  ---
40
40
 
@@ -86,7 +86,8 @@ Each flag applies only to the commands in the table. On another command, the scr
86
86
  | `--min-block <n>` | `compare` | With `--align`: the minimum number of bytes in a block, from 8. The default is 16. |
87
87
  | `--frames <n>` | `compare` | Run each release for `n` frames, and give each listed difference its runtime evidence. The default is no run. |
88
88
  | `--steps <file>` | `compare` | With `--frames`: run the action steps of this file before the frames. The default is no steps. |
89
- | `--out <file>` | `separate`, `leftovers`, `match` | `separate` and `leftovers` write all items to this file. `match` writes the batch of changes to this file. The default is no file. |
89
+ | `--out <file>` | `separate`, `leftovers` | Write all items to this file. The default is no file. |
90
+ | `--apply` | `match` | Write the changes to the project knowledge as one revision of the LLM. Without it, `match` writes nothing. |
90
91
  | `--max-listed <n>` | `separate`, `leftovers`, `match` | List at most `n` items of each list. The default is 50. `count` always gives the full number. |
91
92
  | `--min-text <n>` | `leftovers` | The minimum number of characters in a text, from 4. The default is 8. A short text, for example a group name, can need 6. |
92
93
  | `--library <folder>` | `routine`, `match` | Required. The library folder. |
@@ -265,9 +266,9 @@ Finds each routine of the library in the program of the project knowledge.
265
266
  - `library` and `routines`: the library folder and the number of routines in it.
266
267
  - `matches`: each item has `routine`, `start`, `end` and `shift`. `shift` is the address in the program minus the address in the library.
267
268
  - `differing` in each match: each operand that addresses something outside the routine and that is different. It gives the value in the `library` and in the `program`. Examine each one. For example, the program can use other variables or another SID voice.
268
- - `batch`: only with `--out`. `out`, `bytes` and `sha256` give the batch file. `writes` counts its writes. `known` counts the writes that the project knowledge has already. `leftOut` lists the writes that the script left out, and why. `check` lists each comment of the batch that gives an address outside its routine. Each item has `routine`, `address`, `comment` and the `outside` addresses. Such an address can be different in this program. Examine each comment, and correct its text in the batch file if it is necessary.
269
+ - `changes`: with matches. `writes` lists the writes for the project knowledge. `known` counts the writes that the project knowledge has already. `leftOut` lists the writes that the script left out, and why. `check` lists each comment of `writes` that gives an address outside its routine. Each item has `routine`, `address`, `comment` and the `outside` addresses. Such an address can be different in this program. With `--apply`, `revision` gives the revision of the changes.
269
270
 
270
- The batch has the names, regions, comments, references and operand expressions of each routine at its address in the program. The script leaves out a write in these conditions:
271
+ The changes have the names, regions, comments, references and operand expressions of each routine at its address in the program. The script leaves out a write in these conditions:
271
272
 
272
273
  - The program has a user or LLM row at that place.
273
274
  - The program uses the name at another address.
@@ -275,14 +276,14 @@ The batch has the names, regions, comments, references and operand expressions o
275
276
  - The routine occurs more than one time, and the script did not choose this copy.
276
277
  - The script left out the name that an operand expression uses, or the expression does not give the operand in the program.
277
278
 
278
- A routine can occur more than one time. Then the script finds the nearest routines before and after it in the library that occur only one time. The script writes the names at the copy that has the shift of one of these routines. If no copy or more than one copy has such a shift, the script writes no names for the routine. Then `batch.leftOut` gives each copy with the reason `ambiguous`.
279
+ A routine can occur more than one time. Then the script finds the nearest routines before and after it in the library that occur only one time. The script writes the names at the copy that has the shift of one of these routines. If no copy or more than one copy has such a shift, the script writes no names for the routine. Then `changes.leftOut` gives each copy with the reason `ambiguous`.
279
280
 
280
- An address `$xxxx` in a comment moves with the routine when the address is in the routine. An address outside the routine does not move, and `batch.check` gives the comment.
281
+ An address `$xxxx` in a comment moves with the routine when the address is in the routine. An address outside the routine does not move, and `changes.check` gives the comment.
281
282
 
282
283
  `hint` and `nextAction`:
283
284
 
284
- - Without `--out`, with matches: `nextAction` runs `match` with `--out`. Examine `differing` of each match first.
285
- - With `--out`, with writes: `hint` tells you to apply the changes in the batch file to the project knowledge. Read `batch.leftOut` first. When `batch.check` has comments, `hint` tells you to examine them first. Apply the changes as one revision of the LLM.
285
+ - Without `--apply`, with writes: `nextAction` runs `match` with `--apply`. Examine `differing` of each match, `changes.writes` and `changes.leftOut` first.
286
+ - When `changes.check` has comments, `hint` tells you to examine them after the write. Correct each comment that is different in the project knowledge.
286
287
  - No match: `hint` tells that a packed program can hold a routine in a packed form. Unpack the program, put it into the project knowledge, and run `match` again.
287
288
 
288
289
  Traps:
@@ -333,8 +334,8 @@ Traps:
333
334
  1. Put the program into the project knowledge, and name the routine there.
334
335
  2. Run `routine`. Read `leftOut`.
335
336
  3. In another project, put the program into the project knowledge. Run `match`.
336
- 4. Run `match` with `--out`. Read `batch.leftOut` and `batch.check`.
337
- 5. Apply the changes in the batch file to the project knowledge.
337
+ 4. Read `changes.writes` and `changes.leftOut`. Run `match` with `--apply`.
338
+ 5. Examine the comments in `changes.check`. Correct each comment that is different in the project knowledge.
338
339
 
339
340
  ---
340
341
 
@@ -2,7 +2,7 @@
2
2
  // with one <name>.json for each routine, outside every project. A routine holds
3
3
  // its bytes, which of its bytes move with it, and its knowledge at offsets from
4
4
  // its start, so match finds it in another program at another address and
5
- // suggests its names there as an apply batch. Nothing here writes knowledge.
5
+ // suggests its names there as writes of the knowledge. Nothing here writes knowledge.
6
6
 
7
7
  import { createHash } from "node:crypto";
8
8
  import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
@@ -468,7 +468,7 @@ export interface ProgramKnowledge {
468
468
  referenceSuppressed: (reference: { from: number; to: number; kind: ReferenceKind }) => boolean;
469
469
  }
470
470
 
471
- /** One write of an apply batch, in the form of knowledge.ts apply. */
471
+ /** One change of match, as the result shows it: a write of the knowledge with its addresses as $ text. */
472
472
  export type BatchWrite = Record<string, string | number> & { op: string };
473
473
 
474
474
  export interface Skipped {
@@ -478,7 +478,7 @@ export interface Skipped {
478
478
  reason: string;
479
479
  }
480
480
 
481
- /** A comment of the batch that names an address outside its routine: that address can be different in the program. */
481
+ /** A comment of the changes that names an address outside its routine: that address can be different in the program. */
482
482
  export interface Check {
483
483
  routine: string;
484
484
  address: string;
@@ -487,7 +487,7 @@ export interface Check {
487
487
  }
488
488
 
489
489
  export interface Suggestions {
490
- batch: BatchWrite[];
490
+ writes: BatchWrite[];
491
491
  /** Writes that the program already has. */
492
492
  known: number;
493
493
  leftOut: Skipped[];
@@ -554,7 +554,7 @@ function movedComment(text: string, routine: Routine, shift: number): { text: st
554
554
 
555
555
  /**
556
556
  * The names, regions, comments, references and operand expressions of each
557
- * matched routine at its program addresses, as an apply batch. A write that
557
+ * matched routine at its program addresses, as writes of the knowledge. A write that
558
558
  * the program already has is counted as known. A write that would replace a
559
559
  * user or LLM row, take a name that the program uses elsewhere, undo a
560
560
  * removal, or give an operand that is not in the image, is left out with the
@@ -564,12 +564,12 @@ function movedComment(text: string, routine: Routine, shift: number): { text: st
564
564
  * is in `check`.
565
565
  */
566
566
  export function suggest(found: ReadonlyArray<{ routine: Routine; matches: Match[] }>, program: ProgramKnowledge, image: Searched, platform: ReadonlyMap<string, number>): Suggestions {
567
- const batch: BatchWrite[] = [];
567
+ const writes: BatchWrite[] = [];
568
568
  const leftOut: Skipped[] = [];
569
569
  const check: Check[] = [];
570
570
  let known = 0;
571
571
  const show = formatC64Address;
572
- /** The names that are at their place after the batch: written here or known. */
572
+ /** The names that are at their place after the changes: written here or known. */
573
573
  const placed = new Map<string, number>();
574
574
  const symbolsHere = new Map<number, string>();
575
575
  const regionsHere: Array<{ start: number; end: number }> = [];
@@ -591,11 +591,11 @@ export function suggest(found: ReadonlyArray<{ routine: Routine; matches: Match[
591
591
  placed.set(symbol.name, address);
592
592
  } else if (existing !== undefined && semantic(existing)) skip(address, "rename", `the program names it ${existing.name} (${existing.origin})`);
593
593
  else if (elsewhere !== undefined && elsewhere.address !== address) skip(address, "rename", `the program uses the name ${symbol.name} at ${show(elsewhere.address)}`);
594
- else if (placed.has(symbol.name) && placed.get(symbol.name) !== address) skip(address, "rename", `the batch gives the name ${symbol.name} to ${show(placed.get(symbol.name)!)}`);
595
- else if (symbolsHere.has(address)) skip(address, "rename", `the batch names it ${symbolsHere.get(address)}`);
594
+ else if (placed.has(symbol.name) && placed.get(symbol.name) !== address) skip(address, "rename", `the changes give the name ${symbol.name} to ${show(placed.get(symbol.name)!)}`);
595
+ else if (symbolsHere.has(address)) skip(address, "rename", `the changes name it ${symbolsHere.get(address)}`);
596
596
  else if (program.symbolSuppressed(address)) skip(address, "rename", "a removal of a name holds there");
597
597
  else {
598
- batch.push({ op: "rename", address: show(address), name: symbol.name, kind: symbol.kind });
598
+ writes.push({ op: "rename", address: show(address), name: symbol.name, kind: symbol.kind });
599
599
  placed.set(symbol.name, address);
600
600
  symbolsHere.set(address, symbol.name);
601
601
  }
@@ -609,10 +609,10 @@ export function suggest(found: ReadonlyArray<{ routine: Routine; matches: Match[
609
609
  else if (overlapping.some(semantic)) {
610
610
  const other = overlapping.find(semantic)!;
611
611
  skip(start, "classify", `the program has the ${other.type} region ${show(other.start)}-${show(other.end)} (${other.origin})`);
612
- } else if (regionsHere.some((item) => item.start <= end && item.end >= start)) skip(start, "classify", "the batch classifies an overlapping range");
612
+ } else if (regionsHere.some((item) => item.start <= end && item.end >= start)) skip(start, "classify", "the changes classify an overlapping range");
613
613
  else if (program.regionSuppressed(start, end)) skip(start, "classify", "a removal of a region holds there");
614
614
  else {
615
- batch.push({ op: "classify", start: show(start), end: show(end), type: region.type, ...(region.element === undefined ? {} : { element: region.element }) });
615
+ writes.push({ op: "classify", start: show(start), end: show(end), type: region.type, ...(region.element === undefined ? {} : { element: region.element }) });
616
616
  regionsHere.push({ start, end });
617
617
  }
618
618
  }
@@ -624,7 +624,7 @@ export function suggest(found: ReadonlyArray<{ routine: Routine; matches: Match[
624
624
  if (existing?.text === text) known++;
625
625
  else if (existing !== undefined) skip(address, "comment", `the program has a ${comment.placement} comment there (${existing.origin})`);
626
626
  else {
627
- batch.push({ op: "comment", address: show(address), placement: comment.placement, text });
627
+ writes.push({ op: "comment", address: show(address), placement: comment.placement, text });
628
628
  if (outside.length > 0) check.push({ routine: routine.name, address: show(address), comment: text, outside });
629
629
  }
630
630
  }
@@ -633,7 +633,7 @@ export function suggest(found: ReadonlyArray<{ routine: Routine; matches: Match[
633
633
  const wanted = { from: at(reference.from), to: at(reference.to), kind: reference.kind };
634
634
  if (program.referencesFrom(wanted.from).some((item) => item.to === wanted.to && item.kind === wanted.kind)) known++;
635
635
  else if (program.referenceSuppressed(wanted)) skip(wanted.from, "reference", "a removal of this reference holds");
636
- else batch.push({ op: "reference", from: show(wanted.from), to: show(wanted.to), kind: wanted.kind });
636
+ else writes.push({ op: "reference", from: show(wanted.from), to: show(wanted.to), kind: wanted.kind });
637
637
  }
638
638
 
639
639
  const own = new Set(routine.symbols.map((symbol) => symbol.name));
@@ -660,7 +660,7 @@ export function suggest(found: ReadonlyArray<{ routine: Routine; matches: Match[
660
660
  skip(address, "operand", problem);
661
661
  continue;
662
662
  }
663
- batch.push({
663
+ writes.push({
664
664
  op: "operand",
665
665
  address: show(address),
666
666
  select: operand.select,
@@ -670,7 +670,7 @@ export function suggest(found: ReadonlyArray<{ routine: Routine; matches: Match[
670
670
  });
671
671
  }
672
672
  }
673
- return { batch, known, leftOut, check };
673
+ return { writes, known, leftOut, check };
674
674
  }
675
675
 
676
676
  /** Why the expression is not the operand of the instruction at `address` in the image, or undefined when it is. */
@@ -10,7 +10,7 @@
10
10
 
11
11
  import { basename } from "node:path";
12
12
 
13
- import { type AddressRange, c64AddressOf, formatC64Address } from "#src/c64.ts";
13
+ import { type AddressRange, c64AddressOf, formatC64Address, parseC64Address } from "#src/c64.ts";
14
14
  import { Refusal } from "#src/errors.ts";
15
15
  import { parseEntryState, type EntryState } from "#src/host-client/entry-state.ts";
16
16
  import { readImage } from "#src/host-client/image.ts";
@@ -18,8 +18,9 @@ import { readActionSteps, type ActionStep } from "#src/host-client/steps.ts";
18
18
  import { MAX_EXECUTION_COUNT } from "#src/host-client/tools.ts";
19
19
  import { writeReported } from "#src/host-client/transfer.ts";
20
20
  import { ViceSessionClient } from "#src/host-client/vice-session.ts";
21
- import { openForRead } from "#src/knowledge/database.ts";
22
- import { programCoverage, requireProgram } from "#src/knowledge/program.ts";
21
+ import { openForRead, withWrite } from "#src/knowledge/database.ts";
22
+ import { operandImages, programCoverage, requireProgram } from "#src/knowledge/program.ts";
23
+ import { applyBatch, type BatchOperation } from "#src/knowledge/write.ts";
23
24
  import {
24
25
  commentsAt,
25
26
  currentRevision,
@@ -38,13 +39,13 @@ import {
38
39
  symbolNamed,
39
40
  symbolSuppressed,
40
41
  } from "#src/knowledge/read.ts";
41
- import { CODE_REGION_TYPES, SEMANTIC_ORIGINS } from "#src/knowledge/schema.ts";
42
+ import { CODE_REGION_TYPES, DEFAULT_SPACE, SEMANTIC_ORIGINS } from "#src/knowledge/schema.ts";
42
43
  import { platformNames } from "#src/platform.ts";
43
44
  import { projectRoot } from "#src/project.ts";
44
45
  import { knowledgeAt, knowledgeNames } from "#src/knowledge/names.ts";
45
46
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec } from "#src/script.ts";
46
47
  import { align, compareReleases, identicalShare, shiftSuggestion, suggestShifts, type Release } from "./lib/compare.ts";
47
- import { findRoutine, libraryFolder, readLibrary, routineFrom, saveRoutine, suggest } from "./lib/library.ts";
48
+ import { findRoutine, libraryFolder, readLibrary, routineFrom, saveRoutine, suggest, type BatchWrite } from "./lib/library.ts";
48
49
  import { watchRelease, type Start } from "./lib/runtime.ts";
49
50
  import { findLeftovers } from "./lib/leftovers.ts";
50
51
  import { separate, type Root } from "#src/knowledge/separate.ts";
@@ -462,10 +463,14 @@ function routineCommand(call: Call): unknown {
462
463
  }
463
464
  }
464
465
 
465
- /** match: finds the routines of the library in the program of the knowledge, and with --out writes their names there as an apply batch (D71). */
466
+ /**
467
+ * match: finds the routines of the library in the program of the knowledge,
468
+ * and shows the changes that give the program their names. With --apply it
469
+ * writes the changes to the knowledge as one revision.
470
+ */
466
471
  function matchCommand(call: Call): unknown {
467
472
  const library = call.string("library")!;
468
- const out = call.string("out");
473
+ const apply = call.flag("apply");
469
474
  const max = call.count("max-listed")!;
470
475
  const list = <T>(items: T[]) => listed(items, max);
471
476
  const routines = readLibrary(libraryFolder(library, { create: false, cwd: projectRoot() }));
@@ -493,13 +498,7 @@ function matchCommand(call: Call): unknown {
493
498
  const result: Record<string, unknown> = { library, routines: routines.length, matches: list(matches) };
494
499
  const noMatch = "No routine of the library is in the program. A packed program can hold a routine in a packed form. Unpack the program, put the unpacked program into the project knowledge, and run match again.";
495
500
  const withNote = (shown: unknown, hint: string) => [cutNote(shown, undefined), hint].filter((part) => part !== undefined).join(" ");
496
- if (out === undefined) {
497
- if (matches.length === 0) return reply(result, { hint: noMatch });
498
- return reply(result, {
499
- hint: withNote(result, "Examine differing of each match. Then nextAction writes the names of the found routines as a batch of changes."),
500
- nextAction: call.next("match", "--library", library, "--out", ".c64-re-tools/local/match.json"),
501
- });
502
- }
501
+ if (matches.length === 0) return reply(result, { hint: noMatch });
503
502
  const db = openForRead();
504
503
  let suggestions: ReturnType<typeof suggest>;
505
504
  try {
@@ -522,14 +521,25 @@ function matchCommand(call: Call): unknown {
522
521
  } finally {
523
522
  db?.close();
524
523
  }
525
- const { batch, known, leftOut, check } = suggestions;
526
- const written = writeReported(out, batch.length === 0 ? "[]\n" : `[\n${batch.map((write) => ` ${JSON.stringify(write)}`).join(",\n")}\n]\n`, { what: "--out" });
527
- const body = { ...result, batch: { ...written, writes: batch.length, known, leftOut: list(leftOut), check: list(check) } };
528
- // The batch is applied by the knowledge, not by this script: the hint gives the task, not a command.
529
- if (matches.length === 0) return reply(body, { hint: noMatch });
530
- if (batch.length === 0) return reply(body, { hint: withNote(body, "The batch has no writes. The project knowledge has the names of the found routines already, or batch.leftOut tells why the script left out a write.") });
531
- const review = check.length === 0 ? "" : " First examine batch.check: each comment there gives an address outside its routine, which can be different in this program. Correct the comment text in the batch file when it is different.";
532
- return reply(body, { hint: withNote(body, `Apply the changes in ${out} to the project knowledge.${review}`) });
524
+ const { writes, known, leftOut, check } = suggestions;
525
+ const changes: Record<string, unknown> = { writes: list(writes), known, leftOut: list(leftOut), check: list(check) };
526
+ const body = { ...result, changes };
527
+ if (writes.length === 0) return reply(body, { hint: withNote(body, "There are no changes. The project knowledge has the names of the found routines already, or changes.leftOut tells why the script left out a write.") });
528
+ const review = check.length === 0 ? "" : " Then examine changes.check: each comment there gives an address outside its routine, which can be different in this program. Correct such a comment in the project knowledge.";
529
+ if (!apply) {
530
+ return reply(body, { hint: withNote(body, `Examine differing of each match, and changes.writes and changes.leftOut. Then nextAction writes the changes to the project knowledge.${review}`), nextAction: call.next("match", "--library", library, "--apply") });
531
+ }
532
+ const platformNamed = new Map(platformNames().map((entry) => [entry.name, entry.address]));
533
+ const applied = withWrite((write) => applyBatch(write, { origin: "llm", description: `Names of the routines of the library ${library}`, image: operandImages(write, platformNamed) }, writes.map(toOperation)));
534
+ changes.revision = applied.revision;
535
+ return reply(body, { hint: withNote(body, `The project knowledge has the changes in revision ${applied.revision}.${review}`) });
536
+ }
537
+
538
+ /** A change of match as a write of the knowledge: its addresses as numbers, in the C64 space. */
539
+ function toOperation(write: BatchWrite): BatchOperation {
540
+ const parsed: Record<string, unknown> = { ...write, space: DEFAULT_SPACE };
541
+ for (const key of ["address", "start", "end", "from", "to"]) if (typeof write[key] === "string") parsed[key] = parseC64Address(write[key]);
542
+ return parsed as unknown as BatchOperation;
533
543
  }
534
544
 
535
545
  const LIBRARY = { kind: "text", value: "<folder>", required: true, help: "the library: a plain folder of routine files beside the projects, relative to the project folder, for example ../library" } as const;
@@ -589,7 +599,7 @@ const COMMANDS: CommandSpec[] = [
589
599
  summary: "Finds each routine of the library in the program of the knowledge: the opcodes and other fixed bytes equal, and the addresses into the routine moved by one shift.",
590
600
  options: {
591
601
  library: { ...LIBRARY, help: "the library folder, relative to the project folder, for example ../library" },
592
- out: { ...OPTIONS.out, output: "file", value: "<file>", help: "write the names of the routines at the found addresses as a batch of changes for the project knowledge" },
602
+ apply: { kind: "flag", help: "write the changes to the project knowledge as one revision of the LLM. Without it, the result only shows the changes" },
593
603
  "max-listed": OPTIONS["max-listed"],
594
604
  },
595
605
  run: matchCommand,