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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +149 -78
  3. package/skills/c64-assembler/scripts/assembler.ts +18 -11
  4. package/skills/c64-basic/SKILL.md +90 -52
  5. package/skills/c64-basic/scripts/basic.ts +15 -6
  6. package/skills/c64-development/SKILL.md +46 -73
  7. package/skills/c64-disk/SKILL.md +145 -73
  8. package/skills/c64-disk/scripts/disk.ts +11 -6
  9. package/skills/c64-docs/SKILL.md +199 -118
  10. package/skills/c64-docs/references/page-types.md +3 -3
  11. package/skills/c64-docs/references/style.md +9 -13
  12. package/skills/c64-docs/scripts/docs.ts +39 -15
  13. package/skills/c64-docs/scripts/lib/links.ts +1 -1
  14. package/skills/c64-docs/scripts/lib/reference.ts +2 -2
  15. package/skills/c64-docs/scripts/lib/source-map.ts +2 -2
  16. package/skills/c64-export/SKILL.md +21 -45
  17. package/skills/c64-knowledge/SKILL.md +489 -233
  18. package/skills/c64-knowledge/scripts/knowledge.ts +31 -26
  19. package/skills/c64-memory-map/SKILL.md +131 -65
  20. package/skills/c64-memory-map/scripts/memory-map.ts +19 -11
  21. package/skills/c64-packer/SKILL.md +120 -72
  22. package/skills/c64-packer/scripts/packer.ts +10 -3
  23. package/skills/c64-provenance/SKILL.md +301 -173
  24. package/skills/c64-provenance/scripts/lib/library.ts +6 -6
  25. package/skills/c64-provenance/scripts/provenance.ts +85 -36
  26. package/skills/c64-reverse-engineering/SKILL.md +55 -72
  27. package/skills/c64-source/SKILL.md +316 -224
  28. package/skills/c64-source/scripts/lib/export.ts +9 -14
  29. package/skills/c64-source/scripts/lib/loader.ts +5 -5
  30. package/skills/c64-source/scripts/lib/source.ts +5 -5
  31. package/skills/c64-source/scripts/source.ts +106 -21
  32. package/skills/c64-static-analysis/SKILL.md +188 -112
  33. package/skills/c64-static-analysis/scripts/static-analysis.ts +29 -9
  34. package/skills/c64-testing/SKILL.md +272 -166
  35. package/skills/c64-testing/references/recording-format.md +11 -12
  36. package/skills/c64-testing/references/scenario-format.md +20 -5
  37. package/skills/c64-testing/scripts/lib/diff-files.ts +8 -8
  38. package/skills/c64-testing/scripts/lib/recording.ts +7 -7
  39. package/skills/c64-testing/scripts/lib/replay.ts +7 -7
  40. package/skills/c64-testing/scripts/lib/runs.ts +6 -7
  41. package/skills/c64-testing/scripts/lib/scenario.ts +12 -6
  42. package/skills/c64-testing/scripts/testing.ts +35 -15
  43. package/skills/c64-unpacker/SKILL.md +273 -127
  44. package/skills/c64-unpacker/scripts/lib/loads.ts +3 -3
  45. package/skills/c64-unpacker/scripts/unpacker.ts +70 -11
  46. package/skills/emulator/SKILL.md +12 -12
  47. package/src/errors.ts +22 -2
  48. package/src/host/vice/session.ts +1 -1
  49. package/src/host-client/entry-state.ts +1 -1
  50. package/src/host-client/image.ts +3 -3
  51. package/src/host-client/steps.ts +1 -1
  52. package/src/knowledge/expression.ts +1 -1
  53. package/src/knowledge/names.ts +2 -3
  54. package/src/knowledge/program.ts +2 -3
  55. package/src/knowledge/write.ts +2 -2
  56. package/src/mcp/inputs.ts +1 -1
  57. package/src/mcp/tools/input.ts +1 -1
  58. package/src/mcp/tools/media.ts +1 -1
  59. package/src/native/exomizer.ts +2 -2
  60. package/src/project.ts +2 -2
  61. package/src/script.ts +164 -75
@@ -1,150 +1,226 @@
1
1
  ---
2
2
  name: c64-static-analysis
3
- description: Use this skill to find the structure of a C64 program without running it. DXA gives a fast first pass of code and data regions and a disassembly listing. Ghidra gives a deeper pass with routines, regions, references and decompiled code. The skill records the structure in the project knowledge and reports conflicts with the current knowledge. Do not use it for runtime questions or to name routines.
3
+ description: Finds the structure of a C64 program with DXA or Ghidra, without running it. It records the code and data regions, the analyzer names and the references in the project knowledge. Use it to get a fast first pass of code and data, and a disassembly listing. Use it to get the routines, the references, an instruction list and decompiled code. Use it when the project knowledge has coverage, to find code that only a vector, a table or an interrupt reaches. Use it to find 6502 idioms, pointer candidates, raster pitfalls and macro candidates. It does not run the program. It does not give names to routines.
4
4
  ---
5
5
 
6
- # c64-static-analysis
6
+ # Static analysis
7
7
 
8
- ## Purpose
8
+ Use this script to find the code, the data, the routines and the references of a C64 program without running it.
9
+ Use only the commands of the script. Do not disassemble or decompile the program in another way.
9
10
 
10
- Find the static structure of a C64 program. Record the structure in the project knowledge. Report conflicts with current knowledge.
11
-
12
- ## Inputs
13
-
14
- - The program in the knowledge. Put it in with `image` of the c64-knowledge skill: a PRG, or a capture of the c64-unpacker skill.
15
- - Optional: the coverage in the knowledge. Add it with `coverage` of the c64-knowledge skill.
16
- - Entry points: addresses where code starts, for example the SYS address from the c64-basic skill. Routine symbols in the knowledge are entry points too. Ghidra needs at least one. DXA finds the SYS of a BASIC start by itself.
17
- - Optional: routines to decompile (Ghidra), or a file for the listing (DXA).
11
+ ```bash
12
+ node <skill>/scripts/static-analysis.ts <command>
13
+ ```
18
14
 
19
- ## Tools
15
+ `<skill>` is the base directory of this skill. Run the script with `node`. You can run it from any directory.
16
+ Each command in this skill, for example `analyze --analyzer dxa`, goes in the place of `<command>`.
17
+ Each command prints one JSON envelope on stdout. See the section "JSON output".
18
+ To get the command list, run the script with no arguments.
20
19
 
21
- The script reads the program, the coverage and the current knowledge. It records the result in the project knowledge, `.c64-re-tools/knowledge/`.
20
+ ---
22
21
 
23
- ```
24
- node <skill>/scripts/static-analysis.ts analyze --analyzer dxa --out-listing .c64-re-tools/local/game.lst
25
- node <skill>/scripts/static-analysis.ts analyze --entry '$080d' --decompile '$080d'
26
- ```
22
+ ## Select the command
27
23
 
28
- | Option | Meaning |
24
+ | Goal | Command |
29
25
  |---|---|
30
- | `--analyzer dxa` | Use DXA: a fast first pass. Without this option, the script uses Ghidra. |
31
- | `--entry '$080d'` | An address where code starts. Use it again for more addresses. |
32
- | `--out-listing .c64-re-tools/local/game.lst` | DXA only: write the disassembly listing to this project file. |
33
- | `--decompile '$0818'` | Ghidra only: decompile the routine at this address. Use it again for more routines, at most 32. |
34
- | `--max-listed 20` | List at most this number of labels, functions or candidates. The default is 50. Use 0 to list none. |
35
- | `--out-instructions .c64-re-tools/local/instructions.json` | Ghidra only: write every instruction to this project file as JSON. Each has `address`, `bytes`, `mnemonic`, `mode` and `operand` in 6502 syntax. A branch, jump or call also has its `target`. When the knowledge has coverage, `executed` tells if it ran. |
36
- | `--space drive8` | The knowledge space of the program: `drive8` for code from the 1541 drive, or `bank0` to `bank255` for a cartridge bank. The default is `c64`. The seeds come from that space, and the findings go into it. |
37
- | `--out-macro-batch .c64-re-tools/local/macros.json` | Write the macro candidates to this project file as a batch for `apply` of the c64-knowledge skill. |
26
+ | Get a fast first pass of the code and data regions | `analyze --analyzer dxa` |
27
+ | Get a disassembly listing | `analyze --analyzer dxa --out-listing .c64-re-tools/local/game.lst` |
28
+ | Find the routines and the references | `analyze --entry '$080d'` |
29
+ | Get C-like code of a routine | `analyze --entry '$080d' --decompile '$0818'` |
30
+ | Get each instruction as JSON | `analyze --entry '$080d' --out-instructions .c64-re-tools/local/instructions.json` |
31
+ | Analyze drive code or a cartridge bank | `analyze --space drive8` |
32
+ | Get the macro candidates as a batch of changes | `analyze --out-macro-batch .c64-re-tools/local/macros.json` |
33
+ | Get more items in each list | `analyze --max-listed 500` |
38
34
 
39
- Both analyzers use the knowledge from the user and the LLM as seeds:
35
+ ---
40
36
 
41
- - Each routine is an entry point.
42
- - Each region that is not code stays data.
43
- - Each symbol of the kind `data` or `variable` stays data. The region that is not code and that holds the symbol stays data, also a region of an analyzer. Without such a region, the byte of the symbol stays data. A symbol in a code region or at an executed address is not data. When the region holds an entry point or an executed address, only the byte of the symbol stays data.
44
- - Each name is a label. The listing, Ghidra and the decompiler show that name.
37
+ ## The program and the entry points
38
+
39
+ - The program comes from the project knowledge. Put the program into the project knowledge before you analyze it.
40
+ - Put each coverage map of the program into the project knowledge before you analyze it. With coverage, the analysis finds code that only a vector, an RTS table or an interrupt reaches. It also finds the code after a JSR to a routine that an analyzer thinks does not return.
41
+ - The analysis uses coverage only in the space `c64`.
42
+ - An entry point is an address where code starts. Give it with `--entry`. Get it from these sources:
43
+ - The SYS address of a BASIC start. Get it from a listing of the BASIC program.
44
+ - A vector or an interrupt target that you found in the emulator.
45
+ - An address in `functions` of an earlier Ghidra result.
46
+ - Ghidra needs at least one entry point. DXA finds the SYS address of a BASIC start without help.
47
+ - Each routine, each `code` region and each entry of a `jumps` table in the project knowledge is also an entry point. Each name in the project knowledge is a label in the listing and in the decompiled code.
48
+ - The two start vectors of a `CBM80` header at `$8000` are entry points without help.
49
+ - Each region that is not code in the project knowledge stays data. Each `data` or `variable` symbol also keeps its region as data. If the region holds an entry point or executed code, only the byte of the symbol stays data.
50
+ - If an analyzer decodes data as code, classify the region as data in the project knowledge. Then run `analyze` again.
51
+ - The facts of an analyzer are not entry points or data for the next analysis. Thus a new analysis can correct them.
52
+ - With coverage, the analysis keeps as data the RAM under ROM that the runs did not read or execute. A call into the KERNAL thus does not decode the RAM under it. If the program has code there, give its address with `--entry`.
53
+ - Ghidra does not follow BRK. If the program removes the KERNAL and uses the BRK vector, give the target of the vector with `--entry`.
54
+ - `--decompile` takes the address of a routine. Get it from `functions` of an earlier Ghidra result, or from the routines in the project knowledge.
55
+
56
+ ### Paths and the project folder
57
+
58
+ - Give each path relative to the project folder. The project folder is the nearest folder at or above the working directory that holds `.c64-re-tools/`.
59
+ - If the working directory is not in a project, give `--project <folder>` to each command. If the working directory has projects below it, the script refuses and lists them.
60
+ - An address is `$` and 1 to 4 hex digits, for example `'$c000'` or `'$fb'`, or a name. A name is a symbol, else an analyzer name that only one analyzer gives. Put an address in single quotes in a shell.
61
+ - A range is `<start>-<end>`, for example `'$c000-$cfff'`. In a JSON file, a range is `start` and `end`.
62
+ - Bytes in a JSON file are hex in a field `data`, for example `"data": "a900"`.
63
+ - Write each file that you make for your work in `.c64-re-tools/local/` of the project. Git ignores that folder. Examples are results, batches, step files, runs, snapshots and memory dumps.
64
+ - The script refuses an `--out` path in `.c64-re-tools/knowledge/` and the index of the knowledge. Change the project knowledge only with the commands that change it.
65
+ - The script refuses a folder where the command writes a file. It refuses a file where the command writes a folder.
66
+ - When a file is the evidence for a finding in the project knowledge, move it out of `.c64-re-tools/local/` first. The project knowledge refuses evidence in that folder.
67
+ - Do not move a coverage map after you put it into the project knowledge. The knowledge refers to the map by its path at that time.
68
+ - Put a run that is evidence in `runs/<name>/`, with its run file, its results and its snapshot files. Change the paths in the run file to the new paths. Then git keeps them, and another person can do the run again.
69
+ - A shell redirect (`>`) is relative to the working directory, not to the project folder. From the folder above the project, write `<folder>/.c64-re-tools/local/result.json`.
45
70
 
46
- Facts that an analyzer found are not seeds alone. A new analysis can then correct or remove them.
71
+ ---
47
72
 
48
- More seeds come from evidence:
73
+ ## Flags
49
74
 
50
- - The start of each `code` region and each entry of a `jumps` table from the user or the LLM is an entry point.
51
- - When the knowledge has coverage, each executed instruction of the program that starts a flow is an entry point. A flow starts after a gap, or after RTS, RTI, JMP, BRK or JSR. Then the analyzers find code that only a vector, an RTS table or an interrupt reaches. They also find the code after a JSR to a routine that an analyzer thinks does not return.
52
- - For Ghidra, a flow start is a routine only when no executed branch or JMP from another flow gets to it. Also, no JSR can be immediately before it. Another flow start is code in a routine, and Ghidra does not make a function of it.
53
- - When the knowledge has coverage, Ghidra gives `coverageGaps`: the executed instruction starts in the program that are not in its instructions. Normally the count is 0. Each start in the list is missing from `--out-instructions` and from the source of c64-source. Examine the code at the start. Overlapped instructions and self-modified code can cause a gap. A start in a `dual-use` region is a known overlap, for example a BIT skip, and is not in the list.
54
- - When the knowledge has coverage, some RAM under a ROM is data for the analysis. At these addresses, the runs used the ROM and did not read or execute the RAM. Then a call into the KERNAL does not decode the RAM bytes under it as code. A knowledge routine or an `--entry` in such a range keeps its code. Ghidra does not follow BRK, because the vector at `$fffe` is in ROM unless the program removes the KERNAL.
75
+ Each flag applies only to the commands in the table. On another command, the script refuses the flag.
55
76
 
56
- The analyzers take at most 1024 entry points. Knowledge routines and `--entry` come first, then code regions and tables, then coverage. Ghidra also takes at most 8192 flow starts that are code in a routine. `coverageSeeds` gives how many entry points the coverage gave and how many the analysis used. `romOnlyRanges` and `romOnlyUsed` give the same counts for the data ranges under ROM.
77
+ | Flag | Command | Effect |
78
+ |---|---|---|
79
+ | `--analyzer <dxa\|ghidra>` | `analyze` | The analyzer. `dxa` gives a fast first pass. `ghidra` gives a deeper pass. The default is `ghidra`. |
80
+ | `--entry <address>` | `analyze` | An entry point of the program. Give it again for more entry points. There is no default. |
81
+ | `--decompile <address>` | `analyze` | Ghidra only. Decompile the routine at this address. Give it again for more routines, at most 32. There is no default. |
82
+ | `--space <space>` | `analyze` | The knowledge space of the program: `drive8` for 1541 drive code, or `bank0` to `bank255` for a cartridge bank. The analysis reads the entry points from that space and writes the findings into it. The default is `c64`. |
83
+ | `--max-listed <n>` | `analyze` | List at most `n` items in each list. `0` lists no items. The counts stay complete. The default is 50. |
84
+ | `--out-listing <file>` | `analyze` | DXA only. Write the disassembly listing to this project file. There is no default. |
85
+ | `--out-instructions <file>` | `analyze` | Ghidra only. Write each instruction to this project file as JSON. There is no default. |
86
+ | `--out-macro-batch <file>` | `analyze` | Write the macro candidates to this project file as a batch of changes to the project knowledge. There is no default. |
57
87
 
58
- ### Calling the script
88
+ ---
59
89
 
60
- - Call a script as `node <skill>/scripts/<script>.ts <command> [subjects] [options]`. The command comes first.
61
- - `<script>.ts --help` lists the commands. `<script>.ts <command> --help` gives the subjects and the options of one command. The help is JSON: `{"text": "..."}`.
62
- - An address is `$` and 1 to 4 hex digits, for example `'$c000'` or `'$fb'`, or a name. A name is a symbol, else an analyzer name that only one analyzer gives. Quote an address in a shell.
63
- - A range is `<start>-<end>`, for example `'$c000-$cfff'`. In a JSON file, a range is `start` and `end`.
64
- - Bytes in a JSON file are hex in a field `data`, for example `"data": "a900"`.
65
- - The script examines each `--out` path before it starts work. It refuses a path in `.c64-re-tools/knowledge/` and the index of the knowledge, because only c64-knowledge writes them. It refuses a folder where the command writes a file, and a file where the command writes a folder.
66
- - The result is one JSON object on one line. A file that the script writes shows as `{"out", "bytes", "sha256"}`. A list shows as `{"count", "listed"}`, and `rest` tells where to get the rest of a long list.
67
- - An error is `{"error": {"code": "...", "message": "..."}}`. The message tells what is wrong and what to do.
68
- - The exit status is 0 for done or PASS, 1 for FAIL, 2 for an error and 3 for INCONCLUSIVE.
90
+ ## Analyze the program
69
91
 
70
- ### Project folder
92
+ ### `analyze`
71
93
 
72
- - Paths are relative to the project folder. The project folder is the nearest folder at or above the working directory that holds `.c64-re-tools/`.
73
- - If the working directory is not in a project and has projects below it, the script refuses and lists them. Then give `--project <folder>` to each script.
74
- - Write each file that you make for your work in `.c64-re-tools/local/` of the project. Git ignores that folder. Examples are results, batches, step files, runs, snapshots and memory dumps.
75
- - Move a file out of `.c64-re-tools/local/` only when it is the evidence for a finding. Move it before you give it to `--evidence test:<file>` or `--evidence file:<file>` of c64-knowledge. These two refuse a file in `.c64-re-tools/local/`.
76
- - Do not move a coverage map after `coverage` of c64-knowledge imported it. `--evidence coverage:<map>` names the map by its path at the import. The knowledge keeps the coverage and the SHA-256 of the map, so the evidence stays valid.
77
- - Put a run that is evidence in `runs/<name>/`, with its run file, its results and the snapshot files that it uses. Change the paths in the run file to the new paths. Then git keeps them, and another person can do the run again.
78
- - A shell redirect (`>`) is relative to the working directory, not to the project folder. From the folder above the project, write `<folder>/.c64-re-tools/local/result.json`.
94
+ Runs DXA or Ghidra over the program in the project knowledge. The script records the findings in the project knowledge as one revision. Then it records the 6502 idioms as a second revision.
79
95
 
80
- ## Workflow
96
+ The script records only structure: code and data regions, analyzer names, and the references from Ghidra. It does not record the listing or the decompiled code. Do not record the listing, the decompiled code or the function list as comments in the project knowledge.
97
+
98
+ `body` holds these fields for both analyzers:
81
99
 
82
- 1. Read the knowledge for the program with the c64-knowledge skill.
83
- 2. Run a first pass with `--analyzer dxa`. For a BASIC loader, DXA finds the SYS address. Read the listing for a quick view of the code.
84
- 3. Find the important routines. Give them names with the c64-knowledge skill.
85
- 4. Run a deeper pass with Ghidra. Give the entry points with `--entry`. Ask for decompiled code of the routines that you must understand.
86
- 5. Read the result:
87
- - `changes` counts the analyzer names (`names`), regions and references that the analysis `added`, `changed`, `retired` or kept `unchanged`. `symbols.retired` counts the old symbols of the analyzer that moved to its analyzer names. `suppressed` counts the findings that the analysis did not write, because a removal blocks that place.
88
- - DXA: `regions` lists the code and data regions. `labels` gives the number of names that DXA found (`count`) and lists the first names (`listed`).
89
- - Ghidra: `functions` gives the number of routines that Ghidra found (`count`) and lists the first routines (`listed`). `decompilations` gives C-like code for the requested routines.
90
- - If a list is not complete, `rest` gives the c64-knowledge command that lists all of them. For `candidates`, `rest` tells you to give a larger `--max-listed`.
91
- - `conflicts` lists the places where the analyzer and the current knowledge disagree.
92
- - DXA or Ghidra can find data where a run executed an instruction start (`executed`), or where a `user` or `llm` symbol of kind `label` or `routine` is (`knowledge`). Then the script does not write that data region, and the earlier region of the analyzer stays. `conflicts` lists each such place. Executed code and your names have priority over the guess of an analyzer.
93
- - `idioms` tells what the script found by pattern: RTS dispatch tables (`rtsTables`), JMP tables (`jumpTables`) and BIT skips (`bitSkips`). It also finds the `CBM80` header of a cartridge bank at `$8000` (`cartridgeHeaders`). The two start vectors of the header become entry points. The script writes them as knowledge with the origin `heuristic`, and seeds their targets into the same analysis. `candidates` gives DOP padding (`dop`) and opcodes that the program wrote and executed (`selfModified`). For `selfModified`, the write and the execution must be in one coverage file. A coverage file does not record the order. Thus a candidate can also be code that ran first, and that the program then wrote over. To prevent this, save one coverage file for each part of the program, for example the intro and the game. A loader that copies relocated code is also such a part. Clear the memory map between the parts. Each list has a `count`. The script does not write the candidates. Look at them and decide.
94
- - `candidates.pointers` gives code that makes an address from immediates. The script reads only the instructions of the code regions, from the start of each region. A `vector` or a `zero-page pointer` candidate stores a low byte (`low`) and a high byte (`high`) to a vector or to a zero-page pair. A `(zp),y` instruction of the code uses the zero-page pair. Its `target` is in the program or has a platform name. A `sprite pointer` candidate stores an immediate (`at`) to a sprite pointer of the screen at $0400 in VIC bank 0. Its `target` (the value × 64) is in a `sprite` region. For each candidate that you confirm, write operand expressions with `operand` of the c64-knowledge skill, for example `operand '<low>' --lo <target name>` and `operand '<high>' --hi <target name>`. Then a rebuild can move the target.
95
- - `candidates.pitfalls` gives code that a C64 runs in a different way than it reads. `raster-bit-8`: the instruction at `at` reads $D011, and the instruction at `store` writes the value back. A read of $D011 gives bit 8 of the raster line in bit 7. Thus the write can move the raster interrupt to line 256 or later, and on PAL past line 311 the interrupt never comes. Examine each candidate. Where the code must not keep bit 7, add a comment and test the program.
96
- - `candidates.macros` gives runs of instructions that a macro writes as one line, for example `+inc16 ptr`. The script knows these 6502 idioms: `inc16`, `dec16`, `add16_8`, `add16`, `sub16`, `set16`, `mov16` and `wait_line`. It reads the code regions after the analysis. An arg has the name of a `user` or `llm` symbol or a platform name. A platform name of a ROM that the program does not use is not an arg, because the c64-source skill does not use it. Each candidate has `macro`, `start`, `end`, `args` and `text`. `known` counts the uses that the knowledge has. `leftOut` counts the candidates with a label inside, or with a patch or a use over them. The c64-source skill writes such a candidate as instructions. With `--out-macro-batch`, `batch` gives the file, the count of writes (`writes`) and the `apply` command. The batch holds the macros that the knowledge does not have, and the uses. When the knowledge has a macro with the same name and another body, `otherMacros` tells that the batch does not have its uses. The script does not write the candidates. Apply the batch, then generate the source again.
97
- - When the knowledge has coverage, a code finding replaces the DXA or Ghidra data where a run executed an instruction start. `coverageConflicts` lists the analyzer data regions where the coverage still shows executed code. Classify them as code with the c64-knowledge skill, or as `dual-use` when the bytes are also data. For many conflicts, write all classifications in one `apply` batch of the c64-knowledge skill.
98
- 6. Give each important routine a name with the c64-knowledge skill. Then run the analysis again. The analyzers use the new names.
100
+ - `analyzer`: `dxa` or `ghidra`. `space` is in `body` only for a space that is not `c64`.
101
+ - `revision`: the revision of the findings, or `null` when the knowledge did not change.
102
+ - `coverage`: the ranges that the analyzer examined.
103
+ - `changes`: for analyzer names (`names`), `regions` and `references`, the counts `added`, `changed`, `retired`, `unchanged` and `suppressed`. `suppressed` counts the findings that the script did not record, because the user or the LLM removed a fact at that place. `symbols.retired` counts the old symbols of the analyzer that became analyzer names.
104
+ - `conflicts`: each place where the analyzer and the project knowledge disagree. `problem` tells the disagreement.
105
+ - `coverageSeeds`: only with coverage. `entryPoints` and `used` give how many entry points the coverage gave, and how many the analysis used. `romOnlyRanges` and `romOnlyUsed` give the same counts for the data ranges under ROM.
106
+ - `coverageConflicts`: only with coverage. Each analyzer data region where the coverage shows executed code.
107
+ - `idioms`: the 6502 idioms that the script found by pattern. The counts are `rtsTables`, `jumpTables`, `bitSkips` and `cartridgeHeaders`. `revision`, `changes` and `conflicts` are for the idioms, as above. `candidates` holds what the script did not record.
99
108
 
100
- The script records only structure: generated names, code and data regions, and references from Ghidra. The listing and the decompiled code are only for the current task. The script does not record them in the knowledge.
109
+ DXA also gives:
101
110
 
102
- ## Knowledge
111
+ - `regions`: the code and data regions, each with `start`, `end` and `classification`.
112
+ - `labels`: the names that DXA found, as a list.
113
+ - `listing`: the listing file, with `--out-listing`.
103
114
 
104
- Automatic write:
105
- - code and data regions
106
- - analyzer names: the labels that DXA generated and the functions that Ghidra found, for example `l17e2` and `FUN_17e2`
107
- - references from Ghidra: call, jump, read and write.
115
+ Ghidra also gives:
108
116
 
109
- An analyzer name is a second name of the address. It is not a symbol. Each analyzer keeps its own name at an address. The generated source does not use an analyzer name, unless you give `--analyzer-names` to the c64-source skill. To use a name in the source, give it to the address with `rename` of the c64-knowledge skill. A Ghidra function that only branches and jumps get to is a `label`, not a `routine`.
117
+ - `functions`: the routines that Ghidra found, as a list, each with `entry` and `name`.
118
+ - `decompilations`: the C-like code of each `--decompile` routine, with `entry` and `text`. `truncated` tells that the text is cut.
119
+ - `notDecompiled`: the routines that Ghidra did not decompile, each with a `reason`.
120
+ - `instructions`: the file and the `count`, with `--out-instructions`. Each instruction has `address`, `bytes`, `mnemonic`, `mode` and `operand` in 6502 syntax. A branch, a jump or a call also has `target`. With coverage, `executed` tells if the instruction ran.
121
+ - `coverageGaps`: only with coverage. The executed instruction starts that are not in the instructions of Ghidra.
110
122
 
111
- The script never replaces a name or a region from the user or the LLM. DXA and Ghidra do not replace the facts of each other, with one exception. When the knowledge has coverage, a code finding replaces a DXA or Ghidra data region where a run executed an instruction start. Thus add all coverage maps to the knowledge first. Then run DXA, then Ghidra.
123
+ The `hint` gives each of these cases:
112
124
 
113
- A `heuristic` region replaces the part of a DXA or Ghidra region where it lies, because an idiom is specific evidence about those bytes. DXA and Ghidra never replace a `heuristic` region. If they find code there, the result shows a conflict. A heuristic table can be too long or too short, because the script cannot know its length. Correct it with the c64-knowledge skill. Your region replaces it, and a removal holds.
125
+ - `conflicts` is not empty. Find the correct answer in the emulator. Then correct the project knowledge.
126
+ - `coverageConflicts` is not empty. Classify each range as code in the project knowledge, or as `dual-use` when its bytes are also data. For many ranges, write all classifications in one batch of changes.
127
+ - The batch of `--out-macro-batch` has changes. Apply the changes in the batch file to the project knowledge. Then generate the source again.
128
+ - A list is cut. Give a larger `--max-listed`. The project knowledge has all `labels` and `functions` as analyzer names.
114
129
 
115
- A new analysis replaces the earlier facts of the same analyzer in the analyzed range, also its analyzer names. The history keeps the earlier facts.
130
+ There is no `nextAction`.
116
131
 
117
- A fact that the user or the LLM removes does not come back. The next analysis does not write a fact at that place, and counts it as `suppressed`. To remove a wrong fact, use the c64-knowledge skill.
132
+ #### The candidates
118
133
 
119
- Do not store:
120
- - the listing or decompiled code
121
- - the function list as comments.
134
+ The script does not record the candidates. Examine each candidate and decide.
122
135
 
123
- ## Result
136
+ - `dop`: DOP padding.
137
+ - `selfModified`: opcodes that the program wrote and then executed. The write and the execution must be in one coverage file. A coverage file does not record the order. Thus a candidate can also be code that ran first, and that the program then wrote over. To prevent this, save one coverage file for each part of the program, for example the intro, the game, or a loader that copies code. Clear the memory map between the parts.
138
+ - `pointers`: code that makes an address from immediates. A `vector` or a `zero-page pointer` candidate stores a low byte (`low`) and a high byte (`high`) to a vector or to a zero-page pair. A `sprite pointer` candidate stores an immediate (`at`) to a sprite pointer of the screen at `$0400` in VIC bank 0. For each correct candidate, record a low and a high operand expression to its `target` in the project knowledge. Then a rebuild can move the target.
139
+ - `pitfalls`: code that a C64 runs in a different way than it reads. For `raster-bit-8`, the instruction at `at` reads `$D011`, and the instruction at `store` writes the value back. The write can move the raster interrupt to line 256 or later. On PAL, past line 311, the interrupt never comes. Where the code must not keep bit 7, add a comment and test the program.
140
+ - `macros`: runs of instructions that one macro line can replace, for example `+inc16 ptr`. Each candidate has `macro`, `start`, `end`, `args` and `text`. The macros are `inc16`, `dec16`, `add16_8`, `add16`, `sub16`, `set16`, `mov16` and `wait_line`. An arg is a name of the user or the LLM, or a platform name of a ROM that the program uses. `known` counts the uses that the project knowledge has. `leftOut` counts the candidates with a label inside, or with a patch or a use over them. With `--out-macro-batch`, `batch` gives the file and the count of changes (`writes`). The batch holds the macros that the project knowledge does not have, and the uses. `otherMacros` names each macro that the project knowledge has with another body. The batch does not have the uses of that macro.
124
141
 
125
- The changes to the knowledge and the conflicts. For DXA, also the regions, the labels and the file of the listing (`listing`). For Ghidra, also the routines, the decompiled code and the file of the instructions (`instructions`).
142
+ #### Which facts the analysis replaces
126
143
 
127
- The exit status is 0, also with conflicts.
144
+ - The analysis never replaces a name or a region of the user or the LLM. Each disagreement shows in `conflicts`.
145
+ - DXA and Ghidra do not replace the facts of each other, with one exception. With coverage, a code finding replaces DXA or Ghidra data where a run executed an instruction start. Thus put all coverage maps into the project knowledge first. Then run DXA, then Ghidra.
146
+ - An analyzer can find data where a run executed an instruction start, or at a `label` or `routine` symbol of the user or the LLM. Then the script does not record that data region, and the earlier region stays. The conflict has `executed` or `knowledge`.
147
+ - An idiom region (origin `heuristic`) replaces the part of a DXA or Ghidra region where it lies. DXA and Ghidra never replace an idiom region. If they find code there, the result shows a conflict.
148
+ - An idiom table can be too long or too short. Correct its region in the project knowledge. Your region replaces it.
149
+ - A new analysis replaces the earlier facts of the same analyzer in its `coverage`, also its analyzer names. The history keeps the earlier facts.
150
+ - A fact that the user or the LLM removed does not come back. To remove a wrong fact, remove it in the project knowledge.
151
+ - An analyzer name is a second name of the address, not a symbol. Each analyzer keeps its own name at an address. The generated source does not use an analyzer name by default. To use a name in the source, give the address a name in the project knowledge.
152
+ - A Ghidra function that only branches and jumps reach is a `label`, not a `routine`.
128
153
 
129
- ## Failure and conflicts
154
+ #### Traps
130
155
 
131
- - A conflict: the analyzer finds code where the knowledge has data, or data where the knowledge has code. The knowledge stays unchanged. Find the correct answer with the emulator skill, then correct the knowledge with the c64-knowledge skill.
132
- - A conflict with the problem "another address has this name": the knowledge has the generated name at a different address. The knowledge stays unchanged.
156
+ - A conflict with the problem "another address has this name": the project knowledge has the generated name at a different address. The knowledge stays unchanged.
133
157
  - A false reference through a vector: the code jumps through a vector, for example `JMP ($0408)`, and the program writes the vector at run time. The analyzer follows the bytes that the program has there. Do these steps:
134
- 1. Find the real targets with the emulator skill, or in a coverage file.
135
- 2. If the vector bytes are also code at another time, classify them as `dual-use`.
136
- 3. Remove the false reference with `unreference`. It does not come back.
137
- 4. Add a `jump` reference from the JMP to each real target, and name each target as a routine.
138
- - `invalid-input` with a message about an entry point: no entry point is inside the program for Ghidra. Give one with `--entry`.
139
- - `stale-revision`: the knowledge changed during the analysis. The script recorded nothing. Run the analysis again.
140
- - `operation-failed` with a message about an incomplete result or listing: the analyzer did not give a complete result. The script recorded nothing. Tell the user.
141
- - `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.
142
- - `notDecompiled`: Ghidra did not decompile these routines. Each entry has the reason. If the reason says that the decompiler did not start, tell the user the remedy in the reason.
143
-
144
- ## Handoffs
145
-
146
- - Runtime behavior → emulator
147
- - Names and classifications → c64-knowledge
148
- - The meaning of a C64 hardware address → c64-memory-map
149
- - Source code from the knowledge → c64-source
150
- - Build the source → c64-assembler
158
+ 1. Find the real targets in the emulator, or in a coverage file.
159
+ 2. If the vector bytes are also code at another time, classify them as `dual-use` in the project knowledge.
160
+ 3. Remove the false reference in the project knowledge. It does not come back.
161
+ 4. Record a `jump` reference from the JMP to each real target in the project knowledge. Record each target as a routine.
162
+ - `coverageGaps` has starts. Normally its count is 0. Each start is not in `--out-instructions` and not in the generated source. Examine the code at the start. Overlapped instructions and self-modified code can cause a gap. A start in a `dual-use` region is a known overlap, for example a BIT skip, and is not in the list.
163
+ - `coverageSeeds.used` is smaller than `coverageSeeds.entryPoints`. The analysis did not use all entry points of the coverage. Give the important entry points with `--entry`, or record them as routines in the project knowledge. These come first.
164
+ - `romOnlyUsed` is smaller than `romOnlyRanges`. The analysis did not keep all RAM under ROM as data. Classify the RAM under ROM that is not code as data in the project knowledge.
165
+ - `notDecompiled` has a reason that the decompiler did not start. Give the remedy in the reason to the user.
166
+
167
+ #### Failures
168
+
169
+ - `invalid-input` about an entry point: Ghidra has no entry point in the program. Give one with `--entry`.
170
+ - `stale-revision`: the project knowledge changed during the analysis. The script recorded nothing. Run `analyze` again.
171
+ - `operation-failed` about an incomplete result or listing: the analyzer did not give a complete result. The script recorded nothing. Tell the user.
172
+ - The script did not write the listing: the error tells if the project knowledge has the findings. Correct `--out-listing` and run `analyze` again.
173
+
174
+ ---
175
+
176
+ ## Workflow
177
+
178
+ 1. Read the project knowledge of the program.
179
+ 2. Put each coverage map of the program into the project knowledge.
180
+ 3. Run `analyze --analyzer dxa` for a first pass. Read the listing for a quick view of the code.
181
+ 4. Find the important routines. Give them names in the project knowledge.
182
+ 5. Run `analyze` with Ghidra. Give the entry points with `--entry`. Give `--decompile` for the routines that you must understand.
183
+ 6. Do the action for each `hint`. Examine the candidates.
184
+ 7. Give each important routine a name in the project knowledge. Then run `analyze` again. The analyzers use the new names.
185
+
186
+ ---
187
+
188
+ ## JSON output
189
+
190
+ Each command prints one JSON envelope on one line on stdout. Notes go to stderr.
191
+
192
+ On success, the exit code is 0:
193
+
194
+ ```json
195
+ {"ok": true, "command": "<command>", "body": {}, "hint": "...", "nextAction": "..."}
196
+ ```
197
+
198
+ On failure, the exit code is 2:
199
+
200
+ ```json
201
+ {"ok": false, "command": "<command>", "code": "<code>", "error": "...", "hint": "...", "nextAction": "..."}
202
+ ```
203
+
204
+ - `body` holds the result. The section of each command gives the fields of its body.
205
+ - A check gives its verdict in `body.result`: `PASS`, `FAIL` or `INCONCLUSIVE`. The exit code is 0 for each verdict. Thus read `body.result`, not the exit code.
206
+ - `error` is one sentence. It tells what is wrong.
207
+ - `hint` tells what to do or what to examine. Read it before your next step. Some envelopes have no `hint`.
208
+ - `nextAction` is a full command line. It runs from any directory. Run it when it agrees with your task. Some envelopes have no `nextAction`.
209
+ - `code` does not change between versions. Do the action for the code:
210
+
211
+ | `code` | Action |
212
+ |---|---|
213
+ | `installation-incomplete`, `machine-unavailable` | Stop the task. Give `error` and `hint` to the user and wait for the user. Do not install, start or change a tool. Do not make a replacement for the tool, for example your own disk parser, disassembler or emulator script. |
214
+ | `invalid-input`, `not-found` | Correct the call as `hint` tells. Then run the command again. |
215
+ | `operation-failed` | Give `error` and `hint` to the user. |
216
+ | Another code | Do as `hint` tells. |
217
+
218
+ These fields have the same meaning in each body:
219
+
220
+ | Field | Meaning |
221
+ |---|---|
222
+ | `out`, `bytes`, `sha256` | A file that the command wrote: its path, its size and its SHA-256. |
223
+ | `count`, `listed`, `rest` | A list. `count` is the number of items. `listed` holds the first items, at most `--max-listed`. `rest` tells how to get the other items. |
224
+
225
+ To get the command list, run the script with no arguments. The envelope has `command: "help"`, and `body.commands` gives the name, the summary and the synopsis of each command.
226
+ To get the subjects and the flags of one command, run `<command> --help`. Then `body.subjects` and `body.options` give them.
@@ -18,7 +18,7 @@ import { importFindings, runProvenance, type ImportConflict, type ImportContext,
18
18
  import { currentRevision, listMacros, listMacroUses, listPatches, listReferences, listRegions, listSymbols } from "#src/knowledge/read.ts";
19
19
  import { DEFAULT_SPACE, SEMANTIC_ORIGINS, type Analyzer } from "#src/knowledge/schema.ts";
20
20
  import { platformNames, platformNamesFor, romUseOfProgram, type RomUse } from "#src/platform.ts";
21
- import { listed, OPTIONS, runScript, UsageError, type Call } from "#src/script.ts";
21
+ import { listed, OPTIONS, reply, runScript, UsageError, type Call } from "#src/script.ts";
22
22
  import { codeEntries, coverageConflicts, coverageEntries, coverageSeedKinds, executedStarts, imageReader, romOnlyRanges, type ImageByte } from "./lib/coverage.ts";
23
23
  import { dxaFindings, ghidraFindings, seedsFromKnowledge } from "./lib/findings.ts";
24
24
  import { findIdioms } from "./lib/idioms.ts";
@@ -27,6 +27,23 @@ import { CATALOGUE, findMacroUses, type MacroCandidate } from "./lib/macros.ts";
27
27
  import { findPitfalls, type Pitfall } from "./lib/pitfalls.ts";
28
28
  import { findPointers, type PointerCandidate } from "./lib/pointers.ts";
29
29
 
30
+ /** The rest of a cut label or function list: the knowledge has all of them as analyzer names. */
31
+ const ALL_NAMES = "a larger --max-listed. The project knowledge has all of them as analyzer names";
32
+
33
+ /**
34
+ * The result with a hint for what the agent does next: conflicts to examine,
35
+ * analyzer data over executed code to classify, and a macro batch to apply.
36
+ * The envelope adds the sentence for a cut list.
37
+ */
38
+ function withHint(body: Record<string, unknown>, conflicts: number, coverageConflicts: number, batch: { out: string; writes: number } | undefined) {
39
+ const hints: string[] = [];
40
+ if (conflicts > 0) hints.push("The analysis and the project knowledge disagree at each place in conflicts. Find the correct answer in the emulator. Then correct the project knowledge.");
41
+ if (coverageConflicts > 0) hints.push("The coverage shows executed code in each range of coverageConflicts. Classify each range as code, or as dual-use when its bytes are also data, in the project knowledge.");
42
+ if (batch !== undefined && batch.writes > 0) hints.push(`Apply the changes in ${batch.out} to the project knowledge. Then generate the source again.`);
43
+ if (hints.length === 0) return body;
44
+ return reply(body, { hint: hints.join(" ") });
45
+ }
46
+
30
47
  /** A pitfall with $ addresses and what goes wrong. */
31
48
  function showPitfall(pitfall: Pitfall) {
32
49
  return {
@@ -106,7 +123,6 @@ function macroCandidates(space: string, byteAt: ImageByte, batchPath: string | u
106
123
  ...written,
107
124
  writes: batch.length,
108
125
  ...(other.size === 0 ? {} : { otherMacros: [...other].map((name) => `The knowledge has another macro ${name}: its candidates are not in the batch.`) }),
109
- ...(batch.length === 0 ? {} : { apply: `knowledge.ts apply ${batchPath} --reason "macro uses of 6502 idioms"` }),
110
126
  },
111
127
  };
112
128
  } finally {
@@ -200,7 +216,9 @@ async function analyze(call: Call): Promise<unknown> {
200
216
 
201
217
  const revision = currentRevision(reader);
202
218
  const seeds = seedsFromKnowledge(reader, entries, space, executed.executed);
203
- // Knowledge routines and --entry first, then code regions and JMP tables, then idioms, then coverage, up to the seed bound.
219
+ // Knowledge routines and --entry first, then code regions and JMP tables, then idioms, then coverage, up to the seed bound:
220
+ // at most GHIDRA_LIMITS.entryPoints (1024) entry points for both analyzers, and for Ghidra at most
221
+ // GHIDRA_LIMITS.codeStarts (8192) coverage flow starts that are code in a routine. coverageSeeds gives what was used.
204
222
  const fromCoverage = coverage === undefined ? [] : coverageEntries(coverage, inProgram);
205
223
  const known = [...seeds.entryPoints, ...codeEntries(reader, byteAt, space)];
206
224
  // Ghidra takes the coverage as code starts without a function; DXA has one list.
@@ -286,7 +304,7 @@ async function analyze(call: Call): Promise<unknown> {
286
304
  }
287
305
  }
288
306
  const found = idiomsResult();
289
- return {
307
+ const body = {
290
308
  analyzer: "dxa",
291
309
  ...(space === DEFAULT_SPACE ? {} : { space }),
292
310
  ...found,
@@ -294,9 +312,10 @@ async function analyze(call: Call): Promise<unknown> {
294
312
  coverage: result.coverage.map((range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) })),
295
313
  ...imported,
296
314
  regions: result.regions.map((region) => ({ start: formatC64Address(region.start), end: formatC64Address(region.end), classification: region.classification })),
297
- labels: listed(result.labels, max, (label) => ({ address: formatC64Address(label.address), name: label.name }), "c64-knowledge: knowledge.ts symbols --analyzer --origin dxa"),
315
+ labels: listed(result.labels, max, (label) => ({ address: formatC64Address(label.address), name: label.name }), ALL_NAMES),
298
316
  ...(written === undefined ? {} : { listing: written }),
299
317
  };
318
+ return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, found.idioms.candidates.macros.batch);
300
319
  }
301
320
 
302
321
  const { result } = await analyzeWithGhidra({ imageKind, ...seeds, codeStarts, decompile }, bytes, localToolContext());
@@ -315,7 +334,7 @@ async function analyze(call: Call): Promise<unknown> {
315
334
  const list = instructionList(result.instructions, coverage);
316
335
  instructions = { count: list.length, ...writeReported(instructionsPath, `${JSON.stringify(list, null, 1)}\n`, { what: "--out-instructions" }) };
317
336
  }
318
- return {
337
+ const body = {
319
338
  analyzer: "ghidra",
320
339
  ...(space === DEFAULT_SPACE ? {} : { space }),
321
340
  ...(instructions === undefined ? {} : { instructions }),
@@ -324,12 +343,13 @@ async function analyze(call: Call): Promise<unknown> {
324
343
  ...(coverage === undefined ? {} : { coverageGaps: listed(gaps, max, formatC64Address, "a larger --max-listed") }),
325
344
  coverage: result.coverage.map((range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) })),
326
345
  ...imported,
327
- functions: listed(result.functions, max, (fn) => ({ entry: formatC64Address(fn.entry), name: fn.name }), "c64-knowledge: knowledge.ts symbols --analyzer --origin ghidra"),
346
+ functions: listed(result.functions, max, (fn) => ({ entry: formatC64Address(fn.entry), name: fn.name }), ALL_NAMES),
328
347
  decompilations: result.decompilations.map((item) => ({ entry: formatC64Address(item.entry), text: item.text, ...(item.truncated ? { truncated: true } : {}) })),
329
348
  ...((result.notDecompiled ?? []).length === 0
330
349
  ? {}
331
350
  : { notDecompiled: result.notDecompiled!.map((item) => ({ entry: formatC64Address(item.entry), reason: withRemedy(item.reason) })) }),
332
351
  };
352
+ return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, found.idioms.candidates.macros.batch);
333
353
  }
334
354
 
335
355
  await runScript({
@@ -348,9 +368,9 @@ await runScript({
348
368
  "max-listed": { ...OPTIONS["max-listed"], help: "list at most n labels, functions or candidates (default 50, 0 for none). The counts are always given, and the knowledge has all labels and functions" },
349
369
  "out-listing": { kind: "path", output: "file", value: "<file>", help: "dxa: write the disassembly listing to this project file" },
350
370
  "out-instructions": { kind: "path", output: "file", value: "<file>", help: "ghidra: write every instruction (address, bytes, mnemonic, mode, operand, target, executed) to this project file as JSON" },
351
- "out-macro-batch": { kind: "path", output: "file", value: "<file>", help: "write the macro candidates as an apply batch of c64-knowledge (the macros and their uses) to this project file" },
371
+ "out-macro-batch": { kind: "path", output: "file", value: "<file>", help: "write the macro candidates (the macros and their uses) to this project file as a batch of changes to the project knowledge" },
352
372
  },
353
- notes: "The program and the coverage come from the knowledge: put them in with knowledge.ts image and coverage of the c64-knowledge skill. The executed code of the coverage is seeded. Routine symbols in the knowledge are entry points too. Ghidra needs at least one entry point. DXA finds the SYS of a BASIC start by itself.",
373
+ notes: "The program and the coverage come from the project knowledge: put them into the project knowledge first. The executed code of the coverage gives entry points. Routine symbols in the knowledge are entry points too. Ghidra needs at least one entry point. DXA finds the SYS of a BASIC start by itself.",
354
374
  run: analyze,
355
375
  },
356
376
  ],