@henols/c64-re-tools 2.3.0-rc.1 → 2.3.0-rc.3

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 (34) hide show
  1. package/package.json +2 -3
  2. package/skills/c64-assembler/SKILL.md +4 -6
  3. package/skills/c64-basic/SKILL.md +2 -4
  4. package/skills/c64-development/SKILL.md +3 -3
  5. package/skills/c64-disk/SKILL.md +3 -7
  6. package/skills/c64-docs/SKILL.md +2 -4
  7. package/skills/c64-export/SKILL.md +4 -4
  8. package/skills/c64-knowledge/SKILL.md +3 -3
  9. package/skills/c64-memory-map/SKILL.md +1 -3
  10. package/skills/c64-packer/SKILL.md +9 -11
  11. package/skills/c64-packer/scripts/packer.ts +2 -20
  12. package/skills/c64-provenance/SKILL.md +18 -7
  13. package/skills/c64-provenance/scripts/lib/compare.ts +144 -16
  14. package/skills/c64-provenance/scripts/provenance.ts +37 -8
  15. package/skills/c64-reverse-engineering/SKILL.md +3 -3
  16. package/skills/c64-source/SKILL.md +37 -18
  17. package/skills/c64-source/scripts/lib/loader.ts +281 -43
  18. package/skills/c64-source/scripts/source.ts +37 -9
  19. package/skills/c64-static-analysis/SKILL.md +4 -4
  20. package/skills/c64-testing/SKILL.md +13 -13
  21. package/skills/c64-testing/references/recording-format.md +1 -1
  22. package/skills/c64-testing/references/scenario-format.md +3 -3
  23. package/skills/c64-testing/scripts/lib/play.ts +4 -4
  24. package/skills/c64-testing/scripts/testing.ts +1 -1
  25. package/skills/c64-unpacker/SKILL.md +12 -12
  26. package/skills/c64-unpacker/scripts/lib/loads.ts +17 -4
  27. package/skills/c64-unpacker/scripts/unpacker.ts +15 -3
  28. package/skills/emulator/SKILL.md +3 -3
  29. package/src/cli/cleanup.ts +30 -0
  30. package/src/cli/main.ts +5 -1
  31. package/src/compare.ts +18 -0
  32. package/src/host-client/coverage.ts +26 -0
  33. package/src/mcp/tools/machine.ts +2 -2
  34. package/README.md +0 -143
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henols/c64-re-tools",
3
- "version": "2.3.0-rc.1",
3
+ "version": "2.3.0-rc.3",
4
4
  "description": "Agent-friendly Commodore 64 engineering toolkit for reverse engineering, debugging, development and testing.",
5
5
  "license": "MIT",
6
6
  "author": "Henrik Olsson",
@@ -26,8 +26,7 @@
26
26
  "tools/",
27
27
  "distribution/package.ts",
28
28
  "distribution/plugin.ts",
29
- "LICENSE",
30
- "README.md"
29
+ "LICENSE"
31
30
  ],
32
31
  "engines": {
33
32
  "node": ">=24.0.0"
@@ -18,9 +18,7 @@ This skill does not run the program and does not change project knowledge.
18
18
  - The output path: where to write the PRG, relative to the project folder.
19
19
  - Optional include directories, symbol definitions and a start address.
20
20
 
21
- ## Tools / execution path
22
-
23
- The script runs ACME on this machine. It copies the source root to a temporary directory, assembles it there and writes the program into the project. The host runtime is not necessary.
21
+ ## Tools
24
22
 
25
23
  ```
26
24
  node <skill>/scripts/assembler.ts build src main.a --out build/game.prg
@@ -38,7 +36,7 @@ node <skill>/scripts/assembler.ts build src main.a --out build/game.prg
38
36
  | `--max-listed 200` | Show at most 200 symbols in the result. The default is 50. `symbols.count` gives the count of all symbols. |
39
37
  | `--out-symbols build/game.json` | Write the symbols to this file as `{"symbols": [...]}`. Without `--all-symbols`, the file does not have the constants that the source does not use. Give this file to the c64-testing skill as the symbols of the rebuild. |
40
38
 
41
- The script copies the full source root. Put all files that the program includes under it. Version control directories stay out.
39
+ Put all files that the program includes under the source root.
42
40
 
43
41
  The target CPU is the 6510. The output is a C64 PRG, or the bytes only with `--plain`.
44
42
 
@@ -103,7 +101,7 @@ With `--compare`, `compare` gives `identical` and `segments`: one check for each
103
101
 
104
102
  - `FAIL` with `assembled: false`: the source has errors. Correct the source.
105
103
  - `FAIL` with `assembled: true`: the build is not identical to the program in the knowledge. Read `compare.segments`.
106
- - `installation-incomplete`, or `machine-unavailable` with a message that the host runtime does not run: stop the task. Give the message to the user and wait for the user. The message gives the remedy. Do not make a replacement for the tool or the host runtime, for example your own disk parser, disassembler or emulator script.
104
+ - `installation-incomplete` or `machine-unavailable`: stop the task. Give the message to the user and wait for the user. Do not install, start or change a tool yourself. Do not make a replacement for the tool, for example your own disk parser, disassembler or emulator script.
107
105
  - `invalid-input`: an option or a path is wrong. Read the message and correct the call.
108
106
  - `not-found`: the source root has no main source file with that name, or no folder with files for an `--include`. Give a path relative to the source root.
109
107
 
@@ -112,4 +110,4 @@ With `--compare`, `compare` gives `identical` and `segments`: one check for each
112
110
  - Run or debug the program → emulator
113
111
  - Compare the rebuild with the original → c64-testing
114
112
  - Pack the program into one small PRG that unpacks itself → c64-packer
115
- - Write a new program, or add a feature or a fix → c64-development
113
+ - Write a new program, or add a feature or a correction → c64-development
@@ -15,9 +15,7 @@ This skill does not run the program and does not change project knowledge.
15
15
 
16
16
  - The program: a PRG file, relative to the project folder.
17
17
 
18
- ## Tools / execution path
19
-
20
- The script sends the program to the host runtime. The host decodes it with petcat and finds the handoffs.
18
+ ## Tools
21
19
 
22
20
  ```
23
21
  node <skill>/scripts/basic.ts list extracted/game.prg
@@ -74,7 +72,7 @@ The listing and the handoff addresses.
74
72
 
75
73
  - `invalid-input` with "is no BASIC program": the file is not a BASIC program. Usually the file is machine code. Give it to the c64-static-analysis skill. A memory dump also gives this error: its first two bytes are not a load address, and its bytes go past `$ffff`.
76
74
  - An empty `handoffs` list: the BASIC does not start machine code with SYS or USR. Do not make up a handoff. Look for a POKE into a vector or a LOAD of another file in the listing.
77
- - `installation-incomplete`, or `machine-unavailable` with a message that the host runtime does not run: stop the task. Give the message to the user and wait for the user. The message gives the remedy. Do not make a replacement for the tool or the host runtime, for example your own disk parser, disassembler or emulator script.
75
+ - `installation-incomplete` or `machine-unavailable`: stop the task. Give the message to the user and wait for the user. Do not install, start or change a tool yourself. Do not make a replacement for the tool, for example your own disk parser, disassembler or emulator script.
78
76
  - `not-found` or another `invalid-input`: the path or an argument is wrong. Read the message and correct the call.
79
77
 
80
78
  ## Handoffs
@@ -17,9 +17,9 @@ This skill does not do the specialist work itself.
17
17
  - The acceptance checks: what the user must see or what memory must hold when the work is complete.
18
18
  - The project: its source, its tests and its knowledge.
19
19
 
20
- ## Tools / execution path
20
+ ## Tools
21
21
 
22
- This skill uses the other skills. It does not use the host runtime or the emulator directly.
22
+ This skill uses the other skills. It does not use the emulator tools directly.
23
23
 
24
24
  | Work | Skill |
25
25
  |---|---|
@@ -159,7 +159,7 @@ A program that builds, with a run file in `tests/` for each acceptance check, an
159
159
 
160
160
  ## Failure and conflicts
161
161
 
162
- - A skill reports `installation-incomplete`, or `machine-unavailable` with a message that the host runtime does not run: stop the whole task. Give the message to the user and wait for the user. Do not continue with other skills. Do not make a replacement for the tool or the host runtime, for example your own assembler or emulator script.
162
+ - A skill reports `installation-incomplete` or `machine-unavailable`: stop the whole task. Give the message to the user and wait for the user. Do not continue with other skills. Do not install, start or change a tool yourself. Do not make a replacement for the tool, for example your own assembler or emulator script.
163
163
  - A tool gives a wrong result: tell the user the defect and the evidence, and wait for the user. Do not make a workaround.
164
164
  - A test gives FAIL: change the program until the test gives PASS. Do not change the expected value to make the test pass. Change an expected value only when the user changes the acceptance check.
165
165
  - A run gives FAIL because a `runUntil` did not get to its target: the program did not get to that state. Find why with the emulator skill.
@@ -18,9 +18,7 @@ This skill does not change the disk image and does not change project knowledge.
18
18
  - To extract a file: the output path, relative to the project folder.
19
19
  - A T64 tape file or a CRT cartridge file, relative to the project folder.
20
20
 
21
- ## Tools / execution path
22
-
23
- The script sends a disk image to the host runtime. The host runs c1541 and sends the result back. The script writes an extracted file into the project. It reads T64 and CRT files itself.
21
+ ## Tools
24
22
 
25
23
  ```
26
24
  node <skill>/scripts/disk.ts <command> <image> [name] [--out <file>]
@@ -82,8 +80,6 @@ A downstream skill records the meaning of the extracted content.
82
80
 
83
81
  ## Tapes and cartridges
84
82
 
85
- The script reads T64 and CRT files itself. The host runtime is not necessary for them.
86
-
87
83
  - T64: `directory` and `read`. Many T64 files have a wrong end address. Then the entry has `fixedSize: true`, and the size comes from the position of the next file.
88
84
  - CRT: `directory` and `crt`. The script reads hardware types 0 (normal 8K, 16K or Ultimax), 5 (Ocean), 19 (Magic Desk) and 32 (EasyFlash). It refuses other types by name. `crt` writes `crt.json` and one PRG for each CHIP packet, for example `bank3-8000.prg`.
89
85
  - A cartridge bank uses the same addresses as other banks. Analyze each bank PRG with c64-static-analysis and `--space bank3`, and record its knowledge in space `bank3`.
@@ -99,8 +95,8 @@ The directory, the BAM, an entry or a sector chain as JSON.
99
95
 
100
96
  - `not-found`: the image file is missing, or the image has no file with that name. Read the directory again and compare the names.
101
97
  - `media-error`: the image, the T64 file or the CRT file has a defect, or its content is not of its type. A CRT with a hardware type that the script does not read also gives `media-error`. The message tells the problem, for example a sector chain that loops. Tell the user. Do not change the file.
102
- - `installation-incomplete`, or `machine-unavailable` with a message that the host runtime does not run: stop the task. Give the message to the user and wait for the user. The message gives the remedy. Do not make a replacement for the tool or the host runtime, for example your own disk parser, disassembler or emulator script.
103
- - `invalid-input`: an argument or a path is wrong. A file with an extension that the command does not take is also wrong. The message gives each type that the command takes. Read the message and correct the call.
98
+ - `installation-incomplete` or `machine-unavailable`: stop the task. Give the message to the user and wait for the user. Do not install, start or change a tool yourself. Do not make a replacement for the tool, for example your own disk parser, disassembler or emulator script.
99
+ - `invalid-input`: an argument or a path is wrong. A file with an extension that the command does not take is also wrong. The message gives each type that the command takes. Read the message and change the call.
104
100
 
105
101
  A file that is not `closed` was not written fully. Its data can be incomplete.
106
102
 
@@ -22,9 +22,7 @@ This skill does not change the knowledge.
22
22
  - The program in the knowledge. Put it in with `image` of the c64-knowledge skill. The reference decodes the tables and shows the graphics from it.
23
23
  - The entry page `README.md` and the directory of the other pages, for example `docs`. The reference goes into a directory of its own, for example `docs/reference`.
24
24
 
25
- ## Tools / execution path
26
-
27
- The script runs on this machine. It does not use the emulator or the host runtime.
25
+ ## Tools
28
26
 
29
27
  ```
30
28
  node <skill>/scripts/docs.ts generate src --out docs/reference
@@ -107,7 +105,7 @@ node <skill>/scripts/docs.ts link README.md docs --source src --check
107
105
 
108
106
  - The reference draws each sprite, bitmap and charset region, and it decodes each table. To get the image of a graphic or the entries of a table, classify its region with c64-knowledge. Do not write a script that draws or decodes them.
109
107
  - A script of the project decodes only a format of the program, for example a packed map or a music stream. Put the script in `tools/` of the project. Its output files are the assets, for example in `assets/rooms/`.
110
- - When the code of the program makes the data, run that code in VICE with a run of c64-testing. Observe the memory, or capture the screen. Do not write a 6502 emulator in the script.
108
+ - When the code of the program makes the data, run that code with a run of c64-testing. Observe the memory, or capture the screen. Do not write a 6502 emulator in the script.
111
109
 
112
110
  In the call graph, a solid arrow is a call, a thick arrow is a table entry, and a dotted arrow is a jump. A table entry goes from each routine that reads the table to each target in code. A table of data addresses gives no arrow.
113
111
 
@@ -17,9 +17,9 @@ This skill does not change the rebuilt project or its knowledge.
17
17
  - The folder of the new project. It must be new or empty, and no project can hold it. Use a folder beside the project, for example `../game-new`.
18
18
  - Optional: the coverage of the runs in the knowledge. Without coverage, nothing becomes free by itself.
19
19
 
20
- ## Tools / execution path
20
+ ## Tools
21
21
 
22
- This skill uses the other skills. It does not use the host runtime directly.
22
+ This skill uses the other skills.
23
23
 
24
24
  | Work | Skill |
25
25
  |---|---|
@@ -75,7 +75,7 @@ A new project folder and a zip file of it. Its build is identical to its baselin
75
75
  - `export` gives FAIL with `stage`: read `reason`. The c64-source skill tells what to do for each stage.
76
76
  - `export` refuses the folder: give a new or empty folder outside every project. Remove a folder or a zip file of an earlier export only when this task made it.
77
77
  - A test of the new project gives FAIL: the export dropped a range that the program uses. Remove the folder and the zip file. Run `export` again with `--keep` for the range, then test again.
78
- - A skill reports `installation-incomplete`, or `machine-unavailable` with a message that the host runtime does not run: stop the whole task. Give the message to the user and wait for the user. Do not make a replacement for the tool or the host runtime.
78
+ - A skill reports `installation-incomplete` or `machine-unavailable`: stop the whole task. Give the message to the user and wait for the user. Do not continue with other skills. Do not install, start or change a tool yourself. Do not make a replacement for the tool.
79
79
 
80
80
  ## Handoffs
81
81
 
@@ -84,4 +84,4 @@ A new project folder and a zip file of it. Its build is identical to its baselin
84
84
  - Switches and the code at an address → c64-knowledge
85
85
  - The build of the new project → c64-assembler
86
86
  - The tests of the new project → c64-testing
87
- - A new feature or a fix in the new project → c64-development
87
+ - A new feature or a correction in the new project → c64-development
@@ -7,7 +7,7 @@ description: Use this skill to read, write, correct and review the durable knowl
7
7
 
8
8
  ## Purpose
9
9
 
10
- Read, write, correct and review the durable understanding of a C64 project. The knowledge also holds the program: its bytes, its entry state and the stages of its unpacker. It holds the coverage of the runs too. The other skills read the program and the coverage from the knowledge. The knowledge is text in `.c64-re-tools/knowledge/` in the project folder: one JSON line for each row. Commit that folder with git. The script keeps an index of the text in `.c64-re-tools/local/knowledge.db` and makes the index again when the text changes. Do not commit the index.
10
+ Read, write, correct and review the durable understanding of a C64 project. The knowledge also holds the program: its bytes, its entry state and the stages of its unpacker. It holds the coverage of the runs too. The other skills read the program and the coverage from the knowledge. The knowledge is text in `.c64-re-tools/knowledge/` in the project folder: one JSON line for each row. Commit that folder with git. The index of the text is `.c64-re-tools/local/knowledge.db`. Do not commit the index.
11
11
 
12
12
  This skill is the only write path for conclusions of the user and the LLM. It does not run an emulator or an analyzer. Write the knowledge only with the script. The script checks each write. Do not write or edit the files in `.c64-re-tools/knowledge/` or the index yourself.
13
13
 
@@ -21,7 +21,7 @@ One of these:
21
21
  - a capture of the c64-unpacker skill, a PRG, or coverage maps to put into the knowledge
22
22
  - a request to see the history or a revision.
23
23
 
24
- ## Tools / execution path
24
+ ## Tools
25
25
 
26
26
  ```
27
27
  node <skill>/scripts/knowledge.ts <command> [subjects] [options]
@@ -223,7 +223,7 @@ Give one selector:
223
223
  | `--value <symbol>` | The symbol plus the offset | `lda bar_colours-1,x` |
224
224
  | `--expr <text>` | ACME expression text with names and numbers | `lda #(sprite_bank + 5*64) / 64` |
225
225
 
226
- - The address is the start of an instruction in a code region. The script decodes the instructions from the start of the region, as `listing` does. It refuses an address in no code region and an operand byte of an instruction. Classify the code first.
226
+ - The address is the start of an instruction in a code region, as `listing` shows it. The script refuses an address in no code region and an operand byte of an instruction. Classify the code first.
227
227
  - `--offset` adds a whole number to the symbol. Write a negative offset as `--offset=-1`.
228
228
  - A name is a symbol of the knowledge or a platform name of the c64-memory-map skill.
229
229
  - `--expr` takes `$`, `%` and decimal numbers, names, brackets, the operators `+ - * / % << >> >>> & | XOR`, and `<`, `>`, `-` and `!` before an operand.
@@ -16,9 +16,7 @@ This skill does not read the emulator and does not change project knowledge.
16
16
  - One or more addresses.
17
17
  - Or a register and a value to decode.
18
18
 
19
- ## Tools / execution path
20
-
21
- The script looks up local reference data. It does not use the host runtime.
19
+ ## Tools
22
20
 
23
21
  ```
24
22
  node <skill>/scripts/memory-map.ts at '$d020' '$0314' '$ffd2'
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: c64-packer
3
- description: Use this skill to pack and crunch a C64 program with Exomizer into one PRG that unpacks itself and starts with RUN. It can merge more PRG files into one program. It unpacks the result in an emulator and checks each byte and the entry before it writes the PRG. Use it to make a small release file of a rebuilt or new program. Do not use it to unpack a packed program. Use the c64-unpacker skill for that.
3
+ description: Use this skill to pack and crunch a C64 program with Exomizer into one PRG that unpacks itself and starts with RUN. It can merge more PRG files into one program. It checks each byte and the entry of the result before it writes the PRG. Use it to make a small release file of a rebuilt or new program. Do not use it to unpack a packed program. Use the c64-unpacker skill for that.
4
4
  ---
5
5
 
6
6
  # c64-packer
@@ -9,7 +9,7 @@ description: Use this skill to pack and crunch a C64 program with Exomizer into
9
9
 
10
10
  Pack and crunch PRG files of the project with Exomizer into one PRG. The PRG loads at $0801, starts with RUN, unpacks the program and jumps to its entry. Check the result before you use it.
11
11
 
12
- This skill does not assemble the program, does not run it in VICE and does not change project knowledge.
12
+ This skill does not assemble the program, does not run it in the emulator and does not change project knowledge.
13
13
 
14
14
  ## Inputs
15
15
 
@@ -18,9 +18,7 @@ This skill does not assemble the program, does not run it in VICE and does not c
18
18
  - The entry: the address where the program starts after the unpack. If the first PRG is a BASIC program at $0801 with `SYS` and a number, the script uses that address.
19
19
  - Optional: the value of $01 when the program starts.
20
20
 
21
- ## Tools / execution path
22
-
23
- The script runs Exomizer on this machine. Exomizer packs the files with `sfx`. Then the script unpacks the result with `desfx` in the 6502 emulator of Exomizer. It compares the unpacked bytes with the bytes of the inputs, and the jump address with the entry. The host runtime is not necessary.
21
+ ## Tools
24
22
 
25
23
  ```
26
24
  node <skill>/scripts/packer.ts pack build/game.prg --out build/game-packed.prg
@@ -29,7 +27,7 @@ node <skill>/scripts/packer.ts pack build/loader.prg build/main.prg --entry '$04
29
27
 
30
28
  | Option | Meaning |
31
29
  |---|---|
32
- | `--entry '$0400'` | The address where the program starts after the unpack. It must be `$0400` or higher. A name of the knowledge is also correct. Without it, the script uses the `SYS` address of the BASIC line of the first input. |
30
+ | `--entry '$0400'` | The address where the program starts after the unpack. It must be `$0400` or higher. It can also be a name of the knowledge. Without it, the script uses the `SYS` address of the BASIC line of the first input. |
33
31
  | `--exit-memory '$35'` | The value of $01 when the program starts, `$34` to `$37`. Without it, the value is `$37`: BASIC, KERNAL and I/O. With it, the program starts with interrupts off. |
34
32
 
35
33
  ### Calling the script
@@ -66,7 +64,7 @@ node <skill>/scripts/packer.ts pack build/loader.prg build/main.prg --entry '$04
66
64
 
67
65
  The packed program starts the unpacker with `SYS 2061`, at $080d. A BASIC program at $0801 often has its entry at $080d too. Then the CPU gets to $080d two times: first before the unpack, then at the start of the program. To examine the program at its entry in the emulator, stop at $080d, run one frame, and stop at $080d again.
68
66
 
69
- The unpacker uses $0334 to $03ff and the zero page while it runs. A program that loads into these addresses can fail. Then Exomizer stops with an error, or the check gives `FAIL`.
67
+ The unpacker uses $0334 to $03ff and the zero page while it runs. A program that loads into these addresses can fail. Then the script gives `operation-failed`, or the check gives `FAIL`.
70
68
 
71
69
  ## Knowledge
72
70
 
@@ -83,11 +81,11 @@ Do not store:
83
81
 
84
82
  - `PASS`: the packed program unpacks to the bytes of all inputs and jumps to the entry. The PRG is at `out`.
85
83
  - `FAIL`: the packed program unpacks to different bytes, or jumps to a different address. The script did not write a file.
86
- - `INCONCLUSIVE`: the emulator of Exomizer keeps only the largest range that the unpacker wrote. Bytes of the inputs outside that range have no check. This occurs when the inputs have gaps between them. The PRG is at `out`.
84
+ - `INCONCLUSIVE`: the check has only the largest range that the unpacker wrote. Bytes of the inputs outside that range have no check. This occurs when the inputs have gaps between them. The PRG is at `out`.
87
85
 
88
86
  Other fields:
89
87
  - `packedBytes` and `unpackedBytes`: the size of the packed PRG and of the bytes of the inputs. `percent` is the packed size as a percentage of the unpacked size.
90
- - `unpackSeconds`: the time of the unpack in the emulator of Exomizer, in seconds at the PAL clock. A real C64 can need more time.
88
+ - `unpackSeconds`: the time of the unpack, in seconds at the PAL clock. A real C64 can need more time.
91
89
  - `inputs`: each input with its `loadRange` and its `bytes`.
92
90
  - `check.entry`: the address where the unpacker jumped.
93
91
  - `check.segments`: one check for each segment of the merged inputs. The `result` of a segment is `identical`, `different` with `firstDifference`, or `not covered`. `firstDifference` gives the `address`, the unpacked byte (`built`) and the input byte (`reference`).
@@ -97,8 +95,8 @@ Other fields:
97
95
  - `FAIL`: do not use the packed program. Read `check`. Give the call and the result to the user.
98
96
  - `invalid-input` with `Give --entry`: the first input has no BASIC line with `SYS` and a number. Give `--entry`.
99
97
  - `invalid-input` for the entry: the entry is below $0400. The unpacker runs there. A program with an entry below $0400 needs a different packer.
100
- - `operation-failed` with `Exomizer could not pack the program`: read the last output of Exomizer in the message. Correct the inputs, or give the message to the user.
101
- - `installation-incomplete`, or `machine-unavailable` with a message that the host runtime does not run: stop the task. Give the message to the user and wait for the user. The message gives the remedy. Do not make a replacement for the tool or the host runtime, for example your own disk parser, disassembler or emulator script.
98
+ - `operation-failed` with `Exomizer could not pack the program`: read the last output of Exomizer in the message. Change the inputs, or give the message to the user.
99
+ - `installation-incomplete` or `machine-unavailable`: stop the task. Give the message to the user and wait for the user. Do not install, start or change a tool yourself. Do not make a replacement for the tool, for example your own disk parser, disassembler or emulator script.
102
100
  - `not-found`: there is no file at an input path. Give a path relative to the project folder.
103
101
 
104
102
  ## Handoffs
@@ -6,7 +6,7 @@
6
6
  import { posix } from "node:path";
7
7
 
8
8
  import { findHandoffs, formatC64Address, parseTokenized, prgRange } from "#src/c64.ts";
9
- import { compareBuild, type Reference } from "#src/compare.ts";
9
+ import { compareBuild, mergedPrograms } from "#src/compare.ts";
10
10
  import { isRefusal, Refusal } from "#src/errors.ts";
11
11
  import { readProjectFile, writeReported } from "#src/host-client/transfer.ts";
12
12
  import { knowledgeNames } from "#src/knowledge/names.ts";
@@ -29,24 +29,6 @@ function sysEntry(program: Uint8Array): number | string {
29
29
  return sys.address;
30
30
  }
31
31
 
32
- /** The inputs merged in load order, as the reference of the check: a later file wins where two overlap. */
33
- function merged(programs: ReadonlyArray<{ start: number; body: Uint8Array }>): Reference {
34
- const memory = new Uint8Array(0x10000);
35
- const loaded = new Uint8Array(0x10000);
36
- for (const { start, body } of programs) {
37
- memory.set(body, start);
38
- loaded.fill(1, start, start + body.length);
39
- }
40
- const segments: Array<{ start: number; end: number }> = [];
41
- for (let address = 0; address < 0x10000; address++) {
42
- if (loaded[address] === 0) continue;
43
- const last = segments.at(-1);
44
- if (last !== undefined && last.end === address - 1) last.end = address;
45
- else segments.push({ start: address, end: address });
46
- }
47
- return { segments, byteAt: (address) => memory[address]! };
48
- }
49
-
50
32
  const samePath = (a: string, b: string) => posix.normalize(a.replaceAll("\\", "/")) === posix.normalize(b.replaceAll("\\", "/"));
51
33
 
52
34
  await runScript({
@@ -88,7 +70,7 @@ await runScript({
88
70
  const exitMemory = call.count("exit-memory");
89
71
  const packed = await pack({ programs: programs.map((program) => program.bytes), entry, ...(exitMemory === undefined ? {} : { exitMemory }) }, localToolContext());
90
72
 
91
- const reference = merged(programs);
73
+ const reference = mergedPrograms(programs);
92
74
  const check = compareBuild(packed.unpacked, reference);
93
75
  const entryReached = packed.entry === entry;
94
76
  const different = !entryReached || check.segments.some((segment) => segment.result === "different");
@@ -20,17 +20,17 @@ This skill does not change project knowledge.
20
20
  - Two or more releases, relative to the project folder. A release is `knowledge` (the program in the knowledge), a PRG file, or an `image.json` from c64-unpacker capture with its `entry_state.json` beside it. Extract releases from disk images with the c64-disk skill. Unpack packed releases with the c64-unpacker skill first.
21
21
  - Optional: an address range to compare.
22
22
  - Optional: a shift for a release that loads at a different address.
23
+ - Optional: `--align`, to map two releases with moved code in blocks of equal bytes.
23
24
  - Optional: a number of frames to run each release, and a steps file.
24
25
  - For one release: the program, the coverage and the other knowledge of the project. Put the program and the coverage in with `image` and `coverage` of the c64-knowledge skill.
25
26
  - For the library: the program and the other knowledge of its project, and the library folder.
26
27
 
27
- ## Tools / execution path
28
-
29
- The script compares the releases locally. Only `--frames` uses the host runtime: each release runs in its own emulator.
28
+ ## Tools
30
29
 
31
30
  ```
32
31
  node <skill>/scripts/provenance.ts compare releases/a.prg releases/b.prg releases/c.prg
33
32
  node <skill>/scripts/provenance.ts compare releases/a.prg releases/b.prg --shift 2:-256 --range '$0900-$09ff'
33
+ node <skill>/scripts/provenance.ts compare releases/a/image.json releases/b/image.json --align --range '$0400-$bfff'
34
34
  node <skill>/scripts/provenance.ts compare knowledge .c64-re-tools/local/b/image.json --frames 600 --steps .c64-re-tools/local/start-game.json
35
35
  node <skill>/scripts/provenance.ts separate --out .c64-re-tools/local/separate.json
36
36
  node <skill>/scripts/provenance.ts leftovers --out .c64-re-tools/local/leftovers.json
@@ -40,6 +40,8 @@ node <skill>/scripts/provenance.ts leftovers --out .c64-re-tools/local/leftovers
40
40
  |---|---|
41
41
  | `--shift 2:-256` | Move release 2 (the first release is 1) by -256 bytes. Use it again for more releases. Give one shift for each release. |
42
42
  | `--range '$0900-$09ff'` | Compare only the addresses in this range. |
43
+ | `--align` | Map release 1 to release 2 in blocks of equal bytes. Each block has its own shift. Give two releases. Do not use it with `--shift` or `--frames`. |
44
+ | `--min-block 24` | With `--align`: the minimum number of bytes in a block. The default is 16. |
43
45
  | `--frames 600` | Run each release for this many frames, and give each listed difference its runtime evidence. |
44
46
  | `--steps .c64-re-tools/local/start-game.json` | With `--frames`: a JSON list of action steps to run before the frames, for example a key to start the game. The steps are the steps of a c64-unpacker steps file. |
45
47
 
@@ -47,7 +49,16 @@ The script puts each PRG at its load address. An image has bytes only in its seg
47
49
 
48
50
  With `--shift`, the addresses of `segments`, `common` and `differences` are the release addresses plus the `shift` of the release. The `start` and `end` of `runtime` are the addresses in the release itself, without the shift.
49
51
 
50
- With `--frames`, a PRG starts with autostart and RUN. An image starts from its bytes: the script writes the segments and the entry state from `entry_state.json` into the emulator, and starts at the entry. Watchpoints on each difference stop the run at its first access.
52
+ Use `--align` for two releases with added code and moved data. One shift does not fit them, and the shift suggestions are not useful. The map tells what each block of one release is in the other release. With `--align`, the result has the map, not `differences` and not the shift suggestions:
53
+
54
+ - `blocks`: the blocks of equal bytes, in the order of their addresses in release 1. `a` is the range in release 1. `b` is the range in release 2. `bytes` is the length of the block.
55
+ - `shift`: the address in `b` minus the address in `a`. The address of a byte in release 2 is its address in release 1 plus the `shift` of its block. The blocks can have a different order in release 2, because code moved.
56
+ - `onlyInA`: the ranges of release 1 that no block holds. Release 2 does not have these bytes, or it has other bytes there.
57
+ - `onlyInB`: the ranges of release 2 that no block holds. Release 2 added these bytes, or it changed them.
58
+ - `alignedShare`: the share of the bytes of the two releases that a block holds, with 3 decimals.
59
+ - Each list shows at most 64 items. `moreBlocks`, `moreOnlyInA` and `moreOnlyInB` give the number of the items that the list does not show. Use `--range` to see them.
60
+
61
+ With `--frames`, a PRG starts with autostart and RUN. An image starts at its entry, with the entry state from `entry_state.json`. The run records the first access to each difference.
51
62
 
52
63
  ### Calling the script
53
64
 
@@ -74,7 +85,7 @@ With `--frames`, a PRG starts with autostart and RUN. An image starts from its b
74
85
  ## Workflow
75
86
 
76
87
  1. Run the script on the releases.
77
- 2. Read `identicalShare`. If it is low and `suggestedShifts` is present, the releases are at different addresses. Run the script again with a `--shift` of `suggestedShifts`. `shiftsNotSuggested` tells why a found shift does not fit in `$0000-$ffff`.
88
+ 2. Read `identicalShare`. If it is low and `suggestedShifts` is present, the releases are at different addresses. Run the script again with a `--shift` of `suggestedShifts`. `shiftsNotSuggested` tells why a found shift does not fit in `$0000-$ffff`. If no shift gives a high `identicalShare`, the code and the data can be at other addresses in each release. Then run the script again with `--align`.
78
89
 
79
90
  `suggestedShifts` has at most 3 shifts for each release. The shift with the most `matchingSequences` is first. Data that did not move and code that moved give different shifts. Try each shift. `current: true` marks the shift of this run.
80
91
  3. Read `differences`. Each one has an address range, the bytes of each release, and `groups`: the releases that have the same bytes there.
@@ -201,7 +212,7 @@ Record a confirmed conclusion as a normal comment, region, symbol, release, swit
201
212
 
202
213
  ## Result
203
214
 
204
- The differing ranges with the bytes of each release and the groups that agree, and the share of identical bytes. `identicalShare` has 3 decimals. It is 1 only when no byte differs. `identicalBytes` and `differingBytes` give the counts. `common` gives the ranges where all releases have bytes. `releases` gives the segments and the `shift` of each release. With `--frames`, each difference also has `runtime`, and `run` tells if each release started, or why not.
215
+ The differing ranges with the bytes of each release and the groups that agree, and the share of identical bytes. `identicalShare` has 3 decimals. It is 1 only when no byte differs. `identicalBytes` and `differingBytes` give the counts. `common` gives the ranges where all releases have bytes. `releases` gives the segments and the `shift` of each release. With `--frames`, each difference also has `runtime`, and `run` tells if each release started, or why not. With `--align`, the result has `blocks`, `onlyInA`, `onlyInB` and `alignedShare` in place of `differences`.
205
216
 
206
217
  For `leftovers`: the lists of findings, with `entry`, `roots` and the number of `stages`. `noStages` and `noCoverage` tell which knowledge is missing. Without a root, `roots` tells why `deadCode` is empty.
207
218
 
@@ -213,7 +224,7 @@ The runtime evidence and the leftovers are evidence only. The script does not de
213
224
  - Do not call a byte original only because one release has it. A majority of releases is also not proof.
214
225
  - `common` is empty: the releases do not cover the same addresses. Use `--shift`, or compare a range that all releases cover.
215
226
  - `run.releases` shows `started: false`: a PRG without a BASIC start, or an image without `entry_state.json`. The reason tells which. The other releases still give evidence.
216
- - `installation-incomplete`, or `machine-unavailable` with a message that the host runtime does not run: stop the task. Give the message to the user and wait for the user. The message gives the remedy. Do not make a replacement for the tool or the host runtime, for example your own emulator script.
227
+ - `installation-incomplete` or `machine-unavailable`: stop the task. Give the message to the user and wait for the user. Do not install, start or change a tool yourself. Do not make a replacement for the tool, for example your own emulator script.
217
228
  - `moreDifferences: true`: the script shows only the first differences. Use `--range` to see the others.
218
229
  - `not-found`: the project has no file at that path.
219
230
  - `not-found` from `match`: the library folder does not exist, or it has no routine files. Save a routine with `routine` first.
@@ -2,8 +2,10 @@
2
2
  // has bytes in one or more segments: a PRG at its load address plus an
3
3
  // optional shift, or the segments of an unpacker image. The comparison
4
4
  // covers the addresses where every release has bytes, and reports where the
5
- // releases differ and which releases agree there. It never decides which
6
- // bytes are original: that needs evidence beyond one comparison.
5
+ // releases differ and which releases agree there. For two releases with
6
+ // moved code, align maps the bytes of one to the other in blocks of equal
7
+ // bytes. It never decides which bytes are original: that needs evidence
8
+ // beyond one comparison.
7
9
 
8
10
  import { type AddressRange, formatC64Address } from "#src/c64.ts";
9
11
 
@@ -53,9 +55,13 @@ export function identicalShare(identical: number, differing: number): number {
53
55
 
54
56
  /** The ranges where every release has bytes, inside from..to. */
55
57
  export function commonRanges(releases: Release[], from = 0x0000, to = 0xffff): AddressRange[] {
58
+ return rangesOf(Array.from({ length: to - from + 1 }, (_, offset) => from + offset).filter((address) => releases.every((release) => covers(release, address))));
59
+ }
60
+
61
+ /** Consecutive addresses in order as ranges. */
62
+ function rangesOf(addresses: number[]): AddressRange[] {
56
63
  const ranges: AddressRange[] = [];
57
- for (let address = from; address <= to; address++) {
58
- if (!releases.every((release) => covers(release, address))) continue;
64
+ for (const address of addresses) {
59
65
  const last = ranges.at(-1);
60
66
  if (last !== undefined && last.end + 1 === address) last.end = address;
61
67
  else ranges.push({ start: address, end: address });
@@ -102,6 +108,24 @@ function addressesOf(release: Release): number[] {
102
108
  return release.segments.flatMap((segment) => Array.from({ length: segment.end - segment.start + 1 }, (_, offset) => segment.start + offset));
103
109
  }
104
110
 
111
+ /** The length of the byte sequences that find equal bytes in two releases. */
112
+ const WINDOW = 8;
113
+
114
+ const windowKey = (release: Release, addresses: number[], at: number) => String.fromCharCode(...addresses.slice(at, at + WINDOW).map((address) => release.byteAt(address)));
115
+
116
+ /** The addresses where each 8-byte sequence of `addresses` starts, at most 8 for each sequence. */
117
+ function indexWindows(release: Release, addresses: number[]): Map<string, number[]> {
118
+ const positions = new Map<string, number[]>();
119
+ for (let at = 0; at + WINDOW <= addresses.length; at++) {
120
+ const key = windowKey(release, addresses, at);
121
+ const found = positions.get(key);
122
+ // Very common sequences (fill bytes) say nothing about the alignment.
123
+ if (found === undefined) positions.set(key, [addresses[at]!]);
124
+ else if (found.length < 8) found.push(addresses[at]!);
125
+ }
126
+ return positions;
127
+ }
128
+
105
129
  /** Most shifts that suggestShifts gives: data that did not move can outvote code that did. */
106
130
  export const MAX_SUGGESTED_SHIFTS = 3;
107
131
 
@@ -111,21 +135,11 @@ export const MAX_SUGGESTED_SHIFTS = 3;
111
135
  * less than a tenth of the best one's votes is chance. Empty when nothing matches.
112
136
  */
113
137
  export function suggestShifts(base: Release, other: Release): Array<{ shift: number; matches: number }> {
114
- const WINDOW = 8;
115
- const key = (release: Release, addresses: number[], at: number) =>
116
- String.fromCharCode(...addresses.slice(at, at + WINDOW).map((address) => release.byteAt(address)));
117
- const baseAddresses = addressesOf(base);
138
+ const positions = indexWindows(base, addressesOf(base));
118
139
  const otherAddresses = addressesOf(other);
119
- const positions = new Map<string, number[]>();
120
- for (let at = 0; at + WINDOW <= baseAddresses.length; at++) {
121
- const found = positions.get(key(base, baseAddresses, at));
122
- // Very common sequences (fill bytes) say nothing about the alignment.
123
- if (found === undefined) positions.set(key(base, baseAddresses, at), [baseAddresses[at]!]);
124
- else if (found.length < 8) found.push(baseAddresses[at]!);
125
- }
126
140
  const votes = new Map<number, number>();
127
141
  for (let at = 0; at + WINDOW <= otherAddresses.length; at++) {
128
- for (const address of positions.get(key(other, otherAddresses, at)) ?? []) {
142
+ for (const address of positions.get(windowKey(other, otherAddresses, at)) ?? []) {
129
143
  const shift = address - otherAddresses[at]!;
130
144
  votes.set(shift, (votes.get(shift) ?? 0) + 1);
131
145
  }
@@ -134,6 +148,120 @@ export function suggestShifts(base: Release, other: Release): Array<{ shift: num
134
148
  return ranked.filter((found) => found.matches * 10 >= ranked[0]!.matches).slice(0, MAX_SUGGESTED_SHIFTS);
135
149
  }
136
150
 
151
+ export interface Block {
152
+ a: AddressRange;
153
+ b: AddressRange;
154
+ /** The address in b minus the address in a. */
155
+ shift: number;
156
+ bytes: number;
157
+ }
158
+
159
+ export interface Alignment {
160
+ /** In the order of their addresses in a. */
161
+ blocks: Block[];
162
+ /** The bytes of a that no block holds: removed in b. */
163
+ onlyInA: AddressRange[];
164
+ /** The bytes of b that no block holds: inserted in b. */
165
+ onlyInB: AddressRange[];
166
+ /** The share of the bytes of a and b in the range that a block holds, as identicalShare gives it. */
167
+ alignedShare: number;
168
+ }
169
+
170
+ /**
171
+ * Maps the bytes of `a` to the bytes of `b` in blocks of equal bytes, at least
172
+ * `minBlock` long, for releases with added code and moved data, where no one
173
+ * shift fits. Only the bytes inside `range` and the segments count. Each
174
+ * address of a that no block holds yet gets the longest block through it:
175
+ * from each address of b with the same 8 bytes, and from the shift of the
176
+ * block before. Then the longest blocks are kept with no byte of a or b in two
177
+ * blocks; a block that overlaps a kept one keeps its free parts. Blocks can
178
+ * cross: moved code changes the order.
179
+ */
180
+ export function align(a: Release, b: Release, range: AddressRange, minBlock: number): Alignment {
181
+ const inRange = (address: number) => address >= range.start && address <= range.end;
182
+ const aAddresses = addressesOf(a).filter(inRange);
183
+ const bAddresses = addressesOf(b).filter(inRange);
184
+ // -1 where the release has no byte; an index outside $0000-$ffff gives undefined.
185
+ const bytesOf = (release: Release, addresses: number[]) => {
186
+ const bytes = new Int16Array(0x10000).fill(-1);
187
+ for (const address of addresses) bytes[address] = release.byteAt(address);
188
+ return bytes;
189
+ };
190
+ const bytesA = bytesOf(a, aAddresses);
191
+ const bytesB = bytesOf(b, bAddresses);
192
+ const equal = (x: number, y: number) => {
193
+ const value = bytesA[x];
194
+ return value !== undefined && value >= 0 && value === bytesB[y];
195
+ };
196
+
197
+ type Found = { a: number; b: number; bytes: number };
198
+ const index = indexWindows(b, bAddresses);
199
+ const found: Found[] = [];
200
+ let covered = -1;
201
+ let lastShift: number | undefined;
202
+ for (let at = 0; at < aAddresses.length; at++) {
203
+ const p = aAddresses[at]!;
204
+ if (p <= covered) continue;
205
+ const candidates = at + WINDOW <= aAddresses.length ? [...(index.get(windowKey(a, aAddresses, at)) ?? [])] : [];
206
+ if (lastShift !== undefined) candidates.push(p + lastShift);
207
+ let best: Found | undefined;
208
+ for (const q of candidates) {
209
+ if (!equal(p, q)) continue;
210
+ let back = 0;
211
+ while (equal(p - back - 1, q - back - 1)) back++;
212
+ let forward = 1;
213
+ while (equal(p + forward, q + forward)) forward++;
214
+ if (best === undefined || back + forward > best.bytes) best = { a: p - back, b: q - back, bytes: back + forward };
215
+ }
216
+ if (best === undefined || best.bytes < minBlock) continue;
217
+ found.push(best);
218
+ covered = best.a + best.bytes - 1;
219
+ lastShift = best.b - best.a;
220
+ }
221
+
222
+ // The longest first; a piece that is left of an overlapping block goes back in its place in that order.
223
+ const before = (x: Found, y: Found) => y.bytes - x.bytes || Math.abs(x.b - x.a) - Math.abs(y.b - y.a) || x.a - y.a;
224
+ const queue = found.sort(before);
225
+ const usedA = new Uint8Array(0x10000);
226
+ const usedB = new Uint8Array(0x10000);
227
+ const kept: Found[] = [];
228
+ for (let next = 0; next < queue.length; next++) {
229
+ const block = queue[next]!;
230
+ const pieces: Found[] = [];
231
+ let start: number | undefined;
232
+ for (let offset = 0; offset <= block.bytes; offset++) {
233
+ if (offset < block.bytes && usedA[block.a + offset] === 0 && usedB[block.b + offset] === 0) start ??= offset;
234
+ else if (start !== undefined) {
235
+ pieces.push({ a: block.a + start, b: block.b + start, bytes: offset - start });
236
+ start = undefined;
237
+ }
238
+ }
239
+ if (pieces.length === 1 && pieces[0]!.bytes === block.bytes) {
240
+ kept.push(block);
241
+ usedA.fill(1, block.a, block.a + block.bytes);
242
+ usedB.fill(1, block.b, block.b + block.bytes);
243
+ continue;
244
+ }
245
+ for (const piece of pieces.filter((item) => item.bytes >= minBlock)) {
246
+ let place = next + 1;
247
+ while (place < queue.length && before(queue[place]!, piece) <= 0) place++;
248
+ queue.splice(place, 0, piece);
249
+ }
250
+ }
251
+
252
+ const alignedBytes = kept.reduce((sum, block) => sum + block.bytes, 0);
253
+ const onlyInA = rangesOf(aAddresses.filter((address) => usedA[address] === 0));
254
+ const onlyInB = rangesOf(bAddresses.filter((address) => usedB[address] === 0));
255
+ return {
256
+ blocks: kept
257
+ .sort((x, y) => x.a - y.a)
258
+ .map((block) => ({ a: { start: block.a, end: block.a + block.bytes - 1 }, b: { start: block.b, end: block.b + block.bytes - 1 }, shift: block.b - block.a, bytes: block.bytes })),
259
+ onlyInA,
260
+ onlyInB,
261
+ alignedShare: identicalShare(2 * alignedBytes, aAddresses.length + bAddresses.length - 2 * alignedBytes),
262
+ };
263
+ }
264
+
137
265
  export type ShiftSuggestion = { release: number; shift: number; matchingSequences: number } | { release: number; matchingSequences: number; reason: string };
138
266
 
139
267
  /**