@henols/c64-re-tools 2.7.1 → 2.8.0-rc.1

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 (68) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +23 -38
  3. package/skills/c64-assembler/scripts/assembler.ts +114 -16
  4. package/skills/c64-basic/SKILL.md +11 -31
  5. package/skills/c64-basic/scripts/basic.ts +4 -1
  6. package/skills/c64-development/SKILL.md +2 -2
  7. package/skills/c64-disk/SKILL.md +11 -32
  8. package/skills/c64-docs/SKILL.md +27 -45
  9. package/skills/c64-docs/references/page-types.md +20 -18
  10. package/skills/c64-docs/references/style.md +10 -4
  11. package/skills/c64-docs/scripts/docs.ts +13 -2
  12. package/skills/c64-docs/scripts/lib/reference.ts +47 -5
  13. package/skills/c64-knowledge/SKILL.md +138 -267
  14. package/skills/c64-knowledge/references/batches.md +48 -0
  15. package/skills/c64-knowledge/references/coverage.md +29 -0
  16. package/skills/c64-knowledge/references/source-knowledge.md +72 -0
  17. package/skills/c64-knowledge/references/start-screen.md +44 -0
  18. package/skills/c64-knowledge/scripts/knowledge.ts +266 -61
  19. package/skills/c64-knowledge/scripts/lib/check.ts +133 -0
  20. package/skills/c64-knowledge/scripts/lib/listing.ts +72 -8
  21. package/skills/c64-memory-map/SKILL.md +11 -32
  22. package/skills/c64-packer/SKILL.md +11 -31
  23. package/skills/c64-provenance/SKILL.md +40 -62
  24. package/skills/c64-provenance/scripts/lib/leftovers.ts +8 -3
  25. package/skills/c64-provenance/scripts/provenance.ts +64 -55
  26. package/skills/c64-reverse-engineering/SKILL.md +20 -47
  27. package/skills/c64-reverse-engineering/references/comment-check.md +42 -0
  28. package/skills/c64-reverse-engineering/references/versions.md +47 -0
  29. package/skills/c64-source/SKILL.md +43 -237
  30. package/skills/c64-source/references/export.md +50 -0
  31. package/skills/c64-source/references/loader.md +78 -0
  32. package/skills/c64-source/references/source-format.md +46 -0
  33. package/skills/c64-source/scripts/lib/export.ts +20 -7
  34. package/skills/c64-source/scripts/lib/loader.ts +4 -82
  35. package/skills/c64-source/scripts/source.ts +48 -51
  36. package/skills/c64-static-analysis/SKILL.md +51 -52
  37. package/skills/c64-static-analysis/scripts/lib/coverage.ts +55 -2
  38. package/skills/c64-static-analysis/scripts/lib/idioms.ts +28 -9
  39. package/skills/c64-static-analysis/scripts/static-analysis.ts +69 -15
  40. package/skills/c64-testing/SKILL.md +72 -58
  41. package/skills/c64-testing/references/recording-format.md +5 -80
  42. package/skills/c64-testing/references/scenario-format.md +4 -12
  43. package/skills/c64-testing/scripts/lib/play.ts +16 -8
  44. package/skills/c64-testing/scripts/lib/recording.ts +74 -9
  45. package/skills/c64-testing/scripts/lib/replay.ts +4 -0
  46. package/skills/c64-testing/scripts/lib/runs.ts +112 -1
  47. package/skills/c64-testing/scripts/lib/scenario.ts +12 -6
  48. package/skills/c64-testing/scripts/lib/start-screen.ts +27 -0
  49. package/skills/c64-testing/scripts/testing.ts +34 -13
  50. package/skills/c64-unpacker/SKILL.md +10 -30
  51. package/skills/emulator/SKILL.md +7 -36
  52. package/src/build-name.ts +12 -1
  53. package/src/knowledge/history.ts +8 -0
  54. package/src/knowledge/program.ts +73 -1
  55. package/src/knowledge/read.ts +46 -2
  56. package/src/knowledge/recording-files.ts +32 -0
  57. package/src/knowledge/schema.ts +3 -1
  58. package/src/knowledge/separate.ts +90 -3
  59. package/src/knowledge/start-screen.ts +99 -17
  60. package/src/knowledge/text.ts +2 -1
  61. package/src/knowledge/write.ts +15 -8
  62. package/src/loader.ts +167 -0
  63. package/src/native/decompiler/analyze.ts +7 -6
  64. package/src/native/decompiler/walk.ts +32 -2
  65. package/src/native/dxa.ts +4 -4
  66. package/src/native/types.ts +32 -4
  67. package/src/script.ts +87 -17
  68. package/skills/c64-export/SKILL.md +0 -63
@@ -4,6 +4,9 @@
4
4
  // side, no comparison with another program: an expect step checks the memory
5
5
  // and registers against the values that the run file gives.
6
6
 
7
+ import { existsSync } from "node:fs";
8
+ import { posix } from "node:path";
9
+
7
10
  import { formatC64Address, formatC64Byte, formatSprite, formatVicii, parseC64Address } from "#src/c64.ts";
8
11
  import { screenText } from "#src/graphics.ts";
9
12
  import { runProgram } from "#src/host-client/autostart.ts";
@@ -15,7 +18,9 @@ import { MAX_MEMORY_READ, MAX_TRACE_FRAMES, MAX_TRACE_HITS, MAX_TRACE_POINTS, TR
15
18
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
16
19
  import { readMemoryInParts, ViceSessionClient } from "#src/host-client/vice-session.ts";
17
20
  import { checkSnapshotFile } from "#src/media.ts";
21
+ import { checkOutputPath, LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRelative, resolveProjectPath } from "#src/project.ts";
18
22
  import { namesOf } from "./scenario.ts";
23
+ import { passStartScreen } from "./start-screen.ts";
19
24
 
20
25
  type RunStep =
21
26
  | ActionStep
@@ -335,6 +340,7 @@ export async function runFile(path: string, out: string): Promise<{ output: Reco
335
340
  const client = await ViceSessionClient.open({ videoStandard: run.videoStandard ?? "pal" });
336
341
  let done = 0;
337
342
  let reason: string | undefined;
343
+ let startScreen: "skipped" | "none" = "none";
338
344
  try {
339
345
  await client.reset({ mode: "hard", run: false });
340
346
  if ("snapshot" in run.start) {
@@ -345,6 +351,11 @@ export async function runFile(path: string, out: string): Promise<{ output: Reco
345
351
  } else {
346
352
  const failed = await runProgram(client, run.start.program, readProjectFile(run.start.program).bytes);
347
353
  if (failed !== undefined) reason = failed === "not-loaded" ? "The program was not in memory after autostart." : "The program did not start after RUN; it needs a BASIC start line.";
354
+ else {
355
+ const screen = await passStartScreen(client, symbols);
356
+ if (typeof screen === "object") reason = `${screen.problem[0]!.toUpperCase()}${screen.problem.slice(1)}.`;
357
+ else startScreen = screen;
358
+ }
348
359
  }
349
360
  await client.memmap({ action: "clear" });
350
361
  for (const step of reason === undefined ? run.steps : []) {
@@ -421,14 +432,114 @@ export async function runFile(path: string, out: string): Promise<{ output: Reco
421
432
  done,
422
433
  ...(reason === undefined ? {} : { reason }),
423
434
  pc: formatC64Address(pc),
435
+ ...(startScreen === "skipped" ? { startScreen } : {}),
424
436
  files: [...files],
425
437
  observations,
426
438
  ...(expectations.length === 0 ? {} : { expectations, failedExpectations }),
427
439
  ...(Object.keys(traces).length === 0 ? {} : { traces }),
428
440
  };
429
441
  write("results.json", Buffer.from(`${JSON.stringify(results, null, 2)}\n`));
430
- return { output: { ...results, files: written, observations: Object.keys(observations), out }, failed: reason !== undefined || failedExpectations.length > 0 };
442
+ return { output: { ...results, files: written, out }, failed: reason !== undefined || failedExpectations.length > 0 };
431
443
  } finally {
432
444
  await client.close();
433
445
  }
434
446
  }
447
+
448
+ /** The name of the run file in a kept run, and the folder of the files that it starts from. */
449
+ const KEPT_RUN = "run.json";
450
+ const KEPT_INPUTS = "inputs";
451
+ /** A file name that a run wrote into --out: no folder, no "." or "..". */
452
+ const RESULT_FILE = /^(?!\.\.?$)[A-Za-z0-9._-]+$/;
453
+
454
+ /** A path of a run file that keep changed: the field, the old path and the new path. */
455
+ export interface KeptPath {
456
+ field: string;
457
+ from: string;
458
+ to: string;
459
+ }
460
+
461
+ /**
462
+ * Keeps a run as evidence in a folder that git keeps: the run file as
463
+ * run.json, results.json and each file that the run wrote into `out`, and
464
+ * each file in .c64-re-tools/local/ that the run file starts from (the
465
+ * program, the snapshot, the symbols and the snapshot steps) in inputs/. The
466
+ * run file gets the new paths of those files only; another path stays as it
467
+ * is. All files are read before the first write, and the target must not
468
+ * exist, so a refusal leaves nothing behind.
469
+ */
470
+ export function keepRun(path: string, out: string, target: string): { out: string; files: Written[]; paths: KeptPath[] } {
471
+ const run = readRun(path);
472
+ const raw = JSON.parse(readProjectFile(path).bytes.toString("utf8")) as { start: Record<string, unknown>; symbols?: unknown; steps: Array<Record<string, unknown>> };
473
+ const kept = projectRelative(target);
474
+ if (kept === PROJECT_DIRECTORY || kept.startsWith(`${PROJECT_DIRECTORY}/`)) {
475
+ throw new Refusal("invalid-input", `${target} is in ${PROJECT_DIRECTORY}/, and git does not keep a run there. Give a new folder outside it, for example runs/${run.name.replace(/[^A-Za-z0-9._-]+/g, "_")}.`);
476
+ }
477
+ if (existsSync(resolveProjectPath(kept))) throw new Refusal("conflict", `${target} exists. Give a new folder, or remove the old folder first.`);
478
+ checkOutputPath(kept, "folder", { what: target });
479
+ const results = (() => {
480
+ const file = `${out}/results.json`;
481
+ let value: unknown;
482
+ try {
483
+ value = JSON.parse(readProjectFile(file).bytes.toString("utf8"));
484
+ } catch (error) {
485
+ if (isRefusal(error) && error.code === "not-found") throw new Refusal("not-found", `${out} has no results.json. Give the --out folder of a run of ${path}.`);
486
+ if (isRefusal(error)) throw error;
487
+ throw new Refusal("invalid-input", `${file} is not JSON: ${(error as Error).message}`);
488
+ }
489
+ if (!isObject(value) || value.name !== run.name || !Array.isArray(value.files) || !value.files.every((name) => typeof name === "string" && RESULT_FILE.test(name))) {
490
+ throw new Refusal("invalid-input", `${file} is not the result of the run ${run.name}. Give the --out folder of a run of ${path}.`);
491
+ }
492
+ return { file, names: value.files as string[] };
493
+ })();
494
+ if (results.names.includes(KEPT_RUN)) throw new Refusal("invalid-input", `the run wrote ${out}/${KEPT_RUN}, which is the name of the run file in a kept run. Give the step that writes it another name, and run again.`);
495
+ // The files of the project that the run file names in the local folder: each one once, in inputs/ with its own name.
496
+ const local = `${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/`;
497
+ const inputs = new Map<string, { to: string; bytes: Buffer }>();
498
+ const used = new Set<string>();
499
+ const paths: KeptPath[] = [];
500
+ const keep = (field: string, file: unknown): string | undefined => {
501
+ if (typeof file !== "string" || file === "knowledge" || file === "none") return undefined;
502
+ let from: string;
503
+ try {
504
+ from = projectRelative(file);
505
+ } catch (error) {
506
+ // A path into another project of the group is not in this local folder.
507
+ if (isRefusal(error)) return undefined;
508
+ throw error;
509
+ }
510
+ if (!from.startsWith(local)) return undefined;
511
+ let input = inputs.get(from);
512
+ if (input === undefined) {
513
+ let bytes: Buffer;
514
+ try {
515
+ bytes = readProjectFile(file).bytes;
516
+ } catch (error) {
517
+ if (isRefusal(error)) throw new Refusal(error.code, `run ${path}: ${field}: ${error.message}`);
518
+ throw error;
519
+ }
520
+ const name = posix.basename(from);
521
+ const extension = posix.extname(name);
522
+ let unique = name;
523
+ for (let count = 2; used.has(unique.toLowerCase()); count++) unique = `${name.slice(0, name.length - extension.length)}-${count}${extension}`;
524
+ used.add(unique.toLowerCase());
525
+ input = { to: `${kept}/${KEPT_INPUTS}/${unique}`, bytes };
526
+ inputs.set(from, input);
527
+ }
528
+ paths.push({ field, from: file, to: input.to });
529
+ return input.to;
530
+ };
531
+ const moved = (holder: Record<string, unknown>, key: string, field: string) => {
532
+ const to = keep(field, holder[key]);
533
+ if (to !== undefined) holder[key] = to;
534
+ };
535
+ moved(raw.start, "program", "start.program");
536
+ moved(raw.start, "snapshot", "start.snapshot");
537
+ moved(raw as Record<string, unknown>, "symbols", "symbols");
538
+ raw.steps.forEach((step, index) => {
539
+ if (isObject(step) && "snapshot" in step) moved(step, "snapshot", `step ${index + 1}: snapshot`);
540
+ });
541
+ const outputs = [results.file, ...results.names.map((name) => `${out}/${name}`)].map((file) => ({ to: `${kept}/${posix.basename(file)}`, bytes: readProjectFile(file).bytes }));
542
+ const files = [...inputs.values(), ...outputs].map((file) => writeReported(file.to, file.bytes, { what: target }));
543
+ files.push(writeReported(`${kept}/${KEPT_RUN}`, `${JSON.stringify(raw, null, 1)}\n`, { what: target }));
544
+ return { out: kept, files, paths };
545
+ }
@@ -18,6 +18,7 @@ import { nameTable } from "#src/knowledge/names.ts";
18
18
  import { DEFAULT_SPACE } from "#src/knowledge/schema.ts";
19
19
  import { programImage } from "#src/knowledge/program.ts";
20
20
  import { listed } from "#src/script.ts";
21
+ import { passStartScreen } from "./start-screen.ts";
21
22
 
22
23
  export type Side = "reference" | "rebuild";
23
24
  export const SIDES: Side[] = ["reference", "rebuild"];
@@ -392,16 +393,20 @@ export function baselineName(checkpoint: number, label: string): string {
392
393
  return `test-${checkpoint}-${label}`.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 64);
393
394
  }
394
395
 
395
- /** Autostart that returns only when the program runs (runProgram), or INCONCLUSIVE with the reason. */
396
- async function startProgram(client: ViceSessionClient, program: string, side: Side): Promise<void> {
396
+ /**
397
+ * Autostart that returns only when the program runs (runProgram), and after the
398
+ * start screen of a loader program (passStartScreen), or INCONCLUSIVE with the reason.
399
+ */
400
+ async function startProgram(client: ViceSessionClient, program: string, side: Side, symbols: Map<string, number>): Promise<void> {
397
401
  const failed = await runProgram(client, program, readProjectFile(program).bytes);
398
402
  if (failed === "not-loaded") throw new Inconclusive(`the ${side} program was not in memory after ${LOAD_LIMIT_FRAMES} frames of autostart`);
399
403
  if (failed === "not-started") throw new Inconclusive(`the ${side} program did not start within ${RUN_LIMIT_FRAMES} frames of RUN; autostart runs only a program with a BASIC start line`);
404
+ const screen = await passStartScreen(client, symbols);
405
+ if (typeof screen === "object") throw new Inconclusive(`the ${side} side: ${screen.problem}`);
400
406
  }
401
407
 
402
408
  async function runSide(client: ViceSessionClient, scenario: Scenario, side: Side, symbols: Map<string, number>, files: boolean): Promise<Map<string, Observation>> {
403
409
  const observations = new Map<string, Observation>();
404
- const at = (location: Location) => resolve(location, symbols, side);
405
410
  // Each side starts from a hard reset, stopped at the reset vector, with the control ports released.
406
411
  await client.reset({ mode: "hard", run: false });
407
412
  for (const port of [1, 2] as const) {
@@ -416,7 +421,7 @@ async function runSide(client: ViceSessionClient, scenario: Scenario, side: Side
416
421
  for (const [index, step] of scenario.steps.entries()) {
417
422
  if (step.side !== undefined && step.side !== side) continue;
418
423
  try {
419
- checkpoint = await runStep(client, scenario, side, step, at, checkpoint, files, observations);
424
+ checkpoint = await runStep(client, scenario, side, step, symbols, checkpoint, files, observations);
420
425
  } catch (error) {
421
426
  // The step in the reason or the message: the scenario file has many steps.
422
427
  const where = `step ${index + 1} (${stepKindOf(step)})`;
@@ -433,8 +438,9 @@ async function runSide(client: ViceSessionClient, scenario: Scenario, side: Side
433
438
  const stepKindOf = (step: Step) => Object.keys(step).find((key) => STEP_KINDS.includes(key)) ?? "step";
434
439
 
435
440
  /** Runs one step of one side. Gives the number of the last checkpoint. */
436
- async function runStep(client: ViceSessionClient, scenario: Scenario, side: Side, step: Step, at: (location: Location) => number, last: number, files: boolean, observations: Map<string, Observation>): Promise<number> {
441
+ async function runStep(client: ViceSessionClient, scenario: Scenario, side: Side, step: Step, symbols: Map<string, number>, last: number, files: boolean, observations: Map<string, Observation>): Promise<number> {
437
442
  const subject = scenario[side];
443
+ const at = (location: Location) => resolve(location, symbols, side);
438
444
  let checkpoint = last;
439
445
  // Observe first: an observe step may also carry "registers" or "memory".
440
446
  if ("observe" in step) {
@@ -484,7 +490,7 @@ async function runStep(client: ViceSessionClient, scenario: Scenario, side: Side
484
490
  } else if ("load" in step) {
485
491
  await client.programLoad({ path: subject.program });
486
492
  } else if ("autostart" in step) {
487
- await startProgram(client, subject.program, side);
493
+ await startProgram(client, subject.program, side, symbols);
488
494
  } else if ("snapshot" in step) {
489
495
  await client.snapshotRestore(readProjectFile(step.snapshot).bytes);
490
496
  } else if ("normalize" in step) {
@@ -0,0 +1,27 @@
1
+ // The start screen of a loader program in VICE: the loader of a generated
2
+ // source shows it and waits for a key or a fire button that no step of a run
3
+ // or a scenario gives. Not each VICE can press a key of the keyboard matrix,
4
+ // so test and run let the program come to the wait, then set the PC to the
5
+ // code after the wait, as the check of the loader does. The replay core does
6
+ // the same in recording.ts.
7
+
8
+ import { formatC64Address } from "#src/c64.ts";
9
+ import type { ViceSessionClient } from "#src/host-client/vice-session.ts";
10
+ import { startScreenLabels } from "#src/knowledge/start-screen.ts";
11
+
12
+ /** The frames from RUN to the wait: the copies or the unpack of the loader, then the screen. */
13
+ export const START_SCREEN_FRAMES = 3000;
14
+
15
+ /**
16
+ * Goes past the start screen of a program whose symbols have the labels of a
17
+ * shown start screen. "skipped" when it went past, "none" when the program
18
+ * shows no start screen, or the problem when the program did not come to the wait.
19
+ */
20
+ export async function passStartScreen(client: Pick<ViceSessionClient, "runUntil" | "registersSet">, symbols: ReadonlyMap<string, number>): Promise<"skipped" | "none" | { problem: string }> {
21
+ const labels = startScreenLabels(symbols);
22
+ if (labels === undefined) return "none";
23
+ const reached = await client.runUntil({ target: { kind: "address", address: labels.wait, space: "c64" }, timeoutFrames: START_SCREEN_FRAMES });
24
+ if (!reached.reached) return { problem: `the program did not come to the wait of its start screen at ${formatC64Address(labels.wait)} in ${START_SCREEN_FRAMES} frames; it stopped at ${formatC64Address(reached.pc)}` };
25
+ await client.registersSet("c64", { pc: labels.continue });
26
+ return "skipped";
27
+ }
@@ -1,8 +1,9 @@
1
1
  // The c64-testing script. test runs a scenario on the reference and the
2
2
  // rebuild in one emulator; run runs steps on one side and writes what they
3
- // ask for; record and replay play a session in the replay core (c64run) and
4
- // compare the rebuild with it; diff shows what changed between two states;
5
- // checklist gives the Markdown list for a human tester.
3
+ // ask for; keep copies a run into a folder that git keeps; record and replay
4
+ // play a session in the replay core (c64run) and compare the rebuild with it;
5
+ // show tells what a recording holds; diff shows what changed between two
6
+ // states; checklist gives the Markdown list for a human tester.
6
7
 
7
8
  import { COVERAGE, formatC64Address } from "#src/c64.ts";
8
9
  import { isRefusal, Refusal } from "#src/errors.ts";
@@ -20,9 +21,9 @@ import { LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRelative, projectRoot } from
20
21
  import { OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec, type Reply } from "#src/script.ts";
21
22
  import { diffFiles } from "./lib/diff-files.ts";
22
23
  import { CANCELLED, play } from "./lib/play.ts";
23
- import { readRecordFile, record, RECORDING_FILES } from "./lib/recording.ts";
24
+ import { readRecordFile, record, RECORDING_FILES, showRecording } from "./lib/recording.ts";
24
25
  import { replay } from "./lib/replay.ts";
25
- import { runFile } from "./lib/runs.ts";
26
+ import { keepRun, runFile } from "./lib/runs.ts";
26
27
  import { namesOf, readScenario, runScenario, scenarioNames, type Scenario, type ScenarioResult } from "./lib/scenario.ts";
27
28
 
28
29
  /** The default port of the --play page: next to the Host Runtime's 6464. */
@@ -114,15 +115,15 @@ async function recordCommand(call: Call): Promise<Reply> {
114
115
  const local = (path: string) => projectRelative(path).startsWith(`${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/`);
115
116
  const keep = local(out)
116
117
  ? `Git ignores ${out}. To keep the recording as a test and to add its coverage to the project knowledge, record again with --out tests/recordings/<name>.`
117
- : `Commit ${out} with the scenarios. Add ${out}/${RECORDING_FILES.coverage} to the project knowledge as coverage.`;
118
+ : `Commit ${out} with the scenarios. Put the coverage of the recording folder ${out} into the project knowledge.`;
118
119
  const recordFile = local(call.subject(0)) ? ` Git also ignores the record file ${call.subject(0)}. To record again later, keep a copy in a folder that git keeps, for example tests/record/.` : "";
119
120
  const written = new Set(Object.values(RECORDING_FILES).map((name) => projectRelative(`${out}/${name}`)));
120
121
  const evidence = changedEvidence(db, projectRoot(), (file) => written.has(file));
121
122
  const map = projectRelative(`${out}/${RECORDING_FILES.coverage}`);
122
123
  const cited = [
123
124
  ...(evidence.length === 0 ? [] : [" The project knowledge gives the files in evidence as evidence of earlier revisions, and this record changed them."]),
124
- ...(evidence.some((change) => change.file === map) ? [` Put the new ${RECORDING_FILES.coverage} into the project knowledge as coverage: it replaces the map of the earlier recording.`] : []),
125
- ...(evidence.some((change) => change.file !== map) ? [` For a file other than ${RECORDING_FILES.coverage}, examine the facts of its revisions against the new recording.`] : []),
125
+ ...(evidence.some((change) => change.file === map) ? [` Put the coverage of the recording folder ${out} into the project knowledge again: it replaces the map of the earlier recording.`] : []),
126
+ ...(evidence.some((change) => change.file !== map) ? [" For each other file in evidence, examine the facts of its revisions against the new recording."] : []),
126
127
  ].join("");
127
128
  return reply(
128
129
  { result: "PASS", recorded: true, out, ...summary, files, ...(evidence.length === 0 ? {} : { evidence }) },
@@ -155,7 +156,7 @@ const COMMANDS: CommandSpec[] = [
155
156
  {
156
157
  name: "test",
157
158
  summary: "Runs a scenario on the reference and then on the rebuild in one emulator. result is PASS, FAIL with the differences, or INCONCLUSIVE with the reason.",
158
- subjects: [{ name: "<scenario.json>", help: "a scenario file, relative to the project folder. See references/scenario-format.md" }],
159
+ subjects: [{ name: "<scenario.json>", help: "a scenario file, relative to the project folder. See <skill>/references/scenario-format.md" }],
159
160
  options: {
160
161
  out: { ...OPTIONS.out, output: "folder", value: "<dir>", help: "with a FAIL, write both screens, the difference image and memory.json into this folder: each differing memory item with all its bytes, and each byte that differs" },
161
162
  "max-listed": { ...OPTIONS["max-listed"], help: "list at most n differing bytes of each memory item (default 50). The count is always given" },
@@ -165,20 +166,33 @@ const COMMANDS: CommandSpec[] = [
165
166
  {
166
167
  name: "run",
167
168
  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.",
168
- subjects: [{ name: "<run.json>", help: "a run file, relative to the project folder. See references/scenario-format.md, section Runs" }],
169
+ subjects: [{ name: "<run.json>", help: "a run file, relative to the project folder. See <skill>/references/scenario-format.md, section Runs" }],
169
170
  options: { out: { ...OPTIONS.out, output: "folder", value: "<dir>", required: true, help: "the folder for the files of the steps and results.json" } },
170
171
  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.',
171
172
  run: async (call) => {
172
173
  const { output, failed } = await runFile(call.subject(0), call.string("out")!);
173
174
  if (!failed) return { result: "PASS", ...output };
174
- const hint = output.reason !== undefined ? "reason tells why a step did not run. Correct the step or the start, then run again." : "failedExpectations names the expect steps that failed. expectations in results.json gives the expected and the actual values.";
175
+ const hint = output.reason !== undefined ? "reason tells why a step did not run. Correct the step or the start, then run again." : "failedExpectations names the expect steps that failed. expectations gives the expected and the actual values.";
175
176
  return reply({ result: "FAIL", ...output }, { hint });
176
177
  },
177
178
  },
179
+ {
180
+ name: "keep",
181
+ summary: "Keeps a run as evidence in a new folder that git keeps: the run file as run.json, its results, and the files in .c64-re-tools/local/ that the run file starts from. The run file in the folder gets the new paths of those files.",
182
+ subjects: [
183
+ { name: "<run.json>", help: "the run file, relative to the project folder" },
184
+ { name: "<out>", help: "the --out folder of the run" },
185
+ { name: "<folder>", help: "the new folder, for example runs/<name>" },
186
+ ],
187
+ run: (call) => {
188
+ const kept = keepRun(call.subject(0), call.subject(1), call.subject(2));
189
+ return reply(kept, { hint: `Commit ${kept.out}. Give its files as evidence, for example ${kept.out}/results.json.` });
190
+ },
191
+ },
178
192
  {
179
193
  name: "record",
180
- summary: "Plays the steps of a record file on the reference, and writes the session as a recording folder: recording.json, reads.txt and coverage.bin. result is FAIL when the session did not complete.",
181
- subjects: [{ name: "<record.json>", help: "a record file, relative to the project folder. See references/recording-format.md" }],
194
+ summary: "Plays the steps of a record file on the reference, and writes the session into the recording folder --out. result is FAIL when the session did not complete.",
195
+ subjects: [{ name: "<record.json>", help: "a record file, relative to the project folder. See <skill>/references/recording-format.md" }],
182
196
  options: {
183
197
  out: { ...OPTIONS.out, output: "folder", value: "<dir>", required: true, help: "the recording folder, for example tests/recordings/<name>" },
184
198
  play: { kind: "flag", help: "a person plays after the steps: the script prints the address of a page on stderr. The page shows the start screen frozen until Start (Enter). End (F12) saves the recording, Cancel (F11) ends without one" },
@@ -187,6 +201,13 @@ const COMMANDS: CommandSpec[] = [
187
201
  },
188
202
  run: recordCommand,
189
203
  },
204
+ {
205
+ name: "show",
206
+ summary: "What a recording holds, without a replay: the program, the frames, the events, the comparison of the record file, each input site with its reads and the changes of its value, and the counts of the coverage map.",
207
+ subjects: [{ name: "<recording>", help: "a folder that record wrote, relative to the project folder" }],
208
+ options: { "max-listed": { ...OPTIONS["max-listed"], help: "list at most n input sites (default 50). The count is always given" } },
209
+ run: (call) => showRecording(call.subject(0).replace(/\/+$/, ""), call.count("max-listed")!),
210
+ },
190
211
  {
191
212
  name: "replay",
192
213
  summary: "Replays a recording on the reference, which must end with the recorded state, and with --rebuild on the rebuild, which must have the state of the reference at each checkpoint. result is PASS, FAIL or INCONCLUSIVE.",
@@ -80,12 +80,11 @@ The script refuses a step in an old form. The message gives the step to write.
80
80
  - A range is `<start>-<end>`, for example `'$c000-$cfff'`. In a JSON file, a range is `start` and `end`.
81
81
  - Bytes in a JSON file are hex in a field `data`, for example `"data": "a900"`.
82
82
  - Write each file that you make for your work in `.c64-re-tools/local/` of the project. Git ignores that folder. Examples are results, batches, step files, runs, snapshots and memory dumps.
83
- - The script refuses an `--out` path in `.c64-re-tools/knowledge/` and the index of the knowledge. Change the project knowledge only with the commands that change it.
83
+ - The script refuses an `--out` path in `.c64-re-tools/knowledge/`. Change the project knowledge only with the commands that change it.
84
84
  - The script refuses a folder where the command writes a file. It refuses a file where the command writes a folder.
85
85
  - When a test or another file is the evidence for a finding in the project knowledge, move it out of `.c64-re-tools/local/` first. The project knowledge refuses that evidence in that folder.
86
- - A coverage map can stay in `.c64-re-tools/local/`. The project knowledge keeps its ranges and its SHA-256.
87
- - Do not move a coverage map after you put it into the project knowledge. The knowledge refers to the map by its path at that time.
88
- - Put a run that is evidence in `runs/<name>/`, with its run file, its results and its snapshot files. Change the paths in the run file to the new paths. Then git keeps them, and another person can do the run again.
86
+ - A coverage map can stay in `.c64-re-tools/local/`. Do not move a coverage map after you put it into the project knowledge.
87
+ - To keep a run as evidence, use the command that keeps a run. It copies the run, its results and its snapshot files into `runs/<name>/`, and it changes the paths in the copy. Then git keeps them, and another person can do the run again.
89
88
  - A shell redirect (`>`) is relative to the working directory, not to the project folder. From the folder above the project, write `<folder>/.c64-re-tools/local/result.json`.
90
89
 
91
90
  ---
@@ -297,24 +296,15 @@ Do not record the unpacker in the project knowledge, unless the user asks you to
297
296
 
298
297
  Each command prints one JSON envelope on one line on stdout. Notes go to stderr.
299
298
 
300
- On success, the exit code is 0:
301
-
302
- ```json
303
- {"ok": true, "command": "<command>", "body": {}, "hint": "...", "nextAction": "..."}
304
- ```
305
-
306
- On failure, the exit code is 2:
307
-
308
- ```json
309
- {"ok": false, "command": "<command>", "code": "<code>", "error": "...", "hint": "...", "nextAction": "..."}
310
- ```
311
-
299
+ - On success, the exit code is 0: `{"ok": true, "command": "<command>", "body": {}, "hint": "...", "nextAction": "..."}`
300
+ - On failure, the exit code is 2: `{"ok": false, "command": "<command>", "code": "<code>", "error": "...", "hint": "...", "nextAction": "..."}`
312
301
  - `body` holds the result. The section of each command gives the fields of its body.
313
302
  - A check gives its verdict in `body.result`: `PASS`, `FAIL` or `INCONCLUSIVE`. The exit code is 0 for each verdict. Thus read `body.result`, not the exit code.
314
- - `error` is one sentence. It tells what is wrong.
315
- - `hint` tells what to do or what to examine. Read it before your next step. Some envelopes have no `hint`.
316
- - `nextAction` is a full command line. It runs from any directory. Run it when it agrees with your task. Some envelopes have no `nextAction`.
317
- - `code` does not change between versions. Do the action for the code:
303
+ - `error` is one sentence. It tells what is wrong. `hint` tells what to do or what to examine. Read it before your next step.
304
+ - `nextAction` is a full command line. It runs from any directory. Run it when it agrees with your task.
305
+ - A list has `count`, `listed` and `rest`. `listed` holds at most `--max-listed` items. `rest` tells how to get the other items. A file that the command wrote has `out`, `bytes` and `sha256`.
306
+ - To get only some fields of `body`, give `--fields <path>,<path>`, for example `--fields count,listed.start`. A path through a list gives that field of each item. Do not write code to filter an envelope.
307
+ - To get the command list, run the script with no arguments. To get the subjects and the flags of one command, run `<command> --help`.
318
308
 
319
309
  | `code` | Action |
320
310
  |---|---|
@@ -322,13 +312,3 @@ On failure, the exit code is 2:
322
312
  | `invalid-input`, `not-found` | Correct the call as `hint` tells. Then run the command again. |
323
313
  | `operation-failed` | Give `error` and `hint` to the user. |
324
314
  | Another code | Do as `hint` tells. |
325
-
326
- These fields have the same meaning in each body:
327
-
328
- | Field | Meaning |
329
- |---|---|
330
- | `out`, `bytes`, `sha256` | A file that the command wrote: its path, its size and its SHA-256. |
331
- | `count`, `listed`, `rest` | A list. `count` is the number of items. `listed` holds the first items, at most `--max-listed`. `rest` tells how to get the other items. |
332
-
333
- To get the command list, run the script with no arguments. The envelope has `command: "help"`, and `body.commands` gives the name, the summary and the synopsis of each command.
334
- To get the subjects and the flags of one command, run `<command> --help`. Then `body.subjects` and `body.options` give them.
@@ -13,18 +13,12 @@ This skill does not analyse code statically. It does not write project knowledge
13
13
 
14
14
  The MCP server knows the machine and the emulator. Its instructions, its tool descriptions, its result fields and its error messages give the facts of the machine and the known flaws of the emulator. This skill tells how to use the tools for a task. If this skill and a tool description do not agree, obey the tool description.
15
15
 
16
- ## Inputs
17
-
18
- - The machine action or the runtime question.
19
- - The target address, state or condition, when the question needs one.
20
- - The project path of the program or disk to load, when the question needs one.
21
-
22
- A tool takes addresses, not names. The server instructions give the address format. Get the address of a name from the project knowledge.
23
-
24
16
  ## Tools
25
17
 
26
18
  Use only the MCP tools. Each MCP session has its own machine. Nothing else can change that machine.
27
19
 
20
+ A tool takes addresses, not names. The server instructions give the address format. To get the address of a name, read the name in the project knowledge.
21
+
28
22
  | Need | C64 tool |
29
23
  |---|---|
30
24
  | Reset, power cycle | `c64_reset` |
@@ -35,6 +29,7 @@ Use only the MCP tools. Each MCP session has its own machine. Nothing else can c
35
29
  | Run to a place and read the machine there in one call | `c64_run_until` with `observe` and `history` |
36
30
  | Each access or routine entry over many frames | `c64_trace` |
37
31
  | Stop on an instruction address, stop on a memory access | `c64_breakpoint`, `c64_watchpoint` |
32
+ | Find the instruction that reads or writes an address, and when | `c64_watchpoint` with the access, then `c64_execution` or `c64_run_until`. The stop gives `pc`. |
38
33
  | Memory | `c64_memory_read`, `c64_memory_write`, `c64_memory_search`, `c64_memory_compare` |
39
34
  | CPU registers | `c64_registers` |
40
35
  | Code as it is in memory now | `c64_disassemble` |
@@ -88,28 +83,11 @@ The emulator has no window. When the user must type, play or look at the machine
88
83
 
89
84
  The result field `notCarried` names the data that the open or the close cleared.
90
85
 
91
- ## Knowledge
92
-
93
- Read:
94
- - the current knowledge for each address and range that the question touches.
95
-
96
- Automatic write:
97
- - none.
86
+ ## Knowledge and result
98
87
 
99
- Write after interpretation:
100
- - a symbol, a region or a comment that the runtime evidence justifies. Record it in the project knowledge.
101
-
102
- Do not store:
103
- - breakpoints or watchpoints
104
- - memory reads
105
- - temporary machine state
106
- - a screen capture, unless the user asks for it as an artifact
107
-
108
- ## Result
109
-
110
- The result is the runtime state or evidence that the question asks for.
111
-
112
- If you cannot get the machine into the necessary state, say which state you could not get. Say what you tried.
88
+ - Record in the project knowledge only a symbol, a region or a comment that the runtime evidence justifies.
89
+ - Do not record breakpoints, watchpoints, memory reads or machine state. Record a screen capture only when the user asks for it.
90
+ - If you cannot get the machine into the necessary state, tell the user which state. Tell what you tried.
113
91
 
114
92
  ## Failure and conflicts
115
93
 
@@ -124,10 +102,3 @@ An error is `{"error": {"code": "...", "message": "..."}}`. The message tells wh
124
102
  - A different code: the message names the cause. Change the call, or report the cause.
125
103
 
126
104
  If the runtime evidence does not agree with the current knowledge, do not change the knowledge. Report the conflict with the runtime evidence. Then resolve the conflict in the project knowledge.
127
-
128
- ## Other tasks
129
-
130
- - To explain code without a run, analyze the program statically.
131
- - Record a durable conclusion in the project knowledge.
132
- - To compare runs or to assert values in a run, write a test run file.
133
- - To find the meaning of a C64 address or register, read the memory map of the C64.
package/src/build-name.ts CHANGED
@@ -4,7 +4,8 @@
4
4
  // name when it is on, no_<name> when it is off. A build of an entry other
5
5
  // than main.asm adds the entry, for example clean_loader. The loader of the
6
6
  // packed form alone is only its copier, so its build is clean_copier: the loader
7
- // program, which generate packs, keeps clean_loader. A source without
7
+ // program, which generate or a build with switch values packs, keeps
8
+ // clean_loader. A source without
8
9
  // config.asm and without a release keeps the name of its entry. The symbols
9
10
  // of a build go into symbols/ next to the program, so the program folder
10
11
  // holds only programs.
@@ -30,6 +31,16 @@ export function configValues(text: string): Map<string, 0 | 1> {
30
31
  return values;
31
32
  }
32
33
 
34
+ /**
35
+ * The config.asm text with other values for some switches: the value line of
36
+ * each given name gets the given value, and the other lines stay as they are.
37
+ * A build takes the switch values this way: ACME refuses a define of a symbol
38
+ * that config.asm also sets.
39
+ */
40
+ export function withConfigValues(text: string, values: ReadonlyMap<string, 0 | 1>): string {
41
+ return text.replace(/^([ \t]*([A-Z][A-Z0-9_]*)[ \t]*=[ \t]*)[01](?=[ \t]*(?:;[^\r\n]*)?\r?$)/gm, (line: string, head: string, name: string) => (values.has(name) ? `${head}${values.get(name)}` : line));
42
+ }
43
+
33
44
  /** What a build is made of: a release, or the values of config.asm with the default of each switch (0 when the defaults do not have it). */
34
45
  export type BuildKind = { release: string } | { values: ReadonlyMap<string, number>; defaults: ReadonlyMap<string, number> };
35
46
 
@@ -251,6 +251,14 @@ export interface RevisionChanges {
251
251
  closed: HistoryEntry[];
252
252
  }
253
253
 
254
+ /** The rows that a revision added and closed, counted by kind of row: only the kinds that it changed. */
255
+ export function revisionCounts(changes: Pick<RevisionChanges, "added" | "closed">): Partial<Record<HistoryEntry["entity"], { added: number; closed: number }>> {
256
+ const counts: Partial<Record<HistoryEntry["entity"], { added: number; closed: number }>> = {};
257
+ for (const entry of changes.added) (counts[entry.entity] ??= { added: 0, closed: 0 }).added++;
258
+ for (const entry of changes.closed) (counts[entry.entity] ??= { added: 0, closed: 0 }).closed++;
259
+ return counts;
260
+ }
261
+
254
262
  /** One revision and exactly what it changed. */
255
263
  export function revision(db: DatabaseSync | undefined, text: string): RevisionChanges {
256
264
  const id = resolveRevision(db, text);
@@ -7,7 +7,7 @@ import { createHash } from "node:crypto";
7
7
  import type { DatabaseSync } from "node:sqlite";
8
8
 
9
9
  import { Refusal } from "../errors.ts";
10
- import { type AddressRange, COVERAGE, formatC64Address } from "../c64.ts";
10
+ import { type AddressRange, COVERAGE, formatC64Address, formatC64Byte } from "../c64.ts";
11
11
 
12
12
  import { COVERAGE_KINDS, DEFAULT_SPACE, MEMORY_ROW, type CoverageKind, type Space } from "./schema.ts";
13
13
  import { coverageRuns } from "./read.ts";
@@ -241,6 +241,52 @@ export function addCoverage(
241
241
  });
242
242
  }
243
243
 
244
+ /** What the runs did at an address: executed (x wins), read and written (rw), read, written, or nothing (-). */
245
+ export type Access = "x" | "rw" | "r" | "w" | "-";
246
+
247
+ /** The kinds of coverage ranges that count as an execute, a read and a write: RAM, ROM and the I/O area. */
248
+ const EXECUTES: readonly CoverageKind[] = ["x", "rom-x", "io-x"];
249
+ const READS: readonly CoverageKind[] = ["r", "rom-r", "io-r"];
250
+ const WRITES: readonly CoverageKind[] = ["w", "io-w"];
251
+
252
+ /** The access of a set of coverage kinds: an execute wins, then a read and a write together. */
253
+ function accessOf(kinds: ReadonlySet<CoverageKind>): Access {
254
+ const has = (list: readonly CoverageKind[]) => list.some((kind) => kinds.has(kind));
255
+ if (has(EXECUTES)) return "x";
256
+ if (has(READS)) return has(WRITES) ? "rw" : "r";
257
+ return has(WRITES) ? "w" : "-";
258
+ }
259
+
260
+ /** True when an address is in ranges as text: "$1000-$1002 $1005". */
261
+ function inRanges(text: string, address: number): boolean {
262
+ for (const item of text.split(" ")) {
263
+ const [start, end] = item.split("-");
264
+ if (address >= Number.parseInt(start!.slice(1), 16) && address <= Number.parseInt((end ?? start)!.slice(1), 16)) return true;
265
+ }
266
+ return false;
267
+ }
268
+
269
+ /**
270
+ * The access of the runs at an address in a space: the access of each coverage
271
+ * map that the space has (by its path, also a map without accesses), and the
272
+ * joined access of all maps. Undefined when the space has no coverage map.
273
+ */
274
+ export function coverageAccess(db: DatabaseSync | undefined, space: Space = DEFAULT_SPACE): ((address: number) => { maps: Array<{ map: string; access: Access }>; access: Access }) | undefined {
275
+ if (db === undefined) return undefined;
276
+ const maps = [...new Set(coverageRuns(db).filter((run) => run.space === space).map((run) => run.name))];
277
+ if (maps.length === 0) return undefined;
278
+ const rows = db.prepare("SELECT map, kind, ranges FROM current_coverage WHERE space = ?").all(space) as Array<{ map: string; kind: CoverageKind; ranges: string }>;
279
+ return (address) => {
280
+ const all = new Set<CoverageKind>();
281
+ const each = maps.map((map) => {
282
+ const kinds = new Set(rows.filter((row) => row.map === map && inRanges(row.ranges, address)).map((row) => row.kind));
283
+ for (const kind of kinds) all.add(kind);
284
+ return { map, access: accessOf(kinds) };
285
+ });
286
+ return { maps: each, access: accessOf(all) };
287
+ };
288
+ }
289
+
244
290
  /** The program of a space, or undefined when the knowledge has no bytes for it. */
245
291
  export function programImage(db: DatabaseSync | undefined, space: Space = DEFAULT_SPACE): ProgramImage | undefined {
246
292
  if (db === undefined) return undefined;
@@ -369,3 +415,29 @@ export function releaseImage(db: DatabaseSync | undefined, label: string, space:
369
415
  }
370
416
  return { segments, byteAt: (address) => memory[address]! };
371
417
  }
418
+
419
+ /** The bytes of one !byte line of patch code. */
420
+ const PATCH_LINE_BYTES = 8;
421
+
422
+ /**
423
+ * The bytes of a release in [start, end] as patch code: !byte lines. The base
424
+ * release is refused: its bytes are the program, and a patch holds the other
425
+ * state. A release without a byte at each address of the range is refused.
426
+ */
427
+ export function releaseCode(db: DatabaseSync | undefined, label: string, start: number, end: number, space: Space = DEFAULT_SPACE): string {
428
+ const range = `${formatC64Address(start)}-${formatC64Address(end)}`;
429
+ const release = db?.prepare("SELECT base FROM current_releases WHERE space = ? AND label = ?").get(space, label) as { base: number } | undefined;
430
+ if (release === undefined) throw new Refusal("not-found", `There is no release ${label}${space === DEFAULT_SPACE ? "" : ` in ${space}`}. Record it first with its file.`);
431
+ 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}.`);
432
+ const image = releaseImage(db, label, space)!;
433
+ const inside = (address: number) => image.segments.some((segment) => address >= segment.start && address <= segment.end);
434
+ for (let address = start; address <= end; address++) {
435
+ if (!inside(address)) throw new Refusal("invalid-input", `The release ${label} has no byte at ${formatC64Address(address)}, in the range ${range}. Give a range inside the bytes of the release.`);
436
+ }
437
+ const lines: string[] = [];
438
+ for (let at = start; at <= end; at += PATCH_LINE_BYTES) {
439
+ const bytes = Array.from({ length: Math.min(PATCH_LINE_BYTES, end - at + 1) }, (_, offset) => formatC64Byte(image.byteAt(at + offset)));
440
+ lines.push(`!byte ${bytes.join(",")}`);
441
+ }
442
+ return lines.join("\n");
443
+ }