@henols/c64-re-tools 2.8.0-rc.4 → 2.8.0-rc.6
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.
- package/package.json +1 -1
- package/skills/c64-assembler/SKILL.md +1 -1
- package/skills/c64-assembler/scripts/assembler.ts +78 -24
- package/skills/c64-docs/scripts/docs.ts +31 -10
- package/skills/c64-knowledge/SKILL.md +11 -7
- package/skills/c64-knowledge/references/batches.md +2 -1
- package/skills/c64-knowledge/references/source-knowledge.md +1 -1
- package/skills/c64-knowledge/scripts/knowledge.ts +46 -29
- package/skills/c64-packer/scripts/packer.ts +9 -2
- package/skills/c64-provenance/SKILL.md +2 -2
- package/skills/c64-provenance/scripts/lib/runtime.ts +45 -10
- package/skills/c64-provenance/scripts/provenance.ts +10 -3
- package/skills/c64-source/references/loader.md +8 -7
- package/skills/c64-source/scripts/lib/loader.ts +4 -111
- package/skills/c64-source/scripts/lib/source.ts +3 -1
- package/skills/c64-source/scripts/source.ts +49 -78
- package/skills/c64-static-analysis/SKILL.md +2 -2
- package/skills/c64-static-analysis/scripts/lib/coverage.ts +56 -4
- package/skills/c64-static-analysis/scripts/lib/idioms.ts +92 -42
- package/skills/c64-static-analysis/scripts/static-analysis.ts +32 -21
- package/skills/c64-testing/SKILL.md +7 -0
- package/skills/c64-testing/scripts/lib/play.ts +8 -7
- package/skills/c64-testing/scripts/lib/recording.ts +278 -27
- package/skills/c64-testing/scripts/lib/replay.ts +9 -8
- package/skills/c64-testing/scripts/lib/runs.ts +5 -1
- package/skills/c64-testing/scripts/lib/scenario.ts +4 -0
- package/skills/c64-testing/scripts/testing.ts +30 -11
- package/skills/c64-unpacker/SKILL.md +13 -11
- package/skills/c64-unpacker/scripts/lib/loads.ts +10 -5
- package/skills/c64-unpacker/scripts/lib/machine.ts +163 -3
- package/skills/c64-unpacker/scripts/lib/stages.ts +13 -6
- package/skills/c64-unpacker/scripts/unpacker.ts +34 -15
- package/skills/emulator/SKILL.md +2 -2
- package/src/c64.ts +21 -0
- package/src/host/vice/adapter.ts +2 -1
- package/src/host/vice/chips.ts +6 -9
- package/src/host/vice/session.ts +2 -2
- package/src/host-client/image.ts +40 -4
- package/src/host-client/tools.ts +1 -1
- package/src/host-client/transfer.ts +48 -26
- package/src/host-client/vice-session.ts +15 -0
- package/src/knowledge/database.ts +72 -19
- package/src/knowledge/import.ts +32 -7
- package/src/knowledge/join.ts +50 -2
- package/src/knowledge/names.ts +2 -2
- package/src/knowledge/program.ts +103 -24
- package/src/knowledge/schema.ts +6 -0
- package/src/knowledge/start-screen.ts +57 -7
- package/src/knowledge/write.ts +20 -13
- package/src/loader.ts +101 -33
- package/src/mcp/output.ts +13 -12
- package/src/mcp/server.ts +33 -22
- package/src/mcp/tools/debug.ts +21 -24
- package/src/mcp/tools/media.ts +27 -27
- package/src/mcp/tools/memory.ts +13 -17
- package/src/mcp/tools/video.ts +10 -12
- package/src/native/c64run.ts +39 -1
- package/src/native/decompiler/analyze.ts +1 -1
- package/src/native/dxa.ts +2 -2
- package/src/native/types.ts +26 -7
- package/src/opcodes.ts +5 -0
- package/src/program-code.ts +4 -2
- package/src/project.ts +224 -71
- package/src/protocol/vice.ts +5 -3
- package/src/script.ts +60 -15
- package/{skills/c64-source/scripts/lib → src}/stage.ts +142 -11
- package/tools/c64run.c +18 -5
package/skills/emulator/SKILL.md
CHANGED
|
@@ -47,13 +47,13 @@ Read the description of a tool before you use it for the first time. It gives th
|
|
|
47
47
|
|
|
48
48
|
A result field `emulatorFlaw` names a known flaw of the emulator. Tell the user about the flaw. Do not use a result that the flaw can make wrong as a fact.
|
|
49
49
|
|
|
50
|
-
For a large result, give `out`. Write a file that is only for your work in `.c64-re-tools/local/` of the project. Git ignores that folder.
|
|
50
|
+
Give each path to a tool as an absolute path, for example `/home/me/game/build/game.prg`. A tool refuses a relative path. For a large result, give `out`. The result then gives the absolute path of the file. Write a file that is only for your work in `.c64-re-tools/local/` of the project. Git ignores that folder.
|
|
51
51
|
|
|
52
52
|
To keep a coverage run:
|
|
53
53
|
|
|
54
54
|
1. Clear the memory map with `c64_memmap` action `clear`.
|
|
55
55
|
2. Run the part of the program that you want to keep.
|
|
56
|
-
3. Read the map with `c64_memmap` action `read` and `out
|
|
56
|
+
3. Read the map with `c64_memmap` action `read` and `out`. Give the absolute path of a file in `.c64-re-tools/local/` of the project, for example `/home/me/game/.c64-re-tools/local/attract.bin`.
|
|
57
57
|
4. Add the file to the coverage of the project knowledge.
|
|
58
58
|
|
|
59
59
|
## Workflow
|
package/src/c64.ts
CHANGED
|
@@ -193,6 +193,27 @@ export function d018Offsets(d018: number): { screen: number; characters: number;
|
|
|
193
193
|
return { screen: ((d018 >> 4) & 0x0f) * 0x400, characters: ((d018 >> 1) & 0x07) * 0x800, bitmap: (d018 & 0x08) !== 0 ? 0x2000 : 0 };
|
|
194
194
|
}
|
|
195
195
|
|
|
196
|
+
/**
|
|
197
|
+
* The screen memory that the VIC-II reads, from its registers ($d000-$d02e)
|
|
198
|
+
* and the ports of CIA 2 ($dd00-$dd0f): the screen, and the bitmap in bitmap
|
|
199
|
+
* mode or else the charset.
|
|
200
|
+
*/
|
|
201
|
+
export function vicScreenMemory(vic: Uint8Array, cia2: Uint8Array): { screen: number; bitmap: number } | { screen: number; charset: number } {
|
|
202
|
+
const bank = vicBankBase(cia2[0]!, cia2[2]);
|
|
203
|
+
const offsets = d018Offsets(vic[0x18]!);
|
|
204
|
+
return { screen: bank + offsets.screen, ...((vic[0x11]! & 0x20) !== 0 ? { bitmap: bank + offsets.bitmap } : { charset: bank + offsets.characters }) };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** The address of the pointer of a sprite (0-7): the last 8 bytes of the 1 KiB of screen memory. */
|
|
208
|
+
export function spritePointer(screen: number, sprite: number): number {
|
|
209
|
+
return screen + 0x3f8 + sprite;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** The address of the 64 data bytes of a sprite, from its pointer value and the bank that the ports of CIA 2 ($dd00-$dd0f) select. */
|
|
213
|
+
export function spriteData(cia2: Uint8Array, pointer: number): number {
|
|
214
|
+
return vicBankBase(cia2[0]!, cia2[2]) + pointer * 64;
|
|
215
|
+
}
|
|
216
|
+
|
|
196
217
|
/**
|
|
197
218
|
* Converts text to the PETSCII bytes the C64 keyboard types after a reset
|
|
198
219
|
* (upper case/graphics mode). Letters of either case type the unshifted key,
|
package/src/host/vice/adapter.ts
CHANGED
|
@@ -64,7 +64,8 @@ export function conditionExpression(condition: Condition, space: Space): string
|
|
|
64
64
|
"A memory target or a memory condition tests only space c64 memory. For the drive, use a watchpoint in space drive8, or a c64_run_until address target in space drive8.",
|
|
65
65
|
);
|
|
66
66
|
}
|
|
67
|
-
|
|
67
|
+
const byte = `@${condition.view}:${formatC64Address(condition.address)}`;
|
|
68
|
+
return `(${condition.mask === undefined ? byte : `(${byte} & ${formatC64Byte(condition.mask)})`} ${operator(condition.operator)} ${formatC64Byte(condition.value)})`;
|
|
68
69
|
}
|
|
69
70
|
case "raster": {
|
|
70
71
|
const line = `(RL == $${condition.line.toString(16)})`;
|
package/src/host/vice/chips.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// bank without side effects; the SID's write-only registers read back as
|
|
4
4
|
// last written.
|
|
5
5
|
|
|
6
|
-
import {
|
|
6
|
+
import { spriteData, vicScreenMemory } from "../../c64.ts";
|
|
7
7
|
import type { CiaState, SidState, SpriteState, ViciiMode, ViciiState } from "../../protocol/vice.ts";
|
|
8
8
|
|
|
9
9
|
export function viciiMode(d011: number, d016: number): ViciiMode {
|
|
@@ -20,15 +20,12 @@ export function viciiMode(d011: number, d016: number): ViciiMode {
|
|
|
20
20
|
export function decodeVicii(vic: Uint8Array, cia2: Uint8Array): ViciiState {
|
|
21
21
|
const d011 = vic[0x11]!;
|
|
22
22
|
const d016 = vic[0x16]!;
|
|
23
|
-
const
|
|
24
|
-
const mode = viciiMode(d011, d016);
|
|
25
|
-
const base = vicBankBase(cia2[0x00]!, cia2[0x02]!);
|
|
26
|
-
const bitmap = mode === "bitmap" || mode === "multicolor-bitmap";
|
|
23
|
+
const shown = vicScreenMemory(vic, cia2);
|
|
27
24
|
return {
|
|
28
25
|
rasterLine: ((d011 & 0x80) << 1) | vic[0x12]!,
|
|
29
|
-
mode,
|
|
30
|
-
screenAddress:
|
|
31
|
-
graphicsAddress:
|
|
26
|
+
mode: viciiMode(d011, d016),
|
|
27
|
+
screenAddress: shown.screen,
|
|
28
|
+
graphicsAddress: "bitmap" in shown ? shown.bitmap : shown.charset,
|
|
32
29
|
scrollX: d016 & 0x07,
|
|
33
30
|
scrollY: d011 & 0x07,
|
|
34
31
|
borderColor: vic[0x20]! & 0x0f,
|
|
@@ -49,7 +46,7 @@ export function decodeSprite(index: number, vic: Uint8Array, cia2: Uint8Array, p
|
|
|
49
46
|
expandX: bit(0x1d),
|
|
50
47
|
expandY: bit(0x17),
|
|
51
48
|
behindBackground: bit(0x1b),
|
|
52
|
-
dataAddress:
|
|
49
|
+
dataAddress: spriteData(cia2, pointers[index]!),
|
|
53
50
|
};
|
|
54
51
|
}
|
|
55
52
|
|
package/src/host/vice/session.ts
CHANGED
|
@@ -11,7 +11,7 @@ import { tmpdir } from "node:os";
|
|
|
11
11
|
import { join } from "node:path";
|
|
12
12
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
13
13
|
|
|
14
|
-
import { formatC64Address, instructionLength } from "../../c64.ts";
|
|
14
|
+
import { formatC64Address, instructionLength, spritePointer } from "../../c64.ts";
|
|
15
15
|
import { matrixRows } from "../../c64-keys.ts";
|
|
16
16
|
import { encodePng, type IndexedFrame } from "../../graphics.ts";
|
|
17
17
|
import { accessedValue, instructionText, JAM_OPCODES, OPCODES, operandAddress } from "../../opcodes.ts";
|
|
@@ -1325,7 +1325,7 @@ export class ViceSession implements ViceSessionHandle {
|
|
|
1325
1325
|
const cia2 = await this.#machine.readIo(0xdd00, 0x10);
|
|
1326
1326
|
// Sprite pointers sit in the RAM the VIC-II reads, at the end of screen memory.
|
|
1327
1327
|
const screen = decodeVicii(vic, cia2).screenAddress;
|
|
1328
|
-
const pointers = Buffer.from(await this.#machine.readMemory({ address: screen
|
|
1328
|
+
const pointers = Buffer.from(await this.#machine.readMemory({ address: spritePointer(screen, 0), size: 8, space: "c64", view: "ram" }), "hex");
|
|
1329
1329
|
const wanted = indexes.length === 0 ? [0, 1, 2, 3, 4, 5, 6, 7] : indexes;
|
|
1330
1330
|
return wanted.map((index) => decodeSprite(index, vic, cia2, pointers));
|
|
1331
1331
|
}
|
package/src/host-client/image.ts
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
// An image.json of the c64-unpacker skill (a 64 KiB memory and its segments)
|
|
2
2
|
// or a PRG, read from the project to put it into the knowledge.
|
|
3
3
|
|
|
4
|
-
import {
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
5
6
|
|
|
6
7
|
import { isRefusal, Refusal } from "../errors.ts";
|
|
7
8
|
import { formatC64Address, prgRange } from "../c64.ts";
|
|
8
9
|
import { readEntryState, type EntryState } from "./entry-state.ts";
|
|
9
10
|
import { isObject } from "../protocol/messages.ts";
|
|
11
|
+
import { projectRelative } from "../project.ts";
|
|
10
12
|
import { readProjectFile, readProjectJson } from "./transfer.ts";
|
|
11
13
|
|
|
12
14
|
export interface Image {
|
|
@@ -20,6 +22,35 @@ export interface Image {
|
|
|
20
22
|
state?: EntryState;
|
|
21
23
|
/** The stages of the capture in image.json, as the unpacker wrote them. */
|
|
22
24
|
stages?: Array<Record<string, unknown>>;
|
|
25
|
+
/** The PRG that the capture in image.json ran, as the project path that the capture got, and the SHA-256 of that file. */
|
|
26
|
+
program?: { file: string; sha256: string };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The program file that the capture of the image.json at `path` ran, as a
|
|
31
|
+
* citation of the project: its path in one spelling and its SHA-256. Refused
|
|
32
|
+
* when the project has no such file now, or when its bytes are not the bytes
|
|
33
|
+
* that the capture ran: the citation would not be true.
|
|
34
|
+
*/
|
|
35
|
+
export function checkedProgramCitation(path: string, program: { file: string; sha256: string }): { file: string; sha256: string } {
|
|
36
|
+
const remedy = "Capture the program again from its file in this project, then give the new image.json.";
|
|
37
|
+
let file: string;
|
|
38
|
+
try {
|
|
39
|
+
file = projectRelative(program.file);
|
|
40
|
+
} catch {
|
|
41
|
+
throw new Refusal("invalid-input", `${path} names the program file ${program.file}, which is not a path in this project. ${remedy}`);
|
|
42
|
+
}
|
|
43
|
+
let bytes: Uint8Array;
|
|
44
|
+
try {
|
|
45
|
+
bytes = readProjectFile(file).bytes;
|
|
46
|
+
} catch (error) {
|
|
47
|
+
if (isRefusal(error) && error.code === "not-found") throw new Refusal("not-found", `${path} names the program file ${file}, and the project has no file there. ${remedy}`);
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
if (createHash("sha256").update(bytes).digest("hex") !== program.sha256) {
|
|
51
|
+
throw new Refusal("conflict", `The program file ${file} changed after the capture in ${path}: its bytes are not the bytes that the capture ran. ${remedy}`);
|
|
52
|
+
}
|
|
53
|
+
return { file, sha256: program.sha256 };
|
|
23
54
|
}
|
|
24
55
|
|
|
25
56
|
/** The kinds of media files that are no PRG, by extension. */
|
|
@@ -96,14 +127,19 @@ export function readImage(path: string): Image {
|
|
|
96
127
|
if (segment.end < segment.start) fail(`the segment at ${formatC64Address(segment.start)} ends before it starts`);
|
|
97
128
|
if (index > 0 && segment.start <= segments[index - 1]!.end) fail(`the segments at ${formatC64Address(segments[index - 1]!.start)} and ${formatC64Address(segment.start)} overlap`);
|
|
98
129
|
});
|
|
99
|
-
const directory =
|
|
100
|
-
const memory = readProjectFile(
|
|
130
|
+
const directory = dirname(path);
|
|
131
|
+
const memory = readProjectFile(join(directory, manifest.image as string)).bytes;
|
|
101
132
|
if (memory.length !== 0x10000) fail(`its image has ${memory.length} bytes, not 65536`);
|
|
102
133
|
const image: Image = { segments, byteAt: (at) => memory[at]!, memory };
|
|
103
|
-
const state = entryStateNextTo(
|
|
134
|
+
const state = entryStateNextTo(join(directory, "entry_state.json"));
|
|
104
135
|
if (state !== undefined) image.state = state;
|
|
105
136
|
if (manifest.entry !== undefined) image.entry = address(manifest.entry, "entry");
|
|
106
137
|
if (Array.isArray(manifest.stages)) image.stages = manifest.stages.map((stage, index) => (isObject(stage) ? stage : fail(`stage ${index + 1} is not an object`)));
|
|
138
|
+
if (manifest.program !== undefined) {
|
|
139
|
+
const program = isObject(manifest.program) ? manifest.program : fail("its program is not an object");
|
|
140
|
+
if (typeof program.file !== "string" || program.file === "" || typeof program.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(program.sha256)) fail("its program has no file and SHA-256");
|
|
141
|
+
image.program = { file: program.file as string, sha256: program.sha256 as string };
|
|
142
|
+
}
|
|
107
143
|
return image;
|
|
108
144
|
}
|
|
109
145
|
|
package/src/host-client/tools.ts
CHANGED
|
@@ -87,5 +87,5 @@ export async function decodeBasic(request: { program: string }, options: ToolCal
|
|
|
87
87
|
/** Skill scripts see failures, value guards and wire limits through the host-client, never the private protocol module. */
|
|
88
88
|
export { isInteger, isObject, WireFailure } from "../protocol/messages.ts";
|
|
89
89
|
export { DISK_BLOCK_BYTES, DISK_IMAGE_TYPES, MAX_DISK_SECTORS } from "../protocol/tools.ts";
|
|
90
|
-
export { MAX_BASELINES, MAX_EXECUTION_COUNT, MAX_MASK_RECTANGLES, MAX_MEMORY_READ, MAX_MEMORY_WRITE, maskCoversFrame } from "../protocol/vice.ts";
|
|
90
|
+
export { MAX_BASELINES, MAX_EXECUTION_COUNT, MAX_MASK_RECTANGLES, MAX_MEMORY_READ, MAX_MEMORY_WRITE, MAX_WATCH_SIZE, maskCoversFrame } from "../protocol/vice.ts";
|
|
91
91
|
export { MAX_TRACE_FRAMES, MAX_TRACE_HITS, MAX_TRACE_POINTS, TRACE_KINDS, type TraceHit, type TraceKind } from "../protocol/vice.ts";
|
|
@@ -5,24 +5,34 @@ import { createHash } from "node:crypto";
|
|
|
5
5
|
import { lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
|
|
6
6
|
import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
7
7
|
|
|
8
|
-
import { checkOutputPath, isInside, projectRoot, readGroup,
|
|
8
|
+
import { checkOutputPath, fileProject, isInside, projectRoot, readGroup, realLocation, resolveProjectFile, resolveReadFile, writeProblem } from "../project.ts";
|
|
9
9
|
import { isRefusal } from "../errors.ts";
|
|
10
10
|
import { MAX_ATTACHMENT_BYTES } from "../protocol/framing.ts";
|
|
11
11
|
import { WireFailure } from "../protocol/messages.ts";
|
|
12
12
|
import { MAX_TREE_FILES, type SourceTree } from "../protocol/tools.ts";
|
|
13
13
|
|
|
14
|
+
/** A file that an MCP tool reads or writes: its absolute path, and its project. */
|
|
15
|
+
export interface ToolFile {
|
|
16
|
+
file: string;
|
|
17
|
+
root: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
14
20
|
/**
|
|
15
|
-
* The
|
|
16
|
-
*
|
|
17
|
-
*
|
|
21
|
+
* The file of a path input of an MCP tool, with the project that the project
|
|
22
|
+
* rules find for it (fileProject). Refuses a relative path: the agent cannot
|
|
23
|
+
* see the working folder of the MCP server.
|
|
18
24
|
*/
|
|
19
|
-
export function
|
|
20
|
-
|
|
25
|
+
export function toolFile(path: string, access: "read" | "write"): ToolFile {
|
|
26
|
+
if (!isAbsolute(path)) throw new WireFailure("invalid-input", `${path} is relative. Give the absolute path of the file.`);
|
|
27
|
+
const file = resolve(path);
|
|
28
|
+
return { file, root: fileProject(file, access) };
|
|
21
29
|
}
|
|
22
30
|
|
|
23
|
-
/**
|
|
24
|
-
export function checkOut(path: string
|
|
25
|
-
|
|
31
|
+
/** The file of an MCP `out`, checked before the tool does any work with the checks that every --out of a script gets. */
|
|
32
|
+
export function checkOut(path: string): ToolFile {
|
|
33
|
+
const target = toolFile(path, "write");
|
|
34
|
+
checkOutputPath(target.file, "file", { root: target.root, what: "out" });
|
|
35
|
+
return target;
|
|
26
36
|
}
|
|
27
37
|
|
|
28
38
|
/** The project folder of this process (--project or the project lookup), or a WireFailure. */
|
|
@@ -48,11 +58,12 @@ export function readProjectFile(path: string, options: { root?: string; what?: s
|
|
|
48
58
|
real = resolveReadFile(path, root);
|
|
49
59
|
} catch (error) {
|
|
50
60
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
51
|
-
throw new WireFailure("not-found", `${options.what === undefined ? "" : `${options.what}: `}There is no file at ${path} in the project folder.`);
|
|
61
|
+
throw new WireFailure("not-found", `${options.what === undefined ? "" : `${options.what}: `}There is no file at ${path}${isAbsolute(path) ? "" : " in the project folder"}.`);
|
|
52
62
|
}
|
|
53
63
|
if (isRefusal(error) && error.code === "invalid-input") {
|
|
54
|
-
const
|
|
55
|
-
|
|
64
|
+
const group = readGroup(root);
|
|
65
|
+
const where = group === undefined ? `the project folder ${root}` : `the group folder ${group.root} of the project`;
|
|
66
|
+
throw new WireFailure("invalid-input", `${options.what === undefined ? "" : `${options.what}: `}${path} leads out of ${where}. Give a path that stays inside it.`);
|
|
56
67
|
}
|
|
57
68
|
throw error;
|
|
58
69
|
}
|
|
@@ -94,7 +105,7 @@ export function writeRefusal(error: unknown, path: string, what?: string): WireF
|
|
|
94
105
|
*/
|
|
95
106
|
export function writeProjectFile(path: string, bytes: Uint8Array, options: { root?: string; what?: string } = {}): void {
|
|
96
107
|
const root = options.root ?? currentProject();
|
|
97
|
-
const refuse = () => new WireFailure("invalid-input", `${options.what
|
|
108
|
+
const refuse = () => new WireFailure("invalid-input", `${options.what === undefined ? "" : `${options.what}: `}${path} leads out of the project folder ${root}. Give a path that stays inside it.`);
|
|
98
109
|
let file: string;
|
|
99
110
|
try {
|
|
100
111
|
file = checkOutputPath(path, "file", { root, ...(options.what === undefined ? {} : { what: options.what }) });
|
|
@@ -148,7 +159,7 @@ export function readProjectTree(path: string, options: { root?: string } = {}):
|
|
|
148
159
|
sourceRoot = resolveProjectFile(path, projectRootPath);
|
|
149
160
|
} catch (error) {
|
|
150
161
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") throw new WireFailure("not-found", `There is no directory ${path} in the project folder.`);
|
|
151
|
-
if (isRefusal(error) && error.code === "invalid-input") throw new WireFailure("invalid-input", `${path}
|
|
162
|
+
if (isRefusal(error) && error.code === "invalid-input") throw new WireFailure("invalid-input", `${path} leads out of the project folder ${projectRootPath}. Give a directory inside it, relative to the project folder or absolute.`);
|
|
152
163
|
throw error;
|
|
153
164
|
}
|
|
154
165
|
if (!statSync(sourceRoot).isDirectory()) throw new WireFailure("invalid-input", `${path} is not a directory.`);
|
|
@@ -196,30 +207,41 @@ const posixRelative = (from: string, to: string) => relative(from, to).split(sep
|
|
|
196
207
|
/**
|
|
197
208
|
* Reads a source root and its include folders as one source tree for
|
|
198
209
|
* staging, as readProjectTree does. An include folder is relative to the
|
|
199
|
-
* source root and can be anywhere in the project folder. The
|
|
200
|
-
* the lowest folder that holds all these folders, but it holds
|
|
201
|
-
* files. `sourceDir` is the source root in the tree, "" at its
|
|
202
|
-
* `includeDirs` are the include folders relative to the source root.
|
|
210
|
+
* source root, or absolute, and can be anywhere in the project folder. The
|
|
211
|
+
* tree starts at the lowest folder that holds all these folders, but it holds
|
|
212
|
+
* only their files. `sourceDir` is the source root in the tree, "" at its
|
|
213
|
+
* top, and `includeDirs` are the include folders relative to the source root.
|
|
203
214
|
*/
|
|
204
215
|
export function readSourceTree(sourceRoot: string, includes: readonly string[], options: { root?: string } = {}): { files: SourceTree; contents: Buffer[]; sourceDir: string; includeDirs: string[] } {
|
|
205
216
|
const projectRootPath = options.root ?? currentProject();
|
|
206
217
|
const sourceTree = readProjectTree(sourceRoot, { root: projectRootPath });
|
|
207
218
|
const project = realpathSync(projectRootPath);
|
|
208
219
|
const source = resolveProjectFile(sourceRoot, projectRootPath);
|
|
209
|
-
const missing = (folder: string) => new WireFailure("not-found", `There is no include folder ${folder} with files in the project folder. Give an include folder relative to the source root
|
|
220
|
+
const missing = (folder: string) => new WireFailure("not-found", `There is no include folder ${folder} with files in the project folder. Give an include folder inside the project folder, relative to the source root or absolute.`);
|
|
210
221
|
const folders = includes.map((folder) => {
|
|
211
|
-
const outside = new WireFailure("invalid-input", `The include folder ${folder} is outside the project folder. Give an include folder relative to the source root
|
|
212
|
-
if (isAbsolute(folder)) throw outside;
|
|
222
|
+
const outside = new WireFailure("invalid-input", `The include folder ${folder} is outside the project folder. Give an include folder inside the project folder, relative to the source root or absolute.`);
|
|
213
223
|
const candidate = resolve(source, folder);
|
|
214
|
-
|
|
224
|
+
// A path through a file (ENOTDIR) or to nothing names no folder: it is missing. Another error of the file system is a refusal.
|
|
225
|
+
const refused = (error: unknown) => {
|
|
226
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
227
|
+
if (code === "ENOTDIR" || code === "ENOENT") return missing(folder);
|
|
228
|
+
return new WireFailure("invalid-input", `The include folder ${folder} cannot be read: the file system refuses it (${code ?? "an error"}). Give an include folder inside the project folder that you can read.`);
|
|
229
|
+
};
|
|
230
|
+
// The real location decides, also of a folder that does not exist: an absolute folder can reach the project folder through a link, for example /tmp to /private/tmp.
|
|
215
231
|
let real: string;
|
|
216
232
|
try {
|
|
217
|
-
real =
|
|
218
|
-
} catch {
|
|
219
|
-
throw
|
|
233
|
+
real = realLocation(candidate);
|
|
234
|
+
} catch (error) {
|
|
235
|
+
throw refused(error);
|
|
220
236
|
}
|
|
221
237
|
if (!isInside(project, real)) throw outside;
|
|
222
|
-
|
|
238
|
+
let isFolder: boolean;
|
|
239
|
+
try {
|
|
240
|
+
isFolder = statSync(real, { throwIfNoEntry: false })?.isDirectory() === true;
|
|
241
|
+
} catch (error) {
|
|
242
|
+
throw refused(error);
|
|
243
|
+
}
|
|
244
|
+
if (!isFolder) throw missing(folder);
|
|
223
245
|
return { folder, real };
|
|
224
246
|
});
|
|
225
247
|
let top = source;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// The long-lived Host Runtime connection an MCP process owns: one connection,
|
|
2
2
|
// one VICE. Exposes C64-domain operations only.
|
|
3
3
|
|
|
4
|
+
import { isRefusal } from "../errors.ts";
|
|
4
5
|
import { ProtocolError, WireFailure, type VideoStandard } from "../protocol/messages.ts";
|
|
5
6
|
import { MAX_MEMORY_READ, traceHitsFromAttachment, validateViceResult, type TraceResult, type Breakpoint, type BreakpointParams, type PointRemoved, type Watchpoint, type WatchpointParams, type ExecutionParams, type ExecutionResult, type JoystickState, type MachineStatus, type PressResult, type MemmapRange, type MemoryWriteParams, type ProfileEntry, type RegisterValues, type ResetMode, type RunState, type RunTarget, type RunUntilResult, type MemoryReadParams, type MemoryReadResult, type Registers, type Space, type ViceOperation, type ViceOperations } from "../protocol/vice.ts";
|
|
6
7
|
import type { KeyTap } from "../c64-keys.ts";
|
|
@@ -340,6 +341,20 @@ function projectFile(params: { path: string; root?: string }) {
|
|
|
340
341
|
return readProjectFile(params.path, params.root === undefined ? { what: "path" } : { root: params.root, what: "path" });
|
|
341
342
|
}
|
|
342
343
|
|
|
344
|
+
/**
|
|
345
|
+
* The opcode of the last instruction in the CPU history of the C64: at a stop at a watchpoint, the instruction that made
|
|
346
|
+
* the access. Undefined when the session gives no history (after a JAM, or none since a restore).
|
|
347
|
+
*/
|
|
348
|
+
export async function lastOpcode(client: Pick<ViceSessionClient, "cpuHistory">): Promise<number | undefined> {
|
|
349
|
+
try {
|
|
350
|
+
const [entry] = (await client.cpuHistory({ limit: 1, space: "c64" })).entries;
|
|
351
|
+
return entry === undefined ? undefined : Buffer.from(entry.bytes, "hex")[0];
|
|
352
|
+
} catch (error) {
|
|
353
|
+
if (isRefusal(error) && error.code === "operation-failed") return undefined;
|
|
354
|
+
throw error;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
343
358
|
/** Reads `size` bytes from `address` of a space (the C64 when not given) in reads of at most 4 KiB, in one view: up to all 64 KiB. */
|
|
344
359
|
export async function readMemoryInParts(client: Pick<ViceSessionClient, "memoryRead">, address: number, size: number, view: "cpu" | "ram", space: Space = "c64"): Promise<Buffer> {
|
|
345
360
|
const parts: Buffer[] = [];
|
|
@@ -116,6 +116,16 @@ function freshen(db: DatabaseSync, root: string): void {
|
|
|
116
116
|
/** The project of each index opened for a write: its writes go to the text too. */
|
|
117
117
|
const projects = new WeakMap<DatabaseSync, string>();
|
|
118
118
|
|
|
119
|
+
/** Makes the index fresh from the text. The write lock is taken only when the text changed: a read does not wait for a long write that keeps the index fresh. */
|
|
120
|
+
function refreshIndex(root: string): void {
|
|
121
|
+
const index = openIndex(root);
|
|
122
|
+
try {
|
|
123
|
+
if (!sameHashes(currentHashes(root), storedHashes(index))) transaction(index, () => freshen(index, root));
|
|
124
|
+
} finally {
|
|
125
|
+
index.close();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
119
129
|
/**
|
|
120
130
|
* Opens the project's knowledge read-only, made fresh from the text first. A
|
|
121
131
|
* read never changes the knowledge. Returns undefined when the project has no
|
|
@@ -123,13 +133,7 @@ const projects = new WeakMap<DatabaseSync, string>();
|
|
|
123
133
|
*/
|
|
124
134
|
export function openForRead(root: string = projectRoot()): DatabaseSync | undefined {
|
|
125
135
|
if (!existsSync(textPath(root))) return undefined;
|
|
126
|
-
|
|
127
|
-
try {
|
|
128
|
-
// The lock is taken only when the text changed: a read does not wait for a long write that keeps the index fresh.
|
|
129
|
-
if (!sameHashes(currentHashes(root), storedHashes(index))) transaction(index, () => freshen(index, root));
|
|
130
|
-
} finally {
|
|
131
|
-
index.close();
|
|
132
|
-
}
|
|
136
|
+
refreshIndex(root);
|
|
133
137
|
return open(indexPath(root), true);
|
|
134
138
|
}
|
|
135
139
|
|
|
@@ -164,23 +168,72 @@ export function openForWrite(root: string = projectRoot()): DatabaseSync {
|
|
|
164
168
|
return db;
|
|
165
169
|
}
|
|
166
170
|
|
|
171
|
+
/** An empty database in memory with the schema of this build. */
|
|
172
|
+
function memoryDatabase(): DatabaseSync {
|
|
173
|
+
const db = new DatabaseSync(":memory:");
|
|
174
|
+
try {
|
|
175
|
+
configure(db);
|
|
176
|
+
ensureSchema(db);
|
|
177
|
+
} catch (error) {
|
|
178
|
+
db.close();
|
|
179
|
+
throw error;
|
|
180
|
+
}
|
|
181
|
+
return db;
|
|
182
|
+
}
|
|
183
|
+
|
|
167
184
|
/**
|
|
168
|
-
*
|
|
169
|
-
*
|
|
170
|
-
* write
|
|
171
|
-
* nothing outside the database it gets.
|
|
185
|
+
* A copy in memory of the index of the project, made fresh from the text
|
|
186
|
+
* first. The copy reads the index in one read transaction: it takes no write
|
|
187
|
+
* lock, so a write of another process does not wait for the work on the copy.
|
|
172
188
|
*/
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
189
|
+
function memoryCopy(root: string): DatabaseSync {
|
|
190
|
+
refreshIndex(root);
|
|
191
|
+
const db = memoryDatabase();
|
|
192
|
+
try {
|
|
193
|
+
db.prepare("ATTACH DATABASE ? AS project").run(indexPath(root));
|
|
194
|
+
// The tables come in the order of the index: the foreign keys are checked by the index, not again here.
|
|
195
|
+
db.exec("PRAGMA foreign_keys = OFF; BEGIN");
|
|
176
196
|
try {
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
}
|
|
181
|
-
|
|
197
|
+
const tables = db.prepare("SELECT name FROM project.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'").all() as Array<{ name: string }>;
|
|
198
|
+
for (const { name } of tables) db.exec(`DELETE FROM main."${name}"; INSERT INTO main."${name}" SELECT * FROM project."${name}"`);
|
|
199
|
+
db.exec("COMMIT");
|
|
200
|
+
} catch (error) {
|
|
201
|
+
db.exec("ROLLBACK");
|
|
202
|
+
throw error;
|
|
182
203
|
}
|
|
204
|
+
db.exec("DETACH DATABASE project; PRAGMA foreign_keys = ON");
|
|
205
|
+
} catch (error) {
|
|
206
|
+
db.close();
|
|
207
|
+
throw error;
|
|
208
|
+
}
|
|
209
|
+
return db;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Runs `work` on a copy in memory of the project's knowledge, and closes it:
|
|
214
|
+
* every check of a write runs, and a write sees the writes before it, but
|
|
215
|
+
* neither the knowledge text nor the index changes, and the index is not
|
|
216
|
+
* locked while `work` runs. Without knowledge text, `work` runs on an empty
|
|
217
|
+
* database in memory, and the trial creates nothing. `work` must change
|
|
218
|
+
* nothing outside the database it gets.
|
|
219
|
+
*/
|
|
220
|
+
export function withTrial<T>(work: (db: DatabaseSync) => T, root: string = projectRoot()): T {
|
|
221
|
+
const db = existsSync(textPath(root)) ? memoryCopy(root) : memoryDatabase();
|
|
222
|
+
try {
|
|
223
|
+
return work(db);
|
|
224
|
+
} finally {
|
|
225
|
+
db.close();
|
|
183
226
|
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Runs one write on the project's knowledge and closes it. When the project
|
|
231
|
+
* has no knowledge yet, `work` first runs as a trial: a write that is refused
|
|
232
|
+
* there creates no .c64-re-tools/. `work` must change nothing outside the
|
|
233
|
+
* database it gets.
|
|
234
|
+
*/
|
|
235
|
+
export function withWrite<T>(work: (db: DatabaseSync) => T, root: string = projectRoot()): T {
|
|
236
|
+
if (!existsSync(textPath(root))) withTrial(work, root);
|
|
184
237
|
const db = openForWrite(root);
|
|
185
238
|
try {
|
|
186
239
|
return work(db);
|
package/src/knowledge/import.ts
CHANGED
|
@@ -95,7 +95,10 @@ export interface ImportResult {
|
|
|
95
95
|
/** The new revision, or null when nothing changed. */
|
|
96
96
|
revision: string | null;
|
|
97
97
|
/** The analyzer names. */
|
|
98
|
-
names: ImportCounts
|
|
98
|
+
names: ImportCounts & {
|
|
99
|
+
/** Data names at an executed instruction start that the knowledge names as code: no conflict. */
|
|
100
|
+
onExecutedCode: number;
|
|
101
|
+
};
|
|
99
102
|
regions: ImportCounts & {
|
|
100
103
|
/** Data findings on executed code that the knowledge holds as code: not written, and no conflict. */
|
|
101
104
|
onExecutedCode: number;
|
|
@@ -183,7 +186,10 @@ function ownNames(db: DatabaseSync, analyzer: Analyzer, range: AddressRange, spa
|
|
|
183
186
|
* one for each analyzer at an address, and never to symbols. A run replaces
|
|
184
187
|
* the analyzer's own names in its coverage. A name that the user or the LLM
|
|
185
188
|
* gave the address already is not kept twice. A code or data kind that
|
|
186
|
-
* disagrees with the name of the address is a conflict
|
|
189
|
+
* disagrees with the name of the address is a conflict, except on dual-use
|
|
190
|
+
* bytes: they are code at one time and data at another. A data name at an
|
|
191
|
+
* executed instruction start that the knowledge names as code leaves nothing
|
|
192
|
+
* to decide: it is only counted and not recorded, as a data region there.
|
|
187
193
|
*/
|
|
188
194
|
function importNames(db: DatabaseSync, change: Change, findings: NormalizedFindings, coverage: AddressRange[], result: ImportResult): void {
|
|
189
195
|
const { analyzer } = findings;
|
|
@@ -191,11 +197,28 @@ function importNames(db: DatabaseSync, change: Change, findings: NormalizedFindi
|
|
|
191
197
|
const wanted = new Map(findings.symbols.map((symbol) => [symbol.address, symbol]));
|
|
192
198
|
const settled = new Set<number>();
|
|
193
199
|
const replaced = new Set<number>();
|
|
200
|
+
// What the knowledge has at each finding, read once: the name of the user or the LLM, and whether a dual-use region holds the address.
|
|
201
|
+
// The import changes neither of them. A data name on executed code that the knowledge names as code is only counted, and not recorded.
|
|
202
|
+
const at = new Map(
|
|
203
|
+
findings.symbols.map((finding) => {
|
|
204
|
+
const current = symbolAt(db, finding.address, space);
|
|
205
|
+
const dualUse = current !== undefined && isCode(current.kind) !== isCode(finding.kind) && regionsOverlapping(db, finding.address, finding.address, space).some((row) => row.type === "dual-use");
|
|
206
|
+
const counted = current !== undefined && isCode(current.kind) && !isCode(finding.kind) && !dualUse && findings.executed?.(finding.address) === true;
|
|
207
|
+
return [finding.address, { current, conflict: current !== undefined && isCode(current.kind) !== isCode(finding.kind) && !dualUse && !counted, counted }];
|
|
208
|
+
}),
|
|
209
|
+
);
|
|
194
210
|
for (const range of coverage) {
|
|
195
211
|
for (const own of ownNames(db, analyzer, range, space)) {
|
|
196
212
|
const finding = wanted.get(own.address);
|
|
213
|
+
const known = finding === undefined ? undefined : at.get(finding.address)!;
|
|
214
|
+
// The analyzer's own name where the finding is only counted leaves, also when it is the same name.
|
|
215
|
+
if (known?.counted === true) {
|
|
216
|
+
change.close("analyzer_names", "space = ? AND address = ? AND origin = ?", space, own.address, analyzer);
|
|
217
|
+
result.names.retired++;
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
197
220
|
// A seeded run gives back the name of the user or the LLM: the analyzer's own name there stays.
|
|
198
|
-
const echo = finding !== undefined &&
|
|
221
|
+
const echo = finding !== undefined && known?.current?.name === finding.name;
|
|
199
222
|
if (echo || (finding !== undefined && finding.name === own.name && finding.kind === own.kind)) {
|
|
200
223
|
settled.add(own.address);
|
|
201
224
|
result.names.unchanged++;
|
|
@@ -207,10 +230,12 @@ function importNames(db: DatabaseSync, change: Change, findings: NormalizedFindi
|
|
|
207
230
|
}
|
|
208
231
|
}
|
|
209
232
|
for (const finding of findings.symbols) {
|
|
210
|
-
const current =
|
|
211
|
-
if (
|
|
212
|
-
result.
|
|
233
|
+
const { current, conflict, counted } = at.get(finding.address)!;
|
|
234
|
+
if (counted) {
|
|
235
|
+
result.names.onExecutedCode++;
|
|
236
|
+
continue;
|
|
213
237
|
}
|
|
238
|
+
if (conflict) result.conflicts.push({ category: "symbol", address: finding.address, reason: "kind", current: current!, finding: { name: finding.name, kind: finding.kind } });
|
|
214
239
|
if (settled.has(finding.address)) continue;
|
|
215
240
|
if (current?.name === finding.name) {
|
|
216
241
|
// The analyzer only gives back the name of the address.
|
|
@@ -462,7 +487,7 @@ export function importFindings(db: DatabaseSync, findings: NormalizedFindings, c
|
|
|
462
487
|
const coverage = validateFindings(findings);
|
|
463
488
|
return transaction(db, () => {
|
|
464
489
|
const change = new Change(db, { origin: findings.analyzer, ...context }, `import-${findings.analyzer}`);
|
|
465
|
-
const result: ImportResult = { revision: null, names: counts(), regions: { ...counts(), onExecutedCode: 0 }, references: { ...counts(), inData: 0 }, conflicts: [] };
|
|
490
|
+
const result: ImportResult = { revision: null, names: { ...counts(), onExecutedCode: 0 }, regions: { ...counts(), onExecutedCode: 0 }, references: { ...counts(), inData: 0 }, conflicts: [] };
|
|
466
491
|
importNames(db, change, findings, coverage, result);
|
|
467
492
|
importRegions(db, change, findings, coverage, result);
|
|
468
493
|
importReferences(db, change, findings, coverage, result);
|