@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
@@ -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 }),
@@ -361,23 +359,9 @@ function imageRequest(path: string, space: string): ImageRequest {
361
359
  return request;
362
360
  }
363
361
 
364
- /**
365
- * The program of each space in the knowledge that operand, patch and macro
366
- * use writes in that space are checked against, with the platform names. A
367
- * byte outside the segments of the program is not in it. Each program is
368
- * read once, when a write in its space needs it.
369
- */
362
+ /** The programs that operand, patch and macro use writes are checked against, with the platform names. */
370
363
  function operandImages(db: DatabaseSync): (space: string) => OperandImage {
371
- const images = new Map<string, OperandImage>();
372
- return (space) => {
373
- const known = images.get(space);
374
- if (known !== undefined) return known;
375
- const image = requireProgram(db, space);
376
- const inside = (at: number) => image.segments.some((segment) => at >= segment.start && at <= segment.end);
377
- const made: OperandImage = { byteAt: (at) => (inside(at) ? image.byteAt(at) : undefined), platform: new Map(platformNames().map((entry) => [entry.name, entry.address])) };
378
- images.set(space, made);
379
- return made;
380
- };
364
+ return programImages(db, new Map(platformNames().map((entry) => [entry.name, entry.address])));
381
365
  }
382
366
 
383
367
  /** An offset: a whole number in decimal or $ hex, with an optional minus sign. */
@@ -905,27 +889,23 @@ const WRITE_COMMANDS: CommandSpec[] = [
905
889
  writeCommand(
906
890
  {
907
891
  name: "release",
908
- 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.",
892
+ 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.",
909
893
  subjects: [{ name: "<label>", help: "the release label, for example ORIGINAL or FIRESTAR" }],
910
894
  options: {
911
- file: { kind: "path", value: "<file>", help: "the PRG or image.json of the release, in a folder that git keeps", required: true },
895
+ 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 },
912
896
  base: { kind: "flag", help: "this release is the program of the knowledge: its segments and bytes must be the same" },
913
897
  comment: { kind: "text", value: "<text>", help: "what the release is, for example the group and the date" },
914
898
  },
915
- 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.",
899
+ 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.",
916
900
  },
917
901
  (call) => {
918
902
  const context = contextOf(call);
919
903
  const file = knowledgePath(call.string("file")!, "--file");
920
- const root = projectRoot();
921
- if (isInside(join(root, PROJECT_DIRECTORY, LOCAL_DIRECTORY), resolveProjectPath(file, root))) {
922
- 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/.`);
923
- }
924
904
  const image = readImage(file);
925
- const sha256 = createHash("sha256").update(readProjectFile(file).bytes).digest("hex");
926
905
  const commentText = call.string("comment");
927
906
  const base = call.flag("base");
928
- const request = { space: call.space, label: call.subject(0), file, sha256, ...(base ? { base } : {}), ...(commentText === undefined ? {} : { comment: commentText }) };
907
+ // The base release has no bytes of its own: its bytes are the program.
908
+ const request = { space: call.space, label: call.subject(0), ...(base ? { base } : { rows: memoryRows(image.segments, image.byteAt) }), ...(commentText === undefined ? {} : { comment: commentText }) };
929
909
  return (db) => {
930
910
  if (base) {
931
911
  const program = requireProgram(db, call.space);
@@ -935,7 +915,8 @@ const WRITE_COMMANDS: CommandSpec[] = [
935
915
  });
936
916
  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.`);
937
917
  }
938
- return shown(setRelease(db, context, request), "release", release);
918
+ const bytes = image.segments.reduce((sum, segment) => sum + segment.end - segment.start + 1, 0);
919
+ return { ...shown(setRelease(db, context, request), "release", release), bytes };
939
920
  };
940
921
  },
941
922
  ),
@@ -1134,22 +1115,25 @@ const WRITE_COMMANDS: CommandSpec[] = [
1134
1115
  }
1135
1116
  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"}].`);
1136
1117
  const operations = parsed.map((item, index) => batchOperation(call, item, `write ${index + 1}`));
1137
- return (db) => {
1138
- const applied = applyBatch(db, { ...context, image: operandImages(db) }, operations);
1139
- // replaced: each write that replaced a row of another origin, with that row as previous gives it for one write.
1140
- const replaced = applied.steps.flatMap((step, index) => (step.previous === undefined ? [] : [{ write: index + 1, op: operations[index]!.op, previous: shownPrevious(step.previous) }]));
1141
- return { revision: applied.revision, writes: applied.steps.length, replaced };
1142
- };
1118
+ return (db) => applied(db, context, operations);
1143
1119
  },
1144
1120
  ),
1145
1121
  ];
1146
1122
 
1147
- /** join: the batches of agents that worked in parallel, as one batch for apply. It writes no knowledge. */
1123
+ /** 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. */
1124
+ function applied(db: DatabaseSync, context: WriteContext, operations: BatchOperation[]) {
1125
+ const result = applyBatch(db, { ...context, image: operandImages(db) }, operations);
1126
+ // replaced: each write that replaced a row of another origin, with that row as previous gives it for one write.
1127
+ const replaced = result.steps.flatMap((step, index) => (step.previous === undefined ? [] : [{ write: index + 1, op: operations[index]!.op, previous: shownPrevious(step.previous) }]));
1128
+ return { revision: result.revision, writes: result.steps.length, replaced };
1129
+ }
1130
+
1131
+ /** join: the batches of agents that worked in parallel, as one list of writes. With --apply, it writes them as one revision. */
1148
1132
  const JOIN: CommandSpec = {
1149
1133
  name: "join",
1150
- summary: "Joins the batches of agents that worked in parallel into one batch for apply. It writes no knowledge.",
1134
+ 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.",
1151
1135
  subjects: [{ name: "<batch>", help: 'a batch: a list of writes, or {"owner": {"start": "$1000", "end": "$1fff"}, "ops": [...]}', list: true }],
1152
- options: { ...SPACE, out: { ...OPTIONS.out, output: "file", value: "<file>", help: "the joined batch, relative to the project folder", required: true } },
1136
+ 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 },
1153
1137
  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.",
1154
1138
  run: (call) => {
1155
1139
  if (call.subjects.length < 2) throw new UsageError("join needs two or more batch files.");
@@ -1186,9 +1170,10 @@ const JOIN: CommandSpec = {
1186
1170
  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}`}`;
1187
1171
  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.`);
1188
1172
  }
1189
- const out = call.string("out")!;
1190
- 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" }) };
1191
- return reply(body, { hint: "Examine each item of choices. Then apply the joined batch.", nextAction: call.next("apply", out) });
1173
+ const shown = { repeated: joined.repeated, choices: joined.choices.map(choice) };
1174
+ if (call.flag("apply")) return { ...withWrite((db) => applied(db, contextOf(call), joined.ops)), ...shown };
1175
+ const body = { writes: listed(joined.ops.map(batchJson), call.count("max-listed")!, (write) => write, MORE), ...shown };
1176
+ 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") });
1192
1177
  },
1193
1178
  };
1194
1179
 
@@ -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,
@@ -27,7 +27,7 @@ Do the specialist work of each task as that task tells. Do not do it in another
27
27
  - One repository can hold several programs, with one project folder for each program. Work on one project at a time.
28
28
  - Write all files in the project folder. Do not write files at the root of the repository.
29
29
  - A subagent can have no emulator tools. Give it its experiments as test run files. Many test runs can go at the same time. The emulator tools are for the main session only.
30
- - To name a large program with more agents at the same time, give each agent one range of addresses. Each agent writes a batch of knowledge changes with its owner range. Then join the batches of the agents, and apply the joined batch to the project knowledge one time.
30
+ - To name a large program with more agents at the same time, give each agent one range of addresses. Each agent writes a batch of knowledge changes with its owner range. Then join the batches of the agents, and write them to the project knowledge as one revision.
31
31
  - Do not write a build script or a merge script. The generation of the source writes and assembles the loader. The project knowledge joins the batches.
32
32
  - Do not write a script that makes a deliverable again, for example a capture, copy or replay script. Commit the deliverable.
33
33
 
@@ -91,8 +91,8 @@ Do the stages in this sequence. Go to the next stage only when its exit check is
91
91
  | 4. Unpack | Examine the program for a packer. Trace it and find its stages. Capture a packed program into `.c64-re-tools/local/`. When a segment is the data of a cracktro and the program does not read it, capture again and exclude that range. Put the capture, or the PRG of a program without a packer, into the project knowledge. | The program in the project knowledge has the segments and the entry. |
92
92
  | 5. Run | First, record. Ask the user to play each part that the scope names, in a recording session. Tell the user which parts. Record a part yourself only when the sessions of the user do not have it. Put the recordings in `tests/recordings/`. Then run the parts that a recording cannot have, in the emulator or as test runs. Write a coverage map for each part into `.c64-re-tools/local/`. Add the maps and the `coverage.bin` of each recording to the project knowledge. | The program in the project knowledge has a coverage map for each part that the scope names. |
93
93
  | 6. Analyze | Analyze the program statically. The analysis reads the program and the coverage from the project knowledge. | No coverage conflict is open. |
94
- | 7. Name | If the workspace has a routine library, match the program against it. Apply the matches to the project knowledge. Then name each routine in the scope and give it a comment. Find the platform addresses in the memory map of the C64. Record the modules. When the scope has hundreds of routines, ask the user which routines to name. The source gives the other routines an `l_xxxx` label. | Each routine that the user selected has a name and a comment. |
95
- | 8. Releases and switches | For a capture, copy its folder to `original/<label>/` first, because git ignores `.c64-re-tools/local/`. Record the original file as the base release in the project knowledge. Record each other release. Compare the releases. Find the leftovers. Record a switch for each copy protection, trainer, cheat, crack change and correction. Record a patch for each range of a switch. Record each leftover as a region with a comment. | The project knowledge lists each switch. Each difference between the releases is in a patch, or the answer gives it as an exception. |
94
+ | 7. Name | If the workspace has a routine library, match the program against it. Write the names of the matches to the project knowledge. Then name each routine in the scope and give it a comment. Find the platform addresses in the memory map of the C64. Record the modules. Put the modules of one part of the program in one folder, for example `music/`, `irq/` or `graphics/`. When the scope has hundreds of routines, ask the user which routines to name. The source gives the other routines an `l_xxxx` label. | Each routine that the user selected has a name and a comment. |
95
+ | 8. Releases and switches | Record the original file, or the capture of it, as the base release in the project knowledge. The project knowledge keeps the bytes of each release. Record each other release. Compare the releases. Find the leftovers. Record a switch for each copy protection, trainer, cheat, crack change and correction. Record a patch for each range of a switch. Record each leftover as a region with a comment. | The project knowledge lists each switch. Each difference between the releases is in a patch, or the answer gives it as an exception. |
96
96
  | 9. Generate | Generate the source from the project knowledge into `src`. For an unpacked program, also generate the loader. | The result of the generation is PASS. Each release with the result `layout differs` is a version with a project of its own, or an exception in the answer. See "Versions of one program". |
97
97
  | 10. Build and test | Build the base release into `build/`, and compare it with the original. Build the default build. Run the test scenarios in `tests/`. Replay each recording on the rebuild. For each replay, give the checkpoint routine, the state and the random state with the names of stage 7. | The criteria of stage 1 are true. |
98
98
  | 11. Document | When the criteria ask for documentation, generate it into `README.md` and `docs/`. For versions in a group folder, also write the shared pages of the group folder. Then link the pages. | The link check of the documentation gives PASS. |
@@ -105,7 +105,7 @@ After stage 7, save each routine that other programs can have to the routine lib
105
105
  ### Deliverables of a full rebuild
106
106
 
107
107
  - `.c64-re-tools/knowledge/` with the program, its entry state, the coverage, the names, the regions, the comments, the modules, the releases, the switches and the patches
108
- - the file of each release in `original/`
108
+ - the files of the program in `original/`, as the user gave them
109
109
  - the generated source
110
110
  - the built program and the loader
111
111
  - the test scenarios
@@ -121,7 +121,7 @@ All other files that you made are not deliverables. Keep them in `.c64-re-tools/
121
121
  Give the user a short answer at the end. Do not write a report file. Write a report file only when the user asks for it. The knowledge, `docs/` and the scenarios keep the durable results. The answer has:
122
122
 
123
123
  1. Each criterion of stage 1 and its result, and each exception that the user accepted.
124
- 2. The count of the code ranges that no run executed. The ranges are in `not_executed.json` in the folder of the generated source.
124
+ 2. The count of the code ranges that no run executed. The ranges are in `.c64-re-tools/local/generated/src/not_executed.json` for the source in `src/`.
125
125
  3. The switches: the name, the kind and the default of each, and the releases that have it on. Also a copy protection that a crack removed and that no release has.
126
126
  4. Open questions: what the evidence does not explain.
127
127
 
@@ -142,7 +142,7 @@ tools/ scripts for the formats of this program only
142
142
  README.md the entry page of the documentation
143
143
  ```
144
144
 
145
- Commit each folder of the layout other than `build/`, and `.c64-re-tools/knowledge/`. The knowledge holds the program, the entry state and the coverage, so the project needs no other folder for them. Put all other files that you make in `.c64-re-tools/local/`, also the captures and the coverage maps after you put them into the knowledge. Do not let git ignore a folder of the layout other than `build/`. Do not change the `.gitignore` files of the project.
145
+ Commit each folder of the layout other than `build/`, and `.c64-re-tools/knowledge/`. The knowledge holds the program, the entry state, the bytes of each release and the coverage, so the project needs no other folder for them. Put all other files that you make in `.c64-re-tools/local/`, also the captures and the coverage maps after you put them into the knowledge. Do not let git ignore a folder of the layout other than `build/`. Do not change the `.gitignore` files of the project.
146
146
 
147
147
  If the project has a layout, use that layout.
148
148