@henols/c64-re-tools 2.6.0-rc.19 → 2.6.0-rc.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henols/c64-re-tools",
3
- "version": "2.6.0-rc.19",
3
+ "version": "2.6.0-rc.20",
4
4
  "description": "Agent-friendly Commodore 64 engineering toolkit for reverse engineering, debugging, development and testing.",
5
5
  "license": "MIT",
6
6
  "author": "Henrik Olsson",
@@ -176,12 +176,14 @@ In a group folder, a label names the project of a name. Write the label and a co
176
176
  - `linked`: `links`, the count of the links that it wrote, and `pages`, the pages that it changed. With `--check`, `notUpToDate` has the same fields for the links that are not up to date.
177
177
  - `problems`: `byKind`, `count`, `listed` and `rest`. Each item has `at` (the page and the line), `kind` and `message`. In a group folder, each item also has `project`: the label of the project of the page, or `shared`.
178
178
  - `group`: only in a group folder. `folder` is the group folder, relative to the folder of the pages. `projects` holds the labels.
179
+ - `evidence`: only when the project knowledge gives a file as evidence and the file is missing or changed. `count`, `listed` and `rest`. Each item has the `file`, its `state` (`missing` or `changed`) and the `revisions` that give the file. The project knowledge keeps the SHA-256 of each file of its evidence. An evidence item does not make `result` a FAIL.
179
180
 
180
181
  `hint` and `nextAction`:
181
182
 
182
183
  - A page has a problem: `hint` tells you to correct each problem. `nextAction` runs the same `link` command again.
183
184
  - With `--check`, a link is not up to date and no page has a problem: `nextAction` runs `link` without `--check` to write the links.
184
185
  - `reference` is `none`: no `reference` folder is in or beside the given pages. Give `--reference <dir>`, or run `generate` first.
186
+ - `evidence` has items: for a coverage map that changed, put the map into the project knowledge again. For a file that you did not change on purpose, restore it from git. Else examine the facts of the revisions against the new file. Give the new file as evidence of the next write of these facts.
185
187
 
186
188
  Do this for each `kind` of problem:
187
189
 
@@ -13,12 +13,14 @@ import { WireFailure } from "#src/host-client/tools.ts";
13
13
  import { writeProjectFile, writeReported } from "#src/host-client/transfer.ts";
14
14
  import { conflicts } from "#src/knowledge/conflicts.ts";
15
15
  import { openForRead } from "#src/knowledge/database.ts";
16
+ import { changedEvidence, type EvidenceChange } from "#src/knowledge/evidence.ts";
16
17
  import { programImage, type ProgramImage } from "#src/knowledge/program.ts";
17
18
  import { listComments, listModules, listReferences, listRegions, listSymbols, sourceRevision } from "#src/knowledge/read.ts";
18
19
  import { groupOf, namedGroup, projectRoot, resolveProjectFile, resolveProjectPath, type ProjectGroup } from "#src/project.ts";
20
+ import { GENERATED_MARK, referenceStamp } from "#src/reference-pages.ts";
19
21
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type Reply } from "#src/script.ts";
20
22
  import { checkLinks, linkPage, type Files, type LinkContext, type Names, type Problem } from "./lib/links.ts";
21
- import { buildReference, GENERATED_MARK } from "./lib/reference.ts";
23
+ import { buildReference } from "./lib/reference.ts";
22
24
  import { readSourceMap } from "./lib/source-map.ts";
23
25
 
24
26
  // ---------------------------------------------------------------------------
@@ -247,6 +249,8 @@ function link(call: Call): Reply {
247
249
  const reference = checkedReference !== undefined ? checkedReference : foundReference === undefined ? undefined : foundReference.slice(memberOf(foundReference)!.prefix.length).replace(/^\//, "");
248
250
  const referenceOf = (member: Member) => (reference === undefined ? undefined : posix.join(member.prefix, reference));
249
251
  const problems: Problem[] = [];
252
+ /** The evidence files of the knowledge of each read project that are missing or changed, with paths relative to the root of the run. */
253
+ const evidence: EvidenceChange[] = [];
250
254
 
251
255
  /** The names of a project, read the first time a page needs them. A project with given pages is read before the pages. */
252
256
  const loaded = new Map<Member, Names>();
@@ -268,6 +272,7 @@ function link(call: Call): Reply {
268
272
  try {
269
273
  revision = sourceRevision(db, map.space);
270
274
  symbols = listSymbols(db, undefined, undefined, undefined, map.space);
275
+ for (const change of changedEvidence(db, member.root)) evidence.push({ ...change, file: inProject(change.file) });
271
276
  } finally {
272
277
  db?.close();
273
278
  }
@@ -319,9 +324,9 @@ function link(call: Call): Reply {
319
324
  problems.push(unreadable(page));
320
325
  continue;
321
326
  }
322
- const stamp = /^<!-- Generated by c64-docs from knowledge revision (\S+) /.exec(text);
323
- if (text.startsWith(GENERATED_MARK) && stamp !== null && stamp[1] !== map.revision) {
324
- problems.push({ page, line: 1, kind: "stale-reference", message: `${shown(page)} is from knowledge revision ${stamp[1]}, and the source${of} from ${map.revision}. Run docs.ts generate again.` });
327
+ const stamp = referenceStamp(text);
328
+ if (stamp !== undefined && stamp.revision !== map.revision) {
329
+ problems.push({ page, line: 1, kind: "stale-reference", message: `${shown(page)} is from knowledge revision ${stamp.revision}, and the source${of} from ${map.revision}. Run docs.ts generate again.` });
325
330
  }
326
331
  }
327
332
  const names: Names = {
@@ -395,11 +400,19 @@ function link(call: Call): Reply {
395
400
  ...(check ? { notUpToDate: { links, pages: changedPages } } : { linked: { links, pages: changedPages } }),
396
401
  problems: { byKind, ...shownProblems },
397
402
  };
403
+ const shownEvidence = listed(evidence, call.count("max-listed")!, (change) => ({ ...change, file: shown(change.file) }));
404
+ if (evidence.length > 0) output.evidence = shownEvidence;
398
405
  const again = (withCheck: boolean) =>
399
406
  call.next("link", ...call.subjects, "--source", call.string("source")!, ...(givenReference === undefined ? [] : ["--reference", givenReference]), ...(withCheck ? ["--check"] : []), ...(scope.unnamed ? ["--project", root] : []));
400
407
  const hints: string[] = [];
401
408
  let nextAction: string | undefined;
402
409
  if (reference === undefined) hints.push("No reference/ folder is in or beside the given pages, so the links to the reference are not checked. Give --reference <dir>, or run generate first.");
410
+ if (evidence.length > 0) {
411
+ hints.push(
412
+ "The project knowledge gives the files in evidence as evidence, and each file is missing or changed since the revisions in its item. For a coverage map that changed, put the map into the project knowledge again. For a file that you did not change on purpose, restore it from git. Else examine the facts of the revisions against the new file, and give the new file as evidence of the next write of these facts.",
413
+ );
414
+ if (shownEvidence.rest !== undefined) hints.push(`evidence is cut. To list all files, give ${shownEvidence.rest}.`);
415
+ }
403
416
  if (problems.length > 0) {
404
417
  hints.push("Correct each problem in problems.listed as its message tells. Then run nextAction.");
405
418
  if (shownProblems.rest !== undefined) hints.push(`problems is cut. To list all problems, give ${shownProblems.rest}.`);
@@ -12,11 +12,9 @@ import { mermaidGraph, ownerOf, routineEdges, routineHeads, type GraphReference,
12
12
  import type { CommentRow, ModuleRow, ReferenceRow, RegionRow, SymbolRow } from "#src/knowledge/read.ts";
13
13
  import type { RegionType } from "#src/knowledge/schema.ts";
14
14
  import { platformNames } from "#src/platform.ts";
15
+ import { referenceHeader } from "#src/reference-pages.ts";
15
16
  import type { SourceMap } from "./source-map.ts";
16
17
 
17
- /** The first line of every generated page. A page without it is a page of a person, and docs.ts generate never writes over it. */
18
- export const GENERATED_MARK = "<!-- Generated by c64-docs";
19
-
20
18
  export interface ReferenceInput {
21
19
  /** The reference directory, relative to the project folder. */
22
20
  out: string;
@@ -247,7 +245,7 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
247
245
  }
248
246
  const titleOf = (file: string) => input.modules.find((module) => module.file === file)?.title;
249
247
 
250
- const header = `${GENERATED_MARK} from knowledge revision ${input.revision} and ${map.mapPath}. Do not edit: change the knowledge, generate the source again, then run docs.ts generate. -->`;
248
+ const header = referenceHeader(input.revision, map.mapPath);
251
249
  const files: ReferenceFile[] = [];
252
250
  const write = (path: string, lines: string[]) => files.push({ path, bytes: Buffer.from(`${[header, ...lines].join("\n").replace(/\n{3,}/g, "\n\n")}\n`, "utf8") });
253
251
 
@@ -279,7 +279,7 @@ When a git merge left conflicts in the knowledge, each read body also has `confl
279
279
  ### `revision <revision>`
280
280
 
281
281
  - `body.revision` gives the revision. `body.added` and `body.closed` list the rows that it added and closed.
282
- - The rows include the memory, entry and coverage rows of the program.
282
+ - The rows include the memory, entry and coverage rows of the program. A coverage row gives the `map`, the access `kind` and the number of `ranges` of that kind in the map.
283
283
 
284
284
  ---
285
285
 
@@ -540,8 +540,9 @@ A macro writes a run of instructions as one line of the source, for example `+in
540
540
  ### `coverage <map>...`
541
541
 
542
542
  - `<map>` is a 64 KiB coverage map of a run. Write each map in `.c64-re-tools/local/`.
543
- - `body` holds `revision`, `imported`, `known` and `ranges`. `imported` lists the new maps. `known` lists the maps that the space has already. `ranges` counts the new ranges of accesses that no earlier map has. When `ranges` is 0, the source and the reference do not change.
544
- - `coverage` joins the maps. It keeps each address that a run executed, read or wrote. It also keeps each address that one run wrote and executed: self-modified code.
543
+ - `body` holds `revision`, `imported`, `replaced`, `known`, `added` and `removed`. `imported` lists the new maps. `replaced` lists the new maps that replace an earlier map of the same path. `known` lists the maps that are the latest map of their path in the space already. `added` and `removed` count the ranges of accesses that the coverage gets and loses. When both are 0, the source and the reference do not change.
544
+ - The knowledge keeps one map for each path in a space. A new map of a path replaces the earlier map of that path. Thus, after you record a run again into the same folder, put its new map into the project knowledge. Then the coverage has only the new run of that folder.
545
+ - The coverage of a space is the union of its maps. It has each address that a run executed, read or wrote. It also has each address that one run wrote and executed: self-modified code.
545
546
  - `coverage` puts each map into the space of `--space`. You can add the same map to each space.
546
547
  - `--evidence coverage:<map>` names a map by its path at the import. It refers to the last import of that map into the space of the write.
547
548
 
@@ -17,7 +17,7 @@ import { operandText } from "#src/knowledge/expression.ts";
17
17
  import { historyAt, historyNamed, historyOfMacro, historyOfSwitch, revision, 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, memoryRows, operandImages as programImages, programCoverage, programImage, requireProgram, setImage, type ImageRequest } from "#src/knowledge/program.ts";
20
+ import { addCoverage, coverageRangeCounts, memoryRows, operandImages as programImages, programCoverage, programImage, requireProgram, setImage, type ImageRequest } from "#src/knowledge/program.ts";
21
21
  import { startScreenOfStage } from "#src/knowledge/start-screen.ts";
22
22
  import {
23
23
  analyzerNamesAt,
@@ -203,11 +203,11 @@ function suppression(row: SuppressionRow) {
203
203
  return { ...spaceOf(row), suppresses: row.entity, ...place, origin: row.origin, revision: row.revision };
204
204
  }
205
205
 
206
- /** A row of the program in a revision: memory bytes, the entry, or a coverage range. */
206
+ /** A row of the program in a revision: memory bytes, the entry, or the ranges of one kind of a coverage map. */
207
207
  function programRow(entry: Extract<HistoryEntry, { entity: "memory" | "entry" | "coverage" }>) {
208
208
  if (entry.entity === "memory") return { ...spaceOf(entry.row), start: formatC64Address(entry.row.address), end: formatC64Address(entry.row.address + entry.row.bytes - 1), bytes: entry.row.bytes, origin: entry.row.origin, revision: entry.row.revision };
209
209
  if (entry.entity === "entry") return { ...spaceOf(entry.row), address: formatC64Address(entry.row.address), state: entry.row.state, stages: entry.row.stages, origin: entry.row.origin, revision: entry.row.revision };
210
- return { ...spaceOf(entry.row), kind: entry.row.kind, start: formatC64Address(entry.row.start), end: formatC64Address(entry.row.end), origin: entry.row.origin, revision: entry.row.revision };
210
+ return { ...spaceOf(entry.row), map: entry.row.map, kind: entry.row.kind, ranges: entry.row.ranges, origin: entry.row.origin, revision: entry.row.revision };
211
211
  }
212
212
 
213
213
  function historyEntry(entry: HistoryEntry) {
@@ -598,7 +598,6 @@ const READ_COMMANDS: CommandSpec[] = [
598
598
  readCommand({ name: "spaces", summary: "The address spaces that hold knowledge.", options: LIST }, (db, call) => ({ spaces: list(call, listSpaces(db), (space) => space, MORE) })),
599
599
  readCommand({ name: "program", summary: "The program in the knowledge: its segments and entry, and the coverage maps that coverage imported, with the ranges." }, (db, call) => {
600
600
  const image = programImage(db, call.space);
601
- const ranges = db === undefined ? [] : (db.prepare("SELECT kind, count(*) AS count FROM current_coverage WHERE space = ? GROUP BY kind ORDER BY kind").all(call.space) as Array<{ kind: string; count: number }>);
602
601
  return {
603
602
  ...(call.space === DEFAULT_SPACE ? {} : { space: call.space }),
604
603
  image:
@@ -612,7 +611,7 @@ const READ_COMMANDS: CommandSpec[] = [
612
611
  stages: image.stages?.length ?? 0,
613
612
  },
614
613
  ...((row) => (row === undefined ? {} : { startScreen: startScreen(row) }))(currentStartScreen(db, call.space)),
615
- coverage: { maps: [...new Set(coverageRuns(db).filter((run) => run.space === call.space).map((run) => run.name))], ranges: Object.fromEntries(ranges.map((row) => [row.kind, row.count])) },
614
+ coverage: { maps: [...new Set(coverageRuns(db).filter((run) => run.space === call.space).map((run) => run.name))], ranges: coverageRangeCounts(db, call.space) },
616
615
  };
617
616
  }),
618
617
  readCommand(
@@ -1061,7 +1060,7 @@ const WRITE_COMMANDS: CommandSpec[] = [
1061
1060
  writeCommand(
1062
1061
  {
1063
1062
  name: "coverage",
1064
- summary: "Joins coverage maps of the emulator or of a run into the coverage of the knowledge. Each map is named by its path: --evidence coverage:<path> cites it.",
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.",
1065
1064
  subjects: [{ name: "<map>", help: "a 64 KiB coverage map", list: true }],
1066
1065
  },
1067
1066
  (call) => {
@@ -1069,14 +1068,14 @@ const WRITE_COMMANDS: CommandSpec[] = [
1069
1068
  const maps = call.subjects.map((path) => ({ bytes: readProjectFile(path).bytes, name: knowledgePath(path, "<map>") }));
1070
1069
  return (db) => {
1071
1070
  const { revision, current } = addCoverage(db, context, { space: call.space, maps });
1072
- const body = { revision, ...spaceOf(current), imported: current.imported, known: current.known, ranges: current.ranges };
1073
- // ranges counts the accesses that no earlier map had: only they change the source and the reference.
1071
+ const body = { revision, ...spaceOf(current), imported: current.imported, replaced: current.replaced, known: current.known, added: current.added, removed: current.removed };
1072
+ // Only a range that the coverage gained or lost changes the source and the reference.
1074
1073
  const hint =
1075
1074
  revision === null
1076
1075
  ? "The knowledge has each map already. Nothing changed."
1077
- : current.ranges === 0
1078
- ? "The maps add no access that the knowledge did not have. The knowledge keeps them as evidence. The source and the reference do not change."
1079
- : `The maps add ${current.ranges} ranges of accesses. They can change the leftovers and the code that no run executed. Generate the source again, then the reference.`;
1076
+ : current.added === 0 && current.removed === 0
1077
+ ? "The coverage did not change. The knowledge keeps the maps as evidence. The source and the reference do not change."
1078
+ : `The coverage gained ${current.added} and lost ${current.removed} ranges of accesses. They can change the leftovers and the code that no run executed. Generate the source again, then the reference.`;
1080
1079
  return reply(body, { hint });
1081
1080
  };
1082
1081
  },
@@ -120,6 +120,7 @@ To make the source better, change the project knowledge. Then generate again.
120
120
  - `switches`, `default`, `releases`: the checks of the switches. See "Switches and releases".
121
121
  - `loader`: the check of the loader. See "The loader".
122
122
  - `staleLoader`: a run without `--loader` kept `loader.asm` and the loader program of another knowledge revision, or of another version of the toolkit. `files` gives the files. `revision` gives the revision of `loader.asm`, and `version` its toolkit version. Without `revision`, `loader.asm` does not give one. `noEntryState: true` tells that the knowledge has no entry state for a new loader. A change in a space that the loader does not hold does not make the loader stale. The loader holds space `c64` and the space of the stage of the start screen.
123
+ - `staleReference`: each reference folder of the project that has pages of this source from an earlier knowledge revision. Each item has the `folder` and the `revision` of its pages.
123
124
 
124
125
  `result` is `FAIL` for each of these:
125
126
 
@@ -148,6 +149,7 @@ Do these actions for the findings:
148
149
  | `conflict` | The knowledge has conflicts from a git merge. Merge the open changes of the project knowledge. Then run the command again. |
149
150
  | A list with `rest` | Give a larger `--max-listed`. For `notExecuted`, read the file in `rest`. |
150
151
  | `staleLoader` | The loader can copy bytes that are not the bytes of the source. Run `nextAction`, which generates with `--loader`. With `noEntryState: true`, remove the files when the build does not use them. |
152
+ | `staleReference` | The reference pages do not agree with the new source. When you do not change the knowledge again, generate the reference pages again from this source into each `folder`. |
151
153
 
152
154
  #### The source files
153
155
 
@@ -320,7 +322,7 @@ The program is packed while the screen shows. Thus the picture and the tune have
320
322
  - The loader program has only the bytes of the stage that the start screen uses. These are the screen, the bitmap and the charset. With a call, they are also each byte of the stage that is not free from the call, as in "The free ranges". A call thus needs the coverage of the stage.
321
323
  - With colours from the colour RAM of the capture, the show code holds the 1000 colours. It copies them to the colour RAM.
322
324
  - The patches of the stage are in at the defaults of their switches. Thus a patch under a switch can remove the text of a crack from the picture.
323
- - `start_screen_stage.asm` holds the show code and the bytes of the stage. Do not edit it. To make the loader program again, run `generate --loader`.
325
+ - `start_screen_stage.asm` holds the show code and the bytes of the stage. Do not edit it. To make the loader program again, run `generate --out <dir> --loader`.
324
326
  - The show stage needs Exomizer. The show code needs free memory in $0400-$9fff or $c000-$cfff. When the memory is too small, the reason gives the largest free ranges.
325
327
  - The check runs the loader program to `loader_start_screen_wait` of the show stage. There, it compares the VIC-II with the start screen, the screen bytes in memory with the stage, and the colour RAM with the capture. Then it sets the PC to `loader_start_screen_continue`, and it checks the loader as usual.
326
328
 
@@ -338,7 +340,7 @@ To make the packed loader for other switch values, do these steps:
338
340
  2. Assemble `loader.asm` without an output path, for example to `build/custom_trainer_copier.prg`. This is the copier. The build name has `copier` in place of `loader`, so the build does not write over the loader program.
339
341
  3. Pack the two files into `build/custom_trainer_packed.prg`. The start address is the copier address in the comment at the start of `loader.asm`. The memory configuration at the exit is `$34`.
340
342
 
341
- These steps do not work when a segment starts below $0400. They also do not work when a patch is between the free ranges of `loader.asm`. In these cases, use `generate --loader` for the base release.
343
+ These steps do not work when a segment starts below $0400. They also do not work when a patch is between the free ranges of `loader.asm`. In these cases, use `generate --out <dir> --loader` for the base release.
342
344
 
343
345
  ---
344
346
 
@@ -448,7 +450,7 @@ tests/ the tests of the project, changed for the new program
448
450
  5. Record names, comments, regions and modules in the project knowledge.
449
451
  6. Run `generate` again. Do steps 4 to 6 again until the source is clear.
450
452
  7. Assemble `main.asm` to a program. This is the default build. For a release, give the build option `--release <label>`.
451
- 8. For an unpacked program, run `generate` with `--loader` at the end. Compare the loader program with the original program in a test.
453
+ 8. For an unpacked program, run `generate --out <dir> --loader` at the end. Compare the loader program with the original program in a test.
452
454
  9. To start a new program from the rebuild, run `export`.
453
455
 
454
456
  ---
@@ -32,6 +32,13 @@ const CODE_TYPES: readonly RegionType[] = ["code", "jumps", "dual-use"];
32
32
  /** The hardware vectors $fffa-$ffff: they stay when the image holds them. */
33
33
  const VECTORS: AddressRange = { start: 0xfffa, end: 0xffff };
34
34
 
35
+ /**
36
+ * The coverage flags that can be a use of the RAM byte: a read or a run of the
37
+ * ROM uses the ROM, not the RAM under it, so a JSR into the KERNAL keeps no byte
38
+ * of the image. The I/O flags stay, as VICE gives each access at $d000-$dfff as I/O.
39
+ */
40
+ const RAM_ACCESS = 0xff & ~(COVERAGE.romRead | COVERAGE.romExecute);
41
+
35
42
  /** The I/O area: two immediates stored there are chip values, such as a timer latch, not an address. */
36
43
  const IO_AREA: AddressRange = { start: 0xd000, end: 0xdfff };
37
44
 
@@ -244,7 +251,7 @@ const isTable = (type: RegionType) => type === "jumps" || (POINTER_TABLE_TYPES a
244
251
  */
245
252
  export function planDrops(input: DropInput): DropPlan {
246
253
  const inImage = (address: number) => inside(address, input.segments);
247
- const touched = (address: number) => input.coverage !== undefined && input.coverage[address] !== 0;
254
+ const touched = (address: number) => input.coverage !== undefined && (input.coverage[address]! & RAM_ACCESS) !== 0;
248
255
  const executed = (address: number) => input.coverage !== undefined && (input.coverage[address]! & COVERAGE.ramExecute) !== 0;
249
256
  const regions = input.regions.flatMap((region) => input.segments.filter((segment) => overlaps(region, segment)).map((segment) => ({ start: Math.max(region.start, segment.start), end: Math.min(region.end, segment.end), type: region.type })));
250
257
  // The source writes a data region as data, also where the decompiler decoded instructions in it: those are no code.
@@ -35,6 +35,7 @@ import { localToolContext } from "#src/native/local.ts";
35
35
  import { DECOMPILER_LIMITS, type AssembledSymbol, type Diagnostic } from "#src/native/types.ts";
36
36
  import { decode as decodeRegister, describeAddress, platformNames, platformNamesFor, romRanges, romUseOfProgram } from "#src/platform.ts";
37
37
  import { ensureLocal, generatedDirectory, LOCAL_DIRECTORY, newProjectFolder, PROJECT_DIRECTORY, projectRelative, projectRoot, resolveProjectPath } from "#src/project.ts";
38
+ import { generatedReferences } from "#src/reference-pages.ts";
38
39
  import { isoCet } from "#src/time.ts";
39
40
  import { zipFiles } from "#src/zip.ts";
40
41
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type Reply } from "#src/script.ts";
@@ -1170,6 +1171,10 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1170
1171
  // The reports go to the local folder: the source folder holds only source files.
1171
1172
  const reports = generatedDirectory(projectRelative(out));
1172
1173
  written.push(writeReported(`${reports}/${SOURCE_MAP_FILE}`, sourceMapText(rendered, space, knowledge.sourceRevision, files)));
1174
+ // A reference that the project has from this source, made at an earlier revision: the new source makes it old.
1175
+ const staleReference = generatedReferences(projectRoot())
1176
+ .filter((reference) => reference.mapPath === `${reports}/${SOURCE_MAP_FILE}` && reference.revision !== knowledge.sourceRevision)
1177
+ .map((reference) => ({ folder: reference.folder, revision: reference.revision }));
1173
1178
  const showRange = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
1174
1179
  const inData = entriesInData(entries, knowledge.regions);
1175
1180
  if (rendered.notExecuted !== undefined) {
@@ -1199,6 +1204,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1199
1204
  revision: knowledge.revision,
1200
1205
  // A run without --loader keeps the loader of an earlier run: one of another revision is stale.
1201
1206
  ...(stale === undefined ? {} : { staleLoader: { ...stale, ...(image.state === undefined || image.entry === undefined ? { noEntryState: true } : {}) } }),
1207
+ ...(staleReference.length === 0 ? {} : { staleReference }),
1202
1208
  instructions: rendered.instructions,
1203
1209
  dataBytes: rendered.dataBytes,
1204
1210
  ...(rendered.undecodedBytes === 0 ? {} : { undecodedBytes: rendered.undecodedBytes }),
@@ -1785,7 +1791,9 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
1785
1791
  }
1786
1792
  if ([body.asBytes, body.operandsAsNumbers, body.macrosAsInstructions, body.patchesNotWritten].some(isCut)) steps.push("To see all items of a list, give a larger --max-listed.");
1787
1793
  const staleLoader = body.staleLoader as { noEntryState?: boolean } | undefined;
1788
- if (steps.length === 0 && staleLoader === undefined) return reply(body, { hint: "Read the source. Record names, comments, regions and modules in the project knowledge. Then generate again." });
1794
+ // The reference is made from the source: it is the step after this run, also when the run has no finding.
1795
+ const reference = body.staleReference === undefined ? "" : " The reference pages in staleReference are from an earlier revision of this source. Generate the reference pages again from this source.";
1796
+ if (steps.length === 0 && staleLoader === undefined) return reply(body, { hint: `Read the source. Record names, comments, regions and modules in the project knowledge. Then generate again.${reference}` });
1789
1797
  if (again) steps.push("Then generate again.");
1790
1798
  // The run with --loader writes the loader again, so it is the next action also for the other findings.
1791
1799
  const loaderAgain = staleLoader !== undefined && staleLoader.noEntryState !== true;
@@ -1793,7 +1801,7 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
1793
1801
  steps.push("The loader files in staleLoader.files are of another knowledge revision or toolkit version, and the run kept them.");
1794
1802
  steps.push(loaderAgain ? "To write the loader of this revision, generate with --loader." : "The knowledge has no entry state, so --loader cannot write them again. Remove them when the build does not use them.");
1795
1803
  }
1796
- return reply(body, { hint: steps.join(" "), ...(again || loaderAgain ? { nextAction: generateAgain(call, call.flag("loader") || loaderAgain) } : {}) });
1804
+ return reply(body, { hint: `${steps.join(" ")}${reference}`, ...(again || loaderAgain ? { nextAction: generateAgain(call, call.flag("loader") || loaderAgain) } : {}) });
1797
1805
  }
1798
1806
 
1799
1807
  /** The hint of an export result: the action for a failed stage, or the next steps for the new project. */
@@ -207,10 +207,12 @@ The script does the steps of the record file on the original program. Then it wr
207
207
  - `executed`: the number of instructions in the coverage map.
208
208
  - `coverageFrom`: the `frame` and the `pc` where the coverage map starts. `null` when the coverage did not start.
209
209
  - `reason`: with a FAIL, why the session did not complete.
210
+ - `evidence`: only when the project knowledge gives a file of `--out` as evidence, and this record changed the file. Each item has the `file`, its `state` and the `revisions` that give the file.
210
211
 
211
212
  Do this for each result:
212
213
 
213
214
  - `PASS`: for a folder in `tests/recordings/`, `hint` tells you to commit the folder and to add its `coverage.bin` to the project knowledge as coverage. Git ignores `.c64-re-tools/local/`, thus the project knowledge must not name a file in it. For a folder there, `hint` tells you to record again with `--out tests/recordings/<name>`. `nextAction` replays the recording on the original. Run it to make sure that the recording replays.
215
+ - `PASS` with `evidence`: you recorded into the folder of an earlier recording. Put the new `coverage.bin` into the project knowledge as coverage. It replaces the map of the earlier recording. For another file in `evidence`, examine the facts of its revisions against the new recording.
214
216
  - `FAIL` after a cancel on the page: `hint` tells you to ask the user what to do. Do not record a session from steps in place of the session of the user.
215
217
  - Another `FAIL`: `reason` names the step that did not complete. Examples are a `runUntil` step that did not get to its target, and a `type` step with too many keys. Change the step, then run `record` again.
216
218
  - `coverageFrom` is `null` and `executed` is 0: the coverage did not start, so the coverage map is empty. The recording can still replay.
@@ -239,7 +241,7 @@ A `$` address is an address of the original. On the rebuild, it moves with the n
239
241
 
240
242
  A rebuild can be a loader with a start screen that RUN starts. If the symbols of the rebuild have `loader_start_screen_wait` and `loader_start_screen_continue`, the script runs the rebuild to the wait. Then it sets the PC to `loader_start_screen_continue`. The cycles before the wait do not count.
241
243
 
242
- A rebuild can be the loader program of a generated source. Give its symbols. Then the replay counts from the entry of the program, where the loader jumps to. The checkpoints of both sides start at that entry. A runUntil step to an address does not count the code of the loader, or the code that the original runs before that entry. If another step of the recording runs before the entry, the result is INCONCLUSIVE. Then start the steps of the record file after the entry.
244
+ A rebuild can be the loader program of a generated source. Give its symbols. Then the replay counts from the entry of the program, where the loader jumps to. The checkpoints of both sides start at that entry. At the entry, the rebuild gets the raster position, the CIA timers and the interrupt state of the original. The loader cannot set them as the original has them in the replay. A runUntil step to an address does not count the code of the loader, or the code that the original runs before that entry. If another step of the recording runs before the entry, the result is INCONCLUSIVE. Then start the steps of the record file after the entry.
243
245
 
244
246
  `body` holds `result`, `side`, `firstDifference`, `reason` and `files`. The section "Replay" of `references/recording-format.md` gives each field.
245
247
 
@@ -257,7 +259,7 @@ Do this for each result:
257
259
  Traps:
258
260
 
259
261
  - `idleReads` counts the input reads of the rebuild that the recording had no value for. On the original, such a read makes the result INCONCLUSIVE. The rebuild can read input where the original does not, for example in its loader before the start screen. Such reads do not change a PASS of the rebuild.
260
- - The script refuses a recording of version 2.0 with `invalid-input`. Record the session again.
262
+ - The script refuses a recording of an older version in an old form with `invalid-input`. Record the session again.
261
263
 
262
264
  ---
263
265
 
@@ -127,7 +127,7 @@ The page sends input only between Start and End. The input of the page goes into
127
127
 
128
128
  A site is the address of the instruction that reads. The values are hex. `<from>` and `<count>` are decimal.
129
129
 
130
- `replay` examines `recording.json` before the replay starts. A recording of version 2.0 can have events or a comparison in the old form, for example `"at"` in place of `"address"`. The script refuses it with `invalid-input`. The message names the event, the old field and the form to write. Record the session again.
130
+ `replay` examines `recording.json` before the replay starts. A recording of an older version can have events or a comparison in an old form. For example, `"at"` is in place of `"address"`, or a `runUntil` step to an address has no count of the CPU at its target. The script refuses such a recording with `invalid-input`, and the message names the event. Record the session again.
131
131
 
132
132
  ## Replay
133
133
 
@@ -57,6 +57,8 @@ Before the first step of each side, the script does a hard reset. The CPU stops
57
57
  | `{ "normalize": true }` | Write pages 0 to 3 and `$00`/`$01` from the entry state in the project knowledge. The entry state comes from a capture of the unpacked program. Then both sides have the same zero page, stack and KERNAL work area. |
58
58
  | `{ "observe": "moved", ... }` | Record a checkpoint. |
59
59
 
60
+ The `timeoutFrames` of a `runUntil` step is from 1 to 30000. The default is 3000. For a longer wait, put `frames` steps before the `runUntil` step.
61
+
60
62
  The `port` of a joystick is 1 or 2. The `direction` is `center`, `up`, `down`, `left`, `right`, `up-left`, `up-right`, `down-left` or `down-right`.
61
63
 
62
64
  A `condition` has the `kind` `register`, `memory` or `raster`. A `register` condition has `register` (`a`, `x`, `y` or `sp`), `operator` and `value`. A `memory` condition has `address`, `operator` and `value`. A `raster` condition has `line` and an optional `cycle`.
@@ -95,7 +97,7 @@ A run file is one JSON object in a project file. It has:
95
97
  - `start`: required. `{ "program": "game.prg" }` to autostart a program with a BASIC start line, `{ "program": "game.prg", "load": true }` to load it with the CPU stopped (set `pc` in a step), or `{ "snapshot": ".c64-re-tools/local/snapshots/room0.vsf" }`.
96
98
  - `symbols`: optional, `knowledge`, `none` (default), or a JSON file as for a subject. Without `symbols`, a run has no names: give `"symbols": "knowledge"` to use the names of the knowledge.
97
99
  - `videoStandard`: optional, `pal` (default) or `ntsc`.
98
- - `steps`: required. At least one step. The steps `write`, `registers`, `joystick`, `type`, `frames` and `runUntil` of a scenario, and the run steps `snapshot`, `save`, `screen`, `coverage`, `trace`, `observe` and `expect`.
100
+ - `steps`: required. At least one step. The steps `write`, `registers`, `joystick`, `type`, `press`, `frames` and `runUntil` of a scenario, and the run steps `snapshot`, `save`, `screen`, `coverage`, `trace`, `observe` and `expect`.
99
101
 
100
102
  The run steps have these effects:
101
103
 
@@ -112,7 +114,7 @@ The run steps have these effects:
112
114
 
113
115
  A `trace` step has a name, `points` (1 to 8), `frames` (1 to 3000) and an optional `maxHits` (at most 20000). A point has `kind` (`exec`, `read` or `write`), `start` and an optional `end`. The step writes `<name>.json` with each hit. `results.json` gives the file, the count of hits, the frames and why the trace ended. A trace that a breakpoint, a watchpoint or a JAM ends also ends the run.
114
116
 
115
- In a run, an `observe` step can have `memory`, `registers`, `vicii` and `sprites`. `registers` and `vicii` are `true` or `false`, not a list. `"registers": true` gives all registers. A scenario takes a list of register names, a run does not. `sprites` is a list of sprite numbers from 0 to 7.
117
+ In a run, an `observe` step can have `memory`, `registers`, `vicii` and `sprites`. `registers` and `vicii` are `true` or `false`, not a list. `"registers": true` gives all registers. A scenario takes a list of register names, a run does not. `sprites` is a list of sprite numbers from 0 to 7. In a run, the screen is not a key of `observe`. Write it with a `screen` step, for example `{ "screen": "room3" }`.
116
118
 
117
119
  In a run, a memory item has `address`, `size` (1 to 65536) and `view`. An item larger than 4096 bytes goes into the file `<observe>-<address>.bin`, without the `$`. `results.json` gives the file name.
118
120
 
@@ -296,7 +296,12 @@ export function readRecording(folder: string): Recording {
296
296
  const named = typeof event.step === "number" ? `${at} (step ${event.step})` : at;
297
297
  if (event.action.restore === true && Object.keys(event.action).length === 1) return;
298
298
  // The action with the defaults filled in, as the record file gave it.
299
- event.action = checkActionStep(stepKind(event.action, ACTION_STEP_KINDS, named, where), event.action, named, where);
299
+ const action = checkActionStep(stepKind(event.action, ACTION_STEP_KINDS, named, where), event.action, named, where);
300
+ event.action = action;
301
+ // Before 2.6.0-rc.16, a runUntil to an address had the point of another event: a replay cannot find its target again.
302
+ if ("runUntil" in action && action.runUntil.target.kind === "address" && !("pc" in event.key)) {
303
+ fail(`${named}: a runUntil step to an address has a point of an older version, which a replay cannot find. Record the session again with record`);
304
+ }
300
305
  });
301
306
  return value as unknown as Recording;
302
307
  }
@@ -357,6 +362,11 @@ export function siteMap(sites: RecordedSite[], from: Map<string, number>, to: Ma
357
362
  export interface EntryPoint {
358
363
  /** The tick of the first opcode fetch at the entry. */
359
364
  tick: number;
365
+ /**
366
+ * The phase of the machine at that fetch, as the replay core gives it: the beam position, the CIA timers and
367
+ * the interrupt state. It depends on how the program started, so the rebuild gets it at its own entry.
368
+ */
369
+ phase: string;
360
370
  /** The count of each pc key, by its target, before that fetch. */
361
371
  counts: Map<string, number>;
362
372
  /** The number of events of the recording before the entry: always the first ones. */
@@ -755,9 +765,13 @@ export async function replaySide(
755
765
  if ((await core.status(`run-pc ${hex(jump)} ${limit}`)).word !== "reached") problem = `the rebuild did not come to the jump of its loader at ${formatC64Address(jump)}`;
756
766
  else {
757
767
  await countAt(core, targets);
758
- const entered = await core.status(`run-pc ${hex(handover.entry)} ${limit}`);
759
- if (entered.word !== "reached") problem = `the rebuild did not come to its entry at ${formatC64Address(handover.entry)}`;
768
+ const reached = await core.status(`run-pc ${hex(handover.entry)} ${limit}`);
769
+ if (reached.word !== "reached") problem = `the rebuild did not come to its entry at ${formatC64Address(handover.entry)}`;
760
770
  else {
771
+ // The loader sets the entry state of the capture, but the phase of the frame and of the CIA timers at the entry
772
+ // depends on how the original started: the rebuild waits at its entry for the beam position of the original, and
773
+ // gets its CIA timers and interrupt state there. A program that starts its timers without a load keeps that phase.
774
+ const entered = await core.status(`align ${handover.original.phase}`);
761
775
  // After the entry, a tick key is as far from the entry as in the original.
762
776
  skipped = entered.tick - handover.original.tick;
763
777
  limit = base + Math.max(0, skipped);
@@ -768,9 +782,10 @@ export async function replaySide(
768
782
  // The original with an entry: the events before the mark at the entry came.
769
783
  let eventsBefore = 0;
770
784
  let entryTick: number | undefined;
785
+ let entryPhase = "";
771
786
  const marked = async () => {
772
- const answer = /tick=(\d+)/.exec(await core.command("marked"));
773
- if (answer !== null) entryTick = Number(answer[1]);
787
+ const answer = /tick=(\d+) phase=([0-9a-f]+)/.exec(await core.command("marked"));
788
+ if (answer !== null) [entryTick, entryPhase] = [Number(answer[1]), answer[2]!];
774
789
  };
775
790
  for (const [index, event] of (problem === undefined ? recording.events : []).entries()) {
776
791
  const what = event.step === undefined ? "the RESTORE of the play" : "step " + event.step;
@@ -819,7 +834,7 @@ export async function replaySide(
819
834
  }
820
835
  // A checkpoint at the first fetch at the entry has the tick of the mark. The rebuild starts its checkpoints after that fetch.
821
836
  const after = lines.filter((line) => Number(line.split(" ")[0]) > entryTick!);
822
- entryPoint = { tick: entryTick, counts, eventsBefore, samplesBefore: lines.length - after.length };
837
+ entryPoint = { tick: entryTick, phase: entryPhase, counts, eventsBefore, samplesBefore: lines.length - after.length };
823
838
  lines = after;
824
839
  }
825
840
  return {
@@ -9,7 +9,7 @@ import { screenText } from "#src/graphics.ts";
9
9
  import { runProgram } from "#src/host-client/autostart.ts";
10
10
  import { isRefusal, Refusal } from "#src/errors.ts";
11
11
  import { readCoverage } from "#src/host-client/coverage.ts";
12
- import { ACTION_STEP_KINDS, checkActionStep, checkLocation, checkStepNames, isInteger, isObject, refuseOldStep, renamedField, runActionStep, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
12
+ import { ACTION_STEP_KINDS, aStep, checkActionStep, checkLocation, checkStepNames, isInteger, isObject, refuseOldStep, renamedField, runActionStep, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
13
13
  import { readPrg } from "#src/host-client/image.ts";
14
14
  import { MAX_MEMORY_READ, MAX_TRACE_FRAMES, MAX_TRACE_HITS, MAX_TRACE_POINTS, TRACE_KINDS, WireFailure, type TraceHit, type TraceKind } from "#src/host-client/tools.ts";
15
15
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
@@ -61,6 +61,11 @@ const RUN_FIELDS = "A run file has name, start and steps, and optionally symbols
61
61
  const START_FORMS = '{ "program": "<file.prg>" }, { "program": "<file.prg>", "load": true } or { "snapshot": "<file.vsf>" }';
62
62
  const TRACE_KEYS = ["trace", "points", "frames", "maxHits"];
63
63
  const OBSERVE_KEYS = ["observe", "memory", "registers", "vicii", "sprites"];
64
+ /** The fix for a key that the same step of a scenario has, or none. */
65
+ function scenarioKeyFix(key: string, step: Record<string, unknown>): string {
66
+ if (key === "screen" && "observe" in step) return `. A run writes the screen with its own step: {"screen": "${typeof step.observe === "string" ? step.observe : "<name>"}"}`;
67
+ return key === "side" ? ". A run has one program. Remove side" : "";
68
+ }
64
69
  const EXPECT_KEYS = ["expect", "memory", "registers"];
65
70
  const EXPECTED_MEMORY_KEYS = ["address", "data", "text", "mask", "view"];
66
71
  /** The characters that screenText gives for the screen codes 0 to 63; a graphics code gives a dot. */
@@ -135,7 +140,7 @@ function readRun(path: string): Run {
135
140
  const kind = kinds[0]!;
136
141
  refuseOldStep(kind, step, at, fail);
137
142
  const allowed = kind === "observe" ? OBSERVE_KEYS : kind === "expect" ? EXPECT_KEYS : kind === "trace" ? TRACE_KEYS : [kind];
138
- for (const key of Object.keys(step)) if (!allowed.includes(key)) fail(`${at} has the key ${key}, which a ${kind} step does not have`);
143
+ for (const key of Object.keys(step)) if (!allowed.includes(key)) fail(`${at} has the key ${key}, which ${aStep(kind)} of a run does not have${scenarioKeyFix(key, step)}`);
139
144
  if ((ACTION_STEP_KINDS as readonly string[]).includes(kind)) {
140
145
  // The step with its defaults filled in, as the shared schema of the action steps gives it.
141
146
  (value.steps as unknown[])[index] = checkActionStep(kind as ActionStepKind, step, at, fail);
@@ -7,7 +7,7 @@ import { isRefusal, Refusal } from "#src/errors.ts";
7
7
  import { c64AddressOf, formatC64Address, formatSprite, formatVicii, parseC64Address } from "#src/c64.ts";
8
8
  import { MAX_BASELINES, MAX_MASK_RECTANGLES, maskCoversFrame, WireFailure } from "#src/host-client/tools.ts";
9
9
  import { LOAD_LIMIT_FRAMES, RUN_LIMIT_FRAMES, runProgram } from "#src/host-client/autostart.ts";
10
- import { ACTION_STEP_KINDS, checkActionStep, checkLocation, isInteger, isObject, refuseOldStep, renamedField, runActionStep, type ActionStep, type ActionStepKind, type Location } from "#src/host-client/steps.ts";
10
+ import { ACTION_STEP_KINDS, aStep, checkActionStep, checkLocation, isInteger, isObject, refuseOldStep, renamedField, runActionStep, type ActionStep, type ActionStepKind, type Location } from "#src/host-client/steps.ts";
11
11
  import { applyEntryState, parseEntryState } from "#src/host-client/entry-state.ts";
12
12
  import { readPrg } from "#src/host-client/image.ts";
13
13
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
@@ -154,11 +154,11 @@ export function readScenario(path: string): Scenario {
154
154
  // An observe step names what it observes with "memory" and "registers" too.
155
155
  const kinds = "observe" in step ? ["observe"] : Object.keys(step).filter((key) => STEP_KINDS.includes(key));
156
156
  if (kinds.length > 1) return fail(`${at} has ${kinds.length} step kinds: ${kinds.join(", ")}. Give each one its own step`);
157
- if (kinds.length !== 1) return fail(`${at} must have exactly one of ${STEP_KINDS.join(", ")}`);
157
+ if (kinds.length !== 1) return fail(`${at} must have exactly one of ${STEP_KINDS.join(", ")}${typeof step.screen === "string" ? `. A scenario compares the screen in an observe step: {"observe": "${step.screen}", "screen": {}}` : ""}`);
158
158
  const kind = kinds[0]!;
159
159
  refuseOldStep(kind, step, at, fail);
160
160
  const allowed = [...(STEP_KEYS[kind] ?? [kind]), ...(kind === "observe" ? [] : ["side"])];
161
- for (const key of Object.keys(step)) if (!allowed.includes(key)) fail(`${at} has the key ${key}, which a ${kind} step does not have`);
161
+ for (const key of Object.keys(step)) if (!allowed.includes(key)) fail(`${at} has the key ${key}, which ${aStep(kind)} does not have`);
162
162
  if (step.side !== undefined && !(SIDES as unknown[]).includes(step.side)) fail(`${at}: side must be original or rebuild`);
163
163
  if ((ACTION_STEP_KINDS as readonly string[]).includes(kind)) {
164
164
  // The step with its defaults filled in, as the shared schema of the action steps gives it.
@@ -13,8 +13,10 @@ import { ViceSessionClient } from "#src/host-client/vice-session.ts";
13
13
  import { C64RunSession, PAL_FRAME_CYCLES } from "#src/native/c64run.ts";
14
14
  import { localToolContext } from "#src/native/local.ts";
15
15
  import { Workspace } from "#src/native/staging.ts";
16
+ import { openForRead } from "#src/knowledge/database.ts";
17
+ import { changedEvidence } from "#src/knowledge/evidence.ts";
16
18
  import { knowledgeNames } from "#src/knowledge/names.ts";
17
- import { LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRelative } from "#src/project.ts";
19
+ import { LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRelative, projectRoot } from "#src/project.ts";
18
20
  import { OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec, type Reply } from "#src/script.ts";
19
21
  import { diffFiles } from "./lib/diff-files.ts";
20
22
  import { CANCELLED, play } from "./lib/play.ts";
@@ -79,7 +81,10 @@ async function recordCommand(call: Call): Promise<Reply> {
79
81
  const context = localToolContext();
80
82
  const core = await C64RunSession.open(context);
81
83
  const workspace = Workspace.create(context.supervisor, "c64-re-tools-record-");
84
+ let db: ReturnType<typeof openForRead>;
82
85
  try {
86
+ // The knowledge is read before the session: a record into the folder of an earlier recording can change files that it gives as evidence.
87
+ db = openForRead();
83
88
  const person = playing
84
89
  ? (session: C64RunSession, restore: () => Promise<string | undefined>) => {
85
90
  const ready = (url: string) =>
@@ -111,11 +116,20 @@ async function recordCommand(call: Call): Promise<Reply> {
111
116
  ? `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>.`
112
117
  : `Commit ${out} with the scenarios. Add ${out}/${RECORDING_FILES.coverage} to the project knowledge as coverage.`;
113
118
  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
+ const written = new Set(Object.values(RECORDING_FILES).map((name) => projectRelative(`${out}/${name}`)));
120
+ const evidence = changedEvidence(db, projectRoot(), (file) => written.has(file));
121
+ const map = projectRelative(`${out}/${RECORDING_FILES.coverage}`);
122
+ const cited = [
123
+ ...(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.`] : []),
126
+ ].join("");
114
127
  return reply(
115
- { result: "PASS", recorded: true, out, ...summary, files },
116
- { hint: `${keep}${recordFile} ${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) },
128
+ { result: "PASS", recorded: true, out, ...summary, files, ...(evidence.length === 0 ? {} : { evidence }) },
129
+ { hint: `${keep}${recordFile}${cited} ${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) },
117
130
  );
118
131
  } finally {
132
+ db?.close();
119
133
  await core.close();
120
134
  workspace.remove();
121
135
  }
@@ -344,6 +344,9 @@ export function newStepForm(kind: string, step: Record<string, unknown>): { fiel
344
344
  }
345
345
  }
346
346
 
347
+ /** "a write step", "an observe step": the step kind with its article, for a refusal. */
348
+ export const aStep = (kind: string): string => `${/^[aeiou]/.test(kind) ? "an" : "a"} ${kind} step`;
349
+
347
350
  /** Refuses a step in a form of the 2.0 files: the message names its 2.0 fields and gives the step to write. */
348
351
  export function refuseOldStep(kind: string, step: Record<string, unknown>, at: string, fail: (message: string) => never): void {
349
352
  const found = newStepForm(kind, step);
@@ -359,7 +362,7 @@ export function refuseOldStep(kind: string, step: Record<string, unknown>, at: s
359
362
  */
360
363
  export function checkActionStep(kind: ActionStepKind, step: Record<string, unknown>, at: string, fail: (message: string) => never): ActionStep {
361
364
  refuseOldStep(kind, step, at, fail);
362
- for (const key of Object.keys(step)) if (key !== kind) fail(`${at} has the key ${key}, which a ${kind} step does not have`);
365
+ for (const key of Object.keys(step)) if (key !== kind) fail(`${at} has the key ${key}, which ${aStep(kind)} does not have`);
363
366
  return checkInput(kind, step[kind], at, fail);
364
367
  }
365
368
 
@@ -0,0 +1,66 @@
1
+ // The files that the knowledge gives as evidence, against the project as it
2
+ // is now. A revision keeps the SHA-256 of each file that it rests on, so a
3
+ // file that is gone or that changed since then shows here.
4
+
5
+ import { createHash } from "node:crypto";
6
+ import { readFileSync } from "node:fs";
7
+ import type { DatabaseSync } from "node:sqlite";
8
+
9
+ import { LOCAL_DIRECTORY, PROJECT_DIRECTORY, resolveProjectFile } from "../project.ts";
10
+ import { coverageRuns } from "./read.ts";
11
+
12
+ /** A file of the evidence that is not as the knowledge gives it: missing, or with other bytes. */
13
+ export interface EvidenceChange {
14
+ /** The project path of the file. */
15
+ file: string;
16
+ state: "missing" | "changed";
17
+ /** The revisions that give the file with the SHA-256 that the file no longer has, oldest first. */
18
+ revisions: string[];
19
+ }
20
+
21
+ /** The SHA-256 of a project file, or undefined when it is not there. */
22
+ function fileHash(root: string, path: string): string | undefined {
23
+ try {
24
+ return createHash("sha256").update(readFileSync(resolveProjectFile(path, root))).digest("hex");
25
+ } catch {
26
+ return undefined;
27
+ }
28
+ }
29
+
30
+ /**
31
+ * The evidence files that are missing or changed. A file counts with its
32
+ * latest SHA-256 in the knowledge: for a coverage map, its latest import
33
+ * into each space; for another file, the latest revision that gives it. An
34
+ * earlier SHA-256 of the same file is history. A file in
35
+ * .c64-re-tools/local/ does not count: git does not keep it, and the
36
+ * knowledge keeps what it needs of it. `only` limits the check to some files.
37
+ */
38
+ export function changedEvidence(db: DatabaseSync | undefined, root: string, only?: (file: string) => boolean): EvidenceChange[] {
39
+ if (db === undefined) return [];
40
+ const rows = db.prepare("SELECT revision, kind, ref, sha256 FROM evidence WHERE sha256 IS NOT NULL ORDER BY revision, id").all() as Array<{ revision: string; kind: string; ref: string; sha256: string }>;
41
+ const local = `${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/`;
42
+ const wanted = (file: string) => !file.startsWith(local) && (only === undefined || only(file));
43
+ // The SHA-256 values that each file must have now.
44
+ const expected = new Map<string, Set<string>>();
45
+ const expect = (file: string, sha256: string) => {
46
+ if (!wanted(file)) return;
47
+ if (!expected.has(file)) expected.set(file, new Set());
48
+ expected.get(file)!.add(sha256);
49
+ };
50
+ const latest = new Map<string, string>();
51
+ for (const row of rows) if (row.kind !== "coverage") latest.set(row.ref, row.sha256);
52
+ for (const [file, sha256] of latest) expect(file, sha256);
53
+ // The runs of a name are oldest first: the last run in each space is the map that the knowledge has.
54
+ const maps = new Map(coverageRuns(db).map((run) => [`${run.space}\n${run.name}`, run]));
55
+ for (const run of maps.values()) expect(run.name, run.sha256);
56
+ const changes: EvidenceChange[] = [];
57
+ for (const [file, hashes] of [...expected].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
58
+ const now = fileHash(root, file);
59
+ for (const sha256 of hashes) {
60
+ if (now === sha256) continue;
61
+ const revisions = [...new Set(rows.filter((row) => row.ref === file && row.sha256 === sha256).map((row) => row.revision))];
62
+ changes.push({ file, state: now === undefined ? "missing" : "changed", revisions });
63
+ }
64
+ }
65
+ return changes;
66
+ }
@@ -86,12 +86,12 @@ export interface EntryRow {
86
86
  revision: string;
87
87
  }
88
88
 
89
- /** A coverage range of one kind. */
89
+ /** The ranges of one kind of the coverage map at a project path: their number. */
90
90
  export interface CoverageRow {
91
91
  space: Space;
92
+ map: string;
92
93
  kind: CoverageKind;
93
- start: number;
94
- end: number;
94
+ ranges: number;
95
95
  origin: Origin;
96
96
  revision: string;
97
97
  }
@@ -285,8 +285,8 @@ export function revision(db: DatabaseSync | undefined, text: string): RevisionCh
285
285
  [
286
286
  "coverage",
287
287
  "coverage",
288
- "space, kind, start_address, end_address, origin, valid_from_revision",
289
- (row: Raw): CoverageRow => ({ space: row.space as Space, kind: row.kind as CoverageKind, start: row.start_address as number, end: row.end_address as number, origin: row.origin as Origin, revision: row.valid_from_revision as string }),
288
+ "space, map, kind, length(ranges) - length(replace(ranges, ' ', '')) + 1 AS ranges, origin, valid_from_revision",
289
+ (row: Raw): CoverageRow => ({ space: row.space as Space, map: row.map as string, kind: row.kind as CoverageKind, ranges: row.ranges as number, origin: row.origin as Origin, revision: row.valid_from_revision as string }),
290
290
  ],
291
291
  ] as const;
292
292
  const added: HistoryEntry[] = [];
@@ -139,53 +139,104 @@ export function setImage(db: DatabaseSync, context: WriteContext, request: Image
139
139
  });
140
140
  }
141
141
 
142
- /** The coverage of one space as ranges of each kind. */
142
+ /** Address ranges as the knowledge text keeps them: "$1000-$1002 $1005". */
143
+ function rangesText(ranges: readonly AddressRange[]): string {
144
+ const at = (address: number) => `$${address.toString(16).padStart(4, "0")}`;
145
+ return ranges.map((range) => (range.start === range.end ? at(range.start) : `${at(range.start)}-${at(range.end)}`)).join(" ");
146
+ }
147
+
148
+ /** Sets 1 in `map` at each address of ranges as text. */
149
+ function fillRanges(map: Uint8Array, text: string): void {
150
+ for (const item of text.split(" ")) {
151
+ const [start, end] = item.split("-");
152
+ map.fill(1, Number.parseInt(start!.slice(1), 16), Number.parseInt((end ?? start)!.slice(1), 16) + 1);
153
+ }
154
+ }
155
+
156
+ /** The union of the coverage of one space: a map of each kind, 1 at each address that a map of the space has. */
143
157
  function currentCoverage(db: DatabaseSync, space: Space): Map<CoverageKind, Uint8Array> {
144
158
  const maps = new Map<CoverageKind, Uint8Array>(COVERAGE_KINDS.map((kind) => [kind, new Uint8Array(SIZE)]));
145
- for (const row of db.prepare("SELECT kind, start_address, end_address FROM current_coverage WHERE space = ?").all(space) as Array<{ kind: CoverageKind; start_address: number; end_address: number }>) {
146
- maps.get(row.kind)!.fill(1, row.start_address, row.end_address + 1);
147
- }
159
+ for (const row of db.prepare("SELECT kind, ranges FROM current_coverage WHERE space = ?").all(space) as Array<{ kind: CoverageKind; ranges: string }>) fillRanges(maps.get(row.kind)!, row.ranges);
148
160
  return maps;
149
161
  }
150
162
 
163
+ /** The number of address ranges of each kind in the coverage of a space: the ranges of the union of its maps. */
164
+ export function coverageRangeCounts(db: DatabaseSync | undefined, space: Space = DEFAULT_SPACE): Partial<Record<CoverageKind, number>> {
165
+ if (db === undefined) return {};
166
+ const counts: Partial<Record<CoverageKind, number>> = {};
167
+ for (const [kind, map] of currentCoverage(db, space)) {
168
+ const count = rangesWhere((address) => map[address] === 1).length;
169
+ if (count > 0) counts[kind] = count;
170
+ }
171
+ return counts;
172
+ }
173
+
174
+ /** The ranges of each kind of one coverage map as text, for each kind that it has. wx is each address that the run both wrote and executed. */
175
+ function mapRanges(bytes: Uint8Array): Map<CoverageKind, string> {
176
+ const ranges = new Map<CoverageKind, string>();
177
+ for (const kind of COVERAGE_KINDS) {
178
+ const has = kind === "wx" ? (address: number) => (bytes[address]! & (COVERAGE.ramWrite | COVERAGE.ramExecute)) === (COVERAGE.ramWrite | COVERAGE.ramExecute) : (address: number) => (bytes[address]! & KIND_BITS[kind]) !== 0;
179
+ const found = rangesWhere(has);
180
+ if (found.length > 0) ranges.set(kind, rangesText(found));
181
+ }
182
+ return ranges;
183
+ }
184
+
185
+ /** The number of ranges of each kind that are in `after` and not in `before`. */
186
+ function gained(before: Map<CoverageKind, Uint8Array>, after: Map<CoverageKind, Uint8Array>): number {
187
+ let count = 0;
188
+ for (const kind of COVERAGE_KINDS) count += rangesWhere((address) => after.get(kind)![address] === 1 && before.get(kind)![address] === 0).length;
189
+ return count;
190
+ }
191
+
151
192
  /**
152
- * Joins coverage maps into the coverage of a space: adds the ranges of
153
- * the flags that no imported run set before, and as wx the addresses that one
154
- * run both wrote and executed. Each new map is evidence of the revision, with
155
- * its space. A map that the space has with the same name and bytes is not
156
- * imported again.
193
+ * Puts coverage maps into the coverage of a space. The knowledge keeps the
194
+ * ranges of each map by its project path; the coverage of the space is the
195
+ * union of the maps. A map for a path that the space has already replaces
196
+ * the earlier map of that path: a run that is recorded again counts only
197
+ * with its new map. wx is each address that one run both wrote and
198
+ * executed. Each new map is evidence of the revision, with its space. A map
199
+ * that is the latest map of its path in the space is not imported again.
157
200
  */
158
201
  export function addCoverage(
159
202
  db: DatabaseSync,
160
203
  context: WriteContext,
161
204
  request: { space?: Space; maps: CoverageMap[] },
162
- ): { revision: string | null; current: { space: Space; imported: string[]; known: string[]; ranges: number } } {
205
+ ): { revision: string | null; current: { space: Space; imported: string[]; replaced: string[]; known: string[]; added: number; removed: number } } {
163
206
  checkSpace(request);
164
207
  const space = request.space ?? DEFAULT_SPACE;
165
208
  for (const map of request.maps) {
166
209
  if (map.bytes.length !== SIZE) throw new Refusal("invalid-input", `${map.name} has ${map.bytes.length} bytes; a coverage map has 65536, one for each address.`);
167
210
  }
168
- const hashed = request.maps.map((map) => ({ ...map, sha256: createHash("sha256").update(map.bytes).digest("hex") }));
169
- const known = new Set(coverageRuns(db).filter((run) => run.space === space).map((run) => `${run.name}\n${run.sha256}`));
170
- const fresh = hashed.filter((map) => !known.has(`${map.name}\n${map.sha256}`));
211
+ // A path given twice is one map: the last one.
212
+ const byName = new Map(request.maps.map((map) => [map.name, map]));
213
+ const hashed = [...byName.values()].map((map) => ({ ...map, sha256: createHash("sha256").update(map.bytes).digest("hex") }));
214
+ // The runs of a name are oldest first: the last one is the latest map of the path.
215
+ const latest = new Map(coverageRuns(db).filter((run) => run.space === space).map((run) => [run.name, run.sha256]));
216
+ const withRows = new Set((db.prepare("SELECT DISTINCT map FROM current_coverage WHERE space = ?").all(space) as Array<{ map: string }>).map((row) => row.map));
217
+ // A map that has no access has no rows: it is known by its SHA-256 alone.
218
+ const isKnown = (map: (typeof hashed)[number]) => latest.get(map.name) === map.sha256 && (withRows.has(map.name) || map.bytes.every((byte) => byte === 0));
219
+ const fresh = hashed.filter((map) => !isKnown(map));
171
220
  const evidence: Evidence[] = [...(context.evidence ?? []), ...fresh.map((map): Evidence => ({ kind: "coverage", ref: map.name, sha256: map.sha256, ...(space === DEFAULT_SPACE ? {} : { space }) }))];
172
221
  return write(db, { ...context, evidence }, "coverage", (change) => {
173
- const result = { space, imported: fresh.map((map) => map.name), known: hashed.filter((map) => !fresh.includes(map)).map((map) => map.name), ranges: 0 };
222
+ const result = { space, imported: fresh.map((map) => map.name), replaced: fresh.filter((map) => latest.has(map.name) && latest.get(map.name) !== map.sha256).map((map) => map.name), known: hashed.filter((map) => !fresh.includes(map)).map((map) => map.name), added: 0, removed: 0 };
174
223
  if (fresh.length === 0) return result;
175
- // A revision for each import, also when no flag is new: the maps are its evidence.
224
+ // A revision for each import, also when the coverage does not change: the maps are its evidence.
176
225
  change.id();
177
- const union = currentCoverage(db, space);
226
+ const before = currentCoverage(db, space);
178
227
  for (const map of fresh) {
179
- for (const kind of COVERAGE_KINDS) {
180
- const has = kind === "wx" ? (address: number) => (map.bytes[address]! & (COVERAGE.ramWrite | COVERAGE.ramExecute)) === (COVERAGE.ramWrite | COVERAGE.ramExecute) : (address: number) => (map.bytes[address]! & KIND_BITS[kind]) !== 0;
181
- const known = union.get(kind)!;
182
- for (const range of rangesWhere((address) => known[address] === 0 && has(address))) {
183
- change.insertCoverage({ space, kind, start: range.start, end: range.end, origin: context.origin });
184
- known.fill(1, range.start, range.end + 1);
185
- result.ranges++;
186
- }
228
+ // Only a kind whose ranges differ from the earlier map of the path changes.
229
+ const wanted = mapRanges(map.bytes);
230
+ const rows = db.prepare("SELECT id, kind, ranges FROM current_coverage WHERE space = ? AND map = ?").all(space, map.name) as Array<{ id: string; kind: CoverageKind; ranges: string }>;
231
+ for (const row of rows) {
232
+ if (wanted.get(row.kind) === row.ranges) wanted.delete(row.kind);
233
+ else change.close("coverage", "id = ?", row.id);
187
234
  }
235
+ for (const [kind, ranges] of wanted) change.insertCoverage({ space, map: map.name, kind, ranges, origin: context.origin });
188
236
  }
237
+ const after = currentCoverage(db, space);
238
+ result.added = gained(before, after);
239
+ result.removed = gained(after, before);
189
240
  return result;
190
241
  });
191
242
  }
@@ -268,15 +319,12 @@ export function analyzedBytes(image: ProgramImage): { bytes: Buffer; kind: "prg"
268
319
  */
269
320
  export function programCoverage(db: DatabaseSync | undefined, space: Space = DEFAULT_SPACE): { map: Uint8Array; selfModified: Uint8Array } | undefined {
270
321
  if (db === undefined) return undefined;
271
- const rows = db.prepare("SELECT kind, start_address, end_address FROM current_coverage WHERE space = ?").all(space) as Array<{ kind: CoverageKind; start_address: number; end_address: number }>;
272
- if (rows.length === 0) return undefined;
322
+ const has = db.prepare("SELECT 1 FROM current_coverage WHERE space = ? LIMIT 1").get(space);
323
+ if (has === undefined) return undefined;
324
+ const union = currentCoverage(db, space);
273
325
  const map = new Uint8Array(SIZE);
274
- const selfModified = new Uint8Array(SIZE);
275
- for (const row of rows) {
276
- if (row.kind === "wx") selfModified.fill(1, row.start_address, row.end_address + 1);
277
- else for (let address = row.start_address; address <= row.end_address; address++) map[address]! |= KIND_BITS[row.kind];
278
- }
279
- return { map, selfModified };
326
+ for (const [kind, marks] of union) if (kind !== "wx") for (let address = 0; address < SIZE; address++) if (marks[address] === 1) map[address]! |= KIND_BITS[kind];
327
+ return { map, selfModified: union.get("wx")! };
280
328
  }
281
329
 
282
330
  /**
@@ -393,14 +393,14 @@ function createSchema(db: DatabaseSync): void {
393
393
  CREATE TABLE coverage (
394
394
  id TEXT PRIMARY KEY,
395
395
  space TEXT NOT NULL DEFAULT 'c64' CHECK (${SPACE_CHECK}),
396
+ map TEXT NOT NULL CHECK (length(map) > 0),
396
397
  kind TEXT NOT NULL CHECK (kind IN (${list(COVERAGE_KINDS)})),
397
- start_address INTEGER NOT NULL CHECK (start_address BETWEEN 0 AND 65535),
398
- end_address INTEGER NOT NULL CHECK (end_address BETWEEN start_address AND 65535),
398
+ ranges TEXT NOT NULL CHECK (length(ranges) >= 5),
399
399
  origin TEXT NOT NULL CHECK (origin IN ('user', 'llm')),
400
400
  valid_from_revision TEXT NOT NULL REFERENCES revisions (id),
401
401
  valid_to_revision TEXT REFERENCES revisions (id)
402
402
  );
403
- CREATE INDEX coverage_current ON coverage (space, kind) WHERE valid_to_revision IS NULL;
403
+ CREATE INDEX coverage_current ON coverage (space, map) WHERE valid_to_revision IS NULL;
404
404
  CREATE VIEW current_memory AS SELECT * FROM memory WHERE valid_to_revision IS NULL;
405
405
  CREATE VIEW current_release_memory AS SELECT * FROM release_memory WHERE valid_to_revision IS NULL;
406
406
  CREATE VIEW current_entries AS SELECT * FROM entries WHERE valid_to_revision IS NULL;
@@ -423,7 +423,7 @@ function createSchema(db: DatabaseSync): void {
423
423
  }
424
424
 
425
425
  /** The version of the index this build makes. An index with another version is emptied and made again. */
426
- export const INDEX_VERSION = 14;
426
+ export const INDEX_VERSION = 15;
427
427
 
428
428
  function indexVersion(db: DatabaseSync): number | undefined {
429
429
  const hasMeta = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'meta'").get();
@@ -59,13 +59,18 @@ export function rowId(revision: string, order: number): string {
59
59
  * text, bytes as lowercase hex digits, or a JSON value that the index keeps as
60
60
  * JSON text.
61
61
  */
62
- type Format = "address" | "integer" | "text" | "hex" | "json";
62
+ type Format = "address" | "integer" | "text" | "hex" | "json" | "ranges";
63
+
64
+ /** Address ranges as text: "$1000-$1002 $1005", in address order, one space between them. */
65
+ const RANGES = /^\$[0-9a-f]{4}(?:-\$[0-9a-f]{4})?(?: \$[0-9a-f]{4}(?:-\$[0-9a-f]{4})?)*$/;
63
66
 
64
67
  interface Field {
65
68
  key: string;
66
69
  column: string;
67
70
  format: Format;
68
71
  optional?: boolean;
72
+ /** What to do when a line does not have this key: a key that an earlier toolkit version did not write. */
73
+ remedy?: string;
69
74
  }
70
75
 
71
76
  /** One fact table: its file, its fields in line order, and the column that sorts its lines after the space (an address, or a name). */
@@ -218,8 +223,23 @@ export const TABLES: readonly TableSpec[] = [
218
223
  sort: "address",
219
224
  fields: [space, field("entry", "address", "address"), field("state", "state", "json", true), field("stages", "stages", "json", true), origin],
220
225
  },
221
- // What the runs did: the union of the coverage maps as ranges of one kind each.
222
- { table: "coverage", file: "coverage.jsonl", sort: "start_address", fields: [space, field("kind", "kind", "text"), field("start", "start_address", "address"), field("end", "end_address", "address"), origin] },
226
+ // What the runs did: for each coverage map, by its project path, the ranges of each kind. The coverage of a space is the union of its maps.
227
+ {
228
+ table: "coverage",
229
+ file: "coverage.jsonl",
230
+ sort: "map",
231
+ fields: [
232
+ space,
233
+ {
234
+ ...field("map", "map", "text"),
235
+ remedy:
236
+ "The coverage of an earlier toolkit version does not keep the ranges of each map. Delete .c64-re-tools/knowledge/coverage.jsonl. Then put the coverage maps that you have into the project knowledge again.",
237
+ },
238
+ field("kind", "kind", "text"),
239
+ field("ranges", "ranges", "ranges"),
240
+ origin,
241
+ ],
242
+ },
223
243
  ];
224
244
 
225
245
  export const REVISIONS_FILE = "revisions.jsonl";
@@ -338,6 +358,8 @@ function parseLines(file: string, text: string): Array<{ line: number; value: Ra
338
358
 
339
359
  /** The column values of one line, checked against its fields. */
340
360
  function columnsOf(file: string, line: number, value: Raw, fields: readonly Field[], extra: readonly string[]): Raw {
361
+ // A line of an earlier format: the key that this format added is missing, and the remedy tells what to do.
362
+ for (const { key, remedy } of fields) if (remedy !== undefined && (value[key] === undefined || value[key] === null)) bad(file, line, `the key ${JSON.stringify(key)} is missing. ${remedy}`);
341
363
  const allowed = new Set([...fields.map((item) => item.key), ...extra]);
342
364
  for (const key of Object.keys(value)) if (!allowed.has(key)) bad(file, line, `the key ${JSON.stringify(key)} is not known.`);
343
365
  const columns: Raw = {};
@@ -355,6 +377,9 @@ function columnsOf(file: string, line: number, value: Raw, fields: readonly Fiel
355
377
  } else if (format === "hex") {
356
378
  if (typeof item !== "string" || !/^(?:[0-9a-f]{2})+$/.test(item)) bad(file, line, `${key} must be bytes as lowercase hex digits.`);
357
379
  columns[column] = item;
380
+ } else if (format === "ranges") {
381
+ if (typeof item !== "string" || !RANGES.test(item)) bad(file, line, `${key} must be address ranges such as "$1000-$1002 $1005".`);
382
+ columns[column] = item;
358
383
  } else if (format === "json") {
359
384
  if (typeof item !== "object") bad(file, line, `${key} must be a JSON object or list.`);
360
385
  columns[column] = JSON.stringify(item);
@@ -328,11 +328,11 @@ export class Change {
328
328
  .run(this.#rowId(), row.space, row.address, row.state, row.stages, row.origin, this.id());
329
329
  }
330
330
 
331
- /** One coverage range of one kind. */
332
- insertCoverage(row: { space: Space; kind: string; start: number; end: number; origin: Origin }): void {
331
+ /** The ranges of one kind of the coverage map at a project path, as text. */
332
+ insertCoverage(row: { space: Space; map: string; kind: string; ranges: string; origin: Origin }): void {
333
333
  this.#db
334
- .prepare("INSERT INTO coverage (id, space, kind, start_address, end_address, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?)")
335
- .run(this.#rowId(), row.space, row.kind, row.start, row.end, row.origin, this.id());
334
+ .prepare("INSERT INTO coverage (id, space, map, kind, ranges, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?)")
335
+ .run(this.#rowId(), row.space, row.map, row.kind, row.ranges, row.origin, this.id());
336
336
  }
337
337
  }
338
338
 
@@ -1639,7 +1639,7 @@ const PROGRAM_TABLES = [
1639
1639
  ["memory", "space, address, bytes, origin"],
1640
1640
  ["release_memory", "space, label, address, bytes, origin"],
1641
1641
  ["entries", "space, address, state, stages, origin"],
1642
- ["coverage", "space, kind, start_address, end_address, origin"],
1642
+ ["coverage", "space, map, kind, ranges, origin"],
1643
1643
  ] as const;
1644
1644
 
1645
1645
  const KEYS = {
@@ -1770,7 +1770,7 @@ export function revert(db: DatabaseSync, context: WriteContext, request: { revis
1770
1770
  if (table === "memory") change.insertMemory(values);
1771
1771
  else if (table === "release_memory") change.insertReleaseMemory(values);
1772
1772
  else if (table === "entries") change.insertEntry(values);
1773
- else change.insertCoverage({ ...(values as { space: Space; kind: string; origin: Origin }), start: row.start_address as number, end: row.end_address as number });
1773
+ else change.insertCoverage(values);
1774
1774
  }
1775
1775
  }
1776
1776
  return { restoredRevision: restored };
@@ -12,7 +12,7 @@ import type { SupervisedProcess } from "./processes.ts";
12
12
  import type { ToolContext } from "./run.ts";
13
13
 
14
14
  /** The command protocol that this module speaks; c64run --version and version name it. */
15
- export const C64RUN_PROTOCOL = 6;
15
+ export const C64RUN_PROTOCOL = 7;
16
16
 
17
17
  /** CPU cycles in one PAL frame: 312 lines of 63 cycles. */
18
18
  export const PAL_FRAME_CYCLES = 19_656;
@@ -22,15 +22,18 @@ const STOP_MS = 5_000;
22
22
  const COMMAND_MS = 30_000;
23
23
  /** The slowest run that a command limit allows for: c64run runs about 6 million cycles per second. */
24
24
  const SLOWEST_CYCLES_PER_SECOND = 1_000_000;
25
+ /** The argument of each run command that is the absolute tick it runs to at most: run <tick>, run-pc <pc> <tick> [<n>], run-reads <pc> <addr> <n> <tick>. */
26
+ const UNTIL_ARGUMENT: Record<string, number> = { run: 0, "run-pc": 1, "run-reads": 3 };
25
27
 
26
28
  /**
27
29
  * The time limit of a command, so that a core that hangs cannot keep the
28
- * script running. run, run-pc and run-reads end with the absolute tick that
29
- * they run to at most; the others answer at once.
30
+ * script running. A run command gets the time of the cycles up to the tick
31
+ * that it runs to at most; the others answer at once.
30
32
  */
31
33
  export function commandLimitMs(text: string): number {
32
34
  const [name, ...rest] = text.split(" ");
33
- const target = name === "run" || name === "run-pc" || name === "run-reads" ? Number(rest.at(-1)) : 0;
35
+ const at = UNTIL_ARGUMENT[name!];
36
+ const target = at === undefined ? 0 : Number(rest[at]);
34
37
  return COMMAND_MS + (Number.isFinite(target) ? (target * 1000) / SLOWEST_CYCLES_PER_SECOND : 0);
35
38
  }
36
39
 
@@ -0,0 +1,64 @@
1
+ // The first line of each reference page that c64-docs generates: it names
2
+ // the knowledge revision and the source map that the page was made from. The
3
+ // docs script writes and checks it; the generation of the source reads it to
4
+ // tell when a reference of the project is older than the source.
5
+
6
+ import { closeSync, openSync, readdirSync, readSync } from "node:fs";
7
+ import { join, posix } from "node:path";
8
+
9
+ /** The start of every generated page. A page without it is a page of a person, and the generation never writes over it. */
10
+ export const GENERATED_MARK = "<!-- Generated by c64-docs";
11
+
12
+ /** The first line of a generated page: the knowledge revision and the source map of the source that it was made from. */
13
+ export function referenceHeader(revision: string, mapPath: string): string {
14
+ return `${GENERATED_MARK} from knowledge revision ${revision} and ${mapPath}. Do not edit: change the knowledge, generate the source again, then run docs.ts generate. -->`;
15
+ }
16
+
17
+ const STAMP = /^<!-- Generated by c64-docs from knowledge revision (\S+) and (.+?)\. Do not edit/;
18
+
19
+ /** The revision and the source map that a generated page names, or undefined for a page of a person. */
20
+ export function referenceStamp(text: string): { revision: string; mapPath: string } | undefined {
21
+ const found = STAMP.exec(text);
22
+ return found === null ? undefined : { revision: found[1]!, mapPath: posix.normalize(found[2]!) };
23
+ }
24
+
25
+ /** The first bytes of a file: enough for the first line of a page. */
26
+ function head(path: string): string {
27
+ const descriptor = openSync(path, "r");
28
+ try {
29
+ const buffer = Buffer.alloc(512);
30
+ return buffer.subarray(0, readSync(descriptor, buffer, 0, buffer.length, 0)).toString("utf8");
31
+ } catch {
32
+ return "";
33
+ } finally {
34
+ closeSync(descriptor);
35
+ }
36
+ }
37
+
38
+ /**
39
+ * The generated references in a project folder: each folder with a
40
+ * generated index.md, relative to the project with /, and the revision and
41
+ * source map of its index. Folders that start with a dot are not searched.
42
+ */
43
+ export function generatedReferences(root: string): Array<{ folder: string; revision: string; mapPath: string }> {
44
+ const found: Array<{ folder: string; revision: string; mapPath: string }> = [];
45
+ const walk = (relative: string) => {
46
+ let entries;
47
+ try {
48
+ entries = readdirSync(join(root, relative), { withFileTypes: true });
49
+ } catch {
50
+ return;
51
+ }
52
+ for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
53
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
54
+ const path = posix.join(relative, entry.name);
55
+ if (entry.isDirectory()) walk(path);
56
+ else if (entry.isFile() && entry.name === "index.md") {
57
+ const stamp = referenceStamp(head(join(root, path)));
58
+ if (stamp !== undefined) found.push({ folder: relative === "" ? "." : relative, ...stamp });
59
+ }
60
+ }
61
+ };
62
+ walk("");
63
+ return found;
64
+ }
package/tools/c64run.c CHANGED
@@ -27,7 +27,7 @@
27
27
  #include "systems/c1541.h"
28
28
  #include "systems/c64.h"
29
29
 
30
- #define C64RUN_PROTOCOL 6
30
+ #define C64RUN_PROTOCOL 7
31
31
  // The key code of matrix place 0 (row 0, column 0); place n has code 0x80 + n.
32
32
  #define C64RUN_KEY_PLACE 0x80
33
33
  #ifndef CHIPS_COMMIT
@@ -240,6 +240,44 @@ static uint64_t mark_tick;
240
240
  static int mark_pc = -1; // -1: no mark waits
241
241
  static int mark_set; // marked and mark_tick hold the mark
242
242
 
243
+ // The phase of the machine at the mark: the beam position, the timers and interrupt
244
+ // state of both CIAs and the interrupt state of the CPU. It depends on how the
245
+ // program was started, and no program can set all of it. "align" gives it to
246
+ // another run at its own entry, so both runs go on from the same phase.
247
+ typedef struct {
248
+ uint16_t line, cycle;
249
+ m6526_timer_t ta[2], tb[2];
250
+ m6526_int_t intr[2];
251
+ uint16_t irq_pip;
252
+ uint32_t nmi_pip;
253
+ uint8_t brk_flags;
254
+ uint64_t pins, cpu_pins; // only the IRQ and NMI lines
255
+ } phase_t;
256
+ static phase_t mark_phase;
257
+
258
+ static void phase_get(phase_t* p) {
259
+ memset(p, 0, sizeof *p);
260
+ p->line = sys.vic.rs.v_count;
261
+ p->cycle = sys.vic.rs.h_count;
262
+ const m6526_t* cia[2] = { &sys.cia_1, &sys.cia_2 };
263
+ for (int i = 0; i < 2; i++) { p->ta[i] = cia[i]->ta; p->tb[i] = cia[i]->tb; p->intr[i] = cia[i]->intr; }
264
+ p->irq_pip = sys.cpu.irq_pip;
265
+ p->nmi_pip = sys.cpu.nmi_pip;
266
+ p->brk_flags = sys.cpu.brk_flags;
267
+ p->pins = pins & (M6502_IRQ | M6502_NMI);
268
+ p->cpu_pins = sys.cpu.PINS & (M6502_IRQ | M6502_NMI);
269
+ }
270
+
271
+ static void phase_set(const phase_t* p) {
272
+ m6526_t* cia[2] = { &sys.cia_1, &sys.cia_2 };
273
+ for (int i = 0; i < 2; i++) { cia[i]->ta = p->ta[i]; cia[i]->tb = p->tb[i]; cia[i]->intr = p->intr[i]; }
274
+ sys.cpu.irq_pip = p->irq_pip;
275
+ sys.cpu.nmi_pip = p->nmi_pip;
276
+ sys.cpu.brk_flags = p->brk_flags;
277
+ pins = (pins & ~(M6502_IRQ | M6502_NMI)) | p->pins;
278
+ sys.cpu.PINS = (sys.cpu.PINS & ~(M6502_IRQ | M6502_NMI)) | p->cpu_pins;
279
+ }
280
+
243
281
  static void clear_counts(void) {
244
282
  for (int i = 0; i < counted_pcs; i++) counted_at[counted_pc[i]] = 0;
245
283
  counted_pcs = 0;
@@ -251,6 +289,7 @@ static void count_fetch(uint16_t pc) {
251
289
  if (mark_pc == pc) {
252
290
  for (int i = 0; i < counted_pcs; i++) marked[i] = counted[i];
253
291
  mark_tick = ticks;
292
+ phase_get(&mark_phase);
254
293
  mark_pc = -1;
255
294
  mark_set = 1;
256
295
  }
@@ -579,9 +618,32 @@ int main(int argc, char** argv) {
579
618
  mark_set = 0;
580
619
  printf("ok\n");
581
620
  } else if (!strcmp(cmd, "marked")) {
582
- // marked: the tick of the mark when it came, else none
583
- if (mark_set) printf("ok tick=%llu\n", (unsigned long long)mark_tick);
621
+ // marked: the tick and the phase (hex) of the mark when it came, else none
622
+ if (mark_set) {
623
+ printf("ok tick=%llu phase=", (unsigned long long)mark_tick);
624
+ for (size_t i = 0; i < sizeof mark_phase; i++) printf("%02x", ((const uint8_t*)&mark_phase)[i]);
625
+ printf("\n");
626
+ }
584
627
  else printf("ok none\n");
628
+ } else if (!strcmp(cmd, "align")) {
629
+ // align <phase hex>: at an opcode fetch, hold the CPU on the fetch (RDY, as the VIC-II
630
+ // does on a bad line) until the beam is at the position of the phase, then give the
631
+ // CIAs and the CPU the timers and interrupt state of the phase (from "marked")
632
+ phase_t p;
633
+ if (strlen(a1) != 2 * sizeof p || !(pins & M6502_SYNC)) { printf("err align: give the phase of marked, at an opcode fetch\n"); continue; }
634
+ for (size_t i = 0; i < sizeof p; i++) ((uint8_t*)&p)[i] = (uint8_t)hexbyte(a1 + 2 * i);
635
+ // A PAL frame holds each beam position one time.
636
+ uint64_t held = 0;
637
+ while ((sys.vic.rs.v_count != p.line || sys.vic.rs.h_count != p.cycle) && held <= 312 * 63) {
638
+ pins = _c64_tick(&sys, pins | M6502_RDY);
639
+ ticks++;
640
+ held++;
641
+ }
642
+ if (sys.vic.rs.v_count != p.line || sys.vic.rs.h_count != p.cycle) { printf("err align: the beam never came to line %u cycle %u\n", p.line, p.cycle); continue; }
643
+ phase_set(&p);
644
+ char prefix[64];
645
+ snprintf(prefix, sizeof prefix, "ok held=%llu", (unsigned long long)held);
646
+ status(prefix);
585
647
  } else if (!strcmp(cmd, "hits")) {
586
648
  // hits <pc hex>: the count of a pc of count-pc, and its count at the mark when the mark came
587
649
  unsigned pc;