@henols/c64-re-tools 2.8.0-rc.5 → 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 +4 -3
- package/skills/c64-knowledge/scripts/knowledge.ts +31 -12
- package/skills/c64-packer/scripts/packer.ts +9 -2
- package/skills/c64-provenance/SKILL.md +1 -1
- package/skills/c64-provenance/scripts/lib/runtime.ts +5 -16
- package/skills/c64-source/references/loader.md +8 -7
- package/skills/c64-source/scripts/lib/loader.ts +4 -111
- 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/static-analysis.ts +32 -21
- package/skills/c64-testing/SKILL.md +6 -0
- package/skills/c64-testing/scripts/lib/play.ts +8 -7
- package/skills/c64-testing/scripts/lib/recording.ts +218 -12
- package/skills/c64-testing/scripts/lib/replay.ts +7 -3
- 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 +24 -11
- package/skills/c64-unpacker/SKILL.md +6 -4
- package/skills/c64-unpacker/scripts/lib/loads.ts +4 -2
- package/skills/c64-unpacker/scripts/lib/machine.ts +128 -5
- package/skills/c64-unpacker/scripts/lib/stages.ts +5 -1
- package/skills/c64-unpacker/scripts/unpacker.ts +13 -12
- package/skills/emulator/SKILL.md +2 -2
- package/src/host/vice/adapter.ts +2 -1
- package/src/host-client/image.ts +33 -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 +31 -8
- package/src/knowledge/names.ts +2 -2
- package/src/knowledge/program.ts +67 -7
- package/src/knowledge/schema.ts +6 -0
- package/src/knowledge/start-screen.ts +55 -2
- package/src/knowledge/write.ts +18 -12
- 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/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
|
@@ -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;
|
|
@@ -184,7 +187,9 @@ function ownNames(db: DatabaseSync, analyzer: Analyzer, range: AddressRange, spa
|
|
|
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
189
|
* disagrees with the name of the address is a conflict, except on dual-use
|
|
187
|
-
* bytes: they are code at one time and data at another.
|
|
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.
|
|
188
193
|
*/
|
|
189
194
|
function importNames(db: DatabaseSync, change: Change, findings: NormalizedFindings, coverage: AddressRange[], result: ImportResult): void {
|
|
190
195
|
const { analyzer } = findings;
|
|
@@ -192,11 +197,28 @@ function importNames(db: DatabaseSync, change: Change, findings: NormalizedFindi
|
|
|
192
197
|
const wanted = new Map(findings.symbols.map((symbol) => [symbol.address, symbol]));
|
|
193
198
|
const settled = new Set<number>();
|
|
194
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
|
+
);
|
|
195
210
|
for (const range of coverage) {
|
|
196
211
|
for (const own of ownNames(db, analyzer, range, space)) {
|
|
197
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
|
+
}
|
|
198
220
|
// A seeded run gives back the name of the user or the LLM: the analyzer's own name there stays.
|
|
199
|
-
const echo = finding !== undefined &&
|
|
221
|
+
const echo = finding !== undefined && known?.current?.name === finding.name;
|
|
200
222
|
if (echo || (finding !== undefined && finding.name === own.name && finding.kind === own.kind)) {
|
|
201
223
|
settled.add(own.address);
|
|
202
224
|
result.names.unchanged++;
|
|
@@ -207,12 +229,13 @@ function importNames(db: DatabaseSync, change: Change, findings: NormalizedFindi
|
|
|
207
229
|
else replaced.add(own.address);
|
|
208
230
|
}
|
|
209
231
|
}
|
|
210
|
-
const dualUse = (address: number) => regionsOverlapping(db, address, address, space).some((row) => row.type === "dual-use");
|
|
211
232
|
for (const finding of findings.symbols) {
|
|
212
|
-
const current =
|
|
213
|
-
if (
|
|
214
|
-
result.
|
|
233
|
+
const { current, conflict, counted } = at.get(finding.address)!;
|
|
234
|
+
if (counted) {
|
|
235
|
+
result.names.onExecutedCode++;
|
|
236
|
+
continue;
|
|
215
237
|
}
|
|
238
|
+
if (conflict) result.conflicts.push({ category: "symbol", address: finding.address, reason: "kind", current: current!, finding: { name: finding.name, kind: finding.kind } });
|
|
216
239
|
if (settled.has(finding.address)) continue;
|
|
217
240
|
if (current?.name === finding.name) {
|
|
218
241
|
// The analyzer only gives back the name of the address.
|
|
@@ -464,7 +487,7 @@ export function importFindings(db: DatabaseSync, findings: NormalizedFindings, c
|
|
|
464
487
|
const coverage = validateFindings(findings);
|
|
465
488
|
return transaction(db, () => {
|
|
466
489
|
const change = new Change(db, { origin: findings.analyzer, ...context }, `import-${findings.analyzer}`);
|
|
467
|
-
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: [] };
|
|
468
491
|
importNames(db, change, findings, coverage, result);
|
|
469
492
|
importRegions(db, change, findings, coverage, result);
|
|
470
493
|
importReferences(db, change, findings, coverage, result);
|
package/src/knowledge/names.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { Refusal } from "../errors.ts";
|
|
|
10
10
|
import { projectRoot } from "../project.ts";
|
|
11
11
|
import { withRead } from "./database.ts";
|
|
12
12
|
import { analyzerNamed, listAnalyzerNames, listSymbols, symbolNamed } from "./read.ts";
|
|
13
|
-
import { DEFAULT_SPACE, type Space, type SymbolKind } from "./schema.ts";
|
|
13
|
+
import { DEFAULT_SPACE, inSpace, type Space, type SymbolKind } from "./schema.ts";
|
|
14
14
|
|
|
15
15
|
/** The address of a name in a space. Refuses a name that no symbol and no analyzer has, and an analyzer name at two addresses. */
|
|
16
16
|
export function addressOfName(db: DatabaseSync | undefined, name: string, space: Space = DEFAULT_SPACE): number {
|
|
@@ -19,7 +19,7 @@ export function addressOfName(db: DatabaseSync | undefined, name: string, space:
|
|
|
19
19
|
const rows = analyzerNamed(db, name, space);
|
|
20
20
|
const addresses = [...new Set(rows.map((row) => row.address))];
|
|
21
21
|
if (addresses.length === 1) return addresses[0]!;
|
|
22
|
-
const where = space
|
|
22
|
+
const where = inSpace(space);
|
|
23
23
|
if (addresses.length > 1) throw new Refusal("invalid-input", `the analyzers give ${name} to ${rows.map((row) => `${formatC64Address(row.address)} (${row.origin})`).join(" and ")}${where}. Give the address.`);
|
|
24
24
|
throw new Refusal("not-found", `${name} is not a name in the knowledge${where}. Give a $ address, or a symbol or an analyzer name of the project knowledge${where}.`);
|
|
25
25
|
}
|
package/src/knowledge/program.ts
CHANGED
|
@@ -3,12 +3,14 @@
|
|
|
3
3
|
// capture and the coverage maps are imported one time; every later step reads
|
|
4
4
|
// them here, so a project needs no image or coverage files to be made again.
|
|
5
5
|
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
6
7
|
import type { DatabaseSync } from "node:sqlite";
|
|
7
8
|
|
|
8
9
|
import { Refusal } from "../errors.ts";
|
|
9
10
|
import { type AddressRange, COVERAGE, formatC64Address, formatC64Byte, formatC64Range, inRanges, mergeRanges, prgOf, rangesWhere } from "../c64.ts";
|
|
10
|
-
import { COVERAGE_KINDS, DEFAULT_SPACE, MEMORY_ROW, type CoverageKind, type Space } from "./schema.ts";
|
|
11
|
-
import { coverageRuns } from "./read.ts";
|
|
11
|
+
import { COVERAGE_KINDS, DEFAULT_SPACE, inSpace, MEMORY_ROW, type CoverageKind, type Space } from "./schema.ts";
|
|
12
|
+
import { baseValue, coverageRuns, listPatches, listReleases, listSwitches, type StartScreenRow } from "./read.ts";
|
|
13
|
+
import { capturedColourRam } from "./start-screen.ts";
|
|
12
14
|
import { sha256 } from "./text.ts";
|
|
13
15
|
import { checkAddress, checkSpace, write, type Evidence, type OperandImage, type WriteContext } from "./write.ts";
|
|
14
16
|
|
|
@@ -180,6 +182,28 @@ function gained(before: Map<CoverageKind, Uint8Array>, after: Map<CoverageKind,
|
|
|
180
182
|
return count;
|
|
181
183
|
}
|
|
182
184
|
|
|
185
|
+
/** True at each address that a run executed: in RAM, in a ROM or in the I/O area. */
|
|
186
|
+
function executedIn(maps: Map<CoverageKind, Uint8Array>): (address: number) => boolean {
|
|
187
|
+
const executes = (["x", "rom-x", "io-x"] as const).map((kind) => maps.get(kind)!);
|
|
188
|
+
return (address) => executes.some((map) => map[address] === 1);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** What one import did to the coverage of a space. */
|
|
192
|
+
export interface CoverageImport {
|
|
193
|
+
space: Space;
|
|
194
|
+
imported: string[];
|
|
195
|
+
replaced: string[];
|
|
196
|
+
known: string[];
|
|
197
|
+
/** The ranges of accesses that the coverage gained and lost, of all kinds. */
|
|
198
|
+
added: number;
|
|
199
|
+
removed: number;
|
|
200
|
+
/** At an address: gained when the runs now execute it and did not before, lost when they no longer execute it, else undefined. */
|
|
201
|
+
executeChange: (address: number) => ExecuteChange | undefined;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** How an import changed what the runs execute at an address. */
|
|
205
|
+
export type ExecuteChange = "gained" | "lost";
|
|
206
|
+
|
|
183
207
|
/**
|
|
184
208
|
* Puts coverage maps into the coverage of a space. The knowledge keeps the
|
|
185
209
|
* ranges of each map by its project path; the coverage of the space is the
|
|
@@ -193,7 +217,7 @@ export function addCoverage(
|
|
|
193
217
|
db: DatabaseSync,
|
|
194
218
|
context: WriteContext,
|
|
195
219
|
request: { space?: Space; maps: CoverageMap[] },
|
|
196
|
-
): { revision: string | null; current:
|
|
220
|
+
): { revision: string | null; current: CoverageImport } {
|
|
197
221
|
checkSpace(request);
|
|
198
222
|
const space = request.space ?? DEFAULT_SPACE;
|
|
199
223
|
for (const map of request.maps) {
|
|
@@ -210,7 +234,15 @@ export function addCoverage(
|
|
|
210
234
|
const fresh = hashed.filter((map) => !isKnown(map));
|
|
211
235
|
const evidence: Evidence[] = [...(context.evidence ?? []), ...fresh.map((map): Evidence => ({ kind: "coverage", ref: map.name, sha256: map.sha256, ...(space === DEFAULT_SPACE ? {} : { space }) }))];
|
|
212
236
|
return write(db, { ...context, evidence }, "coverage", (change) => {
|
|
213
|
-
const result = {
|
|
237
|
+
const result: CoverageImport = {
|
|
238
|
+
space,
|
|
239
|
+
imported: fresh.map((map) => map.name),
|
|
240
|
+
replaced: fresh.filter((map) => latest.has(map.name) && latest.get(map.name) !== map.sha256).map((map) => map.name),
|
|
241
|
+
known: hashed.filter((map) => !fresh.includes(map)).map((map) => map.name),
|
|
242
|
+
added: 0,
|
|
243
|
+
removed: 0,
|
|
244
|
+
executeChange: () => undefined,
|
|
245
|
+
};
|
|
214
246
|
if (fresh.length === 0) return result;
|
|
215
247
|
// A revision for each import, also when the coverage does not change: the maps are its evidence.
|
|
216
248
|
change.id();
|
|
@@ -228,6 +260,12 @@ export function addCoverage(
|
|
|
228
260
|
const after = currentCoverage(db, space);
|
|
229
261
|
result.added = gained(before, after);
|
|
230
262
|
result.removed = gained(after, before);
|
|
263
|
+
// One value for each address: a lookup of a comment costs one read, also for many short ranges.
|
|
264
|
+
const was = executedIn(before);
|
|
265
|
+
const is = executedIn(after);
|
|
266
|
+
const changes = new Uint8Array(SIZE);
|
|
267
|
+
for (let address = 0; address < SIZE; address++) if (was(address) !== is(address)) changes[address] = is(address) ? 1 : 2;
|
|
268
|
+
result.executeChange = (address) => (changes[address] === 1 ? "gained" : changes[address] === 2 ? "lost" : undefined);
|
|
231
269
|
return result;
|
|
232
270
|
});
|
|
233
271
|
}
|
|
@@ -330,8 +368,7 @@ export function programEntry(db: DatabaseSync | undefined, space: Space = DEFAUL
|
|
|
330
368
|
export function requireProgram(db: DatabaseSync | undefined, space: Space = DEFAULT_SPACE): ProgramImage {
|
|
331
369
|
const image = programImage(db, space);
|
|
332
370
|
if (image !== undefined) return image;
|
|
333
|
-
|
|
334
|
-
throw new Refusal("not-found", `The knowledge has no program${where}. Put the program into the project knowledge${where}: a PRG, or the image.json of a capture.`);
|
|
371
|
+
throw new Refusal("not-found", `The knowledge has no program${inSpace(space)}. Put the program into the project knowledge${inSpace(space)}: a PRG, or the image.json of a capture.`);
|
|
335
372
|
}
|
|
336
373
|
|
|
337
374
|
/** The pages of an entry state: $0000-$03ff as the capture wrote them, 256 bytes as hex for each page. */
|
|
@@ -376,6 +413,29 @@ export function analyzedBytes(image: ProgramImage): { bytes: Buffer; kind: "prg"
|
|
|
376
413
|
return { bytes: Buffer.from(entryMemory(image).memory), kind: "flat64k" };
|
|
377
414
|
}
|
|
378
415
|
|
|
416
|
+
/**
|
|
417
|
+
* The key of a start screen of a captured stage: a hash of what the bytes of
|
|
418
|
+
* its show stage are made from. These are the fields of the start screen (not
|
|
419
|
+
* its comment), the bytes of the program of the stage, the code of each patch
|
|
420
|
+
* there whose switch default is not its base value, the colour RAM of the
|
|
421
|
+
* capture when the start screen takes its colours from it, and with a call
|
|
422
|
+
* the coverage of the stage. A name, a comment or a module of the stage does
|
|
423
|
+
* not change it. Another key means that a show stage of the source is not of
|
|
424
|
+
* this start screen.
|
|
425
|
+
*/
|
|
426
|
+
export function startScreenKey(db: DatabaseSync | undefined, row: StartScreenRow): string {
|
|
427
|
+
const stage = row.stage!;
|
|
428
|
+
const hash = createHash("sha256").update(JSON.stringify([row.space, row.mode, row.screen, row.bitmap, row.charset, row.colours, row.colour, row.border, row.background, stage, row.call, row.colourRam]));
|
|
429
|
+
const image = programImage(db, stage);
|
|
430
|
+
for (const segment of image?.segments ?? []) hash.update(JSON.stringify([segment.start, segment.end])).update(image!.memory.subarray(segment.start, segment.end + 1));
|
|
431
|
+
const base = listReleases(db, undefined, stage).find((release) => release.base)?.label;
|
|
432
|
+
const changed = new Set(listSwitches(db, undefined, stage).filter((item) => item.default !== baseValue(item, base)).map((item) => item.name));
|
|
433
|
+
hash.update(JSON.stringify(listPatches(db, undefined, undefined, undefined, stage).filter((patch) => changed.has(patch.switch)).map((patch) => [patch.start, patch.end, patch.code])));
|
|
434
|
+
if (row.colourRam === true) hash.update(capturedColourRam(image?.state) ?? new Uint8Array());
|
|
435
|
+
if (row.call !== undefined) hash.update(programCoverage(db, stage)?.map ?? new Uint8Array());
|
|
436
|
+
return hash.digest("hex").slice(0, 16);
|
|
437
|
+
}
|
|
438
|
+
|
|
379
439
|
/**
|
|
380
440
|
* The coverage of a space as a joined coverage map (the bits of COVERAGE in
|
|
381
441
|
* c64.ts), and the addresses that one run both wrote and executed; undefined
|
|
@@ -434,7 +494,7 @@ const PATCH_LINE_BYTES = 8;
|
|
|
434
494
|
export function releaseCode(db: DatabaseSync | undefined, label: string, start: number, end: number, space: Space = DEFAULT_SPACE): string {
|
|
435
495
|
const range = formatC64Range({ start, end });
|
|
436
496
|
const release = db?.prepare("SELECT base FROM current_releases WHERE space = ? AND label = ?").get(space, label) as { base: number } | undefined;
|
|
437
|
-
if (release === undefined) throw new Refusal("not-found", `There is no release ${label}${space
|
|
497
|
+
if (release === undefined) throw new Refusal("not-found", `There is no release ${label}${inSpace(space)}. Record it first with its file.`);
|
|
438
498
|
if (release.base === 1) throw new Refusal("invalid-input", `${label} is the base release: its bytes are the program, and a patch holds the bytes of the other state. Give the release that has the other bytes in ${range}.`);
|
|
439
499
|
const image = releaseImage(db, label, space)!;
|
|
440
500
|
for (let address = start; address <= end; address++) {
|
package/src/knowledge/schema.ts
CHANGED
|
@@ -132,6 +132,12 @@ export const DEFAULT_SPACE: Space = "c64";
|
|
|
132
132
|
/** The space of a request: the C64 when it names none. */
|
|
133
133
|
export const spaceOf = (request: { space?: Space }): Space => request.space ?? DEFAULT_SPACE;
|
|
134
134
|
|
|
135
|
+
/** A space other than the C64 in a message: " in <space>". */
|
|
136
|
+
export const inSpace = (space: Space): string => (space === DEFAULT_SPACE ? "" : ` in ${space}`);
|
|
137
|
+
|
|
138
|
+
/** The option of a command for a space other than the C64 in a message: " --space <space>". */
|
|
139
|
+
export const spaceOption = (space: Space): string => (space === DEFAULT_SPACE ? "" : ` --space ${space}`);
|
|
140
|
+
|
|
135
141
|
/** The order of the spaces: the C64, the drive, the loading, then the banks by number. */
|
|
136
142
|
export const spaceOrder = (space: Space): number => (space === "c64" ? -3 : space === "drive8" ? -2 : space === "loading" ? -1 : Number(space.slice(4)));
|
|
137
143
|
const SPACE_CHECK = "space IN ('c64', 'drive8', 'loading') OR space GLOB 'bank[0-9]' OR space GLOB 'bank[1-9][0-9]' OR space GLOB 'bank[12][0-9][0-9]'";
|
|
@@ -1,12 +1,65 @@
|
|
|
1
1
|
// The start screen of a captured stage, from the entry state of its capture:
|
|
2
2
|
// the VIC-II registers and the VIC bank give the mode and the addresses, and
|
|
3
3
|
// the colour RAM of the capture gives the colours. Thus the start screen of a
|
|
4
|
-
// stage needs no address from the user.
|
|
4
|
+
// stage needs no address from the user. Also the values that the start screen
|
|
5
|
+
// code of a generated loader gets from a start screen of the knowledge.
|
|
5
6
|
|
|
6
|
-
import { formatC64Byte, vicScreenMemory } from "../c64.ts";
|
|
7
|
+
import { formatC64Address, formatC64Byte, vicScreenMemory } from "../c64.ts";
|
|
7
8
|
import { Refusal } from "../errors.ts";
|
|
9
|
+
import { isRomFont, type StartScreenRow } from "./read.ts";
|
|
8
10
|
import { LEFTOVERS_SWITCH, START_SCREEN_SWITCH, type StartScreenMode } from "./schema.ts";
|
|
9
11
|
|
|
12
|
+
/** The file of the start screen code in the generated source. */
|
|
13
|
+
export const START_SCREEN_FILE = "start_screen.asm";
|
|
14
|
+
|
|
15
|
+
/** The VIC-II values of a start screen, as the start screen code sets them. */
|
|
16
|
+
export interface StartScreenPlan {
|
|
17
|
+
d011: number;
|
|
18
|
+
d016: number;
|
|
19
|
+
d018: number;
|
|
20
|
+
/** The VIC bank: 0 for $0000-$3fff to 3 for $c000-$ffff. */
|
|
21
|
+
bank: number;
|
|
22
|
+
border: number;
|
|
23
|
+
background: number;
|
|
24
|
+
/** 0: no colour RAM (hires), 1: one colour, 2: a copy of 1000 bytes. */
|
|
25
|
+
colourMode: 0 | 1 | 2;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The VIC-II values that show a start screen of the knowledge. */
|
|
29
|
+
export function startScreenPlan(row: StartScreenRow): StartScreenPlan {
|
|
30
|
+
const bank = row.screen >> 14;
|
|
31
|
+
const base = (row.bitmap === undefined ? ((row.charset! & 0x3fff) >> 11) << 1 : ((row.bitmap & 0x3fff) >> 13) << 3) | 0x01;
|
|
32
|
+
return {
|
|
33
|
+
d011: row.mode === "text" ? 0x1b : 0x3b,
|
|
34
|
+
d016: row.mode === "multicolour" ? 0x18 : 0x08,
|
|
35
|
+
d018: (((row.screen & 0x3fff) >> 10) << 4) | base,
|
|
36
|
+
bank,
|
|
37
|
+
border: row.border,
|
|
38
|
+
background: row.background,
|
|
39
|
+
colourMode: row.colours !== undefined || row.colourRam === true ? 2 : row.colour !== undefined ? 1 : 0,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The lines of loader.asm or of the show stage that give the start screen code its values. */
|
|
44
|
+
export function startScreenValues(row: StartScreenRow, plan: StartScreenPlan): string[] {
|
|
45
|
+
const value = (name: string, number: number, comment?: string) => `c64_source_ss_${name} = ${formatC64Byte(number)}${comment === undefined ? "" : ` ; ${comment}`}`;
|
|
46
|
+
const font = row.charset !== undefined && isRomFont(row.charset) ? " (the character ROM)" : "";
|
|
47
|
+
const what = [`screen ${formatC64Address(row.screen)}`, ...(row.bitmap === undefined ? [] : [`bitmap ${formatC64Address(row.bitmap)}`]), ...(row.charset === undefined ? [] : [`charset ${formatC64Address(row.charset)}${font}`])];
|
|
48
|
+
return [
|
|
49
|
+
`; The start screen: ${row.mode}, ${what.join(", ")}.${row.comment === undefined ? "" : ` ${row.comment.replace(/\s*\r?\n\s*/g, " ")}`}`,
|
|
50
|
+
value("d011", plan.d011),
|
|
51
|
+
value("d016", plan.d016),
|
|
52
|
+
value("d018", plan.d018),
|
|
53
|
+
value("bank", 3 - plan.bank, `VIC bank ${formatC64Address(plan.bank << 14)}-${formatC64Address((plan.bank << 14) + 0x3fff)}`),
|
|
54
|
+
value("border", plan.border),
|
|
55
|
+
value("background", plan.background),
|
|
56
|
+
value("colour_mode", plan.colourMode),
|
|
57
|
+
value("colour", row.colour ?? 0),
|
|
58
|
+
// The colour RAM of a captured stage is in the show code: STAGE_COLOURS in src/stage.ts.
|
|
59
|
+
`c64_source_ss_colours = ${row.colourRam === true ? "c64_source_stage_colours" : formatC64Address(row.colours ?? 0)}`,
|
|
60
|
+
];
|
|
61
|
+
}
|
|
62
|
+
|
|
10
63
|
/** The labels of the start screen in a generated loader: its wait for a key or a fire button, and the code after the wait. */
|
|
11
64
|
export const START_SCREEN_WAIT = "loader_start_screen_wait";
|
|
12
65
|
export const START_SCREEN_CONTINUE = "loader_start_screen_continue";
|