@henols/c64-re-tools 2.4.0-rc.2 → 2.4.0-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +6 -3
  3. package/skills/c64-assembler/scripts/assembler.ts +6 -16
  4. package/skills/c64-disk/SKILL.md +19 -4
  5. package/skills/c64-disk/scripts/disk.ts +43 -3
  6. package/skills/c64-provenance/SKILL.md +8 -4
  7. package/skills/c64-provenance/scripts/lib/library.ts +85 -11
  8. package/skills/c64-provenance/scripts/provenance.ts +4 -3
  9. package/skills/c64-source/SKILL.md +8 -2
  10. package/skills/c64-source/scripts/lib/export.ts +3 -3
  11. package/skills/c64-source/scripts/lib/source.ts +80 -24
  12. package/skills/c64-source/scripts/source.ts +49 -8
  13. package/skills/c64-static-analysis/SKILL.md +1 -1
  14. package/skills/c64-testing/SKILL.md +11 -1
  15. package/skills/c64-testing/references/recording-format.md +5 -1
  16. package/skills/c64-testing/references/scenario-format.md +5 -3
  17. package/skills/c64-testing/scripts/lib/recording.ts +32 -6
  18. package/skills/c64-testing/scripts/lib/runs.ts +13 -7
  19. package/skills/c64-testing/scripts/lib/scenario.ts +13 -6
  20. package/skills/c64-testing/scripts/testing.ts +6 -3
  21. package/src/host/server.ts +31 -6
  22. package/src/host/tools/c1541.ts +32 -8
  23. package/src/host/vice/binary-monitor.ts +19 -7
  24. package/src/host/vice/session.ts +6 -2
  25. package/src/host-client/connect.ts +12 -2
  26. package/src/host-client/tools.ts +9 -4
  27. package/src/host-client/transfer.ts +54 -1
  28. package/src/host-client/vice-session.ts +10 -3
  29. package/src/knowledge/import.ts +28 -5
  30. package/src/knowledge/write.ts +4 -0
  31. package/src/mcp/main.ts +4 -66
  32. package/src/mcp/session-source.ts +76 -0
  33. package/src/native/acme.ts +45 -12
  34. package/src/native/c64run.ts +1 -1
  35. package/src/native/types.ts +5 -2
  36. package/src/protocol/framing.ts +15 -2
  37. package/src/protocol/messages.ts +77 -25
  38. package/src/protocol/tools.ts +33 -4
  39. package/src/protocol/vice.ts +40 -20
  40. package/tools/c64run.c +48 -12
@@ -55,6 +55,10 @@ interface Run {
55
55
  }
56
56
 
57
57
  const OWN_KINDS = ["snapshot", "save", "screen", "coverage", "observe", "expect", "trace"] as const;
58
+ /** The keys of a run file: name, start and steps are required. */
59
+ const RUN_KEYS = ["name", "start", "steps", "symbols", "videoStandard"];
60
+ const RUN_FIELDS = "A run file has name, start and steps, and optionally symbols and videoStandard";
61
+ const START_FORMS = '{ "program": "<file.prg>" }, { "program": "<file.prg>", "load": true } or { "snapshot": "<file.vsf>" }';
58
62
  const TRACE_KEYS = ["trace", "points", "frames", "maxHits"];
59
63
  const OBSERVE_KEYS = ["observe", "memory", "registers", "vicii", "sprites"];
60
64
  const EXPECT_KEYS = ["expect", "memory", "registers"];
@@ -111,14 +115,16 @@ function readRun(path: string): Run {
111
115
  const fail = (message: string): never => {
112
116
  throw new Refusal("invalid-input", `run ${path}: ${message}`);
113
117
  };
114
- if (!isObject(value)) return fail("is not a JSON object");
115
- if (typeof value.name !== "string" || value.name === "") fail("needs a name");
116
- if (value.videoStandard !== undefined && value.videoStandard !== "pal" && value.videoStandard !== "ntsc") fail("videoStandard must be pal or ntsc");
118
+ if (!isObject(value)) return fail(`is not a JSON object. ${RUN_FIELDS}`);
119
+ for (const key of Object.keys(value)) if (!RUN_KEYS.includes(key)) fail(`has the key ${key}. ${RUN_FIELDS}`);
120
+ if (typeof value.name !== "string" || value.name === "") fail('name must be a non-empty string, for example "rooms"');
121
+ if (value.videoStandard !== undefined && value.videoStandard !== "pal" && value.videoStandard !== "ntsc") fail('videoStandard must be "pal" or "ntsc"');
117
122
  const start = value.start;
118
- if (!isObject(start) || (typeof start.program !== "string") === (typeof start.snapshot !== "string")) fail("start needs program or snapshot");
119
- if (isObject(start) && start.load !== undefined && typeof start.load !== "boolean") fail("start.load must be true or false");
120
- if (value.symbols !== undefined && typeof value.symbols !== "string") fail("symbols must be knowledge, none or a JSON file");
121
- if (!Array.isArray(value.steps) || value.steps.length === 0) fail("needs steps");
123
+ if (!isObject(start) || (typeof start.program !== "string") === (typeof start.snapshot !== "string")) return fail(`start must be ${START_FORMS}`);
124
+ for (const key of Object.keys(start)) if (!(typeof start.program === "string" ? ["program", "load"] : ["snapshot"]).includes(key)) fail(`start has the key ${key}. start must be ${START_FORMS}`);
125
+ if (start.load !== undefined && typeof start.load !== "boolean") fail("start.load must be true or false");
126
+ if (value.symbols !== undefined && typeof value.symbols !== "string") fail('symbols must be "knowledge", "none" or a JSON file');
127
+ if (!Array.isArray(value.steps) || value.steps.length === 0) fail("steps must be a list with at least one step");
122
128
  const labels = new Set<string>();
123
129
  (value.steps as unknown[]).forEach((step, index) => {
124
130
  const at = `step ${index + 1}`;
@@ -109,6 +109,10 @@ const STEP_KINDS = ["reset", "load", "autostart", "snapshot", "normalize", ...AC
109
109
  /** The step kinds that a scenario runs: press is for the replay core only. */
110
110
  const SHOWN_KINDS = ["reset", "load", "autostart", "snapshot", "normalize", ...VICE_STEP_KINDS, "observe"];
111
111
 
112
+ /** The keys of a scenario file: all but videoStandard are required. */
113
+ const SCENARIO_KEYS = ["name", "original", "rebuild", "steps", "videoStandard"];
114
+ const SCENARIO_FIELDS = "A scenario file has name, original, rebuild and steps, and optionally videoStandard";
115
+
112
116
  /** The keys each kind of step can have. */
113
117
  const STEP_KEYS: Record<string, readonly string[]> = {
114
118
  observe: ["observe", "memory", "registers", "screen", "vicii", "sprites"],
@@ -130,15 +134,18 @@ export function readScenario(path: string): Scenario {
130
134
  const fail = (message: string): never => {
131
135
  throw new Refusal("invalid-input", `scenario ${path}: ${message}`);
132
136
  };
133
- if (!isObject(value)) return fail("is not a JSON object");
137
+ if (!isObject(value)) return fail(`is not a JSON object. ${SCENARIO_FIELDS}`);
138
+ for (const key of Object.keys(value)) if (!SCENARIO_KEYS.includes(key)) fail(`has the key ${key}. ${SCENARIO_FIELDS}`);
134
139
  const scenario = value as unknown as Scenario;
135
- if (typeof scenario.name !== "string" || scenario.name === "") fail("needs a name");
136
- if (scenario.videoStandard !== undefined && scenario.videoStandard !== "pal" && scenario.videoStandard !== "ntsc") fail("videoStandard must be pal or ntsc");
140
+ if (typeof scenario.name !== "string" || scenario.name === "") fail('name must be a non-empty string, for example "player moves left"');
141
+ if (scenario.videoStandard !== undefined && scenario.videoStandard !== "pal" && scenario.videoStandard !== "ntsc") fail('videoStandard must be "pal" or "ntsc"');
137
142
  for (const side of SIDES) {
138
- const subject = scenario[side];
139
- if (typeof subject?.program !== "string" || typeof subject.symbols !== "string") fail(`${side} needs a program and symbols`);
143
+ const subject: unknown = scenario[side];
144
+ const form = `${side} must be { "program": "<file.prg>", "symbols": "knowledge" }. symbols can also be "none" or a JSON file`;
145
+ if (!isObject(subject) || typeof subject.program !== "string" || typeof subject.symbols !== "string") return fail(form);
146
+ for (const key of Object.keys(subject)) if (key !== "program" && key !== "symbols") fail(`${side} has the key ${key}. ${form}`);
140
147
  }
141
- if (!Array.isArray(scenario.steps) || scenario.steps.length === 0) fail("needs steps");
148
+ if (!Array.isArray(scenario.steps) || scenario.steps.length === 0) fail("steps must be a list with at least one step");
142
149
  const labels = new Set<string>();
143
150
  let screens = 0;
144
151
  scenario.steps.forEach((step: unknown, index) => {
@@ -4,7 +4,7 @@
4
4
  // compare the rebuild with it; diff shows what changed between two states;
5
5
  // checklist gives the Markdown list for a human tester.
6
6
 
7
- import { COVERAGE } from "#src/c64.ts";
7
+ import { COVERAGE, formatC64Address } from "#src/c64.ts";
8
8
  import { isRefusal, Refusal } from "#src/errors.ts";
9
9
  import { WireFailure } from "#src/host-client/tools.ts";
10
10
  import { readPrg } from "#src/host-client/image.ts";
@@ -92,8 +92,10 @@ async function recordCommand(call: Call): Promise<Reply> {
92
92
  frames: Math.round(outcome.recording.ticks / PAL_FRAME_CYCLES),
93
93
  inputSites: outcome.recording.sites.length,
94
94
  events: outcome.recording.events.length,
95
- // The instructions in the coverage map: 0 when the program never read its input from RAM.
95
+ // The instructions in the coverage map: 0 when the coverage never started.
96
96
  executed: outcome.coverage.reduce((count, byte) => count + ((byte & COVERAGE.ramExecute) === 0 ? 0 : 1), 0),
97
+ // The frame and the instruction where the map starts: the code before them has no marks.
98
+ coverageFrom: outcome.coverageFrom === undefined ? null : { frame: Math.floor(outcome.coverageFrom.tick / PAL_FRAME_CYCLES), pc: formatC64Address(outcome.coverageFrom.pc) },
97
99
  };
98
100
  if (outcome.reason === CANCELLED) return reply({ result: "FAIL", recorded: false, reason: outcome.reason, ...summary }, { hint: "Ask the user what to do. Do not make a scripted recording in place of the session of the user." });
99
101
  if (outcome.reason !== undefined) return reply({ result: "FAIL", recorded: false, reason: outcome.reason, ...summary }, { hint: "reason names the step that did not complete. Change that step, then record again." });
@@ -104,7 +106,7 @@ async function recordCommand(call: Call): Promise<Reply> {
104
106
  ];
105
107
  return reply(
106
108
  { result: "PASS", recorded: true, out, ...summary, files },
107
- { hint: `Commit ${out} with the scenarios. Add ${out}/${RECORDING_FILES.coverage} to the project knowledge as coverage. To make sure that the recording replays, run nextAction.`, nextAction: call.next("replay", out) },
109
+ { hint: `Commit ${out} with the scenarios. Add ${out}/${RECORDING_FILES.coverage} to the project knowledge as coverage. ${summary.coverageFrom === null ? "The coverage did not start: the map is empty." : "The map has no marks for the code that ran before coverageFrom."} To make sure that the recording replays, run nextAction.`, nextAction: call.next("replay", out) },
108
110
  );
109
111
  } finally {
110
112
  await core.close();
@@ -144,6 +146,7 @@ const COMMANDS: CommandSpec[] = [
144
146
  summary: "Runs the steps of a run file in its own emulator and writes what they ask for into --out: screens, coverage maps, snapshot files, traces, and results.json with the observations and the expectations. result is FAIL when a step did not run or an expect step found a value that differs.",
145
147
  subjects: [{ name: "<run.json>", help: "a run file, relative to the project folder. See references/scenario-format.md, section Runs" }],
146
148
  options: { out: { ...OPTIONS.out, output: "folder", value: "<dir>", required: true, help: "the folder for the files of the steps and results.json" } },
149
+ notes: 'A run file is one JSON object. It must have name, start and steps. name is a non-empty string. start is { "program": "<file.prg>" }, { "program": "<file.prg>", "load": true } or { "snapshot": "<file.vsf>" }. steps is a list with at least one step. Optional: symbols ("knowledge", "none" (default) or a JSON file) and videoStandard ("pal" (default) or "ntsc"). The script refuses other keys.',
147
150
  run: async (call) => {
148
151
  const { output, failed } = await runFile(call.subject(0), call.string("out")!);
149
152
  if (!failed) return { result: "PASS", ...output };
@@ -1,7 +1,8 @@
1
1
  import { createServer, type Server, type Socket } from "node:net";
2
2
 
3
- import { encodeFrame, MessageReader } from "../protocol/framing.ts";
3
+ import { encodeFrame, FrameTooLarge, MessageReader } from "../protocol/framing.ts";
4
4
  import { isRefusal } from "../errors.ts";
5
+ import { PACKAGE } from "../package.ts";
5
6
  import { checkHello, isOneOf, HEARTBEAT_TIMEOUT_MS, parseClientMessage, ProtocolError, type HostMessage, type ReceivedRequest, type VideoStandard, type WireError, WireFailure } from "../protocol/messages.ts";
6
7
  import { TOOL_OPERATIONS, validateToolParams, type ToolOperation, type ToolOperations } from "../protocol/tools.ts";
7
8
  import { attachmentCount, VICE_OPERATIONS, validateViceParams, type ViceOperation, type ViceOperations } from "../protocol/vice.ts";
@@ -47,6 +48,8 @@ export interface HostServerOptions {
47
48
  /** How long a ready connection may send nothing (no request, no ping) before it is closed with its session. */
48
49
  heartbeatTimeoutMs?: number;
49
50
  log?: (line: string) => void;
51
+ /** The package version that the host compares with the client's and gives in ready; PACKAGE.version when not given. */
52
+ release?: string;
50
53
  }
51
54
 
52
55
  export interface HostServer {
@@ -86,6 +89,7 @@ class Connection {
86
89
 
87
90
  readonly #socket: Socket;
88
91
  readonly #options: HostServerOptions;
92
+ readonly #release: string;
89
93
  readonly #log: (line: string) => void;
90
94
  readonly #handshakeTimer: NodeJS.Timeout;
91
95
  /** Runs from ready on; every received frame restarts it. */
@@ -96,6 +100,7 @@ class Connection {
96
100
  constructor(socket: Socket, options: HostServerOptions, log: (line: string) => void) {
97
101
  this.#socket = socket;
98
102
  this.#options = options;
103
+ this.#release = options.release ?? PACKAGE.version;
99
104
  // Every line names its connection, so the console shows which client starts and stops what.
100
105
  this.#log = (line) => log(`connection ${this.#id}: ${line}`);
101
106
  this.closed = new Promise((resolve) => (this.#resolveClosed = resolve));
@@ -133,7 +138,27 @@ class Connection {
133
138
  }
134
139
 
135
140
  #send(message: HostMessage, attachments: readonly Uint8Array[] = []): void {
136
- if (this.#state !== "closed" && !this.#socket.destroyed) this.#socket.write(encodeFrame(message, attachments));
141
+ this.#write(encodeFrame(message, attachments));
142
+ }
143
+
144
+ #write(frame: Buffer): void {
145
+ if (this.#state !== "closed" && !this.#socket.destroyed) this.#socket.write(frame);
146
+ }
147
+
148
+ /** Sends a result. A result too large for the wire is refused with its size and a remedy, and the host log tells it. */
149
+ #reply(request: ReceivedRequest, result: unknown, attachments: readonly Uint8Array[]): void {
150
+ let frame: Buffer;
151
+ try {
152
+ frame = encodeFrame({ type: "reply", id: request.id, result }, attachments);
153
+ } catch (error) {
154
+ if (!(error instanceof FrameTooLarge)) throw error;
155
+ this.#log(`the reply to ${request.op} is too large to send: ${error.message}`);
156
+ throw new WireFailure(
157
+ "limit-exceeded",
158
+ `The result of this call is ${error.bytes} bytes, more than the ${error.limit} bytes that one reply can hold. Ask for less in one call: a smaller range, count or limit.`,
159
+ );
160
+ }
161
+ this.#write(frame);
137
162
  }
138
163
 
139
164
  /** Ends the host's side after a refusal; a client that does not close its side in time is cut off. */
@@ -171,7 +196,7 @@ class Connection {
171
196
  if (this.#state === "handshake") {
172
197
  if (message.type !== "hello") throw new ProtocolError("first message is not hello");
173
198
  clearTimeout(this.#handshakeTimer);
174
- const mismatch = checkHello(message);
199
+ const mismatch = checkHello(message, this.#release);
175
200
  if (mismatch !== undefined) {
176
201
  this.#log(`refusing a client: ${mismatch.message}`);
177
202
  trace().event("connection.refused", { connection: this.#id, role: message.role, ...mismatch });
@@ -183,7 +208,7 @@ class Connection {
183
208
  if (message.role === "tool") {
184
209
  this.#isTool = true;
185
210
  this.#state = "open";
186
- this.#send({ type: "ready" });
211
+ this.#send({ type: "ready", release: this.#release });
187
212
  this.#log("ready for tool requests");
188
213
  trace().event("connection.ready", { connection: this.#id, role: "tool" });
189
214
  this.#restartHeartbeat();
@@ -211,7 +236,7 @@ class Connection {
211
236
  if (session === undefined || this.#state === "closed") return;
212
237
  this.#session = session;
213
238
  this.#state = "open";
214
- this.#send({ type: "ready" });
239
+ this.#send({ type: "ready", release: this.#release });
215
240
  this.#log(`VICE session ready after ${Math.round(performance.now() - started)} ms`);
216
241
  trace().event("connection.ready", { connection: this.#id, role: "vice-session", videoStandard, ms: elapsedMs(started) });
217
242
  this.#restartHeartbeat();
@@ -265,7 +290,7 @@ class Connection {
265
290
  }
266
291
  result = await session.handle(op, params, attachments, replyAttachments);
267
292
  }
268
- this.#send({ type: "reply", id: request.id, result }, replyAttachments);
293
+ this.#reply(request, result, replyAttachments);
269
294
  record({ ok: true, result });
270
295
  } catch (error) {
271
296
  if (!isRefusal(error)) {
@@ -12,7 +12,7 @@ import { join } from "node:path";
12
12
 
13
13
  import { petsciiNameToText, textToPetsciiName } from "../../c64.ts";
14
14
  import { WireFailure } from "../../protocol/messages.ts";
15
- import { CBM_FILE_TYPES, type C1541Params, type C1541Result, type CbmFileType, type DiskFile, type DiskSector } from "../../protocol/tools.ts";
15
+ import { CBM_FILE_TYPES, MAX_DISK_SECTORS, type C1541Params, type C1541Result, type CbmFileType, type DiskFile, type DiskSector } from "../../protocol/tools.ts";
16
16
  import { Workspace } from "../../native/staging.ts";
17
17
  import { C1541, findTool } from "../../native/discover.ts";
18
18
  import { requireMinimumVersion } from "./version.ts";
@@ -173,6 +173,23 @@ export function unreferencedSectors(tracks: ReadonlyArray<{ track: number; usedS
173
173
  return tracks.flatMap(({ track, usedSectors }) => usedSectors.filter((sector) => !known.has(`${track}/${sector}`)).map((sector) => ({ track, sector })));
174
174
  }
175
175
 
176
+ /**
177
+ * The sectors of a sectors request: the given ones in their order, then the
178
+ * unreferenced ones. Refuses a sector that the disk does not have (the BAM
179
+ * shows each sector of each track) and more than MAX_DISK_SECTORS sectors.
180
+ */
181
+ export function sectorsToRead(given: readonly DiskSector[], unreferenced: readonly DiskSector[], tracks: ReadonlyArray<{ track: number; freeSectors: number[]; usedSectors: number[] }>): DiskSector[] {
182
+ const sectors = [...given, ...unreferenced];
183
+ for (const at of sectors) {
184
+ const row = tracks[at.track - 1];
185
+ if (row === undefined || at.sector >= row.freeSectors.length + row.usedSectors.length) {
186
+ throw new WireFailure("invalid-input", `The disk has no track ${at.track} sector ${at.sector}. Give a track and a sector that the BAM shows.`);
187
+ }
188
+ }
189
+ if (sectors.length > MAX_DISK_SECTORS) throw new WireFailure("limit-exceeded", `The request reads ${sectors.length} sectors, and one request reads at most ${MAX_DISK_SECTORS}. Give fewer sectors.`);
190
+ return sectors;
191
+ }
192
+
176
193
  const toFile = (entry: DiskEntry): DiskFile => ({ name: entry.name, type: entry.type, blocks: entry.blocks, closed: entry.closed, locked: entry.locked });
177
194
 
178
195
  const sameBytes = (a: Uint8Array, b: Uint8Array) => a.length === b.length && a.every((byte, index) => byte === b[index]);
@@ -250,15 +267,22 @@ export async function inspect(params: C1541Params, image: Buffer, context: ToolC
250
267
 
251
268
  const headerChain = await c1541.chain(layout.header);
252
269
  const directory = parseDirectory(await c1541.blocks(headerChain), layout);
253
- if (params.action === "bam") {
270
+ if (params.action === "bam" || params.action === "sectors") {
254
271
  const tracks = parseBam(await c1541.run(["-bam"]), info.tracks);
255
- // Every sector that the header, the directory or a file holds; a file without blocks has no chain.
256
- const referenced = [...headerChain, ...(RESERVED[info.format] ?? [])];
257
- for (const entry of directory.entries) {
258
- if (entry.startTrack !== 0) referenced.push(...(await c1541.chain({ track: entry.startTrack, sector: entry.startSector })));
259
- if (entry.sideStart !== undefined) referenced.push(...(await c1541.chain(entry.sideStart)));
272
+ let unreferenced: DiskSector[] = [];
273
+ if (params.action === "bam" || params.unreferenced === true) {
274
+ // Every sector that the header, the directory or a file holds; a file without blocks has no chain.
275
+ const referenced = [...headerChain, ...(RESERVED[info.format] ?? [])];
276
+ for (const entry of directory.entries) {
277
+ if (entry.startTrack !== 0) referenced.push(...(await c1541.chain({ track: entry.startTrack, sector: entry.startSector })));
278
+ if (entry.sideStart !== undefined) referenced.push(...(await c1541.chain(entry.sideStart)));
279
+ }
280
+ unreferenced = unreferencedSectors(tracks, referenced);
260
281
  }
261
- return { result: { action: "bam", tracks, unreferenced: unreferencedSectors(tracks, referenced) } };
282
+ if (params.action === "bam") return { result: { action: "bam", tracks, unreferenced } };
283
+ const sectors = sectorsToRead(params.sectors ?? [], unreferenced, tracks);
284
+ const data = Buffer.concat(sectors.length === 0 ? [] : await c1541.blocks(sectors));
285
+ return { result: { action: "sectors", sectors, bytes: data.length }, attachments: [data] };
262
286
  }
263
287
  if (params.action === "directory") {
264
288
  const { diskName, diskId, dosType, entries } = directory;
@@ -233,6 +233,8 @@ interface Pending {
233
233
  resolve: (response: MonitorResponse & { extras: MonitorResponse[] }) => void;
234
234
  reject: (error: Error) => void;
235
235
  timer: NodeJS.Timeout | undefined;
236
+ /** The place of the request in the send order. */
237
+ sequence: number;
236
238
  }
237
239
 
238
240
  export const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;
@@ -257,8 +259,13 @@ export class BinaryMonitor {
257
259
  defaultTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS;
258
260
  /** The time limit of a request while an earlier one is overdue (see OVERDUE_REQUEST_TIMEOUT_MS). */
259
261
  overdueTimeoutMs = OVERDUE_REQUEST_TIMEOUT_MS;
260
- /** Requests that timed out and whose late answer has not come yet. */
261
- readonly #overdue = new Set<number>();
262
+ /**
263
+ * Requests that timed out and whose late answer has not come yet, with
264
+ * their place in the send order. VICE answers in order, so an answer to a
265
+ * later request tells that no answer comes for the earlier ones.
266
+ */
267
+ readonly #overdue = new Map<number, number>();
268
+ #sequence = 0;
262
269
 
263
270
  private constructor(socket: Socket) {
264
271
  this.#socket = socket;
@@ -308,13 +315,16 @@ export class BinaryMonitor {
308
315
  const requestId = this.#nextId;
309
316
  this.#nextId = this.#nextId >= EVENT_REQUEST_ID - 1 ? 1 : this.#nextId + 1;
310
317
  const limit = this.#overdue.size > 0 && timeoutMs !== Infinity ? Math.min(timeoutMs, this.overdueTimeoutMs) : timeoutMs;
318
+ const sequence = ++this.#sequence;
319
+ // An id that wrapped around belongs to this request now, not to a dead one.
320
+ this.#overdue.delete(requestId);
311
321
  return new Promise((resolve, reject) => {
312
322
  const timer =
313
323
  limit === Infinity
314
324
  ? undefined
315
325
  : setTimeout(() => {
316
326
  this.#pending.delete(requestId);
317
- this.#overdue.add(requestId);
327
+ this.#overdue.set(requestId, sequence);
318
328
  reject(new MonitorTimeoutError(`monitor command 0x${command.toString(16)} got no response in ${limit} ms`));
319
329
  }, limit);
320
330
  this.#pending.set(requestId, {
@@ -324,6 +334,7 @@ export class BinaryMonitor {
324
334
  resolve,
325
335
  reject,
326
336
  timer,
337
+ sequence,
327
338
  });
328
339
  this.#socket.write(encodeCommand(requestId, command, body));
329
340
  });
@@ -351,11 +362,12 @@ export class BinaryMonitor {
351
362
  continue;
352
363
  }
353
364
  const pending = this.#pending.get(response.requestId);
354
- if (pending === undefined) {
355
- // A late answer to a timed-out request: VICE went on.
356
- this.#overdue.delete(response.requestId);
357
- continue;
365
+ // An answer, also a late one to a timed-out request: VICE went on, past every request sent before it.
366
+ const sequence = pending?.sequence ?? this.#overdue.get(response.requestId);
367
+ if (sequence !== undefined) {
368
+ for (const [requestId, sent] of this.#overdue) if (sent <= sequence) this.#overdue.delete(requestId);
358
369
  }
370
+ if (pending === undefined) continue;
359
371
  if (response.error !== 0) {
360
372
  this.#settle(response.requestId, pending);
361
373
  pending.reject(new MonitorError(pending.command, response.error));
@@ -516,8 +516,12 @@ export class ViceSession implements ViceSessionHandle {
516
516
  return this.#snapshotFile(params as ViceOperations["snapshotFile"]["params"], attachments, reply);
517
517
  case "cpuHistory":
518
518
  return this.#cpuHistory(params as ViceOperations["cpuHistory"]["params"]);
519
- case "trace":
520
- return this.#trace(params as ViceOperations["trace"]["params"]);
519
+ case "trace": {
520
+ // The hits go as an attachment: thousands of them do not fit in one message.
521
+ const { hits, ...traced } = await this.#trace(params as ViceOperations["trace"]["params"]);
522
+ reply.push(Buffer.from(JSON.stringify(hits), "utf8"));
523
+ return { ...traced, hits: hits.length };
524
+ }
521
525
  case "backtrace": {
522
526
  const { depth, space } = params as ViceOperations["backtrace"]["params"];
523
527
  return this.#observe(async () => {
@@ -4,7 +4,7 @@ import { connect as connectTcp, type Socket } from "node:net";
4
4
 
5
5
  import { encodeFrame, MessageReader } from "../protocol/framing.ts";
6
6
  import { elapsedMs, trace } from "../trace.ts";
7
- import { DEFAULT_HOST_PORT, HEARTBEAT_INTERVAL_MS, HEARTBEAT_TIMEOUT_MS, HOST_PROTOCOL_ID, HOST_PROTOCOL_VERSION, parseHostMessage, ProtocolError, WireFailure, withStopAndAsk, type Hello, type HostMessage, type Ping, type Request, type Role, type VideoStandard } from "../protocol/messages.ts";
7
+ import { DEFAULT_HOST_PORT, HEARTBEAT_INTERVAL_MS, HEARTBEAT_TIMEOUT_MS, HOST_PROTOCOL_ID, HOST_PROTOCOL_VERSION, checkRelease, parseHostMessage, ProtocolError, WireFailure, withStopAndAsk, type Hello, type HostMessage, type Ping, type Request, type Role, type VideoStandard } from "../protocol/messages.ts";
8
8
  import { PACKAGE } from "../package.ts";
9
9
 
10
10
  export interface Endpoint {
@@ -133,6 +133,8 @@ export class HostConnection {
133
133
  env?: NodeJS.ProcessEnv;
134
134
  /** Stops the connect and the handshake at once; the open then fails and its socket is closed. */
135
135
  signal?: AbortSignal;
136
+ /** The package version that this client gives in hello; PACKAGE.version when not given. */
137
+ release?: string;
136
138
  }): Promise<HostConnection> {
137
139
  const signal = options.signal;
138
140
  const started = performance.now();
@@ -151,7 +153,8 @@ export class HostConnection {
151
153
  if (socket === undefined) throw unreachable();
152
154
 
153
155
  const connection = new HostConnection(socket);
154
- const hello: Hello = { type: "hello", protocol: HOST_PROTOCOL_ID, version: HOST_PROTOCOL_VERSION, role: options.role };
156
+ const release = options.release ?? PACKAGE.version;
157
+ const hello: Hello = { type: "hello", protocol: HOST_PROTOCOL_ID, version: HOST_PROTOCOL_VERSION, release, role: options.role };
155
158
  if (options.videoStandard !== undefined) hello.videoStandard = options.videoStandard;
156
159
 
157
160
  const stop = () => void connection.close();
@@ -175,6 +178,13 @@ export class HostConnection {
175
178
  throw stopped();
176
179
  }
177
180
 
181
+ // The host checks the release of hello; the client checks the release of ready too, so neither side relies on the other.
182
+ const mismatch = !(answer instanceof Error) && answer.type === "ready" ? checkRelease(release, answer.release) : undefined;
183
+ if (mismatch !== undefined) {
184
+ trace().event("host.handshake-failed", { role: options.role, ms: elapsedMs(started), ...mismatch });
185
+ await connection.close();
186
+ throw new WireFailure(mismatch.code, mismatch.message);
187
+ }
178
188
  if (!(answer instanceof Error) && answer.type === "ready") {
179
189
  trace().event("host.ready", { role: options.role, ms: elapsedMs(started) });
180
190
  connection.#startHeartbeat();
@@ -4,7 +4,7 @@
4
4
  // ACME, DXA and Ghidra themselves through src/native.
5
5
 
6
6
  import { ProtocolError, WireFailure } from "../protocol/messages.ts";
7
- import { DISK_IMAGE_TYPES, validateToolResult, type C1541Result, type DiskAction, type DiskImageType, type PetcatResult, type ToolOperation, type ToolOperations, type HostInfo, type ToolStatus } from "../protocol/tools.ts";
7
+ import { DISK_IMAGE_TYPES, validateToolResult, type C1541Result, type DiskAction, type DiskImageType, type DiskSector, type PetcatResult, type ToolOperation, type ToolOperations, type HostInfo, type ToolStatus } from "../protocol/tools.ts";
8
8
  import { HostConnection } from "./connect.ts";
9
9
  import { readPrg } from "./image.ts";
10
10
  import { readProjectFile } from "./transfer.ts";
@@ -59,9 +59,12 @@ export interface InspectDiskRequest {
59
59
  action: DiskAction;
60
60
  /** entry, chain and read: the file name as the directory shows it. */
61
61
  name?: string;
62
+ /** sectors: the blocks to read in this order, then with unreferenced each used sector that no file holds. */
63
+ sectors?: DiskSector[];
64
+ unreferenced?: boolean;
62
65
  }
63
66
 
64
- /** c1541.inspect: a found read also returns the file's bytes. */
67
+ /** c1541.inspect: a found read also returns the file's bytes, and sectors the blocks, 256 bytes each. */
65
68
  export async function inspectDisk(request: InspectDiskRequest, options: ToolCallOptions = {}): Promise<C1541Result & { data?: Buffer }> {
66
69
  const file = readProjectFile(request.image);
67
70
  if (!(DISK_IMAGE_TYPES as readonly string[]).includes(file.type)) {
@@ -69,8 +72,10 @@ export async function inspectDisk(request: InspectDiskRequest, options: ToolCall
69
72
  }
70
73
  const params: ToolOperations["c1541.inspect"]["params"] = { action: request.action, imageType: file.type as DiskImageType };
71
74
  if (request.name !== undefined) params.name = request.name;
75
+ if (request.sectors !== undefined) params.sectors = request.sectors;
76
+ if (request.unreferenced !== undefined) params.unreferenced = request.unreferenced;
72
77
  const { result, attachments } = await callTool("c1541.inspect", params, [file.bytes], options);
73
- return result.action === "read" && result.found ? { ...result, data: attachments[0]! } : result;
78
+ return (result.action === "read" && result.found) || result.action === "sectors" ? { ...result, data: attachments[0]! } : result;
74
79
  }
75
80
 
76
81
  /** petcat.decode: the C64 BASIC V2 listing of a project program and its machine-code handoffs. Refuses a file that is no PRG as readPrg does. */
@@ -86,6 +91,6 @@ export async function hostTools(options: ToolCallOptions = {}): Promise<{ host:
86
91
 
87
92
  /** Skill scripts see failures and wire limits through the host-client, never the private protocol module. */
88
93
  export { WireFailure } from "../protocol/messages.ts";
89
- export { DISK_ACTIONS, DISK_IMAGE_TYPES } from "../protocol/tools.ts";
94
+ export { DISK_ACTIONS, DISK_BLOCK_BYTES, DISK_IMAGE_TYPES, MAX_DISK_SECTORS } from "../protocol/tools.ts";
90
95
  export { JOYSTICK_DIRECTIONS, MAX_BASELINES, MAX_EXECUTION_COUNT, MAX_KEYBOARD_BYTES, MAX_MASK_RECTANGLES, MAX_MEMORY_READ, MAX_MEMORY_WRITE, MAX_TIMEOUT_FRAMES, maskCoversFrame } from "../protocol/vice.ts";
91
96
  export { MAX_TRACE_FRAMES, MAX_TRACE_HITS, MAX_TRACE_POINTS, TRACE_KINDS, type TraceHit, type TraceKind } from "../protocol/vice.ts";
@@ -3,7 +3,7 @@
3
3
 
4
4
  import { createHash } from "node:crypto";
5
5
  import { lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
6
- import { dirname, extname, join, relative, sep } from "node:path";
6
+ import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
7
 
8
8
  import { checkOutputPath, isInside, projectRoot, resolveProject, resolveProjectFile, writeProblem } from "../project.ts";
9
9
  import { isRefusal } from "../errors.ts";
@@ -178,3 +178,56 @@ export function readProjectTree(path: string, options: { root?: string } = {}):
178
178
  walk(sourceRoot, sourceRoot, new Set([sourceRoot]));
179
179
  return { files, contents };
180
180
  }
181
+
182
+ /** A path from `from` to `to`, with /. */
183
+ const posixRelative = (from: string, to: string) => relative(from, to).split(sep).join("/");
184
+
185
+ /**
186
+ * Reads a source root and its include folders as one source tree for
187
+ * staging, as readProjectTree does. An include folder is relative to the
188
+ * source root and can be anywhere in the project folder. The tree starts at
189
+ * the lowest folder that holds all these folders, but it holds only their
190
+ * files. `sourceDir` is the source root in the tree, "" at its top, and
191
+ * `includeDirs` are the include folders relative to the source root.
192
+ */
193
+ export function readSourceTree(sourceRoot: string, includes: readonly string[], options: { root?: string } = {}): { files: SourceTree; contents: Buffer[]; sourceDir: string; includeDirs: string[] } {
194
+ const projectRootPath = options.root ?? currentProject();
195
+ const sourceTree = readProjectTree(sourceRoot, { root: projectRootPath });
196
+ const project = realpathSync(projectRootPath);
197
+ const source = resolveProjectFile(sourceRoot, projectRootPath);
198
+ 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, inside the project folder.`);
199
+ const folders = includes.map((folder) => {
200
+ const outside = new WireFailure("invalid-input", `The include folder ${folder} is outside the project folder. Give an include folder relative to the source root, inside the project folder.`);
201
+ if (isAbsolute(folder)) throw outside;
202
+ const candidate = resolve(source, folder);
203
+ if (!isInside(project, candidate)) throw outside;
204
+ let real: string;
205
+ try {
206
+ real = realpathSync(candidate);
207
+ } catch {
208
+ throw missing(folder);
209
+ }
210
+ if (!isInside(project, real)) throw outside;
211
+ if (!statSync(real).isDirectory()) throw missing(folder);
212
+ return { folder, real };
213
+ });
214
+ let top = source;
215
+ for (const { real } of folders) while (!isInside(top, real)) top = dirname(top);
216
+ // Each folder is read once: a folder inside another comes with the files of that folder.
217
+ const roots = [...new Set([source, ...folders.map(({ real }) => real)])];
218
+ const files: SourceTree = [];
219
+ const contents: Buffer[] = [];
220
+ for (const root of roots.filter((root) => !roots.some((other) => other !== root && isInside(other, root)))) {
221
+ const tree = root === source ? sourceTree : readProjectTree(posixRelative(project, root) || ".", { root: project });
222
+ const prefix = posixRelative(top, root);
223
+ files.push(...tree.files.map((file) => ({ ...file, path: prefix === "" ? file.path : `${prefix}/${file.path}` })));
224
+ contents.push(...tree.contents);
225
+ }
226
+ if (files.length > MAX_TREE_FILES) throw new WireFailure("limit-exceeded", `The source root and the include folders have more than ${MAX_TREE_FILES} files.`);
227
+ if (files.reduce((total, file) => total + file.size, 0) > MAX_ATTACHMENT_BYTES) throw new WireFailure("limit-exceeded", `The source root and the include folders hold more than ${MAX_ATTACHMENT_BYTES} bytes.`);
228
+ for (const { folder, real } of folders) {
229
+ const inside = posixRelative(top, real);
230
+ if (!files.some((file) => inside === "" || file.path.startsWith(`${inside}/`))) throw missing(folder);
231
+ }
232
+ return { files, contents, sourceDir: posixRelative(top, source), includeDirs: folders.map(({ real }) => posixRelative(source, real) || ".") };
233
+ }
@@ -2,7 +2,7 @@
2
2
  // one VICE. Exposes C64-domain operations only.
3
3
 
4
4
  import { ProtocolError, WireFailure, type VideoStandard } from "../protocol/messages.ts";
5
- import { MAX_MEMORY_READ, validateViceResult, type Breakpoint, type BreakpointParams, type PointRemoved, type Watchpoint, type WatchpointParams, type ExecutionParams, type ExecutionResult, type JoystickState, type MachineStatus, 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";
5
+ 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 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
6
  import { HostConnection } from "./connect.ts";
7
7
  import { readProjectFile } from "./transfer.ts";
8
8
 
@@ -179,8 +179,15 @@ export class ViceSessionClient {
179
179
  }
180
180
 
181
181
  /** Records each hit of the points while the program runs on. */
182
- trace(params: ViceOperations["trace"]["params"]): Promise<ViceOperations["trace"]["result"]> {
183
- return this.#request("trace", params);
182
+ async trace(params: ViceOperations["trace"]["params"]): Promise<TraceResult> {
183
+ const { result, attachments } = await this.#requestWithAttachments("trace", params);
184
+ try {
185
+ return { ...result, hits: traceHitsFromAttachment(attachments, result.hits) };
186
+ } catch (error) {
187
+ if (!(error instanceof ProtocolError)) throw error;
188
+ this.#fail();
189
+ throw new WireFailure("operation-failed", "The c64-re-tools host runtime sent an invalid reply.");
190
+ }
184
191
  }
185
192
 
186
193
  backtrace(params: ViceOperations["backtrace"]["params"]): Promise<ViceOperations["backtrace"]["result"]> {
@@ -30,7 +30,7 @@ import {
30
30
  type RegionRow,
31
31
  type SymbolRow,
32
32
  } from "./read.ts";
33
- import { ANALYZERS, CODE_REGION_TYPES, DEFAULT_SPACE, POINTER_KIND, REFERENCE_KINDS, REGION_TYPES, SYMBOL_KINDS, type Analyzer, type Origin, type ReferenceKind, type RegionType, type Space, type SymbolKind } from "./schema.ts";
33
+ import { ANALYZERS, CODE_REGION_TYPES, DEFAULT_SPACE, POINTER_KIND, REFERENCE_KINDS, REGION_TYPES, SEMANTIC_ORIGINS, SYMBOL_KINDS, type Analyzer, type Origin, type ReferenceKind, type RegionType, type Space, type SymbolKind } from "./schema.ts";
34
34
  import { Change, checkAddress, checkSpace, subtract, SYMBOL_NAME, type Evidence } from "./write.ts";
35
35
 
36
36
 
@@ -107,7 +107,10 @@ export interface ImportResult {
107
107
  /** The analyzer's own rows from an older version that the run closed in symbols: only `retired` counts. */
108
108
  symbols: ImportCounts;
109
109
  regions: ImportCounts;
110
- references: ImportCounts;
110
+ references: ImportCounts & {
111
+ /** Findings from an address in a data region of the user, the LLM or a heuristic: false code, not written. */
112
+ inData: number;
113
+ };
111
114
  conflicts: ImportConflict[];
112
115
  }
113
116
 
@@ -429,15 +432,35 @@ function keepPiece(desired: Map<string, { start: number; end: number; type: Regi
429
432
  desired.set(`${joined.start}-${joined.end}`, joined);
430
433
  }
431
434
 
435
+ /** Origins whose data regions are not code: an analyzer reference from there is false code. */
436
+ const DATA_HOLDS_NO_REFERENCES = new Set<Origin>([...SEMANTIC_ORIGINS, "heuristic"]);
437
+
438
+ /** True for an address in a data region of the user, the LLM or a heuristic, other than the analyzer itself; dual-use bytes are also code. */
439
+ function inDataRegion(db: DatabaseSync, analyzer: Analyzer, coverage: AddressRange[], space: Space): (address: number) => boolean {
440
+ const data = coverage
441
+ .flatMap((range) => regionsOverlapping(db, range.start, range.end, space))
442
+ .filter((row) => row.origin !== analyzer && DATA_HOLDS_NO_REFERENCES.has(row.origin) && !isCode(row.type) && row.type !== "dual-use");
443
+ return (address) => data.some((row) => row.start <= address && address <= row.end);
444
+ }
445
+
446
+ /**
447
+ * References replace the analyzer's own in its coverage. A reference from a
448
+ * data region of the user, the LLM or a heuristic comes from bytes that the
449
+ * analyzer decoded as code by mistake: it is not imported, and the analyzer's
450
+ * own reference from there closes.
451
+ */
432
452
  function importReferences(db: DatabaseSync, change: Change, findings: NormalizedFindings, coverage: AddressRange[], result: ImportResult): void {
433
453
  const { analyzer } = findings;
434
454
  const space = findings.space ?? DEFAULT_SPACE;
435
455
  const key = (reference: { from: number; to: number; kind: ReferenceKind }) => `${reference.from}|${reference.to}|${reference.kind}`;
436
- const wanted = new Map(findings.references.map((reference) => [key(reference), reference]));
456
+ const inData = inDataRegion(db, analyzer, coverage, space);
457
+ const kept = findings.references.filter((reference) => !inData(reference.from));
458
+ result.references.inData = findings.references.length - kept.length;
459
+ const wanted = new Map(kept.map((reference) => [key(reference), reference]));
437
460
  for (const range of coverage) {
438
461
  for (const own of ownReferences(db, analyzer, range, space)) {
439
462
  if (wanted.has(key(own))) continue;
440
- if (!findings.authoritative.references) continue;
463
+ if (!findings.authoritative.references && !inData(own.from)) continue;
441
464
  change.close('"references"', "space = ? AND from_address = ? AND to_address = ? AND kind = ? AND origin = ?", space, own.from, own.to, own.kind, analyzer);
442
465
  result.references.retired++;
443
466
  }
@@ -460,7 +483,7 @@ export function importFindings(db: DatabaseSync, findings: NormalizedFindings, c
460
483
  const coverage = validateFindings(findings);
461
484
  return transaction(db, () => {
462
485
  const change = new Change(db, { origin: findings.analyzer, ...context }, `import-${findings.analyzer}`);
463
- const result: ImportResult = { revision: null, names: counts(), symbols: counts(), regions: counts(), references: counts(), conflicts: [] };
486
+ const result: ImportResult = { revision: null, names: counts(), symbols: counts(), regions: counts(), references: { ...counts(), inData: 0 }, conflicts: [] };
464
487
  importNames(db, change, findings, coverage, result);
465
488
  importRegions(db, change, findings, coverage, result);
466
489
  importReferences(db, change, findings, coverage, result);
@@ -509,6 +509,10 @@ function classifyStep(db: DatabaseSync, change: Change, origin: Origin, request:
509
509
  clearRange(db, change, request.start, request.end, space);
510
510
  change.insertRegion({ space, start: request.start, end: request.end, type: request.type, ...(request.element === undefined ? {} : { element: request.element }), origin });
511
511
  liftRegionSuppressions(db, change, request.start, request.end, space);
512
+ // Data is not code: an analyzer reference from there is false code. dual-use bytes are also code.
513
+ if (!CODE_REGION_TYPES.includes(request.type) && request.type !== "dual-use") {
514
+ change.close('"references"', "space = ? AND from_address BETWEEN ? AND ? AND origin NOT IN ('user', 'llm')", space, request.start, request.end);
515
+ }
512
516
  const previous = overlapping.filter((row) => row.origin !== origin);
513
517
  const current = regionsOverlapping(db, request.start, request.end, space);
514
518
  return previous.length === 0 ? { current } : { current, previous };