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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +5 -2
  3. package/skills/c64-assembler/scripts/assembler.ts +55 -48
  4. package/skills/c64-disk/scripts/disk.ts +3 -3
  5. package/skills/c64-disk/scripts/lib/containers.ts +2 -2
  6. package/skills/c64-docs/SKILL.md +1 -1
  7. package/skills/c64-docs/scripts/docs.ts +12 -20
  8. package/skills/c64-docs/scripts/lib/links.ts +1 -1
  9. package/skills/c64-docs/scripts/lib/markdown.ts +1 -1
  10. package/skills/c64-docs/scripts/lib/reference.ts +59 -13
  11. package/skills/c64-knowledge/SKILL.md +17 -8
  12. package/skills/c64-knowledge/scripts/knowledge.ts +200 -218
  13. package/skills/c64-knowledge/scripts/lib/check.ts +2 -3
  14. package/skills/c64-knowledge/scripts/lib/listing.ts +56 -24
  15. package/skills/c64-packer/scripts/packer.ts +3 -3
  16. package/skills/c64-provenance/SKILL.md +25 -16
  17. package/skills/c64-provenance/scripts/lib/compare.ts +31 -21
  18. package/skills/c64-provenance/scripts/lib/leftovers.ts +17 -35
  19. package/skills/c64-provenance/scripts/lib/library.ts +10 -10
  20. package/skills/c64-provenance/scripts/lib/runtime.ts +3 -14
  21. package/skills/c64-provenance/scripts/provenance.ts +129 -98
  22. package/skills/c64-source/references/loader.md +2 -1
  23. package/skills/c64-source/scripts/lib/export.ts +54 -303
  24. package/skills/c64-source/scripts/lib/loader.ts +31 -51
  25. package/skills/c64-source/scripts/lib/source.ts +51 -41
  26. package/skills/c64-source/scripts/lib/stage.ts +9 -25
  27. package/skills/c64-source/scripts/source.ts +134 -294
  28. package/skills/c64-static-analysis/SKILL.md +10 -5
  29. package/skills/c64-static-analysis/scripts/lib/coverage.ts +1 -3
  30. package/skills/c64-static-analysis/scripts/lib/findings.ts +16 -3
  31. package/skills/c64-static-analysis/scripts/lib/idioms.ts +82 -10
  32. package/skills/c64-static-analysis/scripts/lib/triage.ts +112 -0
  33. package/skills/c64-static-analysis/scripts/static-analysis.ts +239 -147
  34. package/skills/c64-testing/SKILL.md +13 -7
  35. package/skills/c64-testing/scripts/lib/diff-files.ts +6 -13
  36. package/skills/c64-testing/scripts/lib/recording.ts +47 -66
  37. package/skills/c64-testing/scripts/lib/replay.ts +53 -9
  38. package/skills/c64-testing/scripts/lib/runs.ts +11 -29
  39. package/skills/c64-testing/scripts/lib/scenario.ts +30 -31
  40. package/skills/c64-testing/scripts/lib/start-screen.ts +42 -5
  41. package/skills/c64-testing/scripts/testing.ts +32 -7
  42. package/skills/c64-unpacker/SKILL.md +9 -7
  43. package/skills/c64-unpacker/scripts/lib/evidence.ts +23 -38
  44. package/skills/c64-unpacker/scripts/lib/loads.ts +24 -39
  45. package/skills/c64-unpacker/scripts/lib/machine.ts +38 -18
  46. package/skills/c64-unpacker/scripts/lib/stages.ts +124 -40
  47. package/skills/c64-unpacker/scripts/unpacker.ts +81 -68
  48. package/skills/emulator/SKILL.md +1 -0
  49. package/src/c64.ts +117 -10
  50. package/src/cli/ap-sdk.ts +1 -1
  51. package/src/cli/cleanup.ts +4 -2
  52. package/src/compare.ts +36 -16
  53. package/src/errors.ts +10 -1
  54. package/src/host/main.ts +2 -1
  55. package/src/host/server.ts +7 -11
  56. package/src/host/tools/c1541.ts +9 -3
  57. package/src/host/vice/adapter.ts +20 -43
  58. package/src/host/vice/binary-monitor.ts +22 -21
  59. package/src/host/vice/process.ts +31 -40
  60. package/src/host/vice/session.ts +187 -247
  61. package/src/host/vice/text-monitor.ts +3 -3
  62. package/src/host-client/autostart.ts +1 -1
  63. package/src/host-client/connect.ts +2 -1
  64. package/src/host-client/coverage.ts +0 -3
  65. package/src/host-client/entry-state.ts +4 -11
  66. package/src/host-client/image.ts +6 -11
  67. package/src/host-client/steps.ts +13 -113
  68. package/src/host-client/tools.ts +4 -4
  69. package/src/host-client/transfer.ts +10 -0
  70. package/src/host-client/vice-session.ts +10 -6
  71. package/src/knowledge/code-reach.ts +364 -0
  72. package/src/knowledge/conflicts.ts +34 -72
  73. package/src/knowledge/database.ts +40 -28
  74. package/src/knowledge/evidence.ts +2 -2
  75. package/src/knowledge/graph.ts +3 -3
  76. package/src/knowledge/history.ts +50 -90
  77. package/src/knowledge/import.ts +28 -68
  78. package/src/knowledge/join.ts +1 -1
  79. package/src/knowledge/names.ts +12 -7
  80. package/src/knowledge/program.ts +25 -46
  81. package/src/knowledge/read.ts +104 -100
  82. package/src/knowledge/schema.ts +9 -3
  83. package/src/knowledge/separate.ts +47 -19
  84. package/src/knowledge/start-screen.ts +7 -5
  85. package/src/knowledge/text.ts +56 -33
  86. package/src/knowledge/write.ts +274 -515
  87. package/src/loader.ts +7 -25
  88. package/src/mcp/inputs.ts +3 -3
  89. package/src/mcp/server.ts +19 -38
  90. package/src/mcp/session-source.ts +2 -1
  91. package/src/mcp/tools/debug.ts +97 -24
  92. package/src/mcp/tools/execution.ts +1 -1
  93. package/src/mcp/tools/input.ts +3 -3
  94. package/src/mcp/tools/machine.ts +3 -3
  95. package/src/mcp/tools/media.ts +4 -4
  96. package/src/mcp/tools/memory.ts +13 -17
  97. package/src/mcp/tools/video.ts +11 -25
  98. package/src/native/acme.ts +3 -3
  99. package/src/native/c64run.ts +2 -1
  100. package/src/native/decompiler/analyze.ts +10 -7
  101. package/src/native/decompiler/walk.ts +3 -4
  102. package/src/native/decompiler/wasm.ts +2 -2
  103. package/src/native/discover.ts +1 -1
  104. package/src/native/dxa.ts +9 -11
  105. package/src/native/exomizer.ts +1 -1
  106. package/src/native/processes.ts +4 -1
  107. package/src/native/run.ts +3 -3
  108. package/src/native/types.ts +5 -6
  109. package/src/opcodes.ts +3 -0
  110. package/src/platform.ts +9 -10
  111. package/src/program-code.ts +151 -0
  112. package/src/project.ts +8 -5
  113. package/src/protocol/framing.ts +51 -18
  114. package/src/protocol/messages.ts +1 -11
  115. package/src/protocol/tools.ts +0 -3
  116. package/src/protocol/vice.ts +588 -773
  117. package/src/script.ts +9 -14
  118. package/src/time.ts +1 -1
  119. package/src/trace.ts +3 -2
@@ -12,17 +12,17 @@ import { screenText } from "#src/graphics.ts";
12
12
  import { runProgram } from "#src/host-client/autostart.ts";
13
13
  import { isRefusal, Refusal } from "#src/errors.ts";
14
14
  import { readCoverage } from "#src/host-client/coverage.ts";
15
- import { ACTION_STEP_KINDS, aStep, checkActionStep, checkLocation, checkStepNames, isInteger, isObject, refuseOldStep, renamedField, runActionStep, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
15
+ import { ACTION_STEP_KINDS, aStep, checkActionStep, checkLocation, checkStepNames, runActionStep, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
16
16
  import { readPrg } from "#src/host-client/image.ts";
17
- 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";
18
- import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
17
+ import { isInteger, isObject, MAX_MEMORY_READ, MAX_TRACE_FRAMES, MAX_TRACE_HITS, MAX_TRACE_POINTS, TRACE_KINDS, type TraceHit, type TraceKind } from "#src/host-client/tools.ts";
18
+ import { readProjectFile, readProjectJson, writeReported, type Written } from "#src/host-client/transfer.ts";
19
19
  import { readMemoryInParts, ViceSessionClient } from "#src/host-client/vice-session.ts";
20
20
  import { checkSnapshotFile } from "#src/media.ts";
21
21
  import { checkOutputPath, LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRelative, resolveProjectPath } from "#src/project.ts";
22
22
  import { namesOf } from "./scenario.ts";
23
- import { passStartScreen } from "./start-screen.ts";
23
+ import { namesStartScreen, passStartScreen } from "./start-screen.ts";
24
24
 
25
- type RunStep =
25
+ export type RunStep =
26
26
  | ActionStep
27
27
  | { snapshot: string }
28
28
  | { save: string }
@@ -115,13 +115,7 @@ function checkFileNames(steps: RunStep[], fail: (message: string) => never): voi
115
115
  }
116
116
 
117
117
  function readRun(path: string): Run {
118
- let value: unknown;
119
- try {
120
- value = JSON.parse(readProjectFile(path).bytes.toString("utf8"));
121
- } catch (error) {
122
- if (error instanceof WireFailure) throw error;
123
- throw new Refusal("invalid-input", `the run ${path} is not JSON: ${(error as Error).message}`);
124
- }
118
+ const value = readProjectJson(path, (message) => `the run ${path} is not JSON: ${message}`);
125
119
  const fail = (message: string): never => {
126
120
  throw new Refusal("invalid-input", `run ${path}: ${message}`);
127
121
  };
@@ -143,7 +137,6 @@ function readRun(path: string): Run {
143
137
  if (kinds.length > 1) return fail(`${at} has ${kinds.length} step kinds: ${kinds.join(", ")}. Give each one its own step`);
144
138
  if (kinds.length !== 1) return fail(`${at} must have exactly one of ${[...ACTION_STEP_KINDS, ...OWN_KINDS].join(", ")}`);
145
139
  const kind = kinds[0]!;
146
- refuseOldStep(kind, step, at, fail);
147
140
  const allowed = kind === "observe" ? OBSERVE_KEYS : kind === "expect" ? EXPECT_KEYS : kind === "trace" ? TRACE_KEYS : [kind];
148
141
  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)}`);
149
142
  if ((ACTION_STEP_KINDS as readonly string[]).includes(kind)) {
@@ -164,7 +157,7 @@ function readRun(path: string): Run {
164
157
  if (!Array.isArray(points) || points.length === 0 || points.length > MAX_TRACE_POINTS) return fail(`${at}: points is a list of 1 to ${MAX_TRACE_POINTS} objects with kind and start`);
165
158
  for (const point of points as unknown[]) {
166
159
  if (!isObject(point)) return fail(`${at}: a point is an object with kind, start and end`);
167
- for (const key of Object.keys(point)) if (!["kind", "start", "end"].includes(key)) fail(`${at}: a point has the field ${key}. ${renamedField(key, ["kind", "start", "end"]) ?? "A point has kind, start and end, and nothing else"}`);
160
+ for (const key of Object.keys(point)) if (!["kind", "start", "end"].includes(key)) fail(`${at}: a point has the field ${key}. A point has kind, start and end, and nothing else`);
168
161
  if (!(TRACE_KINDS as readonly unknown[]).includes(point.kind)) fail(`${at}: a point kind is exec, read or write`);
169
162
  if (typeof point.start !== "string" || (point.end !== undefined && typeof point.end !== "string")) fail(`${at}: a point needs start, and end when it is a range, as names or $ addresses`);
170
163
  }
@@ -202,16 +195,6 @@ function readRun(path: string): Run {
202
195
  if (kind !== "observe") return;
203
196
  if (labels.has(name as string)) fail(`${at} needs a new observation name`);
204
197
  labels.add(name as string);
205
- const itemFields = ["address", "size", "view"];
206
- if (Array.isArray(step.memory)) {
207
- for (const item of step.memory as unknown[]) {
208
- if (!isObject(item)) continue;
209
- for (const key of Object.keys(item)) {
210
- const renamed = renamedField(key, itemFields);
211
- if (renamed !== undefined && !itemFields.includes(key)) fail(`${at}: a memory object has the field ${key}. ${renamed}`);
212
- }
213
- }
214
- }
215
198
  const memoryItem = (item: unknown) =>
216
199
  typeof item === "string" ||
217
200
  (isObject(item) &&
@@ -351,7 +334,7 @@ export async function runFile(path: string, out: string): Promise<{ output: Reco
351
334
  } else {
352
335
  const failed = await runProgram(client, run.start.program, readProjectFile(run.start.program).bytes);
353
336
  if (failed !== undefined) reason = failed === "not-loaded" ? "The program was not in memory after autostart." : "The program did not start after RUN; it needs a BASIC start line.";
354
- else {
337
+ else if (!namesStartScreen(run.steps, at, symbols)) {
355
338
  const screen = await passStartScreen(client, symbols);
356
339
  if (typeof screen === "object") reason = `${screen.problem[0]!.toUpperCase()}${screen.problem.slice(1)}.`;
357
340
  else startScreen = screen;
@@ -469,7 +452,7 @@ export interface KeptPath {
469
452
  */
470
453
  export function keepRun(path: string, out: string, target: string): { out: string; files: Written[]; paths: KeptPath[] } {
471
454
  const run = readRun(path);
472
- const raw = JSON.parse(readProjectFile(path).bytes.toString("utf8")) as { start: Record<string, unknown>; symbols?: unknown; steps: Array<Record<string, unknown>> };
455
+ const raw = readProjectJson(path) as { start: Record<string, unknown>; symbols?: unknown; steps: Array<Record<string, unknown>> };
473
456
  const kept = projectRelative(target);
474
457
  if (kept === PROJECT_DIRECTORY || kept.startsWith(`${PROJECT_DIRECTORY}/`)) {
475
458
  throw new Refusal("invalid-input", `${target} is in ${PROJECT_DIRECTORY}/, and git does not keep a run there. Give a new folder outside it, for example runs/${run.name.replace(/[^A-Za-z0-9._-]+/g, "_")}.`);
@@ -480,11 +463,10 @@ export function keepRun(path: string, out: string, target: string): { out: strin
480
463
  const file = `${out}/results.json`;
481
464
  let value: unknown;
482
465
  try {
483
- value = JSON.parse(readProjectFile(file).bytes.toString("utf8"));
466
+ value = readProjectJson(file);
484
467
  } catch (error) {
485
468
  if (isRefusal(error) && error.code === "not-found") throw new Refusal("not-found", `${out} has no results.json. Give the --out folder of a run of ${path}.`);
486
- if (isRefusal(error)) throw error;
487
- throw new Refusal("invalid-input", `${file} is not JSON: ${(error as Error).message}`);
469
+ throw error;
488
470
  }
489
471
  if (!isObject(value) || value.name !== run.name || !Array.isArray(value.files) || !value.files.every((name) => typeof name === "string" && RESULT_FILE.test(name))) {
490
472
  throw new Refusal("invalid-input", `${file} is not the result of the run ${run.name}. Give the --out folder of a run of ${path}.`);
@@ -4,13 +4,13 @@
4
4
  // explicit, and the result is PASS, FAIL or INCONCLUSIVE.
5
5
 
6
6
  import { isRefusal, Refusal } from "#src/errors.ts";
7
- import { c64AddressOf, formatC64Address, formatSprite, formatVicii, parseC64Address } from "#src/c64.ts";
8
- import { MAX_BASELINES, MAX_MASK_RECTANGLES, maskCoversFrame, WireFailure } from "#src/host-client/tools.ts";
7
+ import { c64AddressOf, formatC64Address, formatSprite, formatVicii, hexByte, parseC64Address } from "#src/c64.ts";
8
+ import { isInteger, isObject, 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, aStep, 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, 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
- import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
13
+ import { readProjectFile, readProjectJson, writeReported, type Written } from "#src/host-client/transfer.ts";
14
14
  import { readMemoryInParts, type ViceSessionClient } from "#src/host-client/vice-session.ts";
15
15
  import { checkSnapshotFile } from "#src/media.ts";
16
16
  import { openForRead } from "#src/knowledge/database.ts";
@@ -18,10 +18,10 @@ import { nameTable } from "#src/knowledge/names.ts";
18
18
  import { DEFAULT_SPACE } from "#src/knowledge/schema.ts";
19
19
  import { programImage } from "#src/knowledge/program.ts";
20
20
  import { listed } from "#src/script.ts";
21
- import { passStartScreen } from "./start-screen.ts";
21
+ import { namesStartScreen, passStartScreen } from "./start-screen.ts";
22
22
 
23
23
  export type Side = "reference" | "rebuild";
24
- export const SIDES: Side[] = ["reference", "rebuild"];
24
+ const SIDES: Side[] = ["reference", "rebuild"];
25
25
 
26
26
  /** A "$xxxx" address or a symbol name that each side resolves on its own. */
27
27
  export type { Location };
@@ -120,18 +120,12 @@ const STEP_KEYS: Record<string, readonly string[]> = {
120
120
  };
121
121
 
122
122
  /** The registers an observe step can compare. */
123
- export const OBSERVED_REGISTERS = ["pc", "a", "x", "y", "sp", "flags"] as const;
123
+ const OBSERVED_REGISTERS = ["pc", "a", "x", "y", "sp", "flags"] as const;
124
124
  type ObservedRegister = (typeof OBSERVED_REGISTERS)[number];
125
125
 
126
126
  /** Reads and checks a scenario file. Refuses it with the first problem. */
127
127
  export function readScenario(path: string): Scenario {
128
- let value: unknown;
129
- try {
130
- value = JSON.parse(readProjectFile(path).bytes.toString("utf8"));
131
- } catch (error) {
132
- if (isRefusal(error)) throw error;
133
- throw new Refusal("invalid-input", `cannot read the scenario ${path}: ${(error as Error).message}`);
134
- }
128
+ const value = readProjectJson(path, (message) => `cannot read the scenario ${path}: ${message}`);
135
129
  const fail = (message: string): never => {
136
130
  throw new Refusal("invalid-input", `scenario ${path}: ${message}`);
137
131
  };
@@ -157,7 +151,6 @@ export function readScenario(path: string): Scenario {
157
151
  if (kinds.length > 1) return fail(`${at} has ${kinds.length} step kinds: ${kinds.join(", ")}. Give each one its own step`);
158
152
  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": {}}` : ""}`);
159
153
  const kind = kinds[0]!;
160
- refuseOldStep(kind, step, at, fail);
161
154
  const allowed = [...(STEP_KEYS[kind] ?? [kind]), ...(kind === "observe" ? [] : ["side"])];
162
155
  for (const key of Object.keys(step)) if (!allowed.includes(key)) fail(`${at} has the key ${key}, which ${aStep(kind)} does not have`);
163
156
  if (step.side !== undefined && !(SIDES as unknown[]).includes(step.side)) fail(`${at}: side must be reference or rebuild`);
@@ -210,13 +203,13 @@ function checkObserve(step: Record<string, unknown>, at: string, fail: (message:
210
203
  }
211
204
  const itemFields = ["address", "size", "view", "tolerance", "mask", "exclude"];
212
205
  if (!isObject(item)) return fail(`${at}: memory must be a list of names, $ addresses or objects with address`);
213
- for (const key of Object.keys(item)) if (!itemFields.includes(key)) fail(`${at}: a memory object has the field ${key}. ${renamedField(key, itemFields) ?? `It has ${itemFields.join(", ")}, and nothing else`}`);
206
+ for (const key of Object.keys(item)) if (!itemFields.includes(key)) fail(`${at}: a memory object has the field ${key}. It has ${itemFields.join(", ")}, and nothing else`);
214
207
  if (item.view !== undefined && item.view !== "cpu" && item.view !== "ram") fail(`${at}: memory.view must be cpu or ram`);
215
208
  if (item.exclude !== undefined) {
216
209
  if (!Array.isArray(item.exclude) || item.exclude.length === 0) fail(`${at}: memory.exclude must be a list of objects with address and reason`);
217
210
  for (const excluded of item.exclude as unknown[]) {
218
211
  if (!isObject(excluded)) return fail(`${at}: memory.exclude must be a list of objects with address and reason`);
219
- for (const key of Object.keys(excluded)) if (key !== "address" && key !== "reason") fail(`${at}: an exclude has the field ${key}. ${renamedField(key, ["address", "reason"]) ?? "It has address and reason, and nothing else"}`);
212
+ for (const key of Object.keys(excluded)) if (key !== "address" && key !== "reason") fail(`${at}: an exclude has the field ${key}. It has address and reason, and nothing else`);
220
213
  checkLocation(excluded.address, `${at}: memory.exclude.address`, fail);
221
214
  if (typeof excluded.reason !== "string" || excluded.reason.trim() === "") fail(`${at}: an exclude needs a reason: why this byte may differ`);
222
215
  }
@@ -288,13 +281,7 @@ export function namesOf(source: string, kinds: "code" | "all" = "all"): Map<stri
288
281
  db?.close();
289
282
  }
290
283
  }
291
- let value: unknown;
292
- try {
293
- value = JSON.parse(readProjectFile(source).bytes.toString("utf8"));
294
- } catch (error) {
295
- if (isRefusal(error)) throw error;
296
- throw new Refusal("invalid-input", `cannot read the symbols ${source}: ${(error as Error).message}`);
297
- }
284
+ const value = readProjectJson(source, (message) => `cannot read the symbols ${source}: ${message}`);
298
285
  const assembled = (value as { symbols?: Array<{ name: string; address?: string; value?: string }> }).symbols;
299
286
  const entries: Array<[string, unknown]> = Array.isArray(assembled)
300
287
  ? assembled.flatMap((symbol): Array<[string, unknown]> => {
@@ -313,6 +300,17 @@ export function namesOf(source: string, kinds: "code" | "all" = "all"): Map<stri
313
300
  return names;
314
301
  }
315
302
 
303
+ /** namesOf that reads each source once: a replay asks for the names of its two sides many times. */
304
+ export function cachedNames(): typeof namesOf {
305
+ const read = new Map<string, Map<string, number>>();
306
+ return (source, kinds = "all") => {
307
+ const key = `${kinds} ${source}`;
308
+ const names = read.get(key) ?? namesOf(source, kinds);
309
+ read.set(key, names);
310
+ return names;
311
+ };
312
+ }
313
+
316
314
  /** The remedy for a scenario program that is no PRG. */
317
315
  const PROGRAM_REMEDY = "A scenario program is a PRG. Extract the program file from the disk, tape or cartridge image, and give that PRG";
318
316
 
@@ -389,18 +387,20 @@ async function normalize(client: ViceSessionClient): Promise<void> {
389
387
  * or hyphens. The checkpoint's number comes first, so two checkpoints never
390
388
  * get the same name.
391
389
  */
392
- export function baselineName(checkpoint: number, label: string): string {
390
+ function baselineName(checkpoint: number, label: string): string {
393
391
  return `test-${checkpoint}-${label}`.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 64);
394
392
  }
395
393
 
396
394
  /**
397
395
  * Autostart that returns only when the program runs (runProgram), and after the
398
- * start screen of a loader program (passStartScreen), or INCONCLUSIVE with the reason.
396
+ * start screen of a loader program (passStartScreen) unless a step of the side
397
+ * names it (namesStartScreen), or INCONCLUSIVE with the reason.
399
398
  */
400
- async function startProgram(client: ViceSessionClient, program: string, side: Side, symbols: Map<string, number>): Promise<void> {
399
+ async function startProgram(client: ViceSessionClient, program: string, side: Side, symbols: Map<string, number>, steps: readonly Step[]): Promise<void> {
401
400
  const failed = await runProgram(client, program, readProjectFile(program).bytes);
402
401
  if (failed === "not-loaded") throw new Inconclusive(`the ${side} program was not in memory after ${LOAD_LIMIT_FRAMES} frames of autostart`);
403
402
  if (failed === "not-started") throw new Inconclusive(`the ${side} program did not start within ${RUN_LIMIT_FRAMES} frames of RUN; autostart runs only a program with a BASIC start line`);
403
+ if (namesStartScreen(steps, (location) => resolve(location, symbols, side), symbols)) return;
404
404
  const screen = await passStartScreen(client, symbols);
405
405
  if (typeof screen === "object") throw new Inconclusive(`the ${side} side: ${screen.problem}`);
406
406
  }
@@ -490,7 +490,7 @@ async function runStep(client: ViceSessionClient, scenario: Scenario, side: Side
490
490
  } else if ("load" in step) {
491
491
  await client.programLoad({ path: subject.program });
492
492
  } else if ("autostart" in step) {
493
- await startProgram(client, subject.program, side, symbols);
493
+ await startProgram(client, subject.program, side, symbols, scenario.steps.filter((other) => other.side === undefined || other.side === side));
494
494
  } else if ("snapshot" in step) {
495
495
  await client.snapshotRestore(readProjectFile(step.snapshot).bytes);
496
496
  } else if ("normalize" in step) {
@@ -509,14 +509,13 @@ type MemoryItem = Observation["memory"][number];
509
509
 
510
510
  /** The bytes of a memory item whose bits of the mask differ by more than its tolerance, without the excluded bytes. */
511
511
  function differingBytes(item: MemoryItem, other: MemoryItem): DifferingByte[] {
512
- const hex = (byte: number) => byte.toString(16).padStart(2, "0");
513
512
  const skipped = new Set(item.excluded.map((excluded) => excluded.offset));
514
513
  const bits = (offset: number) => (item.mask === undefined ? 0xff : item.mask.length === 1 ? item.mask[0]! : item.mask[offset]!);
515
- return item.bytes.flatMap((byte, offset) => (!skipped.has(offset) && Math.abs((byte & bits(offset)) - (other.bytes[offset]! & bits(offset))) > item.tolerance ? [{ address: formatC64Address(item.address + offset), reference: hex(byte), rebuild: hex(other.bytes[offset]!) }] : []));
514
+ return item.bytes.flatMap((byte, offset) => (!skipped.has(offset) && Math.abs((byte & bits(offset)) - (other.bytes[offset]! & bits(offset))) > item.tolerance ? [{ address: formatC64Address(item.address + offset), reference: hexByte(byte), rebuild: hexByte(other.bytes[offset]!) }] : []));
516
515
  }
517
516
 
518
517
  /** The most differing bytes of one memory item that a result lists when no --max-listed is given. */
519
- export const DEFAULT_LISTED_BYTES = 50;
518
+ const DEFAULT_LISTED_BYTES = 50;
520
519
 
521
520
  /**
522
521
  * The differences between the two sides' observations at each checkpoint,
@@ -1,13 +1,17 @@
1
1
  // The start screen of a loader program in VICE: the loader of a generated
2
- // source shows it and waits for a key or a fire button that no step of a run
3
- // or a scenario gives. Not each VICE can press a key of the keyboard matrix,
4
- // so test and run let the program come to the wait, then set the PC to the
5
- // code after the wait, as the check of the loader does. The replay core does
6
- // the same in recording.ts.
2
+ // source shows it and waits for a key or a fire button. Not each VICE can
3
+ // press a key of the keyboard matrix, so test and run let the program come to
4
+ // the wait, then set the PC to the code after the wait, as the check of the
5
+ // loader does. Steps that name the wait or the code after the wait test the
6
+ // start screen itself: then the program stays at its start screen. The replay
7
+ // core goes past the start screen in recording.ts.
7
8
 
8
9
  import { formatC64Address } from "#src/c64.ts";
10
+ import { stepLocations as actionStepLocations, type ActionStep, type Location } from "#src/host-client/steps.ts";
9
11
  import type { ViceSessionClient } from "#src/host-client/vice-session.ts";
10
12
  import { startScreenLabels } from "#src/knowledge/start-screen.ts";
13
+ import type { RunStep } from "./runs.ts";
14
+ import type { Step } from "./scenario.ts";
11
15
 
12
16
  /** The frames from RUN to the wait: the copies or the unpack of the loader, then the screen. */
13
17
  export const START_SCREEN_FRAMES = 3000;
@@ -25,3 +29,36 @@ export async function passStartScreen(client: Pick<ViceSessionClient, "runUntil"
25
29
  await client.registersSet("c64", { pc: labels.continue });
26
30
  return "skipped";
27
31
  }
32
+
33
+ /** The names and addresses of a step of a run or a scenario: its points, its memory and its pc, or those of an action step. */
34
+ function stepLocations(step: RunStep | Step): Location[] {
35
+ if ("trace" in step) return step.points.flatMap((point) => [point.start, ...(point.end === undefined ? [] : [point.end])]);
36
+ if ("expect" in step) return [...(step.memory ?? []).map((item) => item.address), ...(step.registers?.pc === undefined ? [] : [step.registers.pc])];
37
+ if ("observe" in step) {
38
+ if (step.memory === undefined || step.memory === "all") return [];
39
+ return step.memory.flatMap((item) => (typeof item === "string" ? [item] : [item.address, ...("exclude" in item ? (item.exclude ?? []).map((excluded) => excluded.address) : [])]));
40
+ }
41
+ // A step of another kind than an action step has no location.
42
+ return actionStepLocations(step as ActionStep);
43
+ }
44
+
45
+ /**
46
+ * True when a step names the start screen: a name or an address of the step
47
+ * resolves with `at`, as the step resolves it, to the wait or to the code
48
+ * after the wait. Such steps test the start screen itself, so test and run do
49
+ * not go past it. A name that `at` does not resolve names no start screen: its
50
+ * step gives the problem when it runs.
51
+ */
52
+ export function namesStartScreen(steps: ReadonlyArray<RunStep | Step>, at: (location: Location) => number, symbols: ReadonlyMap<string, number>): boolean {
53
+ const labels = startScreenLabels(symbols);
54
+ if (labels === undefined) return false;
55
+ const named = (location: Location): boolean => {
56
+ try {
57
+ const address = at(location);
58
+ return address === labels.wait || address === labels.continue;
59
+ } catch {
60
+ return false;
61
+ }
62
+ };
63
+ return steps.some((step) => stepLocations(step).some(named));
64
+ }
@@ -5,6 +5,7 @@
5
5
  // show tells what a recording holds; diff shows what changed between two
6
6
  // states; checklist gives the Markdown list for a human tester.
7
7
 
8
+ import { symbolsPath } from "#src/build-name.ts";
8
9
  import { COVERAGE, formatC64Address } from "#src/c64.ts";
9
10
  import { isRefusal, Refusal } from "#src/errors.ts";
10
11
  import { WireFailure } from "#src/host-client/tools.ts";
@@ -17,12 +18,13 @@ import { Workspace } from "#src/native/staging.ts";
17
18
  import { openForRead } from "#src/knowledge/database.ts";
18
19
  import { changedEvidence } from "#src/knowledge/evidence.ts";
19
20
  import { knowledgeNames } from "#src/knowledge/names.ts";
21
+ import { RECORDING_FILES } from "#src/knowledge/recording-files.ts";
20
22
  import { LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRelative, projectRoot } from "#src/project.ts";
21
23
  import { OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec, type Reply } from "#src/script.ts";
22
24
  import { diffFiles } from "./lib/diff-files.ts";
23
25
  import { CANCELLED, play } from "./lib/play.ts";
24
- import { readRecordFile, record, RECORDING_FILES, showRecording } from "./lib/recording.ts";
25
- import { replay } from "./lib/replay.ts";
26
+ import { readRecordFile, record, showRecording } from "./lib/recording.ts";
27
+ import { replay, replayAll } from "./lib/replay.ts";
26
28
  import { keepRun, runFile } from "./lib/runs.ts";
27
29
  import { namesOf, readScenario, runScenario, scenarioNames, type Scenario, type ScenarioResult } from "./lib/scenario.ts";
28
30
 
@@ -210,28 +212,51 @@ const COMMANDS: CommandSpec[] = [
210
212
  },
211
213
  {
212
214
  name: "replay",
213
- summary: "Replays a recording on the reference, which must end with the recorded state, and with --rebuild on the rebuild, which must have the state of the reference at each checkpoint. result is PASS, FAIL or INCONCLUSIVE.",
214
- subjects: [{ name: "<recording>", help: "a folder that record wrote, relative to the project folder" }],
215
+ summary: "Replays a recording on the reference, which must end with the recorded state, and with --rebuild on the rebuild, which must have the state of the reference at each checkpoint. result is PASS, FAIL or INCONCLUSIVE. More than one recording replay one after the other.",
216
+ subjects: [{ name: "<recording>", help: "a folder that record wrote, relative to the project folder. Give more than one to replay each of them in turn", list: true }],
215
217
  options: {
216
218
  checkpoint: { kind: "text", value: "<routine>", help: "the name or $ address of a routine: each entry is a checkpoint. Without it, the comparison of the record file" },
217
219
  state: { kind: "text", value: "<item>", multiple: true, help: `the state to compare at each checkpoint: ${STATE_ITEM}` },
218
220
  pin: { kind: "text", value: "<item>", multiple: true, help: `random state in RAM, in the form of --state: at each checkpoint the rebuild gets the reference's values there` },
219
221
  rebuild: { kind: "path", value: "<prg>", help: "the rebuild to compare with the reference" },
220
- symbols: { ...OPTIONS.symbols, help: "the names of the rebuild: the symbol file of its build (default: the symbols of the recording)" },
222
+ symbols: { ...OPTIONS.symbols, help: "the names of the rebuild (default: the symbol file of its build, else the names of the recording)" },
221
223
  out: { ...OPTIONS.out, output: "folder", value: "<dir>", help: "with a FAIL, write the RAM of both sides at the first different checkpoint into this folder" },
222
224
  screen: { ...OPTIONS.out, output: "file", value: "<png>", help: "write the screen of the reference at the end of the session into this PNG file" },
223
225
  },
224
226
  notes: "A recording without names takes the names of the knowledge for the reference. A $ address is an address of the reference: on the rebuild it moves with the name before it.",
225
227
  run: async (call) => {
226
228
  const [checkpoint, rebuild, symbols, out, screen] = [call.string("checkpoint"), call.string("rebuild"), call.string("symbols"), call.string("out"), call.string("screen")];
227
- const result = await replay({ folder: call.subject(0), state: call.strings("state"), pin: call.strings("pin"), ...(checkpoint === undefined ? {} : { checkpoint }), ...(rebuild === undefined ? {} : { rebuild }), ...(symbols === undefined ? {} : { symbols }), ...(out === undefined ? {} : { out }), ...(screen === undefined ? {} : { screen }) });
229
+ const values = { state: call.strings("state"), pin: call.strings("pin"), ...(checkpoint === undefined ? {} : { checkpoint }), ...(rebuild === undefined ? {} : { rebuild }), ...(symbols === undefined ? {} : { symbols }), ...(out === undefined ? {} : { out }) };
230
+ const folders = call.rest(0);
231
+ if (folders.length > 1) {
232
+ if (screen !== undefined) throw new UsageError("--screen needs one recording. Give one recording, or leave out --screen.");
233
+ const all = await replayAll(folders, values);
234
+ const first = all.recordings.find((item) => item.result !== "PASS");
235
+ if (first === undefined) return all;
236
+ // The same comparison, alone: its own result gives the hint and the nextAction of that recording.
237
+ const flags = [
238
+ ...(checkpoint === undefined ? [] : ["--checkpoint", checkpoint]),
239
+ ...values.state.flatMap((item) => ["--state", item]),
240
+ ...values.pin.flatMap((item) => ["--pin", item]),
241
+ ...(rebuild === undefined ? [] : ["--rebuild", rebuild]),
242
+ ...(symbols === undefined ? [] : ["--symbols", symbols]),
243
+ ...(out === undefined ? [] : ["--out", `${out}/${first.recording.replace(/\/+$/, "").split("/").at(-1)!}`]),
244
+ ];
245
+ return reply(all, { hint: "Each item of recordings has the result of one recording. Run nextAction: it replays the first recording that did not pass alone, and its result gives the hint for it.", nextAction: call.next("replay", first.recording, ...flags) });
246
+ }
247
+ const result = await replay({ ...values, folder: call.subject(0), ...(screen === undefined ? {} : { screen }) });
228
248
  if (result.result === "INCONCLUSIVE") return reply(result, { hint: INCONCLUSIVE_HINT });
229
249
  if (result.result !== "FAIL") return result;
230
250
  const [reference, rebuilt] = result.files ?? [];
231
251
  if (reference !== undefined && rebuilt !== undefined) {
232
252
  return reply(result, { hint: "files holds the RAM of each side at the first different checkpoint. Run nextAction to compare them. Then examine the first different state item in the emulator.", nextAction: call.next("diff", reference.out, rebuilt.out) });
233
253
  }
234
- if (result.firstDifference === undefined) return reply(result, { hint: "reason tells how many checkpoints the rebuild came to. Examine the rebuild in the emulator after its last checkpoint." });
254
+ if (result.firstDifference === undefined) {
255
+ // Without --symbols and without a symbol file of its build, the rebuild has the names of the recording: no loader or start-screen labels.
256
+ const own = rebuild === undefined ? undefined : symbolsPath(rebuild);
257
+ const unnamed = symbols === undefined && own !== undefined && result.symbols !== own;
258
+ return reply(result, { hint: unnamed ? `The rebuild has the names of the recording, as ${own} does not exist. Give --symbols with the symbol file of the rebuild.` : "reason tells how many checkpoints the rebuild came to. Examine the rebuild in the emulator after its last checkpoint." });
259
+ }
235
260
  return reply(result, { hint: `A difference in a random value with the same input often shows a missing --pin.${out === undefined ? " Give --out to get the RAM of each side at the first different checkpoint." : ""}` });
236
261
  },
237
262
  },
@@ -68,8 +68,6 @@ An address in a step can be a name. The script refuses an unknown name before th
68
68
 
69
69
  A program that reads the keyboard matrix does not see the keys of a `type` step. Use a `press` step for that program. A wait for any key that reads all keyboard columns can end without a key.
70
70
 
71
- The script refuses a step in an old form. The message gives the step to write.
72
-
73
71
  ### Paths and the project folder
74
72
 
75
73
  - Give each path relative to the project folder. The project folder is the nearest folder at or above the working directory that holds `.c64-re-tools/`.
@@ -154,7 +152,7 @@ The script never names a packer. Do not name a packer from this evidence.
154
152
  `body` holds:
155
153
 
156
154
  - `traced`: true when the run completed. `frames` and `pc` give where the run ended.
157
- - `writtenThenExecuted`: the ranges that the program wrote and then executed, as a list. `underRom: true` marks a range in RAM under a ROM.
155
+ - `writtenThenExecuted`: the ranges of RAM that the program wrote and then executed, as a list. This list can have RAM under a ROM. It does not have code that runs in a ROM.
158
156
  - `bytes`: the count of written bytes that the CPU executed.
159
157
  - `packing`, with the reason in `evidence`:
160
158
  - `likely`: the program wrote code and then executed it. It unpacked, decrypted or moved code.
@@ -195,33 +193,37 @@ Traps:
195
193
  - `captured`: true when the CPU got to `--until`. `pc` is that address.
196
194
  - `files`: each file that the command wrote, as `{out, bytes, sha256}`. `removed` names the segment files of an earlier capture that the new `image.json` does not list.
197
195
  - `segments` and `excluded`: the ranges of the segment files, and the ranges that `--exclude` removed. `loaded: true` marks a segment with the bytes that the program loaded.
198
- - `stages`: the count of stages.
196
+ - `dropped`: the ranges from `$0400` that the stages wrote and that no segment holds. The ranges of `excluded` are not in `dropped`. Each range is in a block that is not a segment because it holds the entry of a later stage. `writtenBy` is the stage that wrote the block. `stageEntry` is the entry of the later stage. When the capture dropped no byte, or with `--range`, the body has no `dropped`.
197
+ - `stages`: one item for each stage, as `stages` gives it.
199
198
  - `differsFromReset`: the count of bytes that are not as a clean C64 has them at READY.
200
199
 
201
200
  The folder `--out` gets these files:
202
201
 
203
202
  - `image.bin`: all 64 KiB of RAM at the entry. This RAM includes the RAM under the ROMs and the I/O area. A segment can be in the RAM under the I/O area at `$d000`-`$dfff`.
204
- - `image.json`: the entry, the segments, the vectors and the stages. `writtenBy` of a segment tells the last stage that wrote into it.
203
+ - `image.json`: the entry, the segments, `excluded`, `dropped`, the vectors, the steps and the stages. `writtenBy` of a segment tells the last stage that wrote into it. `steps` holds the steps of `--steps` with their default values. A steps file with these steps gives the same input to the program again. When the capture ran no steps, `image.json` has no `steps`.
205
204
  - One PRG for each segment.
206
205
  - `entry_state.json`: the registers, `$00` and `$01`, pages 0 to 3, the VIC, SID and CIA registers, the colour RAM, and the vectors. `io.colour` holds the 1000 colours at $d800. `cia` gives the CIA timer latches and interrupt masks. `differsFromReset` lists the bytes that are not as a clean C64 has them at READY. A rebuild must make these bytes the same, because the program can read them.
207
206
 
208
- A segment is a block that a stage wrote, also a small block. These blocks are not segments:
207
+ A segment is a block that a stage wrote, also a small block. The script cuts each block at the start and at the end of the I/O area, `$d000`-`$dfff`. These blocks are not segments:
209
208
 
210
209
  - A block that holds the entry of a later stage before the program, when no stage wrote over that entry.
211
210
  - A block that a stage before the program wrote in such a block, for example a variable of a loader.
212
211
  - A block that is fully in pages 0 to 3. `entry_state.json` holds these pages.
213
212
 
213
+ The script runs the program for 250 frames after the entry. If the program executes a part of a block of the first two types in that time, that part is a segment. If the program reads a part of such a block and does not write it, that part is also a segment. A stage can copy code of the program into the block of a loader.
214
+
214
215
  The block with the capture entry is always a segment. Segments do not overlap.
215
216
 
216
217
  If no stage wrote the capture entry, the program runs as it loaded. Then the range of the PRG is a segment with `loaded: true`. The blocks that touch this range are in the same segment. An example is a memory dump that starts with `SYS`.
217
218
 
218
219
  A capture into a folder with an earlier capture removes only the segment files that the new `image.json` does not list. It keeps all other files.
219
220
 
220
- On `PASS`, `hint` tells you to disassemble the code at `pc`, and then to put `<out>/image.json` into the project knowledge.
221
+ On `PASS`, `hint` tells you to disassemble the code at `pc`, and then to put `<out>/image.json` into the project knowledge. When the body has `dropped`, `hint` also gives the count of dropped bytes.
221
222
 
222
223
  Traps:
223
224
 
224
225
  - The capture stops at the first arrival at `--until` after the steps. To capture a later arrival, add a `runUntil` step to an address after the first arrival.
226
+ - A dropped range can be a part of the program. Make sure that the program does not use the bytes in `dropped`. If the program uses them, tell the user.
225
227
  - `captured: false`: the program did not get to `--until` in `--timeout-frames`. The reason tells where it stopped. Find a better address, or give more frames. If it stopped in a key wait, give `--steps` with a `type` step. If the CPU got to `--until` in a step, the reason names that step.
226
228
 
227
229
  ### `loads <program>`
@@ -1,8 +1,8 @@
1
1
  // Local evidence of packing for the c64-unpacker script: where BASIC hands
2
2
  // over and how compressed the bytes look. It never names a packer.
3
3
 
4
- import { basicLineText, findHandoffs, formatC64Address, instructionLength, parseTokenized, prgRange } from "#src/c64.ts";
5
- import { Refusal } from "#src/errors.ts";
4
+ import { basicLineText, COVERAGE, findHandoffs, formatC64Address, instructionLength, parseTokenized, prgRange } from "#src/c64.ts";
5
+ import { IO_RAM } from "#src/host-client/coverage.ts";
6
6
 
7
7
  /** A 256-byte block above this many bits per byte looks compressed. */
8
8
  const HIGH_ENTROPY = 6.9;
@@ -155,51 +155,36 @@ export function inspect(program: Uint8Array): PackingEvidence {
155
155
  };
156
156
  }
157
157
 
158
- /** One range of the emulator's memory map: what the program did with these addresses. */
159
- export interface AccessRange {
160
- start: number;
161
- end: number;
162
- read: boolean;
163
- write: boolean;
164
- execute: boolean;
165
- }
158
+ /** The memory map gives each access in the I/O area as an I/O access, also one with the RAM banked in. */
159
+ const inIoArea = (address: number) => address >= IO_RAM.start && address <= IO_RAM.end;
166
160
 
167
161
  /**
168
- * Reads the memory map of $0000-$ffff in address order. One `read` gives a
169
- * limited number of ranges, and `next` when more follow: the next read starts there.
162
+ * True when the CPU executed RAM at the address that the program wrote. The
163
+ * map keeps RAM and ROM apart, so code that runs in a ROM over written RAM
164
+ * is no written code. In the I/O area, where the map does not show the
165
+ * banking, an executed and written address is RAM code: the CPU does not
166
+ * run code in the chip registers.
170
167
  */
171
- export async function readMemoryMap(read: (start: number) => Promise<{ ranges: AccessRange[]; next?: number }>): Promise<AccessRange[]> {
172
- const ranges: AccessRange[] = [];
173
- for (let start: number | undefined = 0; start !== undefined; ) {
174
- const found: { ranges: AccessRange[]; next?: number } = await read(start);
175
- ranges.push(...found.ranges);
176
- if (found.next !== undefined && found.next <= start) throw new Refusal("operation-failed", `the memory map did not move on from ${start}`);
177
- start = found.next;
178
- }
179
- return ranges;
168
+ function ranWritten(flags: number, address: number): boolean {
169
+ if (inIoArea(address)) return (flags & (COVERAGE.ramExecute | COVERAGE.ioExecute)) !== 0 && (flags & (COVERAGE.ramWrite | COVERAGE.ioWrite)) !== 0;
170
+ return (flags & COVERAGE.ramExecute) !== 0 && (flags & COVERAGE.ramWrite) !== 0;
180
171
  }
181
172
 
182
- /** ROM areas: an address here can be written (RAM below) and executed (ROM) without one being the other. */
183
- export const underRom = (address: number) => (address >= 0xa000 && address <= 0xbfff) || address >= 0xe000;
184
-
185
173
  /**
186
- * The memory that the program wrote and then executed, in pieces of code.
187
- * `bytes` and `running` count only RAM outside the ROM areas: a write under
188
- * a ROM and code that runs in that ROM are not one piece of code.
174
+ * The RAM that the program wrote and then executed, in pieces of code, from
175
+ * a coverage map of $0000-$ffff. `bytes` counts the executed opcode bytes
176
+ * with the operand bytes between them; `running` is the piece that holds `pc`.
189
177
  */
190
- export function writtenThenExecuted(
191
- ranges: AccessRange[],
192
- pc: number,
193
- ): { written: Array<{ start: number; end: number }>; counted: Array<{ start: number; end: number }>; bytes: number; running?: { start: number; end: number } } {
178
+ export function writtenThenExecuted(map: Uint8Array, pc: number): { written: Array<{ start: number; end: number }>; bytes: number; running?: { start: number; end: number } } {
194
179
  // VICE marks only opcode bytes as executed; a gap of at most two operand bytes stays inside one piece of code.
195
180
  const written: Array<{ start: number; end: number }> = [];
196
- for (const range of ranges.filter((candidate) => candidate.write && candidate.execute)) {
181
+ for (let address = 0; address < map.length; address++) {
182
+ if (!ranWritten(map[address]!, address)) continue;
197
183
  const last = written.at(-1);
198
- if (last !== undefined && range.start - last.end <= 3 && underRom(range.start) === underRom(last.start)) last.end = range.end;
199
- else written.push({ start: range.start, end: range.end });
184
+ if (last !== undefined && address - last.end <= 3) last.end = address;
185
+ else written.push({ start: address, end: address });
200
186
  }
201
- const counted = written.filter((range) => !underRom(range.start));
202
- const bytes = counted.reduce((sum, range) => sum + range.end - range.start + 1, 0);
203
- const running = counted.find((range) => pc >= range.start && pc <= range.end);
204
- return { written, counted, bytes, ...(running === undefined ? {} : { running }) };
187
+ const bytes = written.reduce((sum, range) => sum + range.end - range.start + 1, 0);
188
+ const running = written.find((range) => pc >= range.start && pc <= range.end);
189
+ return { written, bytes, ...(running === undefined ? {} : { running }) };
205
190
  }