@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
@@ -2,8 +2,8 @@
2
2
  // project folder (--project, or the one found from the working directory).
3
3
  // Each command prints one JSON result.
4
4
 
5
- import { createHash } from "node:crypto";
6
- import { readFileSync } from "node:fs";
5
+ import { createHash, randomInt } from "node:crypto";
6
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
7
7
  import { join } from "node:path";
8
8
  import type { DatabaseSync } from "node:sqlite";
9
9
 
@@ -14,11 +14,11 @@ import { readProjectFile, writeReported } from "#src/host-client/transfer.ts";
14
14
  import { CONFLICT_RULES, conflicts, type Conflict } from "#src/knowledge/conflicts.ts";
15
15
  import { openForRead, withWrite } from "#src/knowledge/database.ts";
16
16
  import { operandText } from "#src/knowledge/expression.ts";
17
- import { historyAt, historyNamed, historyOfMacro, historyOfSwitch, revision, revisionNote, revisions, type HistoryEntry } from "#src/knowledge/history.ts";
17
+ import { historyAt, historyNamed, historyOfMacro, historyOfSwitch, revision, revisionCounts, revisionNote, revisions, type HistoryEntry } from "#src/knowledge/history.ts";
18
18
  import { joinBatches, type Batch, type JoinChoice, type JoinClash } from "#src/knowledge/join.ts";
19
19
  import { knowledgeNames } from "#src/knowledge/names.ts";
20
- import { addCoverage, coverageRangeCounts, memoryRows, operandImages as programImages, programCoverage, programImage, requireProgram, setImage, type ImageRequest } from "#src/knowledge/program.ts";
21
- import { startScreenOfStage } from "#src/knowledge/start-screen.ts";
20
+ import { addCoverage, coverageAccess, coverageRangeCounts, memoryRows, operandImages as programImages, programCoverage, programImage, releaseCode, requireProgram, setImage, type ImageRequest } from "#src/knowledge/program.ts";
21
+ import { coloursOfCapture, startScreenOfCapture, startScreenOfStage } from "#src/knowledge/start-screen.ts";
22
22
  import {
23
23
  analyzerNamesAt,
24
24
  at,
@@ -27,6 +27,7 @@ import {
27
27
  coverageRuns,
28
28
  currentRevision,
29
29
  currentStartScreen,
30
+ goes,
30
31
  listAnalyzerNames,
31
32
  listComments,
32
33
  listMacros,
@@ -42,8 +43,11 @@ import {
42
43
  listSuppressions,
43
44
  listSymbols,
44
45
  operandAt,
46
+ REFERENCE_DIRECTIONS,
47
+ referenceCounts,
45
48
  referencesFrom,
46
49
  referencesTo,
50
+ regionCounts,
47
51
  search,
48
52
  symbolAt,
49
53
  type CommentRow,
@@ -53,6 +57,7 @@ import {
53
57
  type OperandRow,
54
58
  type PatchRow,
55
59
  type ReferenceRow,
60
+ type ReferenceDirection,
56
61
  type RegionRow,
57
62
  type ReleaseRow,
58
63
  type StartScreenRow,
@@ -97,8 +102,11 @@ import {
97
102
  type WriteContext,
98
103
  } from "#src/knowledge/write.ts";
99
104
  import { platformNames } from "#src/platform.ts";
105
+ import { coverageMapOf } from "#src/knowledge/recording-files.ts";
100
106
  import { isInside, LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRelative, projectRoot, resolveProjectPath } from "#src/project.ts";
101
107
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec, type OptionSpec, type SubjectSpec } from "#src/script.ts";
108
+ import { isoCet } from "#src/time.ts";
109
+ import { CHECK_CLASSES, CHECK_VERDICTS, checkFolder, checkResult, pickSample, seedOfFolder, withVerdict, type CheckClass, type Sample, type Verdicts } from "./lib/check.ts";
102
110
  import { listing, listingText, type ListingSource } from "./lib/listing.ts";
103
111
 
104
112
  function oneOf<T extends string>(values: readonly T[], value: string | undefined, what: string): T {
@@ -161,6 +169,8 @@ const release = (row: ReleaseRow) => ({
161
169
  label: row.label,
162
170
  base: row.base,
163
171
  define: `--define ${RELEASE_DEFINE}${row.label}=1`,
172
+ ...(row.file === undefined ? {} : { file: row.file }),
173
+ ...(row.sha256 === undefined ? {} : { sha256: row.sha256 }),
164
174
  ...(row.comment === undefined ? {} : { comment: row.comment }),
165
175
  origin: row.origin,
166
176
  revision: row.revision,
@@ -265,21 +275,30 @@ function reasonsOf(db: DatabaseSync | undefined, rows: SuppressionRow[]): Map<st
265
275
  return reasons;
266
276
  }
267
277
 
278
+ /** The bytes of a program: the byte at an address inside a segment, else undefined. */
279
+ function programBytes(image: { segments: ReadonlyArray<{ start: number; end: number }>; byteAt: (address: number) => number }): (address: number) => number | undefined {
280
+ return (at) => (image.segments.some((segment) => at >= segment.start && at <= segment.end) ? image.byteAt(at) : undefined);
281
+ }
282
+
283
+ /** The name of an address: a user or LLM name, else the platform name; an analyzer name in symbols (knowledge from an older version) gives way to it. */
284
+ function nameOf(db: DatabaseSync | undefined, space: string): (at: number) => string | undefined {
285
+ const platform = new Map(space === DEFAULT_SPACE ? platformNames().map((entry) => [entry.address, entry.name]) : []);
286
+ return (at) => {
287
+ const own = symbolAt(db, at, space);
288
+ return own !== undefined && isSemantic(own.origin) ? own.name : (platform.get(at) ?? own?.name);
289
+ };
290
+ }
291
+
268
292
  /** The lookups of a listing: the program and the coverage in the knowledge, the knowledge of the space and the platform names of the C64. */
269
293
  function listingSource(db: DatabaseSync | undefined, space: string): ListingSource {
270
294
  const image = requireProgram(db, space);
271
295
  const coverage = programCoverage(db, space)?.map;
272
- const inside = (at: number) => image.segments.some((segment) => at >= segment.start && at <= segment.end);
273
- const platform = new Map(space === DEFAULT_SPACE ? platformNames().map((entry) => [entry.address, entry.name]) : []);
296
+ const byteAt = programBytes(image);
274
297
  const entries = space === DEFAULT_SPACE ? platformNames().filter((entry) => entry.end > entry.address) : [];
275
298
  return {
276
- byteAt: (at) => (inside(at) ? image.byteAt(at) : undefined),
277
- entryStart: (at) => (inside(at) ? undefined : entries.find((entry) => at > entry.address && at <= entry.end)?.address),
278
- // A user or LLM name, else the platform name; an analyzer name in symbols (knowledge from an older version) gives way to it.
279
- nameOf: (at) => {
280
- const own = symbolAt(db, at, space);
281
- return own !== undefined && isSemantic(own.origin) ? own.name : (platform.get(at) ?? own?.name);
282
- },
299
+ byteAt,
300
+ entryStart: (at) => (byteAt(at) !== undefined ? undefined : entries.find((entry) => at > entry.address && at <= entry.end)?.address),
301
+ nameOf: nameOf(db, space),
283
302
  secondNames: (at) => analyzerNamesAt(db, at, space).map((row) => row.name),
284
303
  regions: listRegions(db, undefined, undefined, undefined, space),
285
304
  comments: (at) => {
@@ -409,6 +428,14 @@ const BATCH_FIELDS: Record<BatchOperation["op"], string[]> = {
409
428
  unuse: ["start"],
410
429
  };
411
430
 
431
+ /** The fields of a batch write that it can leave out. */
432
+ const BATCH_OPTIONAL = new Set(["rename.kind", "classify.element", "module.title", "operand.symbol", "operand.offset", "operand.expression", "patch.code", "patch.comment", "unpatch.switch", "macro.params", "macro.comment", "use.args"]);
433
+
434
+ /** The fields of each op of a batch, for the help of apply: the optional ones in brackets. */
435
+ const BATCH_OPS = Object.entries(BATCH_FIELDS)
436
+ .map(([op, fields]) => `${op}: ${fields.map((name) => (BATCH_OPTIONAL.has(`${op}.${name}`) ? `[${name}]` : name)).join(", ")}`)
437
+ .join("; ");
438
+
412
439
  /** A write of a batch as JSON again: addresses as $ and four hex digits, the C64 space left out. */
413
440
  function batchJson(write: BatchOperation): Record<string, unknown> {
414
441
  const out: Record<string, unknown> = {};
@@ -463,6 +490,28 @@ const originsOf = (call: Call) => {
463
490
  return value === undefined ? undefined : originFilter(value);
464
491
  };
465
492
 
493
+ /** A file of the check of a seed, or undefined when the project has none. */
494
+ function checkFile<T>(seed: number, file: "sample.json" | "verdicts.json"): T | undefined {
495
+ const path = `${checkFolder(seed)}/${file}`;
496
+ if (!existsSync(resolveProjectPath(path))) return undefined;
497
+ try {
498
+ return JSON.parse(readProjectFile(path).bytes.toString("utf8")) as T;
499
+ } catch (error) {
500
+ if (error instanceof SyntaxError) throw new Refusal("invalid-input", `${path} is not JSON. Start a check with another seed.`);
501
+ throw error;
502
+ }
503
+ }
504
+
505
+ /** The sample of the check of a seed; refuses a seed without a check. */
506
+ function sampleOf(seed: number): Sample {
507
+ const sample = checkFile<Sample>(seed, "sample.json");
508
+ if (sample === undefined) throw new Refusal("not-found", `The project has no check of seed ${seed}. Get the seeds of the checks with checks, or start a check with sample --seed ${seed}.`);
509
+ return sample;
510
+ }
511
+
512
+ const SEED: SubjectSpec = { name: "<seed>", help: "the seed of a check" };
513
+ const seedOf = (call: Call) => call.parseCount(call.subject(0), "<seed>", 0, 999_999);
514
+
466
515
  /** A read command: it opens the knowledge for reading, and its answer shows the conflicts that a git merge left. */
467
516
  function readCommand(spec: Omit<CommandSpec, "run">, answer: (db: DatabaseSync | undefined, call: Call) => Record<string, unknown>): CommandSpec {
468
517
  return {
@@ -526,24 +575,35 @@ function textOrFile(call: Call, option: string): string | undefined {
526
575
  const commaList = (value: string) => (value.trim() === "" ? [] : value.split(",").map((item) => item.trim()));
527
576
 
528
577
  const READ_COMMANDS: CommandSpec[] = [
529
- readCommand({ name: "at", summary: "Everything known at one address.", subjects: [ADDRESS] }, (db, call) => {
530
- const known = at(db, call.parseAddress(call.subject(0), "<address>"), call.space);
531
- return {
532
- ...(call.space === DEFAULT_SPACE ? {} : { space: call.space }),
533
- address: formatC64Address(known.address),
534
- ...(known.symbol === undefined ? {} : { symbol: symbol(known.symbol) }),
535
- ...(known.analyzerNames.length === 0 ? {} : { analyzerNames: known.analyzerNames.map(symbol) }),
536
- ...(known.region === undefined ? {} : { region: region(known.region) }),
537
- comments: known.comments.map(comment),
538
- referencesFrom: known.referencesFrom.map(reference),
539
- referencesTo: known.referencesTo.map(reference),
540
- ...(known.operand === undefined ? {} : { operand: operand(known.operand) }),
541
- ...(known.patch === undefined ? {} : { patch: patch(known.patch) }),
542
- ...(known.macroUse === undefined ? {} : { macroUse: macroUse(known.macroUse) }),
543
- ...(known.suppressions.length === 0 ? {} : { suppressions: known.suppressions.map(suppression) }),
544
- revision: known.revision,
545
- };
546
- }),
578
+ readCommand(
579
+ {
580
+ name: "at",
581
+ summary: "Everything known at each address, with the access of the runs in each coverage map of the space and the joined access (x executed, rw read and written, r read, w written, - none).",
582
+ subjects: [{ ...ADDRESS, list: true }],
583
+ },
584
+ (db, call) => {
585
+ const access = coverageAccess(db, call.space);
586
+ const addresses = call.subjects.map((text) => {
587
+ const known = at(db, call.parseAddress(text, "<address>"), call.space);
588
+ const runs = access?.(known.address);
589
+ return {
590
+ address: formatC64Address(known.address),
591
+ ...(known.symbol === undefined ? {} : { symbol: symbol(known.symbol) }),
592
+ ...(known.analyzerNames.length === 0 ? {} : { analyzerNames: known.analyzerNames.map(symbol) }),
593
+ ...(known.region === undefined ? {} : { region: region(known.region) }),
594
+ comments: known.comments.map(comment),
595
+ referencesFrom: known.referencesFrom.map(reference),
596
+ referencesTo: known.referencesTo.map(reference),
597
+ ...(known.operand === undefined ? {} : { operand: operand(known.operand) }),
598
+ ...(known.patch === undefined ? {} : { patch: patch(known.patch) }),
599
+ ...(known.macroUse === undefined ? {} : { macroUse: macroUse(known.macroUse) }),
600
+ ...(known.suppressions.length === 0 ? {} : { suppressions: known.suppressions.map(suppression) }),
601
+ ...(runs === undefined ? {} : { coverage: runs.maps, access: runs.access }),
602
+ };
603
+ });
604
+ return { ...(call.space === DEFAULT_SPACE ? {} : { space: call.space }), revision: currentRevision(db), addresses };
605
+ },
606
+ ),
547
607
  readCommand(
548
608
  {
549
609
  name: "search",
@@ -565,13 +625,65 @@ const READ_COMMANDS: CommandSpec[] = [
565
625
  return { symbols: list(call, listSymbols(db, rangeOf(call), kind, originsOf(call), call.space), symbol, RANGE_REST) };
566
626
  },
567
627
  ),
568
- readCommand({ name: "regions", summary: "The regions: code, data, tables and the other types.", options: { ...FILTER, type: { kind: "choice", value: "<type>", choices: REGION_TYPES, help: `one of ${REGION_TYPES.join(", ")}` }, ...LIST } }, (db, call) => ({
569
- regions: list(call, listRegions(db, rangeOf(call), call.string("type") as (typeof REGION_TYPES)[number] | undefined, originsOf(call), call.space), region, RANGE_REST),
570
- })),
628
+ readCommand(
629
+ {
630
+ name: "regions",
631
+ summary: "The regions: code, data, tables and the other types, with the count and the bytes in the range of each type.",
632
+ options: { ...FILTER, type: { kind: "choice", value: "<type>", choices: REGION_TYPES, help: `one of ${REGION_TYPES.join(", ")}` }, ...LIST },
633
+ },
634
+ (db, call) => {
635
+ const rows = listRegions(db, rangeOf(call), call.string("type") as (typeof REGION_TYPES)[number] | undefined, originsOf(call), call.space);
636
+ return { regions: list(call, rows, region, RANGE_REST), byType: regionCounts(rows, rangeOf(call)) };
637
+ },
638
+ ),
571
639
  readCommand({ name: "comments", summary: "The comments.", options: { ...FILTER, ...LIST } }, (db, call) => ({ comments: list(call, listComments(db, rangeOf(call), originsOf(call), call.space), comment, RANGE_REST) })),
572
- readCommand({ name: "references", summary: "The references: calls, jumps, reads, writes and pointers.", options: { ...FILTER, kind: REFERENCE_KIND, ...LIST } }, (db, call) => ({
573
- references: list(call, listReferences(db, rangeOf(call), call.string("kind") as (typeof REFERENCE_KINDS)[number] | undefined, originsOf(call), call.space), reference, RANGE_REST),
574
- })),
640
+ readCommand(
641
+ {
642
+ name: "sample",
643
+ summary: "Selects comments at random for a check by an agent that did not write them, and starts the check of the seed.",
644
+ options: {
645
+ count: { kind: "count", value: "<n>", min: 1, max: 500, default: 30, help: "the comments in the sample (default 30)" },
646
+ seed: { kind: "count", value: "<n>", min: 0, max: 999_999, help: "the seed of the sample. Without it, the script selects one" },
647
+ range: OPTIONS.range,
648
+ origin: { ...OPTIONS.origin, help: "the origins of the comments: llm (the default), user, semantic, or a comma list" },
649
+ },
650
+ notes: "Record the verdict of each comment with verdict. Get the comments and the result with checks <seed>. A seed whose check has verdicts is refused.",
651
+ },
652
+ (db, call) => {
653
+ const seed = call.count("seed") ?? randomInt(1_000_000);
654
+ if (checkFile(seed, "verdicts.json") !== undefined) throw new Refusal("conflict", `The check of seed ${seed} has verdicts. Give another seed.`);
655
+ const rows = listComments(db, rangeOf(call), originFilter(call.string("origin") ?? "llm"), call.space);
656
+ const comments = pickSample(rows, seed, call.count("count")!).map((row) => {
657
+ const name = symbolAt(db, row.address, call.space)?.name;
658
+ return { ...comment(row), ...(name === undefined ? {} : { name }) };
659
+ });
660
+ const sample: Sample = { seed, createdAt: isoCet(), revision: currentRevision(db), ...(call.space === DEFAULT_SPACE ? {} : { space: call.space }), population: rows.length, comments };
661
+ writeReported(`${checkFolder(seed)}/sample.json`, `${JSON.stringify(sample, null, 2)}\n`, { what: "sample" });
662
+ return { seed, revision: sample.revision, population: rows.length, sampled: comments.length };
663
+ },
664
+ ),
665
+ readCommand(
666
+ {
667
+ name: "references",
668
+ summary: "The references: calls, jumps, reads, writes and pointers, with their counts by kind and by target.",
669
+ options: {
670
+ ...FILTER,
671
+ kind: REFERENCE_KIND,
672
+ direction: { kind: "choice", value: "<in|out|inside>", choices: REFERENCE_DIRECTIONS, help: "with --range: in from outside the range, out of the range, or inside it at both ends" },
673
+ ...LIST,
674
+ },
675
+ },
676
+ (db, call) => {
677
+ const direction = call.string("direction") as ReferenceDirection | undefined;
678
+ const range = call.range("range");
679
+ if (direction !== undefined && range === undefined) throw new UsageError(`--direction needs --range: the direction is seen from that range. Give --range <start>-<end> --direction ${direction}.`);
680
+ const rows = listReferences(db, rangeOf(call), call.string("kind") as (typeof REFERENCE_KINDS)[number] | undefined, originsOf(call), call.space).filter(direction === undefined ? () => true : goes(range!, direction));
681
+ const { byKind, byTarget } = referenceCounts(rows);
682
+ const named = nameOf(db, call.space);
683
+ const target = ({ to, count }: { to: number; count: number }) => ((name) => ({ to: formatC64Address(to), ...(name === undefined ? {} : { name }), count }))(named(to));
684
+ return { references: list(call, rows, reference, RANGE_REST), byKind, byTarget: list(call, byTarget, target, MORE) };
685
+ },
686
+ ),
575
687
  readCommand({ name: "suppressions", summary: "The places that removals keep free of analyzer facts, with the reason of each.", options: { range: OPTIONS.range, ...LIST } }, (db, call) => {
576
688
  const rows = listSuppressions(db, rangeOf(call), call.space);
577
689
  const reasons = reasonsOf(db, rows.slice(0, call.count("max-listed")!));
@@ -651,10 +763,13 @@ const READ_COMMANDS: CommandSpec[] = [
651
763
  return { revisions: list(call, rows, (row) => row, "a larger --max-listed, or --before <revision> with the oldest revision in listed") };
652
764
  },
653
765
  ),
654
- readCommand({ name: "revision", summary: "The rows that one revision added and closed: knowledge rows, and memory, entry and coverage rows of the program.", subjects: [REVISION], options: LIST }, (db, call) => {
655
- const changes = revision(db, call.subject(0));
656
- return { revision: changes.revision, added: list(call, changes.added, historyEntry, MORE), closed: list(call, changes.closed, historyEntry, MORE) };
657
- }),
766
+ readCommand(
767
+ { name: "revision", summary: "The rows that one revision added and closed, with their counts by kind of row: knowledge rows, and memory, entry and coverage rows of the program.", subjects: [REVISION], options: LIST },
768
+ (db, call) => {
769
+ const changes = revision(db, call.subject(0));
770
+ return { revision: changes.revision, counts: revisionCounts(changes), added: list(call, changes.added, historyEntry, MORE), closed: list(call, changes.closed, historyEntry, MORE) };
771
+ },
772
+ ),
658
773
  readCommand({ name: "export", summary: "All current knowledge to a project file as JSON.", options: { ...FILTER, out: { ...OPTIONS.out, output: "file", value: "<file>", help: "the JSON file, relative to the project folder", required: true } } }, (db, call) => {
659
774
  const range = rangeOf(call);
660
775
  const origins = originsOf(call);
@@ -685,11 +800,15 @@ const READ_COMMANDS: CommandSpec[] = [
685
800
  name: "listing",
686
801
  summary: "The program as ACME lines with names, operand expressions, comments, the access of each line in the coverage (x executed, r read, w written) and the references in and out.",
687
802
  subjects: [RANGE],
688
- options: { out: { ...OPTIONS.out, output: "file", value: "<file>", help: "write the listing as text to this file in place of the lines in the result" }, ...LIST },
803
+ options: {
804
+ code: { kind: "flag", help: "only the instructions of the code regions: no data lines" },
805
+ out: { ...OPTIONS.out, output: "file", value: "<file>", help: "write the listing as text to this file in place of the lines in the result" },
806
+ ...LIST,
807
+ },
689
808
  },
690
809
  (db, call) => {
691
810
  const { start, end } = call.parseRange(call.subject(0), "<range>");
692
- const lines = listing(listingSource(db, call.space), start, end);
811
+ const lines = listing(listingSource(db, call.space), start, end, { code: call.flag("code") });
693
812
  const out = call.string("out");
694
813
  if (out !== undefined) return { lines: lines.length, ...writeReported(out, listingText(lines), { what: "--out" }) };
695
814
  return { lines: list(call, lines, (row) => ({ ...row, address: formatC64Address(row.address) }), "a larger --max-listed, a smaller <range>, or --out <file> for all lines") };
@@ -822,17 +941,23 @@ const WRITE_COMMANDS: CommandSpec[] = [
822
941
  code: { kind: "text", value: "<text>", help: "the ACME code" },
823
942
  "code-file": { kind: "path", value: "<file>", help: "a project file with the ACME code" },
824
943
  nop: { kind: "flag", help: "put only NOP" },
944
+ "from-release": { kind: "text", value: "<label>", help: "the code is the bytes of this release in the range, as !byte lines. Not the base release" },
825
945
  comment: { kind: "text", value: "<text>", help: "a comment for the patch" },
826
946
  },
827
- notes: "Give exactly one of --code, --code-file and --nop. Write the switch first (switch). The program holds the bytes of the base release: when the base release has the switch on, the code is the bytes with the switch off. Another switch can have a patch at the same range, as an alternative.",
947
+ notes: "Give exactly one of --code, --code-file, --nop and --from-release. Write the switch first (switch). The program holds the bytes of the base release: when the base release has the switch on, the code is the bytes with the switch off. Another switch can have a patch at the same range, as an alternative.",
828
948
  },
829
949
  (call) => {
830
950
  const context = contextOf(call);
831
951
  const code = textOrFile(call, "code");
832
- if ((code === undefined) === !call.flag("nop")) throw new UsageError("patch needs exactly one of --code, --code-file or --nop.");
952
+ const from = call.string("from-release");
953
+ if ([code !== undefined, call.flag("nop"), from !== undefined].filter(Boolean).length !== 1) throw new UsageError("patch needs exactly one of --code, --code-file, --nop or --from-release.");
833
954
  const commentText = call.string("comment");
834
- const request = { space: call.space, ...call.parseRange(call.subject(0), "<range>"), switch: call.subject(1), code: code ?? "", ...(commentText === undefined ? {} : { comment: commentText }) };
835
- return (db) => shown(setPatch(db, { ...context, image: operandImages(db) }, request), "patch", patch);
955
+ const range = call.parseRange(call.subject(0), "<range>");
956
+ const request = (text: string) => ({ space: call.space, ...range, switch: call.subject(1), code: text, ...(commentText === undefined ? {} : { comment: commentText }) });
957
+ return (db) => {
958
+ const text = from === undefined ? (code ?? "") : releaseCode(db, from, range.start, range.end, call.space);
959
+ return shown(setPatch(db, { ...context, image: operandImages(db) }, request(text)), "patch", patch);
960
+ };
836
961
  },
837
962
  ),
838
963
  writeCommand(
@@ -890,7 +1015,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
890
1015
  writeCommand(
891
1016
  {
892
1017
  name: "release",
893
- summary: "Records a release of the program from its PRG or the image.json of its capture: the knowledge keeps the bytes of the release. The base release is the one whose bytes are the program of the knowledge.",
1018
+ summary: "Records a release of the program from its PRG or the image.json of its capture: the knowledge keeps the bytes of the release, and the path and the SHA-256 of the file. The base release is the one whose bytes are the program of the knowledge.",
894
1019
  subjects: [{ name: "<label>", help: "the release label, for example FIRESTAR or V2" }],
895
1020
  options: {
896
1021
  file: { kind: "path", value: "<file>", help: "the PRG or image.json of the release. After the write, the knowledge does not need the file", required: true },
@@ -903,10 +1028,11 @@ const WRITE_COMMANDS: CommandSpec[] = [
903
1028
  const context = contextOf(call);
904
1029
  const file = knowledgePath(call.string("file")!, "--file");
905
1030
  const image = readImage(file);
1031
+ const sha256 = createHash("sha256").update(readProjectFile(file).bytes).digest("hex");
906
1032
  const commentText = call.string("comment");
907
1033
  const base = call.flag("base");
908
1034
  // The base release has no bytes of its own: its bytes are the program.
909
- const request = { space: call.space, label: call.subject(0), ...(base ? { base } : { rows: memoryRows(image.segments, image.byteAt) }), ...(commentText === undefined ? {} : { comment: commentText }) };
1035
+ const request = { space: call.space, label: call.subject(0), file, sha256, ...(base ? { base } : { rows: memoryRows(image.segments, image.byteAt) }), ...(commentText === undefined ? {} : { comment: commentText }) };
910
1036
  return (db) => {
911
1037
  if (base) {
912
1038
  const program = requireProgram(db, call.space);
@@ -931,19 +1057,24 @@ const WRITE_COMMANDS: CommandSpec[] = [
931
1057
  name: "start-screen",
932
1058
  summary: "Records the start screen of the program: a loading, title or presentation screen of the program itself, in memory at the entry or in a captured stage of the loading. The loader of the generated source shows it and waits for a key or a fire button before the entry.",
933
1059
  options: {
934
- mode: { kind: "choice", value: "<mode>", choices: START_SCREEN_MODES, help: `one of ${START_SCREEN_MODES.join(", ")}. Necessary without --stage` },
935
- screen: { kind: "address", value: "<address>", help: "the screen: the 1000 characters of a text screen, or the 1000 colour bytes of a bitmap. Necessary without --stage" },
1060
+ mode: { kind: "choice", value: "<mode>", choices: START_SCREEN_MODES, help: `one of ${START_SCREEN_MODES.join(", ")}. Necessary without --stage and --capture` },
1061
+ screen: { kind: "address", value: "<address>", help: "the screen: the 1000 characters of a text screen, or the 1000 colour bytes of a bitmap. Necessary without --stage and --capture" },
936
1062
  bitmap: { kind: "address", value: "<address>", help: "the 8000 bytes of the bitmap. hires and multicolour need it" },
937
1063
  charset: { kind: "address", value: "<address>", help: "the 2048 bytes of the charset, or '$1000' or '$1800' for the character ROM in VIC bank 0. text needs it" },
938
1064
  colours: { kind: "address", value: "<address>", help: "the 1000 bytes that the loader copies to the colour RAM" },
939
1065
  colour: { kind: "count", value: "<0-15>", min: 0, max: 15, help: "one colour for all of the colour RAM, in place of --colours" },
940
- border: { kind: "count", value: "<0-15>", min: 0, max: 15, help: "the border colour. Necessary without --stage" },
941
- background: { kind: "count", value: "<0-15>", min: 0, max: 15, help: "the background colour. Necessary without --stage" },
1066
+ border: { kind: "count", value: "<0-15>", min: 0, max: 15, help: "the border colour. Necessary without --stage and --capture" },
1067
+ background: { kind: "count", value: "<0-15>", min: 0, max: 15, help: "the background colour. Necessary without --stage and --capture" },
942
1068
  stage: { kind: "text", value: "<space>", help: "the space of the captured stage that shows the screen: loading. The script takes the mode, the addresses and the colours from the capture of the stage. Without it, the bytes are in the program at the entry" },
1069
+ capture: {
1070
+ kind: "path",
1071
+ value: "<image.json>",
1072
+ help: "a capture of the program while it shows the screen: the script takes the mode, the addresses and the border and background colours from it, and the colours from 1000 bytes of the program with the colour RAM of the capture, or one colour",
1073
+ },
943
1074
  call: { kind: "address", value: "<address>", help: "a routine of the stage that the start screen calls before it waits, for example the routine that starts the loading tune. It must return with RTS. Needs --stage" },
944
1075
  comment: { kind: "text", value: "<text>", help: "what the screen is" },
945
1076
  },
946
- notes: "Record only a screen of the program itself, never a screen of a crack. If a release changed the screen, for example with the text of a crack, stop and ask the user how to deal with it. text and multicolour need --colours or --colour; hires uses neither. With --stage, the script takes the screen from the capture of the stage: give only --stage, and --call for a tune. A flag that you give too replaces the value of the capture. A write replaces the start screen of the knowledge.",
1077
+ notes: "Record only a screen of the program itself, never a screen of a crack. If a release changed the screen, for example with the text of a crack, stop and ask the user how to deal with it. text and multicolour need --colours or --colour; hires uses neither. With --stage, the script takes the screen from the capture of the stage: give only --stage, and --call for a tune. With --capture, the script takes the screen in the program from a capture of the program while it shows the screen. A flag that you give too replaces the value of the capture. A write replaces the start screen of the knowledge.",
947
1078
  },
948
1079
  (call) => {
949
1080
  const context = contextOf(call);
@@ -961,6 +1092,8 @@ const WRITE_COMMANDS: CommandSpec[] = [
961
1092
  if (value !== undefined) given[key] = value;
962
1093
  }
963
1094
  const stage = call.string("stage");
1095
+ const capture = call.string("capture");
1096
+ if (stage !== undefined && capture !== undefined) throw new UsageError("Give --stage or --capture, not both. --stage takes the screen of a captured stage of the loading; --capture takes the screen in the program from a capture of the program.");
964
1097
  const routine = call.address("call");
965
1098
  const extra = {
966
1099
  space: call.space,
@@ -973,8 +1106,20 @@ const WRITE_COMMANDS: CommandSpec[] = [
973
1106
  if (missing.length > 0) throw new UsageError(`Give ${missing.map((key) => `--${key}`).join(", ")}, ${remedy}`);
974
1107
  return { ...values, mode: values.mode!, screen: values.screen!, border: values.border!, background: values.background!, ...extra };
975
1108
  };
1109
+ if (capture !== undefined) {
1110
+ // The capture gives the VIC-II values; the colours come from the program. A flag of the call replaces a value of the capture.
1111
+ const state = readImage(capture).state?.raw;
1112
+ const fromCapture = mode === undefined ? startScreenOfCapture(state, capture) : {};
1113
+ const wanted = { ...fromCapture, ...given };
1114
+ const ownColours = given.colours !== undefined || given.colour !== undefined;
1115
+ return (db) => {
1116
+ const colours = wanted.mode === "hires" || ownColours ? {} : coloursOfCapture(state, capture, programBytes(requireProgram(db, call.space)));
1117
+ const request = complete({ ...colours, ...wanted }, "or give --capture alone to take the screen from the capture.");
1118
+ return shown(setStartScreen(db, context, request), "startScreen", startScreen);
1119
+ };
1120
+ }
976
1121
  if (stage === undefined) {
977
- const request = complete(given, "or give --stage with the space of a captured stage that shows the screen.");
1122
+ const request = complete(given, "or give --stage with the space of a captured stage that shows the screen, or --capture with a capture of the program while it shows the screen.");
978
1123
  return (db) => shown(setStartScreen(db, context, request), "startScreen", startScreen);
979
1124
  }
980
1125
  return (db) => {
@@ -1060,12 +1205,16 @@ const WRITE_COMMANDS: CommandSpec[] = [
1060
1205
  writeCommand(
1061
1206
  {
1062
1207
  name: "coverage",
1063
- summary: "Puts coverage maps of the emulator or of a run into the coverage of the knowledge. Each map is named by its path: a new map of a path replaces the earlier map of that path, and --evidence coverage:<path> cites it.",
1064
- subjects: [{ name: "<map>", help: "a 64 KiB coverage map", list: true }],
1208
+ summary: "Puts coverage maps of the emulator, of a run or of a recording folder into the coverage of the knowledge. Each map is named by its path: a new map of a path replaces the earlier map of that path, and --evidence coverage:<path> cites it.",
1209
+ subjects: [{ name: "<map>", help: "a 64 KiB coverage map, or a recording folder: then its coverage map", list: true }],
1065
1210
  },
1066
1211
  (call) => {
1067
1212
  const context = contextOf(call);
1068
- const maps = call.subjects.map((path) => ({ bytes: readProjectFile(path).bytes, name: knowledgePath(path, "<map>") }));
1213
+ const maps = call.subjects.map((given) => {
1214
+ // A recording folder gives its coverage map: the knowledge names it by the path of the map in the folder.
1215
+ const path = coverageMapOf(given);
1216
+ return { bytes: readProjectFile(path).bytes, name: knowledgePath(path, "<map>") };
1217
+ });
1069
1218
  return (db) => {
1070
1219
  const { revision, current } = addCoverage(db, context, { space: call.space, maps });
1071
1220
  const body = { revision, ...spaceOf(current), imported: current.imported, replaced: current.replaced, known: current.known, added: current.added, removed: current.removed };
@@ -1110,7 +1259,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
1110
1259
  name: "apply",
1111
1260
  summary: "Many writes from a JSON file, all as one revision, or none when one is refused.",
1112
1261
  subjects: [{ name: "<file>", help: "the batch: a JSON list of writes, or - for standard input" }],
1113
- notes: 'A write is {"op": "<command>", ...}, for example {"op": "rename", "address": "$2100", "name": "update_player"}. A range is "start" and "end". A write can name its own "space". operand, patch and use writes are checked against the program of their space.',
1262
+ notes: `A write is {"op": "<command>", ...} with the fields of the command, for example {"op": "rename", "address": "$2100", "name": "update_player"}. A range is "start" and "end". A write can name its own "space". The fields of each op, the optional ones in brackets: ${BATCH_OPS}. operand: select is lo, hi or value with symbol and [offset], or expr with expression. patch: an empty or no code is NOP only. macro params and use args: a JSON list of strings or a comma list. operand, patch and use writes are checked against the program of their space.`,
1114
1263
  },
1115
1264
  (call) => {
1116
1265
  const context = contextOf(call);
@@ -1137,6 +1286,62 @@ function applied(db: DatabaseSync, context: WriteContext, operations: BatchOpera
1137
1286
  return { revision: result.revision, writes: result.steps.length, replaced };
1138
1287
  }
1139
1288
 
1289
+ /** verdict: records the verdict of one comment of a check. It writes no knowledge. */
1290
+ const VERDICT: CommandSpec = {
1291
+ name: "verdict",
1292
+ summary: "Records the verdict of one comment of the sample of a check: correct, wrong or unsure.",
1293
+ subjects: [SEED, ADDRESS, { name: "<verdict>", help: `one of ${CHECK_VERDICTS.join(", ")}` }],
1294
+ options: {
1295
+ placement: { kind: "choice", value: "<line|side>", choices: COMMENT_PLACEMENTS, help: "the placement of the comment, when the sample has a line and a side comment at the address" },
1296
+ class: { kind: "choice", value: "<class>", choices: CHECK_CLASSES, help: `with wrong: the class of the error, one of ${CHECK_CLASSES.join(", ")}` },
1297
+ why: { kind: "text", value: "<text>", help: "with wrong: the evidence, with the addresses and the instructions. With unsure: the run that can show the claim" },
1298
+ text: { kind: "text", value: "<text>", help: "with wrong: the correct comment" },
1299
+ name: { kind: "text", value: "<name>", help: "with wrong: the correct name at the address" },
1300
+ },
1301
+ notes: "A wrong verdict needs --class, --why, and --text or --name. An unsure verdict needs --why. A new verdict of a comment replaces its earlier verdict.",
1302
+ run: (call) => {
1303
+ const seed = seedOf(call);
1304
+ const sample = sampleOf(seed);
1305
+ const request = {
1306
+ address: formatC64Address(call.parseAddress(call.subject(1), "<address>")),
1307
+ verdict: oneOf(CHECK_VERDICTS, call.subject(2), "<verdict>"),
1308
+ ...Object.fromEntries((["placement", "class", "why", "text", "name"] as const).flatMap((option) => (call.string(option) === undefined ? [] : [[option, call.string(option)]]))),
1309
+ } as Parameters<typeof withVerdict>[2] & { class?: CheckClass };
1310
+ const verdicts = withVerdict(sample, checkFile<Verdicts>(seed, "verdicts.json"), request);
1311
+ writeReported(`${checkFolder(seed)}/verdicts.json`, `${JSON.stringify(verdicts, null, 2)}\n`, { what: "verdict" });
1312
+ const written = verdicts.items.find((item) => item.address === request.address && (request.placement === undefined || item.placement === request.placement))!;
1313
+ return { seed, verdict: written, checked: verdicts.items.length, sampled: sample.comments.length };
1314
+ },
1315
+ };
1316
+
1317
+ /** checks: the comment checks of the project, or one check with its items. */
1318
+ const CHECKS: CommandSpec = {
1319
+ name: "checks",
1320
+ summary: "The comment checks of the project, newest first, with their counts. With a seed: that check, with each comment of its sample and its verdict.",
1321
+ subjects: [{ ...SEED, optional: true }],
1322
+ options: LIST,
1323
+ run: (call) => {
1324
+ if (call.subjects.length > 0) {
1325
+ const seed = seedOf(call);
1326
+ const verdicts = checkFile<Verdicts>(seed, "verdicts.json");
1327
+ const { items, ...counts } = checkResult(sampleOf(seed), verdicts);
1328
+ const folder = checkFolder(seed);
1329
+ return { ...counts, files: { sample: `${folder}/sample.json`, ...(verdicts === undefined ? {} : { verdicts: `${folder}/verdicts.json` }) }, items: list(call, items, (item) => item, MORE) };
1330
+ }
1331
+ const runs = resolveProjectPath("runs");
1332
+ const seeds = existsSync(runs) ? readdirSync(runs).flatMap((name) => ((seed) => (seed === undefined ? [] : [seed]))(seedOfFolder(name))) : [];
1333
+ const checks = seeds
1334
+ .flatMap((seed) => {
1335
+ const sample = checkFile<Sample>(seed, "sample.json");
1336
+ if (sample === undefined) return [];
1337
+ const { items: _items, ...counts } = checkResult(sample, checkFile<Verdicts>(seed, "verdicts.json"));
1338
+ return [counts];
1339
+ })
1340
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt));
1341
+ return { checks: list(call, checks, (check) => check, MORE) };
1342
+ },
1343
+ };
1344
+
1140
1345
  /** join: the batches of agents that worked in parallel, as one list of writes. With --apply, it writes them as one revision. */
1141
1346
  const JOIN: CommandSpec = {
1142
1347
  name: "join",
@@ -1268,5 +1473,5 @@ await runScript({
1268
1473
  name: "knowledge",
1269
1474
  summary: "Reads and writes the knowledge of the project: names, regions, comments, references, the program and its coverage, and the source knowledge. A read needs no knowledge folder. Every command takes --space: c64 (the default), drive8 for 1541 drive code, loading for a captured stage of the loading, or bank0 to bank255 for cartridge banks. revert without --space reverts all spaces.",
1270
1475
  names: knowledgeNames,
1271
- commands: [...READ_COMMANDS, ...WRITE_COMMANDS, JOIN],
1476
+ commands: [...READ_COMMANDS, ...WRITE_COMMANDS, JOIN, VERDICT, CHECKS],
1272
1477
  });