@orkestrel/capture 0.0.8 → 0.0.10

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.
@@ -1,16 +1,62 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { appendFileSync, closeSync, existsSync, fstatSync, globSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
3
  import { dirname, isAbsolute, matchesGlob, relative, resolve, sep } from "node:path";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
5
  import { parseArgs } from "node:util";
5
6
  import { crc32, deflateSync, inflateSync } from "node:zlib";
6
- import { arrayOf, attempt, isArray, isError, isFunction, isRecord, isString, parseJSON, preview } from "@orkestrel/contract";
7
- import { CAPTURE_LOOKUPS_FILE, CAPTURE_MANIFEST_FILE, CAPTURE_PNG_SIGNATURE, CAPTURE_REGISTRY_FILE, CAPTURE_REQUEST_PREFIX, CAPTURE_VERSION, CaptureError, collectCaptureChanges, collectCaptureDuplicates, describeCaptureDeclaration, describeCaptureDestination, describeCaptureError, describeCaptureIdentity, describeCaptureRequest, isCaptureError, isCaptureGeometry, isCaptureLookupJournal, isCapturePath, isCapturePattern, isCaptureReceipt, isCaptureRegistry, isCaptureRequest, isCaptureRun, isCaptureSegment, isCaptureSelector, isCaptureStoredManifest, matchesCaptureMembers, matchesCaptureSelector, readCaptureDirty, readCaptureReport, requireCaptureUnique, resolveCaptureKey, resolveCaptureOwner, resolveCaptureStatus, resolveLookupKey, validateCaptureReceipt, validateCaptureRun } from "../core/index.js";
8
- import { pathToFileURL } from "node:url";
9
- import { createDuplex, executeSync } from "@orkestrel/process/server";
7
+ import { arrayOf, attempt, failure, isArray, isError, isFailure, isFunction, isRecord, isString, isSuccess, parseJSON, preview, success } from "@orkestrel/contract";
8
+ import { createDuplex, executeSync, inspectProcess } from "@orkestrel/process/server";
9
+ import { computeProgress, computeProgressRun, createProgressPlugin, extractProgressEvents, readFileSnapshot, renderProgress } from "@orkestrel/test/server";
10
+ import { CAPTURE_LOOKUPS_FILE, CAPTURE_MANIFEST_FILE, CAPTURE_OWNER_PREFIX, CAPTURE_PNG_SIGNATURE, CAPTURE_REGISTRY_FILE, CAPTURE_REQUEST_PREFIX, CAPTURE_VERSION, CaptureError, buildCaptureTags, collectCaptureAncestors, collectCaptureChanges, collectCaptureDuplicates, describeCaptureDeclaration, describeCaptureDestination, describeCaptureError, describeCaptureIdentity, describeCaptureRequest, isCaptureError, isCaptureGeometry, isCaptureLookupJournal, isCaptureManifestDocument, isCapturePath, isCapturePattern, isCaptureReceipt, isCaptureRegistry, isCaptureRequest, isCaptureRun, isCaptureSegment, isCaptureSelector, matchesCaptureMembers, matchesCaptureSelector, readCaptureArtifact, readCaptureDirty, readCaptureReport, requireCaptureUnique, resolveCaptureKey, resolveCaptureOwner, resolveCaptureStatus, resolveLookupKey, validateCaptureReceipt, validateCaptureRun } from "../core/index.js";
10
11
  import { StringDecoder } from "node:string_decoder";
11
12
  import { createTimeout } from "@orkestrel/timeout";
12
13
  // src/server/constants.ts
13
14
  /**
15
+ * Names the command that clears each refusal condition, or none where no command clears it.
16
+ *
17
+ * @remarks
18
+ * `registry` is the complete-registry refresh, and `journey` is the selected owner's journey, which
19
+ * refreshes its state lookups. A runner prints the command on stdout after the report line it
20
+ * follows, ahead of the refusal on stderr, and on stderr after the refusal when no report line
21
+ * precedes it; a condition with no command prints none.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * CAPTURE_RECOVERIES.REGISTRY // 'registry'
26
+ * ```
27
+ */
28
+ var CAPTURE_RECOVERIES = Object.freeze({
29
+ USAGE: void 0,
30
+ SELECTION: void 0,
31
+ HOST: void 0,
32
+ STAGE: void 0,
33
+ EVIDENCE: void 0,
34
+ REGISTRY: "registry",
35
+ LOOKUP: "journey",
36
+ CONTAINMENT: void 0
37
+ });
38
+ /**
39
+ * Names the command that clears each freshness classification, or none where no command clears it.
40
+ *
41
+ * @remarks
42
+ * `capture` is a frames run over the read selection. A `duplicate` or an `orphan` names a registry
43
+ * or a file that no frames run changes, and a `current` frame needs nothing.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * CAPTURE_STATUS_RECOVERIES['stale-own'] // 'capture'
48
+ * ```
49
+ */
50
+ var CAPTURE_STATUS_RECOVERIES = Object.freeze({
51
+ current: void 0,
52
+ duplicate: void 0,
53
+ orphan: void 0,
54
+ missing: "capture",
55
+ unstamped: "capture",
56
+ "stale-shared": "capture",
57
+ "stale-own": "capture"
58
+ });
59
+ /**
14
60
  * Names the executable subcommand each runner command answers to.
15
61
  *
16
62
  * @remarks
@@ -52,6 +98,14 @@ var CAPTURE_EXIT = Object.freeze({
52
98
  */
53
99
  var CAPTURE_OWNER_FILE = ".capture-owner";
54
100
  /**
101
+ * Holds the largest process id a POSIX or Windows host can assign, the signed 32-bit maximum.
102
+ * @example
103
+ * ```ts
104
+ * CAPTURE_PID_LIMIT // 2147483647
105
+ * ```
106
+ */
107
+ var CAPTURE_PID_LIMIT = 2147483647;
108
+ /**
55
109
  * Caps each refusal population so hostile records cannot flood a terminal or agent context.
56
110
  * @example
57
111
  * ```ts
@@ -83,6 +137,9 @@ var CAPTURE_STAGES = Object.freeze({
83
137
  /**
84
138
  * Defines each command's frozen options for Node's standard argument parser.
85
139
  *
140
+ * @remarks A boolean option whose default is `true` reads only its `--no-` form, which sets it to
141
+ * `false`; `bail` is the one such option.
142
+ *
86
143
  * @example
87
144
  * ```ts
88
145
  * CAPTURE_COMMAND_OPTIONS.journey.variant.multiple // true
@@ -98,6 +155,10 @@ var CAPTURE_COMMAND_OPTIONS = Object.freeze({
98
155
  case: Object.freeze({ type: "string" }),
99
156
  changed: Object.freeze({ type: "string" }),
100
157
  plan: Object.freeze({ type: "boolean" }),
158
+ bail: Object.freeze({
159
+ type: "boolean",
160
+ default: true
161
+ }),
101
162
  mode: Object.freeze({ type: "string" })
102
163
  }),
103
164
  capture: Object.freeze({
@@ -110,6 +171,10 @@ var CAPTURE_COMMAND_OPTIONS = Object.freeze({
110
171
  state: Object.freeze({ type: "string" }),
111
172
  changed: Object.freeze({ type: "string" }),
112
173
  plan: Object.freeze({ type: "boolean" }),
174
+ bail: Object.freeze({
175
+ type: "boolean",
176
+ default: true
177
+ }),
113
178
  mode: Object.freeze({ type: "string" })
114
179
  }),
115
180
  stale: Object.freeze({
@@ -156,8 +221,13 @@ var CAPTURE_COMMAND_OPTIONS = Object.freeze({
156
221
  multiple: true
157
222
  }),
158
223
  config: Object.freeze({ type: "string" }),
224
+ bail: Object.freeze({
225
+ type: "boolean",
226
+ default: true
227
+ }),
159
228
  mode: Object.freeze({ type: "string" })
160
- })
229
+ }),
230
+ progress: Object.freeze({})
161
231
  });
162
232
  /**
163
233
  * Lists the words a tag name can never be, because a tag filter reads them as operators.
@@ -173,15 +243,6 @@ var CAPTURE_TAG_OPERATORS = Object.freeze([
173
243
  "not"
174
244
  ]);
175
245
  /**
176
- * Names the tag prefix that marks a case's owner path and each ancestor of it.
177
- *
178
- * @example
179
- * ```ts
180
- * `${CAPTURE_OWNER_PREFIX}pages:mail` // 'owner:pages:mail'
181
- * ```
182
- */
183
- var CAPTURE_OWNER_PREFIX = "owner:";
184
- /**
185
246
  * Names the environment variable that turns frame capture on for a Vitest child.
186
247
  *
187
248
  * @example
@@ -217,6 +278,32 @@ var CAPTURE_VITEST_ENTRY = "node_modules/vitest/vitest.mjs";
217
278
  * ```
218
279
  */
219
280
  var CAPTURE_RUNS_DIRECTORY = "runs";
281
+ /**
282
+ * Names the ending of the progress file each stage writes beneath its invocation's run directory.
283
+ *
284
+ * @remarks The stage's name precedes it, so `selected` writes `selected.progress.jsonl`.
285
+ *
286
+ * @example
287
+ * ```ts
288
+ * `tmp/capture/${CAPTURE_RUNS_DIRECTORY}/a/selected${CAPTURE_PROGRESS_SUFFIX}`
289
+ * ```
290
+ */
291
+ var CAPTURE_PROGRESS_SUFFIX = ".progress.jsonl";
292
+ /**
293
+ * Names the prefixes a journey wrapper derives its own paths from.
294
+ *
295
+ * @remarks `scratch` precedes the variant in the sibling of the evidence root a run without frame
296
+ * capture writes to, and `direct` precedes the random identity of a run no runner started.
297
+ *
298
+ * @example
299
+ * ```ts
300
+ * `tmp/captures/${CAPTURE_WRAPPER_PREFIXES.scratch}light-390` // 'tmp/captures/no-capture-light-390'
301
+ * ```
302
+ */
303
+ var CAPTURE_WRAPPER_PREFIXES = Object.freeze({
304
+ scratch: "no-capture-",
305
+ direct: "direct-"
306
+ });
220
307
  /** Names the create-only child record beneath an invocation's run directory.
221
308
  * @example
222
309
  * ```ts
@@ -351,7 +438,8 @@ var CAPTURE_SUBCOMMANDS = Object.freeze([
351
438
  "stale",
352
439
  "preflight",
353
440
  "sheets",
354
- "registry"
441
+ "registry",
442
+ "progress"
355
443
  ]);
356
444
  /**
357
445
  * Holds the repository-relative paths the executable falls back to when the command line names none.
@@ -418,17 +506,20 @@ var CAPTURE_DISCOVERY = Object.freeze({
418
506
  var CAPTURE_USAGE = [
419
507
  "Usage: capture <command> [arguments]",
420
508
  "Commands:",
421
- " journey <selector> [--variant <name>]... [--case <full name>] [--mode <name>] [--config <file>]",
422
- " journey --changed <ref> [--plan] [--variant <name>]... [--case <full name>] [--mode <name>] [--config <file>]",
423
- " frames <selector> [--variant <name>]... [--case <full name>] [--state <name>] [--mode <name>] [--config <file>]",
424
- " frames --changed <ref> [--plan] [--variant <name>]... [--case <full name>] [--state <name>] [--mode <name>] [--config <file>]",
509
+ " journey <selector> [--variant <name>]... [--case <full name>] [--no-bail] [--mode <name>] [--config <file>]",
510
+ " journey --changed <ref> [--plan] [--variant <name>]... [--case <full name>] [--no-bail] [--mode <name>] [--config <file>]",
511
+ " frames <selector> [--variant <name>]... [--case <full name>] [--state <name>] [--no-bail] [--mode <name>] [--config <file>]",
512
+ " frames --changed <ref> [--plan] [--variant <name>]... [--case <full name>] [--state <name>] [--no-bail] [--mode <name>] [--config <file>]",
425
513
  " stale <selector> [--variant <name>]... [--case <full name>] [--state <name>] [--portfolio <name>] [--mode <name>] [--config <file>]",
426
514
  " preflight <selector> [--variant <name>]... [--state <name>] [--case <full name>] [--portfolio <name>] [--mode <name>] [--config <file>] [--journeys <directory>] [--checks <module>]",
427
515
  " sheets <selector> --output <new directory> [--variant <name>]... [--state <name>] [--case <full name>] [--portfolio <name>] [--mode <name>] [--config <file>] [--journeys <directory>] [--checks <module>]",
428
- " registry [--variant <name>]... [--mode <name>] [--config <file>]",
516
+ " registry [--variant <name>]... [--no-bail] [--mode <name>] [--config <file>]",
517
+ " progress",
429
518
  "--changed takes one Git ref; HEAD selects uncommitted work. It cannot accompany a selector.",
430
519
  "--plan requires --changed and prints paths and commands after read-only discovery; no execution child starts.",
431
- "Only --variant repeats. Every flag except --plan takes one nonempty value, as --flag value or --flag=value; use --flag=-x for a value beginning with a dash. The -- terminator is refused.",
520
+ "--no-bail runs every selected case after a failure; by default a stage stops at its first failed case.",
521
+ "progress prints where the stage that is running, or that ran last, stands, from its progress file.",
522
+ "Only --variant repeats. Every flag except --plan and --no-bail takes one nonempty value, as --flag value or --flag=value; use --flag=-x for a value beginning with a dash. The -- terminator is refused.",
432
523
  "Exit: 0 passed, 1 failed or refused by the evidence, 64 refused usage."
433
524
  ].join("\n");
434
525
  // src/server/helpers.ts
@@ -482,8 +573,13 @@ function buildCaptureChangePlan(paths, entries) {
482
573
  /**
483
574
  * Renders an exact owner command with the selected variants and filters in host shell syntax.
484
575
  *
576
+ * @remarks
577
+ * A flag is rendered only when the rendered command's `CAPTURE_COMMAND_OPTIONS` entry declares it,
578
+ * so a journey drops `--state`, a registry refresh drops `--case`, and only `stale` keeps
579
+ * `--portfolio`. `--changed` and `--plan` are never rendered.
580
+ *
485
581
  * @param command - The request command, translated to its executable name, or the registry command
486
- * @param parsed - The parsed flags; changed and plan flags are deliberately replaced by the owner
582
+ * @param parsed - The parsed flags, a `false` bail rendered as `--no-bail`; changed and plan flags are deliberately replaced by the owner
487
583
  * @param selector - The explicit owner or all selector; omitted for a registry refresh
488
584
  * @param root - The workspace that makes the wrapper path relative
489
585
  * @returns The command ready to copy into the host shell
@@ -495,14 +591,17 @@ function buildCaptureChangePlan(paths, entries) {
495
591
  */
496
592
  function renderCaptureCommand(command, parsed, selector, root) {
497
593
  const config = resolveCaptureRelative(root, parsed.config);
594
+ const options = CAPTURE_COMMAND_OPTIONS[command];
498
595
  return [
499
596
  "capture",
500
597
  command === "registry" ? command : CAPTURE_COMMAND_NAMES[command],
501
598
  ...selector === void 0 ? [] : [selector],
502
- ...parsed.variants.flatMap((variant) => ["--variant", variant]),
503
- ...parsed.mode === void 0 ? [] : ["--mode", parsed.mode],
504
- ...parsed.case === void 0 ? [] : parsed.case.startsWith("-") ? [`--case=${parsed.case}`] : ["--case", parsed.case],
505
- ...parsed.state === void 0 ? [] : ["--state", parsed.state],
599
+ ...Object.hasOwn(options, "variant") ? parsed.variants.flatMap((variant) => ["--variant", variant]) : [],
600
+ ...parsed.mode === void 0 || !Object.hasOwn(options, "mode") ? [] : ["--mode", parsed.mode],
601
+ ...parsed.case === void 0 || !Object.hasOwn(options, "case") ? [] : parsed.case.startsWith("-") ? [`--case=${parsed.case}`] : ["--case", parsed.case],
602
+ ...parsed.state === void 0 || !Object.hasOwn(options, "state") ? [] : ["--state", parsed.state],
603
+ ...parsed.portfolio === void 0 || !Object.hasOwn(options, "portfolio") ? [] : ["--portfolio", parsed.portfolio],
604
+ ...parsed.bail === false && Object.hasOwn(options, "bail") ? ["--no-bail"] : [],
506
605
  ...config.startsWith("-") ? [`--config=${config}`] : ["--config", config]
507
606
  ].map((argument) => /^[\w./:-]+$/u.test(argument) ? argument : process.platform === "win32" ? `'${argument.replaceAll("'", "''")}'` : `'${argument.replaceAll("'", "'\\''")}'`).join(" ");
508
607
  }
@@ -734,6 +833,45 @@ function buildCaptureDigest(patterns, files) {
734
833
  };
735
834
  }
736
835
  /**
836
+ * Computes the key under which a pattern list's matched subset of one input population is memoized.
837
+ *
838
+ * @remarks
839
+ * The key joins the population's digest with the sorted patterns, so a list in any order over one
840
+ * population shares a key, and one population never answers for another.
841
+ *
842
+ * @param inputs - The digested input population the patterns match against
843
+ * @param patterns - The native glob patterns, in any order
844
+ * @returns The memo key of the population and the pattern list
845
+ *
846
+ * @example
847
+ * ```ts
848
+ * const inputs = buildCaptureDigest(['src/**'], { 'src/a.ts': 'f'.repeat(64) })
849
+ * computeCaptureMatchKey(inputs, ['src/*.ts', 'src/*.md']) === computeCaptureMatchKey(inputs, ['src/*.md', 'src/*.ts']) // true
850
+ * ```
851
+ */
852
+ function computeCaptureMatchKey(inputs, patterns) {
853
+ return JSON.stringify([inputs.digest, patterns.toSorted()]);
854
+ }
855
+ /**
856
+ * Filters an input population's paths that match any listed pattern.
857
+ *
858
+ * @remarks
859
+ * Each path is matched with the `matchesGlob` function from `node:path`.
860
+ *
861
+ * @param inputs - The digested input population whose paths are matched
862
+ * @param patterns - The native glob patterns
863
+ * @returns The population's paths that match at least one pattern, in population order
864
+ *
865
+ * @example
866
+ * ```ts
867
+ * const inputs = buildCaptureDigest(['src/**'], { 'src/a.ts': 'f'.repeat(64), 'src/b.md': 'e'.repeat(64) })
868
+ * filterCaptureInputs(inputs, ['src/*.ts']) // Set { 'src/a.ts' }
869
+ * ```
870
+ */
871
+ function filterCaptureInputs(inputs, patterns) {
872
+ return new Set(Object.keys(inputs.files).filter((path) => patterns.some((pattern) => matchesGlob(path, pattern))));
873
+ }
874
+ /**
737
875
  * Stores each distinct lookup input population once in a manifest-bound journal.
738
876
  *
739
877
  * @param lookups - The expanded passing case evidence to publish
@@ -743,55 +881,341 @@ function buildCaptureDigest(patterns, files) {
743
881
  *
744
882
  * @example
745
883
  * ```ts
746
- * buildCaptureLookupJournal([], []).inputs // {}
884
+ * buildCaptureLookupJournal([], []).populations // {}
747
885
  * ```
748
886
  */
749
887
  function buildCaptureLookupJournal(lookups, collections, manifest) {
750
- const populations = /* @__PURE__ */ new Map();
751
- const references = lookups.map((lookup) => {
752
- const known = populations.get(lookup.inputs);
753
- const population = known ?? buildCaptureDigest([], lookup.inputs);
754
- if (known === void 0) populations.set(lookup.inputs, population);
755
- return {
756
- ...lookup,
757
- inputs: population.digest
758
- };
759
- });
888
+ const memo = /* @__PURE__ */ new Map();
889
+ const references = lookups.map((lookup) => ({
890
+ ...lookup,
891
+ inputs: computeCaptureTableKey(lookup.inputs, memo)
892
+ }));
760
893
  return {
761
894
  version: CAPTURE_VERSION,
762
895
  ...manifest === void 0 ? {} : { manifest },
763
- inputs: Object.fromEntries([...populations.values()].map((population) => [population.digest, population.files])),
896
+ populations: buildCaptureTable(memo),
764
897
  lookups: references,
765
898
  collections
766
899
  };
767
900
  }
768
901
  /**
902
+ * Admits a decoded lookup journal, checking its declared version before its schema.
903
+ *
904
+ * @param value - The decoded journal file
905
+ * @param file - The journal path each refusal names
906
+ * @returns The journal, whose table digests `readCaptureLookups` verifies
907
+ * @throws Thrown with the removal and the refresh commands when the journal declares another
908
+ * protocol version, and thrown naming the file when its schema is invalid.
909
+ *
910
+ * @example
911
+ * ```ts
912
+ * readCaptureLookupJournal(JSON.parse(text), 'tmp/captures/states/lookups.json').lookups.length
913
+ * ```
914
+ */
915
+ function readCaptureLookupJournal(value, file) {
916
+ requireCaptureVersion(value, "Lookup journal", file, [file]);
917
+ if (!isCaptureLookupJournal(value)) throw new CaptureError(`Invalid lookup journal schema: ${file}`, {
918
+ code: "EVIDENCE",
919
+ context: { file }
920
+ });
921
+ return value;
922
+ }
923
+ /**
769
924
  * Resolves journal lookup references after verifying each stored input population's digest.
770
925
  *
771
926
  * @param journal - A structurally validated lookup journal
927
+ * @param file - The journal path each refusal names
772
928
  * @returns Every expanded lookup in its stored order, sharing the verified input maps
773
- * @throws Thrown when an input digest differs from its map or a lookup names an unknown digest.
929
+ * @throws Thrown when a population does not hash to its key or a lookup names an unknown key.
774
930
  *
775
931
  * @example
776
932
  * ```ts
777
- * readCaptureLookups(buildCaptureLookupJournal([], [])) // []
933
+ * readCaptureLookups(buildCaptureLookupJournal([], []), 'tmp/captures/states/lookups.json') // []
778
934
  * ```
779
935
  */
780
- function readCaptureLookups(journal) {
781
- const populations = new Map(Object.entries(journal.inputs).map(([digest, inputs]) => {
782
- if (buildCaptureDigest([], inputs).digest !== digest) throw new CaptureError(`Lookup input digest differs from its map: ${digest}`, { code: "EVIDENCE" });
783
- return [digest, inputs];
936
+ function readCaptureLookups(journal, file) {
937
+ const subject = `Lookup journal at ${file}`;
938
+ const populations = readCaptureTable(journal.populations, subject);
939
+ return journal.lookups.map((lookup) => ({
940
+ ...lookup,
941
+ inputs: requireCaptureTableEntry(populations, lookup.inputs, subject, "inputs")
784
942
  }));
785
- return journal.lookups.map((lookup) => {
786
- const inputs = populations.get(lookup.inputs);
787
- if (inputs === void 0) throw new CaptureError(`Lookup names an unknown inputs digest: ${lookup.inputs}`, { code: "EVIDENCE" });
788
- return {
943
+ }
944
+ /**
945
+ * Computes the table key of a file map, the digest from `buildCaptureDigest([], files)`, once per map.
946
+ *
947
+ * @remarks
948
+ * The memo belongs to one document build: it holds each map by identity beside its ordered,
949
+ * digested population, so equal maps from different objects share one key.
950
+ *
951
+ * @param files - The path-to-hash map a document stores once
952
+ * @param memo - The build's memo from each map to its ordered, digested population
953
+ * @returns The digest that names the map in the document's population table
954
+ *
955
+ * @example
956
+ * ```ts
957
+ * const memo = new Map()
958
+ * computeCaptureTableKey({ 'src/a.ts': 'f'.repeat(64) }, memo).length // 64
959
+ * ```
960
+ */
961
+ function computeCaptureTableKey(files, memo) {
962
+ const known = memo.get(files);
963
+ if (known !== void 0) return known.digest;
964
+ const population = buildCaptureDigest([], files);
965
+ memo.set(files, population);
966
+ return population.digest;
967
+ }
968
+ /**
969
+ * Builds a document's population table from the memo its table keys were computed through.
970
+ *
971
+ * @param memo - The memo `computeCaptureTableKey` filled for one document build
972
+ * @returns Each distinct ordered map under its digest, in the order the build first met it
973
+ *
974
+ * @example
975
+ * ```ts
976
+ * const memo = new Map()
977
+ * const key = computeCaptureTableKey({ 'src/a.ts': 'f'.repeat(64) }, memo)
978
+ * buildCaptureTable(memo)[key] // { 'src/a.ts': 'ffff…' }
979
+ * ```
980
+ */
981
+ function buildCaptureTable(memo) {
982
+ return Object.fromEntries([...memo.values()].map((population) => [population.digest, population.files]));
983
+ }
984
+ /**
985
+ * Reads a document's population table after verifying that each map hashes to the key it is stored under.
986
+ *
987
+ * @param table - The stored table from each digest to its path-to-hash map
988
+ * @param subject - The document and its path, which open the refusal message
989
+ * @returns Each verified map by its digest
990
+ * @throws Thrown when a stored map does not hash to its key.
991
+ *
992
+ * @example
993
+ * ```ts
994
+ * readCaptureTable({}, 'Manifest at tmp/captures/states/manifest.json').size // 0
995
+ * ```
996
+ */
997
+ function readCaptureTable(table, subject) {
998
+ return new Map(Object.entries(table).map(([digest, files]) => {
999
+ if (buildCaptureDigest([], files).digest !== digest) throw new CaptureError(`${subject} stores a population that does not hash to its key: ${digest}`, { code: "EVIDENCE" });
1000
+ return [digest, files];
1001
+ }));
1002
+ }
1003
+ /**
1004
+ * Returns the verified map a table key names, refusing a key the table does not hold.
1005
+ *
1006
+ * @param table - The verified table `readCaptureTable` returns
1007
+ * @param key - The digest a stored member names
1008
+ * @param subject - The document and its path, which open the refusal message
1009
+ * @param field - The referencing field the refusal message names
1010
+ * @returns The file map stored under the key
1011
+ * @throws Thrown when the table holds no map under the key.
1012
+ *
1013
+ * @example
1014
+ * ```ts
1015
+ * requireCaptureTableEntry(new Map([[key, files]]), key, 'Manifest at manifest.json', 'inputs') === files // true
1016
+ * ```
1017
+ */
1018
+ function requireCaptureTableEntry(table, key, subject, field) {
1019
+ const files = table.get(key);
1020
+ if (files === void 0) throw new CaptureError(`${subject} names an unknown ${field} digest: ${key}`, { code: "EVIDENCE" });
1021
+ return files;
1022
+ }
1023
+ /**
1024
+ * Stores each distinct file map of an expanded manifest once, in a table keyed by the map's digest.
1025
+ *
1026
+ * @param manifest - The expanded manifest the engine publishes
1027
+ * @returns The document whose stamps, lookups, and collections name their maps by table key
1028
+ *
1029
+ * @example
1030
+ * ```ts
1031
+ * const document = buildCaptureManifestDocument(manifest)
1032
+ * Object.keys(document.populations) // one digest per distinct shared or input map
1033
+ * ```
1034
+ */
1035
+ function buildCaptureManifestDocument(manifest) {
1036
+ const memo = /* @__PURE__ */ new Map();
1037
+ const entries = Object.fromEntries(Object.entries(manifest.entries).map(([key, stamp]) => [key, {
1038
+ ...stamp,
1039
+ shared: {
1040
+ ...stamp.shared,
1041
+ files: computeCaptureTableKey(stamp.shared.files, memo)
1042
+ }
1043
+ }]));
1044
+ const lookups = manifest.lookups.map((lookup) => ({
1045
+ ...lookup,
1046
+ inputs: computeCaptureTableKey(lookup.inputs, memo)
1047
+ }));
1048
+ const collections = manifest.collections?.map((receipt) => ({
1049
+ ...receipt,
1050
+ inputs: {
1051
+ ...receipt.inputs,
1052
+ files: computeCaptureTableKey(receipt.inputs.files, memo)
1053
+ }
1054
+ }));
1055
+ return {
1056
+ version: manifest.version,
1057
+ populations: buildCaptureTable(memo),
1058
+ registry: manifest.registry,
1059
+ entries,
1060
+ lookups,
1061
+ ...collections === void 0 ? {} : { collections }
1062
+ };
1063
+ }
1064
+ /**
1065
+ * Admits a stored manifest and expands every table reference into the file map it names.
1066
+ *
1067
+ * @param value - The decoded manifest file
1068
+ * @param file - The manifest path each refusal names
1069
+ * @returns The expanded manifest, whose references to one key share one verified map
1070
+ * @throws Thrown with the removal and the refresh commands when the document declares another
1071
+ * protocol version, and thrown when its schema is invalid, a table map does not hash to its key,
1072
+ * or a reference names no table key.
1073
+ *
1074
+ * @example
1075
+ * ```ts
1076
+ * const manifest = readCaptureManifest(JSON.parse(text), 'tmp/captures/states/manifest.json')
1077
+ * manifest.lookups[0]?.inputs // the expanded input map
1078
+ * ```
1079
+ */
1080
+ function readCaptureManifest(value, file) {
1081
+ requireCaptureVersion(value, "Manifest", file, [file, "its lookup journal"]);
1082
+ if (!isCaptureManifestDocument(value)) throw new CaptureError(`Invalid inherited manifest schema: ${file}`, { code: "EVIDENCE" });
1083
+ const subject = `Manifest at ${file}`;
1084
+ const table = readCaptureTable(value.populations, subject);
1085
+ return {
1086
+ version: value.version,
1087
+ registry: value.registry,
1088
+ entries: Object.fromEntries(Object.entries(value.entries).map(([key, stamp]) => [key, {
1089
+ ...stamp,
1090
+ shared: {
1091
+ ...stamp.shared,
1092
+ files: requireCaptureTableEntry(table, stamp.shared.files, subject, "shared.files")
1093
+ }
1094
+ }])),
1095
+ lookups: value.lookups.map((lookup) => ({
789
1096
  ...lookup,
790
- inputs
791
- };
1097
+ inputs: requireCaptureTableEntry(table, lookup.inputs, subject, "inputs")
1098
+ })),
1099
+ ...value.collections === void 0 ? {} : { collections: value.collections.map((receipt) => ({
1100
+ ...receipt,
1101
+ inputs: {
1102
+ ...receipt.inputs,
1103
+ files: requireCaptureTableEntry(table, receipt.inputs.files, subject, "inputs.files")
1104
+ }
1105
+ })) }
1106
+ };
1107
+ }
1108
+ /**
1109
+ * Refuses a document that declares a numeric version other than `CAPTURE_VERSION`, naming what to remove and the refresh commands.
1110
+ *
1111
+ * @remarks
1112
+ * A document with no numeric version passes, so the schema check that follows names that fault.
1113
+ * No document of another version is converted.
1114
+ *
1115
+ * @param value - The decoded document
1116
+ * @param subject - The document kind that opens the refusal, such as `Registry`
1117
+ * @param file - The document path the refusal names
1118
+ * @param removal - The paths, or the phrases naming them, to remove before the refresh
1119
+ * @throws Thrown as an `EVIDENCE` capture error whose context carries `file` and `version` when the
1120
+ * document declares another numeric version.
1121
+ *
1122
+ * @example
1123
+ * ```ts
1124
+ * requireCaptureVersion({ version: 1 }, 'Registry', 'registry.json', ['registry.json'])
1125
+ * // throws: Registry version 1 at registry.json is not version 2, … Remove registry.json, then refresh explicitly with: capture registry, then capture frames all
1126
+ * ```
1127
+ */
1128
+ function requireCaptureVersion(value, subject, file, removal) {
1129
+ const version = isRecord(value) ? value.version : void 0;
1130
+ if (typeof version === "number" && version !== CAPTURE_VERSION) throw new CaptureError(`${subject} version ${String(version)} at ${file} is not version ${String(CAPTURE_VERSION)}, and no other version is converted. Remove ${new Intl.ListFormat("en", { type: "conjunction" }).format(removal)}, then refresh explicitly with: capture registry, then capture frames all`, {
1131
+ code: "EVIDENCE",
1132
+ context: {
1133
+ file,
1134
+ version
1135
+ }
1136
+ });
1137
+ }
1138
+ /**
1139
+ * Checks whether an error is the refusal `requireCaptureVersion` throws for another document version.
1140
+ *
1141
+ * @remarks
1142
+ * A caller that adds its own recovery to a refusal passes this one through unchanged, because it
1143
+ * already names the removal and the refresh.
1144
+ *
1145
+ * @param error - The caught value
1146
+ * @returns True if it is an `EVIDENCE` capture error whose context carries a file and a numeric version; false otherwise
1147
+ *
1148
+ * @example
1149
+ * ```ts
1150
+ * matchesCaptureVersionRefusal(captureError(() => requireCaptureVersion({ version: 1 }, 'Registry', file, [file]))) // true
1151
+ * matchesCaptureVersionRefusal(new Error('Invalid')) // false
1152
+ * ```
1153
+ */
1154
+ function matchesCaptureVersionRefusal(error) {
1155
+ return isCaptureError(error) && error.code === "EVIDENCE" && typeof error.context?.file === "string" && typeof error.context.version === "number";
1156
+ }
1157
+ /**
1158
+ * Classifies a failure raised while reading the accepted registry as the registry condition.
1159
+ *
1160
+ * @remarks
1161
+ * The complete-registry refresh clears every such failure but a document of another version, whose
1162
+ * refusal names its own removal and refresh.
1163
+ *
1164
+ * @param error - The value a registry read threw
1165
+ * @returns A `REGISTRY` capture error with the same message and the original as its cause, for a
1166
+ * value that is not a capture error or is an `EVIDENCE` capture error other than a version refusal;
1167
+ * otherwise the value itself
1168
+ *
1169
+ * @example
1170
+ * ```ts
1171
+ * resolveCaptureRegistryFault(new CaptureError('Invalid accepted registry schema or digest', { code: 'EVIDENCE' })) // a REGISTRY capture error
1172
+ * resolveCaptureRegistryFault(new CaptureError('Unknown portfolio: x', { code: 'SELECTION' })) // the same error
1173
+ * ```
1174
+ */
1175
+ function resolveCaptureRegistryFault(error) {
1176
+ return isCaptureError(error) && (error.code !== "EVIDENCE" || matchesCaptureVersionRefusal(error)) ? error : new CaptureError(describeCaptureError(error), {
1177
+ code: "REGISTRY",
1178
+ cause: error
792
1179
  });
793
1180
  }
794
1181
  /**
1182
+ * Collects the variants that produce each destination across the registry receipts and the lookup runs.
1183
+ *
1184
+ * @param evidence - The accepted registry and the authenticated lookup runs
1185
+ * @returns Each destination description mapped to its distinct producing variants, in first-seen order
1186
+ *
1187
+ * @example
1188
+ * ```ts
1189
+ * collectCaptureProducers({ registry, runs: [] }).get(describeCaptureDestination(destination)) // ['light-390']
1190
+ * ```
1191
+ */
1192
+ function collectCaptureProducers(evidence) {
1193
+ const sources = [...evidence.registry.receipts, ...evidence.runs.map((entry) => entry.run)];
1194
+ const attributions = Map.groupBy(sources.flatMap((source) => source.registry.map((entry) => ({
1195
+ description: describeCaptureDestination(entry),
1196
+ variant: source.variant
1197
+ }))), (entry) => entry.description);
1198
+ return new Map([...attributions].map(([description, entries]) => [description, [...new Set(entries.map((entry) => entry.variant))]]));
1199
+ }
1200
+ /**
1201
+ * Returns the one variant that produces a destination, refusing a destination with none or several.
1202
+ *
1203
+ * @param destination - The destination whose producer is read
1204
+ * @param producers - The map `collectCaptureProducers` returns
1205
+ * @returns The destination's unique producing variant
1206
+ * @throws Thrown as an `EVIDENCE` capture error when no variant or more than one produces the destination.
1207
+ *
1208
+ * @example
1209
+ * ```ts
1210
+ * requireCaptureProducer(destination, collectCaptureProducers({ registry, runs: [] })) // 'light-390'
1211
+ * ```
1212
+ */
1213
+ function requireCaptureProducer(destination, producers) {
1214
+ const variants = producers.get(describeCaptureDestination(destination)) ?? [];
1215
+ if (variants.length !== 1 || variants[0] === void 0) throw new CaptureError("Destination has no unique producing variant", { code: "EVIDENCE" });
1216
+ return variants[0];
1217
+ }
1218
+ /**
795
1219
  * Computes the registry identity from its authenticated receipts and exact output population.
796
1220
  *
797
1221
  * @param registry - The registry fields before its digest is attached
@@ -799,7 +1223,7 @@ function readCaptureLookups(journal) {
799
1223
  *
800
1224
  * @example
801
1225
  * ```ts
802
- * computeRegistryDigest({ version: 1, receipts: [], entries: [] }).length // 64
1226
+ * computeRegistryDigest({ version: 2, receipts: [], entries: [] }).length // 64
803
1227
  * ```
804
1228
  */
805
1229
  function computeRegistryDigest(registry) {
@@ -883,12 +1307,10 @@ function matchesCaptureSignature(bytes) {
883
1307
  */
884
1308
  function predictCaptureByte(left, up, corner) {
885
1309
  const estimate = left + up - corner;
886
- const distances = [
887
- Math.abs(estimate - left),
888
- Math.abs(estimate - up),
889
- Math.abs(estimate - corner)
890
- ];
891
- return (distances[0] ?? 0) <= (distances[1] ?? 0) && (distances[0] ?? 0) <= (distances[2] ?? 0) ? left : (distances[1] ?? 0) <= (distances[2] ?? 0) ? up : corner;
1310
+ const west = Math.abs(estimate - left);
1311
+ const north = Math.abs(estimate - up);
1312
+ const diagonal = Math.abs(estimate - corner);
1313
+ return west <= north && west <= diagonal ? left : north <= diagonal ? up : corner;
892
1314
  }
893
1315
  /**
894
1316
  * Reads PNG compressed-data chunks while refusing truncated or corrupt image bytes.
@@ -896,7 +1318,10 @@ function predictCaptureByte(left, up, corner) {
896
1318
  * @param bytes - The complete PNG
897
1319
  * @param offset - The next chunk header. Default: 8.
898
1320
  * @returns Ordered compressed-data chunks
899
- * @throws Thrown for truncated chunks, bad checksums, or a missing closing chunk.
1321
+ * @throws Thrown for bytes over the file budget; a truncated chunk, which a file with no closing
1322
+ * chunk also meets; a bad checksum; a closing chunk that is not empty and last; an IHDR chunk
1323
+ * anywhere but offset 8; a critical chunk other than IHDR, PLTE, IDAT, and IEND; or IDAT chunks
1324
+ * that are not consecutive.
900
1325
  *
901
1326
  * @example
902
1327
  * ```ts
@@ -905,23 +1330,89 @@ function predictCaptureByte(left, up, corner) {
905
1330
  */
906
1331
  function readCaptureChunks(bytes, offset = 8) {
907
1332
  requireCaptureImageSize(bytes.length);
908
- const positions = [offset];
909
- const chunks = [];
910
- for (const position of positions) {
911
- if (!Number.isSafeInteger(position) || position < 8 || position + 12 > bytes.length) throw new CaptureError("Truncated capture PNG", { code: "EVIDENCE" });
1333
+ const positions = scanCaptureChunks(bytes, offset, Infinity);
1334
+ const types = positions.map((position) => bytes.readUInt32BE(position + 4));
1335
+ const header = Buffer.from("IHDR", "latin1").readUInt32BE(0);
1336
+ const palette = Buffer.from("PLTE", "latin1").readUInt32BE(0);
1337
+ const data = Buffer.from("IDAT", "latin1").readUInt32BE(0);
1338
+ const end = Buffer.from("IEND", "latin1").readUInt32BE(0);
1339
+ const last = positions.at(-1);
1340
+ if (last === void 0 || types.at(-1) !== end) throw new CaptureError(`Missing capture PNG closing chunk: ${last === void 0 ? `no chunk follows offset ${preview(offset)}` : `the last chunk is ${preview(bytes.toString("latin1", last + 4, last + 8))} at offset ${String(last)}`}; expected an empty IEND chunk that ends the file`, { code: "EVIDENCE" });
1341
+ const first = types.indexOf(data);
1342
+ const final = types.lastIndexOf(data);
1343
+ const placed = positions.find((position, index) => types[index] === header && position !== 8);
1344
+ if (placed !== void 0) throw new CaptureError(`Invalid capture PNG chunk order: ${describeCaptureChunk(bytes, placed)}; expected one IHDR chunk, at offset 8`, { code: "EVIDENCE" });
1345
+ const unknown = positions.find((position, index) => ((bytes[position + 4] ?? 0) & 32) === 0 && ![
1346
+ header,
1347
+ palette,
1348
+ data,
1349
+ end
1350
+ ].includes(types[index] ?? 0));
1351
+ if (unknown !== void 0) throw new CaptureError(`Unsupported capture PNG chunk: critical ${describeCaptureChunk(bytes, unknown)}; expected a critical chunk to be IHDR, PLTE, IDAT, or IEND`, { code: "EVIDENCE" });
1352
+ const gap = types.findIndex((type, index) => index > first && index < final && type !== data);
1353
+ const resume = gap === -1 ? -1 : types.indexOf(data, gap);
1354
+ const resumed = positions[resume];
1355
+ const before = positions[resume - 1];
1356
+ if (resumed !== void 0 && before !== void 0) throw new CaptureError(`Invalid capture PNG chunk order: ${describeCaptureChunk(bytes, resumed)} follows ${preview(bytes.toString("latin1", before + 4, before + 8))} at offset ${String(before)}; expected every IDAT chunk in one consecutive run`, { code: "EVIDENCE" });
1357
+ return positions.flatMap((position, index) => {
912
1358
  const length = bytes.readUInt32BE(position);
913
- const end = position + 12 + length;
914
- if (end > bytes.length) throw new CaptureError("Truncated capture PNG chunk", { code: "EVIDENCE" });
915
- const name = bytes.toString("latin1", position + 4, position + 8);
916
- if (crc32(bytes.subarray(position + 4, end - 4)) >>> 0 !== bytes.readUInt32BE(end - 4)) throw new CaptureError("Capture PNG checksum differs", { code: "EVIDENCE" });
917
- if (name === "IEND") {
918
- if (length !== 0 || end !== bytes.length) throw new CaptureError("Invalid capture PNG closing chunk", { code: "EVIDENCE" });
919
- return chunks;
920
- }
921
- if (name === "IDAT" && length > 0) chunks.push(bytes.subarray(position + 8, end - 4));
922
- positions.push(end);
1359
+ return types[index] === data && length > 0 ? [bytes.subarray(position + 8, position + 8 + length)] : [];
1360
+ });
1361
+ }
1362
+ /**
1363
+ * Walks a PNG's checked chunks from one header and returns each header's offset, up to the closing chunk.
1364
+ *
1365
+ * @remarks
1366
+ * The walk reads at most `count` chunks, and never more than the bytes can hold, so an infinite or
1367
+ * very large count ends at the closing chunk or at a refusal. Each level halves the count, so the
1368
+ * call depth grows with the logarithm of the chunks the bytes can hold.
1369
+ *
1370
+ * @param bytes - The complete PNG
1371
+ * @param position - The offset of the first chunk header to read
1372
+ * @param count - The most chunks to read
1373
+ * @returns The offset of each chunk header read, in order
1374
+ * @throws Thrown for a truncated chunk, a bad checksum, or a closing chunk that is not empty and last.
1375
+ *
1376
+ * @example
1377
+ * ```ts
1378
+ * scanCaptureChunks(encodeCapturePicture({ width: 1, height: 1, pixels: Uint8Array.from([1, 2, 3]) }), 8, Infinity) // [8, 33, 57]
1379
+ * ```
1380
+ */
1381
+ function scanCaptureChunks(bytes, position, count) {
1382
+ const limit = Math.min(count, Math.floor(bytes.length / 12) + 1);
1383
+ if (limit >= 2) {
1384
+ const half = Math.ceil(limit / 2);
1385
+ const head = scanCaptureChunks(bytes, position, half);
1386
+ const last = head.at(-1);
1387
+ if (last === void 0 || bytes.toString("latin1", last + 4, last + 8) === "IEND") return head;
1388
+ return [...head, ...scanCaptureChunks(bytes, last + 12 + bytes.readUInt32BE(last), limit - half)];
923
1389
  }
924
- throw new CaptureError("Missing capture PNG closing chunk", { code: "EVIDENCE" });
1390
+ if (!(limit >= 1)) return [];
1391
+ if (!Number.isSafeInteger(position) || position < 8 || position + 12 > bytes.length) throw new CaptureError(`Truncated capture PNG: no 12-byte chunk frame fits at offset ${preview(position)} in ${String(bytes.length)} bytes; expected a whole offset from 8 with 12 bytes after it`, { code: "EVIDENCE" });
1392
+ const end = position + 12 + bytes.readUInt32BE(position);
1393
+ if (end > bytes.length) throw new CaptureError(`Truncated capture PNG chunk: ${describeCaptureChunk(bytes, position)} ends at byte ${String(end)}; expected it to end within the file's ${String(bytes.length)} bytes`, { code: "EVIDENCE" });
1394
+ const stored = bytes.readUInt32BE(end - 4);
1395
+ const computed = crc32(bytes.subarray(position + 4, end - 4)) >>> 0;
1396
+ if (computed !== stored) throw new CaptureError(`Capture PNG checksum differs: ${describeCaptureChunk(bytes, position)} stores ${stored.toString(16).padStart(8, "0")}; expected ${computed.toString(16).padStart(8, "0")}`, { code: "EVIDENCE" });
1397
+ if (bytes.toString("latin1", position + 4, position + 8) === "IEND" && (end !== position + 12 || end !== bytes.length)) throw new CaptureError(`Invalid capture PNG closing chunk: ${describeCaptureChunk(bytes, position)} ends at byte ${String(end)} of ${String(bytes.length)}; expected an empty IEND chunk that ends the file`, { code: "EVIDENCE" });
1398
+ return [position];
1399
+ }
1400
+ /**
1401
+ * Describes the PNG chunk whose header sits at an offset by its type, offset, and length.
1402
+ *
1403
+ * @remarks The type is untrusted file bytes, so it is JSON-encoded and length-capped.
1404
+ *
1405
+ * @param bytes - The complete PNG
1406
+ * @param position - The offset of the chunk header, with its 8 header bytes inside `bytes`
1407
+ * @returns The chunk's description for a refusal
1408
+ *
1409
+ * @example
1410
+ * ```ts
1411
+ * describeCaptureChunk(encodeCapturePicture(picture), 8) // '"IHDR" at offset 8 with length 13'
1412
+ * ```
1413
+ */
1414
+ function describeCaptureChunk(bytes, position) {
1415
+ return `${preview(bytes.toString("latin1", position + 4, position + 8))} at offset ${String(position)} with length ${String(bytes.readUInt32BE(position))}`;
925
1416
  }
926
1417
  /**
927
1418
  * Reads an image only after its opened file's size is inside the compressed-byte budget.
@@ -951,7 +1442,7 @@ function readCaptureImage(file) {
951
1442
  * ```
952
1443
  */
953
1444
  function requireCaptureImageSize(size) {
954
- if (!Number.isSafeInteger(size) || size < 0 || size > CAPTURE_PNG_LIMITS.bytes) throw new CaptureError("Capture PNG exceeds the file budget", { code: "EVIDENCE" });
1445
+ if (!Number.isSafeInteger(size) || size < 0 || size > CAPTURE_PNG_LIMITS.bytes) throw new CaptureError(`Capture PNG size is outside the file budget: ${preview(size)} bytes; expected a whole number of bytes from 0 to ${String(CAPTURE_PNG_LIMITS.bytes)}`, { code: "EVIDENCE" });
955
1446
  }
956
1447
  /**
957
1448
  * Reconstructs one filtered PNG scanline from its filter byte and the row above.
@@ -968,21 +1459,20 @@ function requireCaptureImageSize(size) {
968
1459
  * ```
969
1460
  */
970
1461
  function unfilterCaptureRow(filter, line, above, channels) {
971
- const bytes = [];
972
- for (const [index, value] of line.entries()) {
973
- const left = index >= channels ? bytes[index - channels] ?? 0 : 0;
974
- const up = above?.[index] ?? 0;
975
- const corner = index >= channels ? above?.[index - channels] ?? 0 : 0;
976
- const predicted = filter === 1 ? left : filter === 2 ? up : filter === 3 ? left + up >> 1 : filter === 4 ? predictCaptureByte(left, up, corner) : 0;
977
- bytes.push(value + predicted & 255);
978
- }
979
- return Uint8Array.from(bytes);
1462
+ const bytes = new Uint8Array(line.length);
1463
+ if (filter === 1) for (const index of line.keys()) bytes[index] = (line[index] ?? 0) + (index >= channels ? bytes[index - channels] ?? 0 : 0) & 255;
1464
+ else if (filter === 2) for (const index of line.keys()) bytes[index] = (line[index] ?? 0) + (above?.[index] ?? 0) & 255;
1465
+ else if (filter === 3) for (const index of line.keys()) bytes[index] = (line[index] ?? 0) + ((index >= channels ? bytes[index - channels] ?? 0 : 0) + (above?.[index] ?? 0) >> 1) & 255;
1466
+ else if (filter === 4) for (const index of line.keys()) bytes[index] = (line[index] ?? 0) + predictCaptureByte(index >= channels ? bytes[index - channels] ?? 0 : 0, above?.[index] ?? 0, index >= channels ? above?.[index - channels] ?? 0 : 0) & 255;
1467
+ else bytes.set(line);
1468
+ return bytes;
980
1469
  }
981
1470
  /**
982
1471
  * Inflates a PNG's compressed stream, refusing one that is corrupt or longer than declared.
983
1472
  *
984
1473
  * @param data - The concatenated data-chunk payloads
985
- * @param length - The inflated length the header's dimensions declare
1474
+ * @param length - The inflated length the header's dimensions declare, a whole number from 1 to
1475
+ * `Number.MAX_SAFE_INTEGER`; any other value gives an unspecified result that might throw
986
1476
  * @returns The inflated scanlines
987
1477
  * @throws Thrown when the stream is not valid deflate data or inflates past `length`.
988
1478
  *
@@ -995,7 +1485,7 @@ function inflateCaptureStream(data, length) {
995
1485
  try {
996
1486
  return inflateSync(data, { maxOutputLength: length });
997
1487
  } catch (error) {
998
- throw new CaptureError("Capture PNG stream is corrupt or longer than declared", {
1488
+ throw new CaptureError(`Capture PNG stream is corrupt or longer than declared: ${preview(isError(error) ? error.message : error)} in ${String(data.length)} compressed bytes; expected a zlib stream that inflates to at most ${preview(length)} bytes`, {
999
1489
  code: "EVIDENCE",
1000
1490
  cause: error
1001
1491
  });
@@ -1020,30 +1510,48 @@ function inflateCaptureStream(data, length) {
1020
1510
  */
1021
1511
  function decodeCapturePicture(bytes) {
1022
1512
  requireCaptureImageSize(bytes.length);
1023
- if (bytes.length < 33 || !matchesCaptureSignature(bytes) || bytes.toString("latin1", 12, 16) !== "IHDR" || bytes.readUInt32BE(8) !== 13) throw new CaptureError("Invalid capture PNG header", { code: "EVIDENCE" });
1513
+ if (bytes.length < 33 || !matchesCaptureSignature(bytes) || bytes.toString("latin1", 12, 16) !== "IHDR" || bytes.readUInt32BE(8) !== 13) throw new CaptureError(`Invalid capture PNG header: ${bytes.length < 33 ? `the file is ${String(bytes.length)} bytes` : !matchesCaptureSignature(bytes) ? `the signature is ${bytes.toString("hex", 0, 8)}` : `the first chunk is ${preview(bytes.toString("latin1", 12, 16))} with length ${String(bytes.readUInt32BE(8))}`}; expected at least 33 bytes that open with the signature ${Buffer.from(CAPTURE_PNG_SIGNATURE).toString("hex")} and an IHDR chunk with length 13`, { code: "EVIDENCE" });
1514
+ scanCaptureChunks(bytes, 8, 1);
1024
1515
  const width = bytes.readUInt32BE(16);
1025
1516
  const height = bytes.readUInt32BE(20);
1026
1517
  const channels = bytes[25] === 6 ? 4 : bytes[25] === 2 ? 3 : bytes[25] === 4 ? 2 : bytes[25] === 0 ? 1 : 0;
1027
1518
  const gray = bytes[25] === 0 || bytes[25] === 4;
1028
- if (width === 0 || height === 0 || channels === 0 || bytes[24] !== 8 || bytes[26] !== 0 || bytes[27] !== 0 || bytes[28] !== 0) throw new CaptureError("Unsupported capture PNG encoding", { code: "EVIDENCE" });
1519
+ if (channels === 0 || bytes[24] !== 8 || bytes[26] !== 0 || bytes[27] !== 0 || bytes[28] !== 0) throw new CaptureError(`Unsupported capture PNG encoding: bit depth ${String(bytes[24])}, colour type ${String(bytes[25])}, compression ${String(bytes[26])}, filter ${String(bytes[27])}, interlace ${String(bytes[28])}; expected bit depth 8, colour type 0, 2, 4, or 6, compression 0, filter 0, and interlace 0`, { code: "EVIDENCE" });
1520
+ const size = `${String(width)} × ${String(height)}`;
1521
+ if (width === 0 || height === 0) throw new CaptureError(`Invalid capture PNG dimensions: ${size}; expected a width and a height of at least 1`, { code: "EVIDENCE" });
1029
1522
  const stride = width * channels;
1030
1523
  const length = (stride + 1) * height;
1031
- if (!Number.isSafeInteger(length)) throw new CaptureError("Invalid capture PNG dimensions", { code: "EVIDENCE" });
1032
- if (width * height > CAPTURE_PNG_LIMITS.pixels) throw new CaptureError("Capture PNG exceeds the pixel budget", { code: "EVIDENCE" });
1033
- if (width > CAPTURE_PNG_LIMITS.side || height > CAPTURE_PNG_LIMITS.side) throw new CaptureError("Capture PNG exceeds the dimension budget", { code: "EVIDENCE" });
1524
+ if (!Number.isSafeInteger(length)) throw new CaptureError(`Invalid capture PNG dimensions: ${size} at ${String(channels)} bytes per pixel; expected scanlines of at most ${String(Number.MAX_SAFE_INTEGER)} bytes in all`, { code: "EVIDENCE" });
1525
+ if (width * height > CAPTURE_PNG_LIMITS.pixels) throw new CaptureError(`Capture PNG exceeds the pixel budget: ${size} is ${String(width * height)} pixels; expected at most ${String(CAPTURE_PNG_LIMITS.pixels)} pixels`, { code: "EVIDENCE" });
1526
+ if (width > CAPTURE_PNG_LIMITS.side || height > CAPTURE_PNG_LIMITS.side) throw new CaptureError(`Capture PNG exceeds the dimension budget: ${size}; expected at most ${String(CAPTURE_PNG_LIMITS.side)} pixels per side`, { code: "EVIDENCE" });
1034
1527
  const chunks = readCaptureChunks(bytes);
1035
1528
  const raw = inflateCaptureStream(chunks.length === 1 && chunks[0] !== void 0 ? chunks[0] : Buffer.concat(chunks), length);
1036
- if (raw.length !== length) throw new CaptureError("Capture PNG scanline length differs", { code: "EVIDENCE" });
1037
- const rows = [];
1529
+ if (raw.length !== length) throw new CaptureError(`Capture PNG scanline length differs: the stream inflates to ${String(raw.length)} bytes; expected ${String(length)} bytes for ${size} at ${String(channels)} bytes per pixel and one filter byte per row`, { code: "EVIDENCE" });
1530
+ const rows = new Uint8Array(stride * height);
1038
1531
  for (const row of new Array(height).keys()) {
1039
1532
  const filter = raw[row * (stride + 1)];
1040
- if (filter === void 0 || filter > 4) throw new CaptureError("Unsupported capture PNG filter", { code: "EVIDENCE" });
1041
- rows.push(unfilterCaptureRow(filter, raw.subarray(row * (stride + 1) + 1, (row + 1) * (stride + 1)), rows[row - 1], channels));
1533
+ if (filter === void 0 || filter > 4) throw new CaptureError(`Unsupported capture PNG filter: type ${String(filter)} on row ${String(row)}; expected a type from 0 to 4`, { code: "EVIDENCE" });
1534
+ const line = raw.subarray(row * (stride + 1) + 1, (row + 1) * (stride + 1));
1535
+ rows.set(filter === 0 ? line : unfilterCaptureRow(filter, line, row === 0 ? void 0 : rows.subarray((row - 1) * stride, row * stride), channels), row * stride);
1536
+ }
1537
+ if (channels === 3) return {
1538
+ width,
1539
+ height,
1540
+ pixels: rows
1541
+ };
1542
+ const pixels = new Uint8Array(width * height * 3);
1543
+ const columns = Array.from({ length: width }, (_, column) => column);
1544
+ for (const row of new Array(height).keys()) for (const column of columns) {
1545
+ const source = (row * width + column) * channels;
1546
+ const target = (row * width + column) * 3;
1547
+ pixels[target] = rows[source] ?? 0;
1548
+ pixels[target + 1] = rows[source + (gray ? 0 : 1)] ?? 0;
1549
+ pixels[target + 2] = rows[source + (gray ? 0 : 2)] ?? 0;
1042
1550
  }
1043
1551
  return {
1044
1552
  width,
1045
1553
  height,
1046
- pixels: Uint8Array.from({ length: width * height * 3 }, (_, index) => rows[Math.floor(index / (width * 3))]?.[Math.floor(index % (width * 3) / 3) * channels + (gray ? 0 : index % 3)] ?? 0)
1554
+ pixels
1047
1555
  };
1048
1556
  }
1049
1557
  /**
@@ -1092,7 +1600,8 @@ function encodeCaptureChunk(name, data) {
1092
1600
  * @param picture - The complete RGB pixel buffer
1093
1601
  * @param compressed - If `true`, compresses scanlines; if `false`, stores them in the deflate stream. Default: `true`.
1094
1602
  * @returns A PNG file
1095
- * @throws Thrown when dimensions and pixel length disagree.
1603
+ * @throws Thrown when a dimension is not a whole number of at least 1, or when the pixel length is
1604
+ * not `width * height * 3`.
1096
1605
  *
1097
1606
  * @example
1098
1607
  * ```ts
@@ -1121,11 +1630,78 @@ function encodeCapturePicture(picture, compressed = true) {
1121
1630
  ]);
1122
1631
  }
1123
1632
  /**
1633
+ * Sums a run of samples three bytes apart, one channel of consecutive RGB pixels.
1634
+ *
1635
+ * @remarks
1636
+ * The caller bounds the run: the call reads one sample per column, inside the bytes or not, so a
1637
+ * count that is not above 0 sums nothing and a fractional count reads its ceiling. Each sample reads
1638
+ * `pixels[index] ?? 0` at the index the call computes, so an index outside the bytes, a fractional
1639
+ * index, or a `NaN` index reads 0. For whole-number arguments, the sum equals the direct sum of
1640
+ * those samples where every number the call computes from its arguments is a safe integer, each
1641
+ * sample index among them.
1642
+ *
1643
+ * @param pixels - The source RGB bytes
1644
+ * @param start - The index of the first sample
1645
+ * @param columns - The number of samples to sum
1646
+ * @returns The sum, reading an index outside the bytes or a fractional index as 0
1647
+ * @throws Thrown as an `EVIDENCE` capture error when `columns` is `Infinity`.
1648
+ *
1649
+ * @example
1650
+ * ```ts
1651
+ * sumCaptureRow(Uint8Array.from([1, 0, 0, 2, 0, 0, 3]), 0, 3) // 6
1652
+ * ```
1653
+ */
1654
+ function sumCaptureRow(pixels, start, columns) {
1655
+ if (columns > 8) {
1656
+ if (columns === Infinity) throw new CaptureError("Capture sum columns must be a finite sample count, not Infinity", { code: "EVIDENCE" });
1657
+ const half = Math.ceil(columns / 2);
1658
+ return sumCaptureRow(pixels, start, half) + sumCaptureRow(pixels, start + half * 3, columns - half);
1659
+ }
1660
+ return (columns > 0 ? pixels[start] ?? 0 : 0) + (columns > 1 ? pixels[start + 3] ?? 0 : 0) + (columns > 2 ? pixels[start + 6] ?? 0 : 0) + (columns > 3 ? pixels[start + 9] ?? 0 : 0) + (columns > 4 ? pixels[start + 12] ?? 0 : 0) + (columns > 5 ? pixels[start + 15] ?? 0 : 0) + (columns > 6 ? pixels[start + 18] ?? 0 : 0) + (columns > 7 ? pixels[start + 21] ?? 0 : 0);
1661
+ }
1662
+ /**
1663
+ * Sums one channel of a picture over a block of source rows.
1664
+ *
1665
+ * @remarks
1666
+ * Source row `top + row` starts its block at `(top + row) * picture.width * 3 + left`, and each row
1667
+ * contributes `columns` samples through `sumCaptureRow`. The caller bounds the block: the call reads
1668
+ * `rows × columns` samples, inside the bytes or not, so a row count that is not above 0 sums nothing
1669
+ * and a fractional row count reads its ceiling. For whole-number arguments, the sum equals the
1670
+ * direct sum of those samples where every number the call computes from its arguments is a safe
1671
+ * integer, each row number, each intermediate sum and product of a row start, and each sample index
1672
+ * among them.
1673
+ *
1674
+ * @param picture - The source RGB picture
1675
+ * @param top - The block's first source row
1676
+ * @param left - The byte offset of the block's first sample inside a row, its channel included
1677
+ * @param row - The first row to sum, counted from `top`
1678
+ * @param rows - The number of rows to sum
1679
+ * @param columns - The number of samples to sum in each row
1680
+ * @returns The block's sum
1681
+ * @throws Thrown as an `EVIDENCE` capture error when `rows` is `Infinity`, or when `columns` is
1682
+ * `Infinity` and the block reads a row.
1683
+ *
1684
+ * @example
1685
+ * ```ts
1686
+ * sumCaptureBlock({ width: 2, height: 2, pixels: Uint8Array.from([1, 0, 0, 2, 0, 0, 3, 0, 0, 4, 0, 0]) }, 0, 0, 0, 2, 2) // 10
1687
+ * ```
1688
+ */
1689
+ function sumCaptureBlock(picture, top, left, row, rows, columns) {
1690
+ if (rows > 2) {
1691
+ if (rows === Infinity) throw new CaptureError("Capture sum rows must be a finite row count, not Infinity", { code: "EVIDENCE" });
1692
+ const half = Math.ceil(rows / 2);
1693
+ return sumCaptureBlock(picture, top, left, row, half, columns) + sumCaptureBlock(picture, top, left, row + half, rows - half, columns);
1694
+ }
1695
+ return (rows > 0 ? sumCaptureRow(picture.pixels, (top + row) * picture.width * 3 + left, columns) : 0) + (rows > 1 ? sumCaptureRow(picture.pixels, (top + (row + 1)) * picture.width * 3 + left, columns) : 0);
1696
+ }
1697
+ /**
1124
1698
  * Scales a picture with an exact area average and clips its displayed height.
1125
1699
  *
1126
1700
  * @param picture - The source RGB picture
1127
- * @param factor - The integer reduction factor
1128
- * @param limit - The maximum displayed height
1701
+ * @param factor - The reduction factor, a whole number of at least 1; any other value gives an
1702
+ * unspecified result that might throw
1703
+ * @param limit - The maximum displayed height, a whole number of at least 1; any other value gives
1704
+ * an unspecified result that might throw
1129
1705
  * @returns A separately owned scaled picture
1130
1706
  *
1131
1707
  * @example
@@ -1136,23 +1712,24 @@ function encodeCapturePicture(picture, compressed = true) {
1136
1712
  function shrinkCapturePicture(picture, factor, limit) {
1137
1713
  const width = Math.max(1, Math.ceil(picture.width / factor));
1138
1714
  const height = Math.min(Math.max(1, Math.ceil(picture.height / factor)), limit);
1139
- const span = Array.from({ length: Math.ceil(Math.min(factor, Math.max(picture.width, picture.height))) }, (_, index) => index);
1715
+ const reach = Array.from({ length: Math.ceil(Math.min(factor, Math.max(picture.width, picture.height))) }).length;
1716
+ const pixels = new Uint8Array(Math.min(Math.max(Math.trunc(width * height * 3) || 0, 0), Number.MAX_SAFE_INTEGER));
1717
+ const offsets = Array.from({ length: Math.min(width * 3, pixels.length) }, (_, offset) => offset);
1718
+ const lines = pixels.length === 0 ? 0 : Math.ceil(pixels.length / (width * 3));
1719
+ for (const y of new Array(lines).keys()) {
1720
+ const rows = Math.min(factor, picture.height - y * factor);
1721
+ for (const offset of offsets) {
1722
+ const index = y * width * 3 + offset;
1723
+ if (index >= pixels.length) break;
1724
+ const x = Math.floor(offset / 3);
1725
+ const columns = Math.min(factor, picture.width - x * factor);
1726
+ pixels[index] = Math.round(sumCaptureBlock(picture, y * factor, x * Math.ceil(factor) * 3 + offset % 3, 0, rows > 0 ? Math.min(reach, Math.ceil(rows)) : 0, columns > 0 ? Math.min(reach, Math.ceil(columns)) : 0) / (rows * columns));
1727
+ }
1728
+ }
1140
1729
  return {
1141
1730
  width,
1142
1731
  height,
1143
- pixels: Uint8Array.from({ length: width * height * 3 }, (_, index) => {
1144
- const channel = index % 3;
1145
- const x = Math.floor(index / 3) % width;
1146
- const y = Math.floor(index / 3 / width);
1147
- const rows = Math.min(factor, picture.height - y * factor);
1148
- const columns = Math.min(factor, picture.width - x * factor);
1149
- const sum = span.reduce((total, row) => {
1150
- if (row >= rows) return total;
1151
- const start = (y * factor + row) * picture.width * 3 + x * Math.ceil(factor) * 3 + channel;
1152
- return span.reduce((block, column) => column >= columns ? block : block + (picture.pixels[start + column * 3] ?? 0), total);
1153
- }, 0);
1154
- return Math.round(sum / (rows * columns));
1155
- })
1732
+ pixels
1156
1733
  };
1157
1734
  }
1158
1735
  /**
@@ -1162,7 +1739,10 @@ function shrinkCapturePicture(picture, factor, limit) {
1162
1739
  * @param vertical - If `true`, stacks rows; if `false`, places cells side by side
1163
1740
  * @param gap - The space between source pictures. Default: 6.
1164
1741
  * @returns A separately owned composite
1165
- * @throws Thrown for an empty picture selection.
1742
+ * @throws Thrown for an empty picture selection, with the `USAGE` condition.
1743
+ * @throws Thrown with the `EVIDENCE` condition when a width, a height, or the gap is not a whole
1744
+ * number from 0 to `CAPTURE_PNG_LIMITS.side`, or when the composite exceeds that side or the
1745
+ * `CAPTURE_PNG_LIMITS.pixels` budget.
1166
1746
  *
1167
1747
  * @example
1168
1748
  * ```ts
@@ -1171,42 +1751,164 @@ function shrinkCapturePicture(picture, factor, limit) {
1171
1751
  */
1172
1752
  function composeCapturePictures(pictures, vertical, gap = 6) {
1173
1753
  if (pictures.length === 0) throw new CaptureError("Empty contact-sheet picture selection", { code: "USAGE" });
1174
- const width = vertical ? Math.max(...pictures.map((entry) => entry.width)) : pictures.reduce((sum, entry) => sum + entry.width, 0) + gap * (pictures.length - 1);
1175
- const height = vertical ? pictures.reduce((sum, entry) => sum + entry.height, 0) + gap * (pictures.length - 1) : Math.max(...pictures.map((entry) => entry.height));
1176
- const offsets = pictures.map((_picture, position) => pictures.slice(0, position).reduce((sum, entry) => sum + (vertical ? entry.height : entry.width) + gap, 0));
1754
+ const { side, pixels: budget } = CAPTURE_PNG_LIMITS;
1755
+ const faults = [...pictures.flatMap((picture, position) => ["width", "height"].flatMap((axis) => Number.isSafeInteger(picture[axis]) && picture[axis] >= 0 && picture[axis] <= side ? [] : [`pictures[${String(position)}].${axis} is ${preview(picture[axis])}`])), ...Number.isSafeInteger(gap) && gap >= 0 && gap <= side ? [] : [`gap is ${preview(gap)}`]];
1756
+ const { width, height } = computeCaptureComposite(pictures, vertical, gap);
1757
+ if (faults.length > 0 || !matchesCaptureLimits({
1758
+ width,
1759
+ height
1760
+ })) throw new CaptureError(`Contact-sheet geometry is out of range: ${faults.length === 0 ? `composite is ${String(width)} × ${String(height)}` : [...faults.slice(0, 16), ...faults.length > 16 ? [`… ${String(faults.length - 16)} more`] : []].join("; ")}; expected whole numbers from 0 to ${String(side)} for every width, height, and gap, and a composite of at most ${String(side)} per side and ${String(budget)} pixels`, { code: "EVIDENCE" });
1761
+ const ends = [];
1762
+ for (const picture of pictures) ends.push((ends.at(-1) ?? 0) + (vertical ? picture.height : picture.width) + gap);
1763
+ const spans = pictures.map((picture, position) => ({
1764
+ picture,
1765
+ start: ends[position - 1] ?? 0,
1766
+ end: Math.min(ends[position] ?? 0, vertical ? height : width)
1767
+ })).filter((span) => span.end > span.start);
1768
+ const pixels = new Uint8Array(width * height * 3);
1769
+ if (vertical) {
1770
+ for (const { picture, start, end } of spans) for (const row of new Array(Math.max(0, end - start)).keys()) {
1771
+ const copied = row < picture.height ? picture.width : 0;
1772
+ const target = (start + row) * width * 3;
1773
+ pixels.set(picture.pixels.subarray(row * picture.width * 3, (row * picture.width + copied) * 3), target);
1774
+ pixels.fill(128, target + copied * 3, target + width * 3);
1775
+ }
1776
+ return {
1777
+ width,
1778
+ height,
1779
+ pixels
1780
+ };
1781
+ }
1782
+ for (const row of new Array(height).keys()) for (const { picture, start, end } of spans) {
1783
+ const copied = row < picture.height ? Math.min(picture.width, end - start) : 0;
1784
+ const target = (row * width + start) * 3;
1785
+ pixels.set(picture.pixels.subarray(row * picture.width * 3, (row * picture.width + copied) * 3), target);
1786
+ pixels.fill(128, target + copied * 3, (row * width + end) * 3);
1787
+ }
1177
1788
  return {
1178
1789
  width,
1179
1790
  height,
1180
- pixels: Uint8Array.from({ length: width * height * 3 }, (_value, index) => {
1181
- const x = Math.floor(index % (width * 3) / 3);
1182
- const y = Math.floor(index / (width * 3));
1183
- const position = offsets.findLastIndex((offset) => offset <= (vertical ? y : x));
1184
- const picture = pictures[position];
1185
- const offset = offsets[position];
1186
- if (picture === void 0 || offset === void 0) return 128;
1187
- const column = vertical ? x : x - offset;
1188
- const row = vertical ? y - offset : y;
1189
- return column < picture.width && row < picture.height ? picture.pixels[(row * picture.width + column) * 3 + index % 3] ?? 0 : 128;
1190
- })
1791
+ pixels
1792
+ };
1793
+ }
1794
+ /**
1795
+ * Computes the width and height of the composite that `composeCapturePictures` builds from
1796
+ * pictures of these sizes.
1797
+ *
1798
+ * @param pictures - The ordered source sizes
1799
+ * @param vertical - If `true`, stacks them; if `false`, places them side by side
1800
+ * @param gap - The space between source pictures. Default: 6.
1801
+ * @returns The composite's width and height, each 0 for no pictures
1802
+ *
1803
+ * @example
1804
+ * ```ts
1805
+ * computeCaptureComposite([{ width: 4, height: 2 }, { width: 3, height: 5 }], false) // { width: 13, height: 5 }
1806
+ * ```
1807
+ */
1808
+ function computeCaptureComposite(pictures, vertical, gap = 6) {
1809
+ const span = gap * Math.max(0, pictures.length - 1);
1810
+ return vertical ? {
1811
+ width: pictures.reduce((widest, entry) => Math.max(widest, entry.width), 0),
1812
+ height: pictures.reduce((sum, entry) => sum + entry.height, 0) + span
1813
+ } : {
1814
+ width: pictures.reduce((sum, entry) => sum + entry.width, 0) + span,
1815
+ height: pictures.reduce((tallest, entry) => Math.max(tallest, entry.height), 0)
1191
1816
  };
1192
1817
  }
1193
1818
  /**
1819
+ * Checks whether a picture size fits `CAPTURE_PNG_LIMITS`, per side and in pixels.
1820
+ *
1821
+ * @param picture - The size to check
1822
+ * @returns True if neither side passes `CAPTURE_PNG_LIMITS.side` and the area does not pass
1823
+ * `CAPTURE_PNG_LIMITS.pixels`; false otherwise
1824
+ *
1825
+ * @example
1826
+ * ```ts
1827
+ * matchesCaptureLimits({ width: 13040, height: 1636 }) // false
1828
+ * ```
1829
+ */
1830
+ function matchesCaptureLimits(picture) {
1831
+ const { side, pixels } = CAPTURE_PNG_LIMITS;
1832
+ return picture.width <= side && picture.height <= side && picture.width * picture.height <= pixels;
1833
+ }
1834
+ /**
1835
+ * Splits contact-sheet rows into consecutive pages of at most `size` rows whose stacked composite
1836
+ * fits `CAPTURE_PNG_LIMITS`.
1837
+ *
1838
+ * @remarks
1839
+ * A page takes each next row while it holds fewer than `size` rows and the stacked composite,
1840
+ * with `gap` between rows, still fits; otherwise the row opens the next page.
1841
+ *
1842
+ * @param rows - The ordered rows, each with its composite width and height
1843
+ * @param size - The most rows a page holds, a whole number of at least 1; any other value gives an
1844
+ * unspecified result that might throw
1845
+ * @param gap - The space between stacked rows
1846
+ * @returns The pages, in order
1847
+ * @throws Thrown with the `USAGE` condition when one row alone does not fit `CAPTURE_PNG_LIMITS`,
1848
+ * naming its composite, the limits, and the narrower `--variant` selection that recovers.
1849
+ *
1850
+ * @example
1851
+ * ```ts
1852
+ * splitCaptureSheets([{ width: 13040, height: 400 }, { width: 13040, height: 400 }], 4, 12).length // 1
1853
+ * ```
1854
+ */
1855
+ function splitCaptureSheets(rows, size, gap) {
1856
+ const wide = rows.find((row) => !matchesCaptureLimits(row));
1857
+ if (wide !== void 0) throw new CaptureError(`Contact-sheet row is out of range: composite is ${String(wide.width)} × ${String(wide.height)}; expected at most ${String(CAPTURE_PNG_LIMITS.side)} per side and ${String(CAPTURE_PNG_LIMITS.pixels)} pixels; select fewer variants with --variant`, { code: "USAGE" });
1858
+ const marks = [];
1859
+ for (const [index, row] of rows.entries()) {
1860
+ const last = marks.at(-1);
1861
+ const joined = last === void 0 ? void 0 : {
1862
+ first: last.first,
1863
+ width: Math.max(last.width, row.width),
1864
+ height: last.height + gap + row.height
1865
+ };
1866
+ marks.push(joined !== void 0 && index - joined.first < size && matchesCaptureLimits(joined) ? joined : {
1867
+ first: index,
1868
+ width: row.width,
1869
+ height: row.height
1870
+ });
1871
+ }
1872
+ const starts = marks.flatMap((mark, index) => mark.first === index ? [index] : []);
1873
+ return starts.map((first, page) => rows.slice(first, starts[page + 1] ?? rows.length));
1874
+ }
1875
+ /**
1194
1876
  * Reads the process id that a request file, or its temporary sibling, names.
1195
1877
  *
1196
1878
  * @param name - A file name from the request directory
1197
- * @returns The positive process id the name carries, or `undefined` for any other name
1879
+ * @returns The process id the name carries, from 1 to `CAPTURE_PID_LIMIT`, or `undefined` for any
1880
+ * other name
1198
1881
  *
1199
1882
  * @example
1200
1883
  * ```ts
1201
1884
  * readCaptureRequestOwner('journey-selection-4242.json') // 4242
1202
1885
  * readCaptureRequestOwner('journey-selection-4242.json.tmp') // 4242
1203
1886
  * readCaptureRequestOwner('journey-selection.json') // undefined
1887
+ * readCaptureRequestOwner('journey-selection-4294967296.json') // undefined
1204
1888
  * ```
1205
1889
  */
1206
1890
  function readCaptureRequestOwner(name) {
1207
1891
  const match = new RegExp(`^${CAPTURE_REQUEST_PREFIX}-(\\d+)\\.json(?:\\.tmp)?$`, "u").exec(name);
1208
1892
  const pid = Number(match?.[1]);
1209
- return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
1893
+ return Number.isSafeInteger(pid) && pid > 0 && pid <= 2147483647 ? pid : void 0;
1894
+ }
1895
+ /**
1896
+ * Describes the request holders that keep a workspace busy, naming apart those the host could not inspect.
1897
+ *
1898
+ * @param holders - The holders `CaptureInvocationInterface.holders` lists
1899
+ * @param directory - The workspace-relative request directory that holds their request files
1900
+ * @returns The running holders' sentence, then the uninspected holders' sentence with its correction
1901
+ *
1902
+ * @example
1903
+ * ```ts
1904
+ * describeCaptureHolders([{ pid: 4242, inspected: true }], 'tmp/capture')
1905
+ * // 'Another runner holds this workspace (process 4242)'
1906
+ * ```
1907
+ */
1908
+ function describeCaptureHolders(holders, directory) {
1909
+ const running = holders.filter((holder) => holder.inspected).map((holder) => holder.pid);
1910
+ const unknown = holders.filter((holder) => !holder.inspected).map((holder) => holder.pid);
1911
+ return [...running.length === 0 ? [] : [`Another runner holds this workspace (process ${running.join(", ")})`], ...unknown.length === 0 ? [] : [`Request holder process ${unknown.join(", ")} could not be inspected; confirm no capture process or surviving child is running before deleting its request file in ${directory}`]].join(". ");
1210
1912
  }
1211
1913
  /**
1212
1914
  * Resolves a path to the slash-separated form the evidence documents store, relative to a root.
@@ -1321,6 +2023,19 @@ function resolveCaptureVariants(selected, projects) {
1321
2023
  return variants;
1322
2024
  }
1323
2025
  /**
2026
+ * Collects the owner selectors the projects' owner tags declare, once each, in tag order.
2027
+ *
2028
+ * @param projects - The discovered host projects
2029
+ * @returns Each tagged owner selector, ancestors included where the wrapper tags them
2030
+ * @example
2031
+ * ```ts
2032
+ * collectCaptureOwners(projects) // ['pages', 'pages:mail'] for owner:pages and owner:pages:mail tags
2033
+ * ```
2034
+ */
2035
+ function collectCaptureOwners(projects) {
2036
+ return [...new Set(projects.flatMap((project) => project.tags))].filter((tag) => tag.startsWith(CAPTURE_OWNER_PREFIX)).map((tag) => tag.slice(CAPTURE_OWNER_PREFIX.length));
2037
+ }
2038
+ /**
1324
2039
  * Refuses unknown command selections from the wrapper before authenticating disk evidence.
1325
2040
  * @example
1326
2041
  * ```ts
@@ -1328,7 +2043,7 @@ function resolveCaptureVariants(selected, projects) {
1328
2043
  * ```
1329
2044
  */
1330
2045
  function requireCaptureSelection(selector, variants, projects, outputs = [], portfolio) {
1331
- const fault = describeCaptureSelectorFault(selector, [...new Set(projects.flatMap((project) => [...project.tags.filter((tag) => tag.startsWith(CAPTURE_OWNER_PREFIX)).map((tag) => tag.slice(CAPTURE_OWNER_PREFIX.length)), ...project.standalone.map((entry) => entry.portfolio)]))]);
2046
+ const fault = describeCaptureSelectorFault(selector, [...new Set(projects.flatMap((project) => [...collectCaptureOwners([project]), ...project.standalone.map((entry) => entry.portfolio)]))]);
1332
2047
  if (fault !== void 0) throw new CaptureError(fault, { code: "USAGE" });
1333
2048
  const portfolios = [...new Set(projects.flatMap((project) => [...project.portfolios, ...project.standalone].map((entry) => entry.portfolio)))];
1334
2049
  if (portfolio !== void 0 && !portfolios.includes(portfolio)) throw new CaptureError(describeCaptureFault("--portfolio", portfolio, "a portfolio declared by the wrapper", portfolios), { code: "USAGE" });
@@ -1336,6 +2051,27 @@ function requireCaptureSelection(selector, variants, projects, outputs = [], por
1336
2051
  for (const variant of variants) if (!declared.includes(variant)) throw new CaptureError(describeCaptureFault("--variant", variant, "a variant declared by the wrapper or registry output population", declared), { code: "USAGE" });
1337
2052
  }
1338
2053
  /**
2054
+ * Picks the standalone portfolio root a selection names by its selector or its portfolio.
2055
+ *
2056
+ * @remarks
2057
+ * A standalone root has no stamping route and no registry refresh, so a selection reads it only
2058
+ * when it names the root's portfolio. Every other selection reads the primary directory.
2059
+ *
2060
+ * @param roots - The wrapper's standalone roots
2061
+ * @param selector - The selected owner selector
2062
+ * @param portfolio - The selected portfolio, when the selection names one
2063
+ * @returns The named standalone root, or `undefined` for a primary selection
2064
+ * @example
2065
+ * ```ts
2066
+ * const vue = { portfolio: 'vue', directory: 'tmp/captures/vue', scoped: false }
2067
+ * resolveCaptureStandalone([vue], 'vue:home') // vue
2068
+ * resolveCaptureStandalone([vue], 'pages:mail') // undefined
2069
+ * ```
2070
+ */
2071
+ function resolveCaptureStandalone(roots, selector, portfolio) {
2072
+ return roots.find((root) => portfolio === root.portfolio || selector === root.portfolio || selector.startsWith(`${root.portfolio}:`));
2073
+ }
2074
+ /**
1339
2075
  * Reads output variant candidates without authenticating or accepting registry evidence.
1340
2076
  * @remarks Missing, unreadable, or malformed registries supply no candidate hints; the integrity engine still authenticates every accepted read.
1341
2077
  * @example
@@ -1355,7 +2091,7 @@ function readCaptureVariants(root, file) {
1355
2091
  * spaces and quotes. An exact case adds `-t` with the anchored pattern for that case and the
1356
2092
  * final case, so the final case still writes the run record.
1357
2093
  *
1358
- * @param options - The entry, wrapper, report, projects, tag filter, and optional exact case and mode
2094
+ * @param options - The entry, wrapper, report and progress files, projects, tag filter, bail switch, and optional exact case and mode
1359
2095
  * @returns The arguments after the Node executable
1360
2096
  *
1361
2097
  * @example
@@ -1364,6 +2100,7 @@ function readCaptureVariants(root, file) {
1364
2100
  * entry: '/repo/node_modules/vitest/vitest.mjs',
1365
2101
  * config: '/repo/vite.journey.config.ts',
1366
2102
  * report: '/repo/tmp/units/runs/a/journey-selected.json',
2103
+ * progress: '/repo/tmp/units/runs/a/selected.progress.jsonl',
1367
2104
  * projects: ['journey:light-390'],
1368
2105
  * filter: 'owner:pages:mail',
1369
2106
  * final: 'closes the run',
@@ -1382,13 +2119,13 @@ function buildCaptureArguments(options) {
1382
2119
  "--configLoader",
1383
2120
  "runner",
1384
2121
  "--no-cache",
1385
- "--bail=1",
2122
+ ...options.bail === false ? [] : ["--bail=1"],
1386
2123
  "--reporter=dot",
1387
2124
  "--reporter=json",
1388
2125
  `--outputFile.json=${options.report}`,
2126
+ `--outputFile.progress=${options.progress}`,
1389
2127
  ...options.projects.flatMap((project) => ["--project", project]),
1390
- "--tags-filter",
1391
- options.filter,
2128
+ ...options.filter === void 0 ? [] : ["--tags-filter", options.filter],
1392
2129
  ...options.case === void 0 ? [] : ["-t", `^(?:${[options.case, options.final].map((name) => escapeCapturePattern((options.titles?.[name] ?? [name]).join(separator))).join("|")})$`]
1393
2130
  ];
1394
2131
  }
@@ -1396,7 +2133,7 @@ function buildCaptureArguments(options) {
1396
2133
  * Reads the installed workspace Vitest's exact title separator, refusing unsupported majors.
1397
2134
  * @example
1398
2135
  * ```ts
1399
- * readCaptureSeparator('/workspace/node_modules/vitest/vitest.mjs') // ' ' on Vitest 4
2136
+ * readCaptureSeparator('/workspace/node_modules/vitest/vitest.mjs') // ' > ' on Vitest 5
1400
2137
  * ```
1401
2138
  */
1402
2139
  function readCaptureSeparator(entry) {
@@ -1408,9 +2145,8 @@ function readCaptureSeparator(entry) {
1408
2145
  });
1409
2146
  const manifest = loaded.value;
1410
2147
  const version = isRecord(manifest) ? manifest.version : void 0;
1411
- if (typeof version === "string" && version.split(".")[0] === "4") return " ";
1412
2148
  if (typeof version === "string" && version.split(".")[0] === "5") return " > ";
1413
- throw new CaptureError(describeCaptureFault("vitest.version", version, "a supported installed Vitest major", ["4", "5"]), { code: "HOST" });
2149
+ throw new CaptureError(describeCaptureFault("vitest.version", version, "a supported installed Vitest major", ["5"]), { code: "HOST" });
1414
2150
  }
1415
2151
  /**
1416
2152
  * Reads original title segments from the accepted registry's authenticated JSON reporter files.
@@ -1418,37 +2154,54 @@ function readCaptureSeparator(entry) {
1418
2154
  * @param file - The accepted registry path
1419
2155
  * @param selector - The optional owner selector that bounds the case candidates
1420
2156
  * @returns Exact case names mapped to their original title segments within the selected owners
2157
+ * @throws Thrown with the removal of the registry and the manifest and lookup journal beside it,
2158
+ * and the refresh commands, when the registry declares another protocol version; thrown as a
2159
+ * `REGISTRY` capture error when the registry or a reporter it names is absent, unreadable, or fails
2160
+ * authentication.
1421
2161
  * @example
1422
2162
  * ```ts
1423
2163
  * const titles = readCaptureTitles('/workspace', '/workspace/tmp/captures/states/registry.json')
1424
2164
  * ```
1425
2165
  */
1426
2166
  function readCaptureTitles(root, file, selector) {
1427
- const path = requireCaptureContained(root, file);
1428
- const loaded = attempt(() => readFileSync(path, "utf8"));
1429
- if (!loaded.success) throw new CaptureError(`Missing accepted registry; run the explicit complete-registry refresh: capture registry. Registry path: ${file}`, {
1430
- code: "EVIDENCE",
1431
- cause: loaded.error
1432
- });
1433
- const registry = parseJSON(loaded.value);
1434
- if (!isCaptureRegistry(registry)) throw new CaptureError("Invalid accepted registry for case titles", { code: "EVIDENCE" });
1435
- return Object.fromEntries(registry.receipts.flatMap((receipt) => {
1436
- const text = readFileSync(requireCaptureContained(root, resolve(root, receipt.report.file)), "utf8");
1437
- if (computeCaptureHash(text) !== receipt.report.digest) throw new CaptureError("Registry reporter digest differs for case titles", { code: "EVIDENCE" });
1438
- const report = parseJSON(text);
1439
- if (!isRecord(report) || !arrayOf(isRecord)(report.testResults)) throw new CaptureError("Invalid registry reporter for case titles", { code: "EVIDENCE" });
1440
- const selected = selector === void 0 ? void 0 : new Set(readCaptureReport(report).assertions.filter((entry) => matchesCaptureSelector(entry.owner, selector)).map((entry) => entry.case));
1441
- return report.testResults.flatMap((result) => !arrayOf(isRecord)(result.assertionResults) ? [] : result.assertionResults.flatMap((assertion) => {
1442
- if (!isString(assertion.fullName) || !isString(assertion.title) || !arrayOf(isString)(assertion.ancestorTitles)) return [];
1443
- const titles = [...assertion.ancestorTitles, assertion.title];
1444
- if (titles.join(" ") !== assertion.fullName) throw new CaptureError("Registry reporter title segments differ from its case", { code: "EVIDENCE" });
1445
- return selected === void 0 || selected.has(assertion.fullName) ? [[assertion.fullName, titles]] : [];
2167
+ try {
2168
+ const path = requireCaptureContained(root, file);
2169
+ const loaded = attempt(() => readFileSync(path, "utf8"));
2170
+ if (!loaded.success) throw new CaptureError(`Missing accepted registry; run the explicit complete-registry refresh: capture registry. Registry path: ${file}`, {
2171
+ code: "EVIDENCE",
2172
+ cause: loaded.error
2173
+ });
2174
+ const registry = parseJSON(loaded.value);
2175
+ requireCaptureVersion(registry, "Registry", file, [
2176
+ file,
2177
+ resolve(dirname(file), CAPTURE_MANIFEST_FILE),
2178
+ resolve(dirname(file), CAPTURE_LOOKUPS_FILE)
2179
+ ]);
2180
+ if (!isCaptureRegistry(registry)) throw new CaptureError("Invalid accepted registry for case titles", { code: "EVIDENCE" });
2181
+ return Object.fromEntries(registry.receipts.flatMap((receipt) => {
2182
+ const text = readFileSync(requireCaptureContained(root, resolve(root, receipt.report.file)), "utf8");
2183
+ if (computeCaptureHash(text) !== receipt.report.digest) throw new CaptureError("Registry reporter digest differs for case titles", { code: "EVIDENCE" });
2184
+ const report = parseJSON(text);
2185
+ if (!isRecord(report) || !arrayOf(isRecord)(report.testResults)) throw new CaptureError("Invalid registry reporter for case titles", { code: "EVIDENCE" });
2186
+ const selected = selector === void 0 ? void 0 : new Set(readCaptureReport(report).assertions.filter((entry) => matchesCaptureSelector(entry.owner, selector)).map((entry) => entry.case));
2187
+ return report.testResults.flatMap((result) => !arrayOf(isRecord)(result.assertionResults) ? [] : result.assertionResults.flatMap((assertion) => {
2188
+ if (!isString(assertion.fullName) || !isString(assertion.title) || !arrayOf(isString)(assertion.ancestorTitles)) return [];
2189
+ const titles = [...assertion.ancestorTitles, assertion.title];
2190
+ if (titles.join(" ") !== assertion.fullName) throw new CaptureError("Registry reporter title segments differ from its case", { code: "EVIDENCE" });
2191
+ return selected === void 0 || selected.has(assertion.fullName) ? [[assertion.fullName, titles]] : [];
2192
+ }));
1446
2193
  }));
1447
- }));
2194
+ } catch (error) {
2195
+ throw resolveCaptureRegistryFault(error);
2196
+ }
1448
2197
  }
1449
2198
  /**
1450
2199
  * Parses standard option tokens and refuses empty values, terminators, and repeated single options.
1451
2200
  *
2201
+ * @remarks A boolean option whose default is `true` reads its `--no-` form as `false` and refuses
2202
+ * its positive form, so `--no-bail` is the one spelling of `bail`; the `--no-` form of any other
2203
+ * option is refused as unknown. An option and its `--no-` form repeat each other.
2204
+ *
1452
2205
  * @param argv - The arguments after the subcommand
1453
2206
  * @param options - The command's frozen Node option definitions
1454
2207
  * @param usage - The command syntax appended to every parser refusal
@@ -1456,6 +2209,7 @@ function readCaptureTitles(root, file, selector) {
1456
2209
  * @example
1457
2210
  * ```ts
1458
2211
  * readCaptureOptions(['--case=-draft'], CAPTURE_COMMAND_OPTIONS.journey, 'Usage: capture journey <selector>').values.case // '-draft'
2212
+ * readCaptureOptions(['--no-bail'], CAPTURE_COMMAND_OPTIONS.journey, 'Usage: capture journey <selector>').values.bail // false
1459
2213
  * ```
1460
2214
  */
1461
2215
  function readCaptureOptions(argv, options, usage) {
@@ -1465,11 +2219,14 @@ function readCaptureOptions(argv, options, usage) {
1465
2219
  options,
1466
2220
  tokens: true,
1467
2221
  strict: true,
1468
- allowPositionals: true
2222
+ allowPositionals: true,
2223
+ allowNegative: true
1469
2224
  });
1470
2225
  for (const token of parsed.tokens) {
1471
2226
  if (token.kind === "option-terminator") throw new CaptureError("The -- option terminator is refused", { code: "USAGE" });
1472
2227
  if (token.kind !== "option") continue;
2228
+ if (token.rawName === `--no-${token.name}` && options[token.name]?.default !== true) throw new CaptureError(`Unknown option '${token.rawName}'`, { code: "USAGE" });
2229
+ if (token.rawName === `--${token.name}` && options[token.name]?.default === true) throw new CaptureError(`Unknown option '${token.rawName}'; ${token.name} is on by default, and --no-${token.name} turns it off`, { code: "USAGE" });
1473
2230
  if (token.value === "") throw new CaptureError(`Missing value: --${token.name}`, { code: "USAGE" });
1474
2231
  if (options[token.name]?.multiple !== true && parsed.tokens.some((earlier) => earlier.kind === "option" && earlier.name === token.name && earlier.index < token.index)) throw new CaptureError(`Repeated option: --${token.name}`, { code: "USAGE" });
1475
2232
  }
@@ -1486,7 +2243,8 @@ function readCaptureOptions(argv, options, usage) {
1486
2243
  *
1487
2244
  * @remarks
1488
2245
  * `--state` belongs to `capture` and `stale`, and `--portfolio` to `stale`. Journey and capture
1489
- * accept `--changed <ref>` instead of a selector, with optional valueless `--plan`. Every other
2246
+ * accept `--changed <ref>` instead of a selector, with optional valueless `--plan`, and valueless
2247
+ * `--no-bail`, which sets `bail` to `false`. Every other
1490
2248
  * flag takes one nonempty value, either separated or in equals form, and only `--variant` repeats.
1491
2249
  * A value beginning with a dash requires equals form. A bare invocation leaves its selector absent
1492
2250
  * so the caller can print usage with the declared selectors.
@@ -1522,12 +2280,14 @@ function readCaptureArguments(argv, command, root, fallback) {
1522
2280
  const selector = positional.at(0);
1523
2281
  const changed = "changed" in values && typeof values.changed === "string" ? values.changed : void 0;
1524
2282
  const plan = "plan" in values && values.plan === true;
2283
+ const bail = !("bail" in values) || values.bail !== false;
1525
2284
  if (changed !== void 0 && selector !== void 0) throw new CaptureError("A selector cannot be combined with --changed; use --changed <ref> alone", { code: "USAGE" });
1526
2285
  if (plan && changed === void 0) throw new CaptureError("--plan requires --changed <ref>", { code: "USAGE" });
1527
2286
  return {
1528
2287
  ...selector === void 0 ? {} : { selector },
1529
2288
  ...changed === void 0 ? {} : { changed },
1530
2289
  ...plan ? { plan: true } : {},
2290
+ ...bail ? {} : { bail: false },
1531
2291
  config: resolve(root, values.config ?? fallback),
1532
2292
  ...mode === void 0 ? {} : { mode },
1533
2293
  variants,
@@ -1787,7 +2547,7 @@ function readCaptureRequest(options) {
1787
2547
  code: "HOST",
1788
2548
  context: { file }
1789
2549
  });
1790
- if (parsed.version !== 1) throw new CaptureError("Journey selection request has invalid version", { code: "HOST" });
2550
+ if (parsed.version !== CAPTURE_VERSION) throw new CaptureError("Journey selection request has invalid version", { code: "HOST" });
1791
2551
  if (!isCaptureSegment(parsed.id) || !isCaptureSegment(parsed.stage)) throw new CaptureError("Journey selection request has invalid identity", { code: "HOST" });
1792
2552
  if (parsed.config !== options.config) throw new CaptureError("Journey selection request has invalid config", { code: "HOST" });
1793
2553
  if (parsed.mode !== void 0 && (typeof parsed.mode !== "string" || parsed.mode.trim() === "")) throw new CaptureError("Journey selection request has invalid mode", { code: "HOST" });
@@ -1797,7 +2557,7 @@ function readCaptureRequest(options) {
1797
2557
  const variants = arrayOf(isString)(parsed.variants) ? parsed.variants : void 0;
1798
2558
  if (command === void 0 || selector === void 0 || selector.trim() === "" || selector !== "all" && !options.owners.some((owner) => matchesCaptureSelector(owner, selector)) || variants === void 0 || variants.length === 0 || new Set(variants).size !== variants.length || variants.some((variant) => !options.variants.includes(variant)) || parsed.case !== void 0 && (typeof parsed.case !== "string" || parsed.case.trim() === "")) throw new CaptureError("Journey selection request has invalid command, selector, variants, or case", { code: "HOST" });
1799
2559
  return {
1800
- version: 1,
2560
+ version: CAPTURE_VERSION,
1801
2561
  id: parsed.id,
1802
2562
  stage: parsed.stage,
1803
2563
  config: options.config,
@@ -1970,45 +2730,49 @@ function scanCaptureFrames(images, producers) {
1970
2730
  * ```
1971
2731
  */
1972
2732
  function collectCaptureIdentical(images) {
1973
- return [...new Set(images.map((image) => image.digest))].map((digest) => images.filter((image) => image.digest === digest).map((image) => image.entry.file)).filter((files) => files.length > 1);
2733
+ return [...Map.groupBy(images, (image) => image.digest).values()].filter((group) => group.length > 1).map((group) => group.map((image) => image.entry.file));
1974
2734
  }
1975
2735
  /**
1976
- * Finds the journey artifact lines that report an uncaught, unhandled, or logged error.
2736
+ * Builds the report a preflight prints and a contact-sheet index carries from one preflight result.
1977
2737
  *
1978
- * @param file - The artifact's repository-relative path, which prefixes each finding
1979
- * @param text - The artifact's text
1980
- * @returns One finding per matching line
2738
+ * @param result - The judged selection
2739
+ * @returns The selection, freshness, mixed observations, issues, identical groups, image sizes, and `acceptance: false`
1981
2740
  *
1982
2741
  * @example
1983
2742
  * ```ts
1984
- * collectCaptureErrors('tmp/journey/light-390.txt', 'ok\nUncaught TypeError') // ['tmp/journey/light-390.txt: Uncaught TypeError']
2743
+ * buildCaptureReaderReport(await preflight.check()).acceptance // false
1985
2744
  * ```
1986
2745
  */
1987
- function collectCaptureErrors(file, text) {
1988
- return text.split(/\r\n|\n/u).filter((line) => /\b(uncaught|unhandled|error:)/iu.test(line)).map((line) => `${file}: ${line}`);
2746
+ function buildCaptureReaderReport(result) {
2747
+ return {
2748
+ selection: result.selection,
2749
+ freshness: result.freshness,
2750
+ mixed: result.mixed,
2751
+ issues: result.issues,
2752
+ identical: collectCaptureIdentical(result.images),
2753
+ sizes: result.images.map(({ entry, picture, size }) => ({
2754
+ file: entry.file,
2755
+ width: picture.width,
2756
+ height: picture.height,
2757
+ bytes: size
2758
+ })),
2759
+ acceptance: false
2760
+ };
1989
2761
  }
1990
2762
  /**
1991
- * Checks whether a process with this id is running, counting one the caller may not signal.
1992
- *
1993
- * @remarks
1994
- * A zero signal tests existence without sending one. A refusal for permission still proves the
1995
- * process exists, so only a missing process reads as not running.
2763
+ * Finds the journey artifact lines that report an uncaught, unhandled, or logged error.
1996
2764
  *
1997
- * @param pid - The process id
1998
- * @returns True if the process exists; false otherwise
2765
+ * @param file - The artifact's repository-relative path, which prefixes each finding
2766
+ * @param text - The artifact's text
2767
+ * @returns One finding per matching line
1999
2768
  *
2000
2769
  * @example
2001
2770
  * ```ts
2002
- * readCaptureRunning(process.pid) // true
2771
+ * collectCaptureErrors('tmp/journey/light-390.txt', 'ok\nUncaught TypeError') // ['tmp/journey/light-390.txt: Uncaught TypeError']
2003
2772
  * ```
2004
2773
  */
2005
- function readCaptureRunning(pid) {
2006
- try {
2007
- process.kill(pid, 0);
2008
- return true;
2009
- } catch (error) {
2010
- return isError(error) && "code" in error && error.code === "EPERM";
2011
- }
2774
+ function collectCaptureErrors(file, text) {
2775
+ return text.split(/\r\n|\n/u).filter((line) => /\b(uncaught|unhandled|error:)/iu.test(line)).map((line) => `${file}: ${line}`);
2012
2776
  }
2013
2777
  /**
2014
2778
  * Resolves one entry of a wrapper's project list to the project it declares.
@@ -2129,7 +2893,7 @@ function readCaptureDescription(value, expected) {
2129
2893
  "pid",
2130
2894
  "projects"
2131
2895
  ];
2132
- if (!isRecord(value) || value.version !== CAPTURE_VERSION || !isArray(value.projects) || keys.some((key) => value[key] === void 0) || Object.keys(value).some((key) => !keys.includes(key))) throw new CaptureError(`The host description is malformed; ${describeCaptureFault("description", value, "{ version: 1, id: invocation id, nonce: challenge, config: wrapper path, parent: parent pid, pid: discovery child pid, projects: project[] }", keys, keys)}`, { code: "HOST" });
2896
+ if (!isRecord(value) || value.version !== CAPTURE_VERSION || !isArray(value.projects) || keys.some((key) => value[key] === void 0) || Object.keys(value).some((key) => !keys.includes(key))) throw new CaptureError(`The host description is malformed; ${describeCaptureFault("description", value, `{ version: ${String(CAPTURE_VERSION)}, id: invocation id, nonce: challenge, config: wrapper path, parent: parent pid, pid: discovery child pid, projects: project[] }`, keys, keys)}`, { code: "HOST" });
2133
2897
  if (value.id !== expected.id) throw new CaptureError(`The host description answers another invocation; ${describeCaptureFault("description.id", value.id, "the active invocation id", [expected.id])}`, { code: "HOST" });
2134
2898
  if (value.nonce !== expected.nonce) throw new CaptureError(`The host description answers another challenge (a replay); ${describeCaptureFault("description.nonce", value.nonce, "the active discovery challenge", [expected.nonce])}`, { code: "HOST" });
2135
2899
  if (value.config !== expected.config) throw new CaptureError(`The host description names another wrapper; ${describeCaptureFault("description.config", value.config, "the requested wrapper path", [expected.config])}`, { code: "HOST" });
@@ -2213,12 +2977,294 @@ async function answerCaptureDiscovery(options) {
2213
2977
  return true;
2214
2978
  }
2215
2979
  /**
2980
+ * Lists a directory through a reader, answering an empty list for a missing directory.
2981
+ *
2982
+ * @param directory - The absolute directory to list
2983
+ * @param list - Reads the directory's entries, such as `readdirSync` with its options
2984
+ * @returns The entries the reader returned, or none when the directory is missing
2985
+ * @throws Thrown as an `EVIDENCE` capture error naming the directory for any other failure to read it.
2986
+ *
2987
+ * @example
2988
+ * ```ts
2989
+ * readCaptureListing('/repo/tmp/captures/states/pages', (path) => readdirSync(path)) // ['inbox--light-390.png']
2990
+ * ```
2991
+ */
2992
+ function readCaptureListing(directory, list) {
2993
+ const listed = attempt(() => list(directory));
2994
+ if (listed.success) return listed.value;
2995
+ if (isError(listed.error) && "code" in listed.error && listed.error.code === "ENOENT") return [];
2996
+ throw new CaptureError(`Cannot list capture frames under ${directory}`, {
2997
+ code: "EVIDENCE",
2998
+ cause: listed.error,
2999
+ context: { directory }
3000
+ });
3001
+ }
3002
+ /**
3003
+ * Lists the frames a portfolio directory holds, as paths relative to it, in sorted order.
3004
+ *
3005
+ * @remarks
3006
+ * A frame is a `.png` file at the directory's top level or directly inside one of the scope
3007
+ * directories. The run records directory holds no frame, and every other directory is unknown. A
3008
+ * missing directory, or one removed between the listing and its read, holds no frame.
3009
+ *
3010
+ * @param directory - The absolute portfolio directory
3011
+ * @param scopes - The scope directories the owners declare, each an owner path's first segment
3012
+ * @returns Each frame's slash-separated path relative to the directory
3013
+ * @throws Thrown as an `EVIDENCE` capture error for a frame beneath the run records, an unknown
3014
+ * directory, a directory inside a scope, or a directory the host refuses to read.
3015
+ *
3016
+ * @example
3017
+ * ```ts
3018
+ * readCaptureFrames('/repo/tmp/captures/states', ['pages']) // ['pages/inbox--light-390.png']
3019
+ * ```
3020
+ */
3021
+ function readCaptureFrames(directory, scopes) {
3022
+ return readCaptureListing(directory, (path) => readdirSync(path, { withFileTypes: true })).flatMap((entry) => {
3023
+ if (!entry.isDirectory()) return entry.name.endsWith(".png") ? [entry.name] : [];
3024
+ if (entry.name === "runs") {
3025
+ const frames = readCaptureListing(resolve(directory, entry.name), (path) => readdirSync(path, {
3026
+ recursive: true,
3027
+ encoding: "utf8"
3028
+ })).filter((name) => name.endsWith(".png"));
3029
+ if (frames.length > 0) throw new CaptureError(`Frames sit beneath the run records: ${describeCaptureMembers(frames.map(normalizeSlashes))}`, {
3030
+ code: "EVIDENCE",
3031
+ context: { directory }
3032
+ });
3033
+ return [];
3034
+ }
3035
+ if (!scopes.includes(entry.name)) throw new CaptureError(`Unknown capture directory: ${describeCaptureFault("directory", entry.name, "a scope the owners declare, or the run records", [...scopes, CAPTURE_RUNS_DIRECTORY])}`, {
3036
+ code: "EVIDENCE",
3037
+ context: { directory }
3038
+ });
3039
+ return readCaptureListing(resolve(directory, entry.name), (path) => readdirSync(path, { withFileTypes: true })).flatMap((file) => {
3040
+ if (file.isDirectory()) throw new CaptureError(`Unknown capture directory: ${preview(`${entry.name}/${file.name}`)}; a scope holds frames only`, {
3041
+ code: "EVIDENCE",
3042
+ context: { directory }
3043
+ });
3044
+ return file.name.endsWith(".png") ? [`${entry.name}/${file.name}`] : [];
3045
+ });
3046
+ }).toSorted();
3047
+ }
3048
+ /**
3049
+ * Reads the progress file of the stage that is running, or that ran last, in a workspace.
3050
+ *
3051
+ * @remarks
3052
+ * The file is the most recently modified `<stage>.progress.jsonl` beneath the request directory's
3053
+ * run directories. The progress file is an observation of the run and never evidence. A partial
3054
+ * last line, which the reporter can still be appending, is not read, so a file with no complete
3055
+ * line holds no run. For each run with no `end` line, `alive` reads the process id its `init` line
3056
+ * records: a writer that has ended turns the run `interrupted`, measured to the time of its last
3057
+ * line, and a writer the host cannot inspect, or an id that is not a positive safe integer, lists
3058
+ * the run's id in `uninspected`.
3059
+ *
3060
+ * @param root - The absolute workspace path
3061
+ * @param requests - The workspace-relative request directory
3062
+ * @param now - The wall-clock time of the reading, in milliseconds since the Unix epoch. Default: `Date.now()`
3063
+ * @param alive - Reads whether a writer process exists, or `undefined` when the host cannot tell. Default: `inspectProcess` from `@orkestrel/process/server`
3064
+ * @returns The workspace-relative file, one reading per process that wrote it, and the writers the host could not inspect
3065
+ * @throws Thrown as a `STAGE` capture error when no stage has written a progress file, or when the
3066
+ * file cannot be read or holds a complete line that is not a progress event.
3067
+ *
3068
+ * @example
3069
+ * ```ts
3070
+ * readCaptureProgress('/repo', 'tmp/capture').runs[0]?.state // 'live' while the stage runs
3071
+ * ```
3072
+ */
3073
+ function readCaptureProgress(root, requests, now = Date.now(), alive = inspectProcess) {
3074
+ const runs = resolve(root, requests, CAPTURE_RUNS_DIRECTORY);
3075
+ const [newest] = globSync(`*/*${CAPTURE_PROGRESS_SUFFIX}`, { cwd: runs }).flatMap((name) => {
3076
+ const stat = attempt(() => statSync(resolve(runs, name)));
3077
+ return stat.success && stat.value.isFile() ? [{
3078
+ file: resolveCaptureRelative(root, resolve(runs, name)),
3079
+ time: stat.value.mtimeMs
3080
+ }] : [];
3081
+ }).toSorted((left, right) => right.time - left.time || right.file.localeCompare(left.file));
3082
+ if (newest === void 0) throw new CaptureError(`No stage has written a progress file under ${resolveCaptureRelative(root, runs)}; run a journey, frames, or registry command first`, {
3083
+ code: "STAGE",
3084
+ context: { directory: resolveCaptureRelative(root, runs) }
3085
+ });
3086
+ const read = attempt(() => extractProgressEvents(readFileSnapshot(resolve(root, newest.file)).toString("utf8")));
3087
+ if (!read.success) throw new CaptureError(`Cannot read the progress file ${newest.file}: ${describeCaptureOutput(describeCaptureError(read.error))}`, {
3088
+ code: "STAGE",
3089
+ cause: read.error,
3090
+ context: { file: newest.file }
3091
+ });
3092
+ const events = read.value;
3093
+ const computed = computeProgress(events, now);
3094
+ const writers = new Map(computed.filter((run) => run.state === "live").map((run) => [run.pid, Number.isSafeInteger(run.pid) && run.pid > 0 ? alive(run.pid) : void 0]));
3095
+ return {
3096
+ file: newest.file,
3097
+ runs: computed.map((run) => {
3098
+ if (writers.get(run.pid) !== false) return run;
3099
+ const own = events.filter((event) => event.pid === run.pid);
3100
+ const init = own.findLast((event) => event.event === "init");
3101
+ const last = own.at(-1);
3102
+ return {
3103
+ ...init === void 0 || last === void 0 ? run : computeProgressRun(own, init.wall + last.time - init.time) ?? run,
3104
+ state: "interrupted",
3105
+ running: [],
3106
+ remaining: void 0
3107
+ };
3108
+ }),
3109
+ uninspected: [...writers].flatMap(([pid, answer]) => answer === void 0 ? [pid] : [])
3110
+ };
3111
+ }
3112
+ /**
3113
+ * Renders a progress reading as the text `capture progress` prints.
3114
+ *
3115
+ * @param progress - The reading `readCaptureProgress` returns
3116
+ * @returns The file line, then each run as `renderProgress` from `@orkestrel/test/server` renders it,
3117
+ * followed by an unknown-state line for each run whose writer the host could not inspect
3118
+ *
3119
+ * @example
3120
+ * ```ts
3121
+ * renderCaptureProgress({ file: 'tmp/capture/runs/a/selected.progress.jsonl', runs: [], uninspected: [] })
3122
+ * // 'progress tmp/capture/runs/a/selected.progress.jsonl\nNo run has written a complete progress line yet'
3123
+ * ```
3124
+ */
3125
+ function renderCaptureProgress(progress) {
3126
+ return [`progress ${progress.file}`, ...progress.runs.length === 0 ? ["No run has written a complete progress line yet"] : progress.runs.flatMap((run) => [renderProgress([run]), ...progress.uninspected.includes(run.pid) ? [` state unknown: the host could not inspect writer ${String(run.pid)}, so the run might have ended without its end line`] : []])].join("\n");
3127
+ }
3128
+ /**
3129
+ * Builds the values capture merges into one variant's Vitest project.
3130
+ *
3131
+ * @param options - The wrapper's declarations
3132
+ * @param variant - The variant the project produces
3133
+ * @param provided - The variant's frame directory, run record path, capture switch, and runner request
3134
+ * @returns The owner tags, the provided values, and the `readCaptureFrames` browser command over the directory
3135
+ *
3136
+ * @example
3137
+ * ```ts
3138
+ * buildCaptureOverride(options, variant, { directory, record, capture: true }).test.provide.record
3139
+ * // 'tmp/captures/states/runs/run-1/selected/light-390.json'
3140
+ * ```
3141
+ */
3142
+ function buildCaptureOverride(options, variant, provided) {
3143
+ const scopes = [...new Set(options.owners.flatMap((owner) => collectCaptureAncestors(owner).slice(0, 1)))];
3144
+ return { test: {
3145
+ tags: buildCaptureTags(options.owners).map((name) => ({ name })),
3146
+ provide: {
3147
+ variant: variant.name,
3148
+ variants: options.variants,
3149
+ directory: provided.directory,
3150
+ record: provided.record,
3151
+ inputs: options.inputs,
3152
+ sources: options.sources,
3153
+ final: options.final,
3154
+ first: options.first,
3155
+ ...options.uniform === void 0 ? {} : { uniform: options.uniform },
3156
+ portfolios: options.portfolios,
3157
+ capture: provided.capture,
3158
+ ...provided.request === void 0 ? {} : { request: provided.request }
3159
+ },
3160
+ browser: { commands: { readCaptureFrames: () => readCaptureFrames(provided.directory, scopes) } }
3161
+ } };
3162
+ }
3163
+ /**
3164
+ * Builds a journey wrapper's Vitest configuration as plain data, answering discovery first.
3165
+ *
3166
+ * @remarks
3167
+ * Call it inside the wrapper's own `defineConfig` callback, before any other work: capture imports
3168
+ * neither Vite nor Vitest, so the result is data the wrapper returns. The wrapper path is `url`
3169
+ * relative to the working directory, which is the workspace root for every child the runner
3170
+ * spawns. During a discovery request it describes each variant's project as `{ name, tags,
3171
+ * provide }`, with the name the host's `project` chose, and returns `buildCaptureDiscoveryConfig()`.
3172
+ * Otherwise it reads the runner's request, provides each project the values `CaptureProvided`
3173
+ * declares except `standalone`, and registers the browser command `readCaptureFrames`, which lists the frames under
3174
+ * the provided directory. With the capture variable unset, each variant writes to its own scratch
3175
+ * sibling of the evidence root, emptied first. The result's root `plugins` holds one
3176
+ * `createProgressPlugin()`, so a stage the runner passes `--outputFile.progress` writes its
3177
+ * progress file.
3178
+ *
3179
+ * @param options - The wrapper path, variants, owners, stage and final names, evidence root, inputs, sources, portfolios, and project builder
3180
+ * @returns The discovery configuration while discovery runs, and otherwise the progress plugin and one project per variant
3181
+ * @throws Thrown as a `HOST` capture error, before any directory work, for a `url` that is no
3182
+ * `file:` URL, an evidence root that is not a portable relative path, or a variant name that is no
3183
+ * capture segment, and later for an invalid owner or a runner request that fails its checks; and as
3184
+ * a `CONTAINMENT` capture error for a wrapper or scratch path outside the workspace.
3185
+ *
3186
+ * @example
3187
+ * ```ts
3188
+ * export default defineConfig(({ mode }) =>
3189
+ * buildCaptureWrapper({ ...declarations, url: import.meta.url, project: (variant, override) => appJourney(variant, mode, override) }),
3190
+ * )
3191
+ * ```
3192
+ */
3193
+ async function buildCaptureWrapper(options) {
3194
+ const root = process.cwd();
3195
+ const path = attempt(() => fileURLToPath(options.url));
3196
+ if (!path.success) throw new CaptureError(`Invalid wrapper url; ${describeCaptureFault("url", options.url, "the wrapper module's import.meta.url, a file: URL")}`, {
3197
+ code: "HOST",
3198
+ cause: path.error
3199
+ });
3200
+ requireCaptureContained(root, path.value);
3201
+ if (!isCapturePath(options.directory)) throw new CaptureError(`Invalid evidence root; ${describeCaptureFault("directory", options.directory, "a portable workspace-relative path")}`, { code: "HOST" });
3202
+ const invalid = options.variants.findIndex((variant) => !isCaptureSegment(variant.name));
3203
+ if (invalid !== -1) throw new CaptureError(`Invalid variant name; ${describeCaptureFault(`variants[${String(invalid)}].name`, options.variants[invalid]?.name, "a portable nonempty identity segment")}`, { code: "HOST" });
3204
+ const roots = [options.directory, ...options.portfolios.map((entry) => entry.directory)];
3205
+ for (const variant of options.variants) {
3206
+ const scratch = resolve(root, dirname(options.directory), `${CAPTURE_WRAPPER_PREFIXES.scratch}${variant.name}`);
3207
+ const overlap = roots.find((entry) => [relative(resolve(root, entry), scratch), relative(scratch, resolve(root, entry))].some((step) => step === "" || !step.startsWith("..") && !isAbsolute(step)));
3208
+ if (overlap !== void 0) throw new CaptureError(`Invalid evidence root; the no-capture scratch directory ${resolveCaptureRelative(root, scratch)} of variant ${variant.name} overlaps ${overlap}, which it would empty`, { code: "HOST" });
3209
+ }
3210
+ const config = resolveCaptureRelative(root, path.value);
3211
+ const argv = process.argv.slice(1);
3212
+ const capture = process.env[CAPTURE_FLAG] === "1";
3213
+ const evidence = resolve(root, options.directory);
3214
+ if (await answerCaptureDiscovery({
3215
+ ppid: process.ppid,
3216
+ argv,
3217
+ config,
3218
+ projects: options.variants.map((variant) => () => {
3219
+ const override = buildCaptureOverride(options, variant, {
3220
+ directory: evidence,
3221
+ record: `${options.directory}/runs/${CAPTURE_DISCOVERY.phase}/${variant.name}.json`,
3222
+ capture
3223
+ });
3224
+ const project = options.project(variant, override);
3225
+ return { test: {
3226
+ name: isRecord(project) && isRecord(project.test) ? project.test.name : void 0,
3227
+ tags: override.test.tags,
3228
+ provide: override.test.provide
3229
+ } };
3230
+ })
3231
+ })) return buildCaptureDiscoveryConfig();
3232
+ const request = readCaptureRequest({
3233
+ ppid: process.ppid,
3234
+ argv,
3235
+ config,
3236
+ owners: options.owners,
3237
+ variants: options.variants.map((variant) => variant.name)
3238
+ });
3239
+ const invocation = request === void 0 ? `${CAPTURE_WRAPPER_PREFIXES.direct}${randomUUID()}` : `${request.id}/${request.stage}`;
3240
+ return {
3241
+ plugins: [createProgressPlugin()],
3242
+ test: { projects: options.variants.map((variant) => {
3243
+ const directory = capture ? evidence : requireCaptureContained(root, resolve(root, dirname(options.directory), `${CAPTURE_WRAPPER_PREFIXES.scratch}${variant.name}`));
3244
+ if (!capture) {
3245
+ rmSync(directory, {
3246
+ recursive: true,
3247
+ force: true
3248
+ });
3249
+ mkdirSync(directory, { recursive: true });
3250
+ }
3251
+ return options.project(variant, buildCaptureOverride(options, variant, {
3252
+ directory,
3253
+ record: `${options.directory}/${CAPTURE_RUNS_DIRECTORY}/${invocation}/${variant.name}.json`,
3254
+ capture,
3255
+ ...request === void 0 ? {} : { request }
3256
+ }));
3257
+ }) }
3258
+ };
3259
+ }
3260
+ /**
2216
3261
  * Reads the registry command line into the wrapper path, the variants to refresh, and the mode.
2217
3262
  *
2218
3263
  * @remarks
2219
3264
  * The command takes no selector: it refreshes every producing variant the wrapper declares, or the
2220
- * variants named by repeated `--variant` flags. Every flag takes one value, and only `--variant`
2221
- * repeats. `--mode` is forwarded to the wrapper's Vitest process unread.
3265
+ * variants named by repeated `--variant` flags. Every flag but valueless `--no-bail` takes one
3266
+ * value, and only `--variant` repeats. `--mode` is forwarded to the wrapper's Vitest process
3267
+ * unread, and `--no-bail` sets `bail` to `false`.
2222
3268
  *
2223
3269
  * @param argv - The arguments after the subcommand
2224
3270
  * @param root - The absolute workspace path the wrapper path resolves against
@@ -2234,7 +3280,7 @@ async function answerCaptureDiscovery(options) {
2234
3280
  * ```
2235
3281
  */
2236
3282
  function readCaptureRegistryArguments(argv, root, fallback) {
2237
- const usage = "Usage: capture registry [--variant <name>]... [--mode <name>] [--config <file>]";
3283
+ const usage = "Usage: capture registry [--variant <name>]... [--no-bail] [--mode <name>] [--config <file>]";
2238
3284
  const { values, positionals } = readCaptureOptions(argv, CAPTURE_COMMAND_OPTIONS.registry, usage);
2239
3285
  if (positionals.length > 0) throw new CaptureError(`Unexpected argument ${JSON.stringify(positionals[0]?.slice(0, 80))}: the registry command takes no selector and refreshes every producing variant, or those named by --variant. ${usage}`, { code: "USAGE" });
2240
3286
  const variants = values.variant ?? [];
@@ -2245,7 +3291,8 @@ function readCaptureRegistryArguments(argv, root, fallback) {
2245
3291
  return {
2246
3292
  config: resolve(root, values.config ?? fallback),
2247
3293
  variants,
2248
- ...mode === void 0 ? {} : { mode }
3294
+ ...mode === void 0 ? {} : { mode },
3295
+ ...values.bail === false ? { bail: false } : {}
2249
3296
  };
2250
3297
  }
2251
3298
  /**
@@ -2446,6 +3493,7 @@ var CaptureIntegrity = class {
2446
3493
  #root;
2447
3494
  #roots;
2448
3495
  #hash;
3496
+ #matches = /* @__PURE__ */ new Map();
2449
3497
  /**
2450
3498
  * Binds the engine to an explicit workspace and host portfolio mapping.
2451
3499
  *
@@ -2675,15 +3723,15 @@ var CaptureIntegrity = class {
2675
3723
  if (request.command === "capture" && stamps.length > 0) {
2676
3724
  const inherited = Object.entries(evidence.manifest?.entries ?? {});
2677
3725
  const replaced = new Set(stamps.map(resolveCaptureKey));
2678
- const next = {
3726
+ const document = buildCaptureManifestDocument({
2679
3727
  collections,
2680
3728
  version: CAPTURE_VERSION,
2681
3729
  registry: evidence.registry,
2682
3730
  entries: Object.fromEntries([...inherited.filter(([key]) => !replaced.has(key)), ...stamps.map((stamp) => [resolveCaptureKey(stamp), stamp])]),
2683
3731
  lookups: merged
2684
- };
2685
- if (!isCaptureStoredManifest(next)) throw new CaptureError("Invalid next manifest", { code: "EVIDENCE" });
2686
- this.#commit(this.#options.manifest, next, options.signal);
3732
+ });
3733
+ if (!isCaptureManifestDocument(document)) throw new CaptureError("Invalid next manifest", { code: "EVIDENCE" });
3734
+ this.#commit(this.#options.manifest, document, options.signal);
2687
3735
  } else if (request.command === "journey" && collected.length > 0) {
2688
3736
  const manifest = before.files.find((file) => file.file === this.#options.manifest)?.image.digest;
2689
3737
  this.#commit(this.#options.lookups, buildCaptureLookupJournal(merged, collections, manifest), options.signal);
@@ -2727,12 +3775,13 @@ var CaptureIntegrity = class {
2727
3775
  const destinations = this.#destinations(populated);
2728
3776
  this.#uniqueRegistry(destinations);
2729
3777
  const variants = this.#variants(destinations, options);
2730
- const entries = this.#select(populated, destinations, {
3778
+ const entries = this.#select(destinations, {
2731
3779
  ...options,
2732
3780
  variants
2733
- }, false);
3781
+ });
2734
3782
  const inputs = this.#digest(this.#options.inputs, snapshots, digests);
2735
- for (const variant of new Set(entries.map((entry) => this.#producer(entry, populated)))) {
3783
+ const producers = collectCaptureProducers(populated);
3784
+ for (const variant of new Set(entries.map((entry) => requireCaptureProducer(entry, producers)))) {
2736
3785
  const anchor = evidence.registry.receipts.find((receipt) => receipt.variant === variant);
2737
3786
  if (anchor !== void 0 && collectCaptureChanges(anchor.inputs, inputs.files).length === 0) continue;
2738
3787
  if (!collections.some((entry) => entry.run.variant === variant && entry.receipt.inputs.digest === inputs.digest)) throw new CaptureError(`No current full-collection evidence for producing variant: ${variant}`, {
@@ -2746,6 +3795,7 @@ var CaptureIntegrity = class {
2746
3795
  entries
2747
3796
  };
2748
3797
  } catch (error) {
3798
+ if (matchesCaptureVersionRefusal(error)) throw error;
2749
3799
  throw new CaptureError(`${describeCaptureError(error)}. Prepare the explicit complete-registry refresh, or an explicit capture-free owner/case run whose full collection equals that anchor for each affected producing variant; this read starts no process.`, {
2750
3800
  code: isCaptureError(error) ? error.code : "EVIDENCE",
2751
3801
  cause: error
@@ -2776,7 +3826,7 @@ var CaptureIntegrity = class {
2776
3826
  const attested = /* @__PURE__ */ new Set([...evidence.registry.receipts.map((receipt) => receipt.variant), ...evidence.runs.map(({ run }) => run.variant)]);
2777
3827
  const unattested = selection.variants === void 0 ? (selection.declared ?? []).filter((variant) => !attested.has(variant)) : [];
2778
3828
  if (unattested.length > 0) throw new CaptureError(`Unattested declared variant: ${unattested.join(", ")}`, {
2779
- code: "EVIDENCE",
3829
+ code: "REGISTRY",
2780
3830
  context: { variants: unattested }
2781
3831
  });
2782
3832
  const registry = this.#destinations(evidence);
@@ -2784,7 +3834,7 @@ var CaptureIntegrity = class {
2784
3834
  ...selection,
2785
3835
  variants: this.#variants(registry, selection)
2786
3836
  };
2787
- const required = this.#select(evidence, registry, options, false);
3837
+ const required = this.#select(registry, options);
2788
3838
  const disk = this.#images();
2789
3839
  const identities = /* @__PURE__ */ new Map();
2790
3840
  const physical = Map.groupBy(disk, (file) => this.#physicalIdentity(file, identities));
@@ -2874,8 +3924,9 @@ var CaptureIntegrity = class {
2874
3924
  *
2875
3925
  * @param options - The original selector, producing variants, state, and optional exact case
2876
3926
  * @returns The agreed declaring case, output mappings, and validated lookup receipts
2877
- * @throws Thrown when evidence is missing, stale, ambiguous, or disagrees with the selection;
2878
- * the message names the explicit refresh command.
3927
+ * @throws Thrown when evidence is missing, stale, ambiguous, or disagrees with the selection; a
3928
+ * refusal of the requested state names the owner's journey refresh, and a fault in the evidence
3929
+ * read keeps its own message.
2879
3930
  *
2880
3931
  * @example
2881
3932
  * ```ts
@@ -2887,7 +3938,7 @@ var CaptureIntegrity = class {
2887
3938
  const snapshots = /* @__PURE__ */ new Map();
2888
3939
  const digests = /* @__PURE__ */ new Map();
2889
3940
  const evidence = this.#evidence(snapshots);
2890
- const entries = this.#select(evidence, this.#destinations(evidence), options, true);
3941
+ const entries = this.#select(this.#destinations(evidence), options, collectCaptureProducers(evidence));
2891
3942
  this.#uniqueRegistry(entries);
2892
3943
  const cases = [...new Set(entries.map((entry) => entry.case))];
2893
3944
  const [name] = cases;
@@ -2898,15 +3949,17 @@ var CaptureIntegrity = class {
2898
3949
  lookups: entries.map((entry) => {
2899
3950
  const run = evidence.runs.find((record) => record.run.registry.some((destination) => describeCaptureDestination(destination) === describeCaptureDestination(entry)));
2900
3951
  const lookup = evidence.lookups.find((candidate) => candidate.case === entry.case && candidate.variant === run?.run.variant && candidate.states.includes(options.state));
2901
- if (lookup === void 0 || lookup.registry !== evidence.registry.digest || !matchesCaptureSelector(lookup.owner, options.selector) || collectCaptureChanges(lookup.inputs, this.#digest(this.#options.inputs, snapshots, digests).files).length > 0) throw new CaptureError(`Missing or stale state lookup: ${entry.state} in ${entry.project}`, { code: "EVIDENCE" });
3952
+ if (lookup === void 0 || lookup.registry !== evidence.registry.digest || !matchesCaptureSelector(lookup.owner, options.selector) || collectCaptureChanges(lookup.inputs, this.#digest(this.#options.inputs, snapshots, digests).files).length > 0) throw new CaptureError(`Missing or stale state lookup: ${entry.state} in ${entry.project}`, { code: "LOOKUP" });
2902
3953
  const stamp = evidence.manifest?.entries[resolveCaptureKey(entry)];
2903
3954
  if (stamp !== void 0 && describeCaptureIdentity(stamp) !== describeCaptureIdentity(entry)) throw new CaptureError("State lookup disagrees with the manifest identity", { code: "EVIDENCE" });
2904
3955
  return lookup;
2905
3956
  })
2906
3957
  };
2907
3958
  } catch (error) {
2908
- throw new CaptureError(`${describeCaptureError(error)}. Refresh explicitly with: capture journey ${options.selector}${options.variants.map((variant) => ` --variant ${variant}`).join("")}${options.case === void 0 ? "" : ` --case ${JSON.stringify(options.case)}`}. Registry declaration changes require the complete-registry refresh: capture registry.`, {
2909
- code: isCaptureError(error) ? error.code : "EVIDENCE",
3959
+ if (matchesCaptureVersionRefusal(error)) throw error;
3960
+ const code = isCaptureError(error) ? error.code : "EVIDENCE";
3961
+ throw new CaptureError(code === "LOOKUP" || code === "USAGE" || code === "SELECTION" ? `${describeCaptureError(error)}. Refresh explicitly with: capture journey ${options.selector}${options.variants.map((variant) => ` --variant ${variant}`).join("")}${options.case === void 0 ? "" : ` --case ${JSON.stringify(options.case)}`}. Registry declaration changes require the complete-registry refresh: capture registry.` : describeCaptureError(error), {
3962
+ code,
2910
3963
  cause: error
2911
3964
  });
2912
3965
  }
@@ -3089,12 +4142,24 @@ var CaptureIntegrity = class {
3089
4142
  ]) {
3090
4143
  const current = this.#digest(patterns, snapshots, digests);
3091
4144
  if (Object.keys(current.files).some((file) => before.files[file] === void 0)) throw new CaptureError(`Attribution outside the predeclared host population: ${entry.file}`, { code: "STAGE" });
3092
- const previous = Object.fromEntries(Object.entries(before.files).filter(([file]) => patterns.some((pattern) => matchesGlob(file, pattern))));
4145
+ const matched = this.#match(before, patterns);
4146
+ const previous = Object.fromEntries(Object.entries(before.files).filter(([file]) => matched.has(file)));
3093
4147
  if (collectCaptureChanges(previous, current.files).length > 0) throw new CaptureError(`Attributed inputs or membership changed during execution: ${entry.file}`, { code: "STAGE" });
3094
- if (patterns.some((pattern) => !Object.keys(current.files).some((file) => matchesGlob(file, pattern)))) throw new CaptureError(`Declared source pattern has no files: ${entry.file}`, { code: "HOST" });
4148
+ if (patterns.some((pattern) => {
4149
+ const files = this.#match(before, [pattern]);
4150
+ return !Object.keys(current.files).some((file) => files.has(file));
4151
+ })) throw new CaptureError(`Declared source pattern has no files: ${entry.file}`, { code: "HOST" });
3095
4152
  }
3096
4153
  stable.set(key, true);
3097
4154
  }
4155
+ #match(inputs, patterns) {
4156
+ const key = computeCaptureMatchKey(inputs, patterns);
4157
+ const known = this.#matches.get(key);
4158
+ if (known !== void 0) return known;
4159
+ const matched = filterCaptureInputs(inputs, patterns);
4160
+ this.#matches.set(key, matched);
4161
+ return matched;
4162
+ }
3098
4163
  #destination(entry, paths) {
3099
4164
  const portfolio = this.#options.portfolios.find((candidate) => candidate.portfolio === entry.portfolio);
3100
4165
  if (portfolio === void 0) throw new CaptureError(`Unknown portfolio: ${entry.portfolio}`, { code: "SELECTION" });
@@ -3107,26 +4172,34 @@ var CaptureIntegrity = class {
3107
4172
  requireCaptureUnique(entries.map((entry) => entry.file), "registry paths", true);
3108
4173
  }
3109
4174
  #registry(snapshots, paths) {
3110
- if (!existsSync(this.#path(this.#options.registry, paths))) throw new CaptureError("Missing accepted registry; run the explicit complete-registry refresh", { code: "EVIDENCE" });
3111
- const registry = this.#json(this.#options.registry, paths);
3112
- if (!isCaptureRegistry(registry) || registry.digest !== computeRegistryDigest(registry) || registry.receipts.length === 0) throw new CaptureError("Invalid accepted registry schema or digest", { code: "EVIDENCE" });
3113
- requireCaptureUnique(registry.receipts.map((receipt) => receipt.variant), "complete receipt variants", true);
3114
- for (const receipt of registry.receipts) {
3115
- const report = this.#file(receipt.report.file, snapshots, paths);
3116
- if (!receipt.complete || report?.image.digest !== receipt.report.digest) throw new CaptureError("Registry receipt is incomplete or its report changed", { code: "EVIDENCE" });
3117
- validateCaptureReceipt(receipt, readCaptureReport(this.#json(receipt.report.file, paths)));
3118
- for (const path of Object.keys(receipt.inputs)) this.#path(path, paths);
3119
- requireCaptureUnique(Object.keys(receipt.inputs), "receipt input paths", true);
4175
+ try {
4176
+ if (!existsSync(this.#path(this.#options.registry, paths))) throw new CaptureError("Missing accepted registry; run the explicit complete-registry refresh", { code: "EVIDENCE" });
4177
+ const registry = this.#json(this.#options.registry, paths);
4178
+ requireCaptureVersion(registry, "Registry", this.#options.registry, [
4179
+ this.#options.registry,
4180
+ this.#options.manifest,
4181
+ this.#options.lookups
4182
+ ]);
4183
+ if (!isCaptureRegistry(registry) || registry.digest !== computeRegistryDigest(registry) || registry.receipts.length === 0) throw new CaptureError("Invalid accepted registry schema or digest", { code: "EVIDENCE" });
4184
+ requireCaptureUnique(registry.receipts.map((receipt) => receipt.variant), "complete receipt variants", true);
4185
+ for (const receipt of registry.receipts) {
4186
+ const report = this.#file(receipt.report.file, snapshots, paths);
4187
+ if (!receipt.complete || report?.image.digest !== receipt.report.digest) throw new CaptureError("Registry receipt is incomplete or its report changed", { code: "EVIDENCE" });
4188
+ validateCaptureReceipt(receipt, readCaptureReport(this.#json(receipt.report.file, paths)));
4189
+ for (const path of Object.keys(receipt.inputs)) this.#path(path, paths);
4190
+ requireCaptureUnique(Object.keys(receipt.inputs), "receipt input paths", true);
4191
+ }
4192
+ if (!matchesCaptureMembers(registry.entries.map(describeCaptureDestination), registry.receipts.flatMap((receipt) => receipt.registry.map(describeCaptureDestination)))) throw new CaptureError("Registry entries differ from complete receipts", { code: "EVIDENCE" });
4193
+ for (const entry of registry.entries) this.#destination(entry, paths);
4194
+ return registry;
4195
+ } catch (error) {
4196
+ throw resolveCaptureRegistryFault(error);
3120
4197
  }
3121
- if (!matchesCaptureMembers(registry.entries.map(describeCaptureDestination), registry.receipts.flatMap((receipt) => receipt.registry.map(describeCaptureDestination)))) throw new CaptureError("Registry entries differ from complete receipts", { code: "EVIDENCE" });
3122
- for (const entry of registry.entries) this.#destination(entry, paths);
3123
- return registry;
3124
4198
  }
3125
4199
  #evidence(snapshots) {
3126
4200
  const paths = /* @__PURE__ */ new Map();
3127
4201
  const registry = this.#registry(snapshots, paths);
3128
- const manifest = existsSync(this.#path(this.#options.manifest, paths)) ? this.#json(this.#options.manifest, paths) : void 0;
3129
- if (manifest !== void 0 && !isCaptureStoredManifest(manifest)) throw new CaptureError("Invalid inherited manifest schema", { code: "EVIDENCE" });
4202
+ const manifest = existsSync(this.#path(this.#options.manifest, paths)) ? readCaptureManifest(this.#json(this.#options.manifest, paths), this.#options.manifest) : void 0;
3130
4203
  if (manifest !== void 0) {
3131
4204
  requireCaptureUnique(Object.keys(manifest.entries), "manifest keys", true);
3132
4205
  if (manifest.registry.digest !== computeRegistryDigest(manifest.registry)) throw new CaptureError("Invalid inherited registry digest", { code: "EVIDENCE" });
@@ -3141,10 +4214,9 @@ var CaptureIntegrity = class {
3141
4214
  ]) this.#path(path, paths);
3142
4215
  }
3143
4216
  }
3144
- const separate = existsSync(this.#path(this.#options.lookups, paths)) ? this.#json(this.#options.lookups, paths) : void 0;
3145
- if (separate !== void 0 && !isCaptureLookupJournal(separate)) throw new CaptureError("Invalid separate lookup schema", { code: "EVIDENCE" });
4217
+ const separate = existsSync(this.#path(this.#options.lookups, paths)) ? readCaptureLookupJournal(this.#json(this.#options.lookups, paths), this.#options.lookups) : void 0;
3146
4218
  const manifestDigest = this.#file(this.#options.manifest, snapshots, paths)?.image.digest;
3147
- const current = separate !== void 0 && separate.manifest === manifestDigest ? readCaptureLookups(separate) : [];
4219
+ const current = separate !== void 0 && separate.manifest === manifestDigest ? readCaptureLookups(separate, this.#options.lookups) : [];
3148
4220
  const lookups = mergeCaptureLookups(manifest?.lookups ?? [], current).filter((entry) => entry.registry === registry.digest);
3149
4221
  const populations = /* @__PURE__ */ new Map();
3150
4222
  const runs = [...Map.groupBy(lookups, (entry) => entry.run.file)].map(([file, referenced]) => {
@@ -3188,9 +4260,9 @@ var CaptureIntegrity = class {
3188
4260
  const declarations = receipt?.declarations ?? previous?.declarations;
3189
4261
  const registry = receipt?.registry ?? previous?.registry;
3190
4262
  if (declarations !== void 0 && registry !== void 0) {
3191
- if (!matchesCaptureMembers(declarations.map(describeCaptureDeclaration), run.declarations.map(describeCaptureDeclaration)) || !matchesCaptureMembers(registry.map(describeCaptureDestination), run.registry.map(describeCaptureDestination))) throw new CaptureError("Collected registry declarations changed; run the explicit complete-registry refresh", { code: "EVIDENCE" });
4263
+ if (!matchesCaptureMembers(declarations.map(describeCaptureDeclaration), run.declarations.map(describeCaptureDeclaration)) || !matchesCaptureMembers(registry.map(describeCaptureDestination), run.registry.map(describeCaptureDestination))) throw new CaptureError("Collected registry declarations changed; run the explicit complete-registry refresh", { code: "REGISTRY" });
3192
4264
  } else if (!evidence.registry.receipts.some((entry) => collectCaptureChanges(entry.inputs, inputs).length === 0)) throw new CaptureError("Unattested producing variant; run the explicit complete-registry refresh before its owner lookup refresh", {
3193
- code: "EVIDENCE",
4265
+ code: "REGISTRY",
3194
4266
  context: { variant: run.variant }
3195
4267
  });
3196
4268
  }
@@ -3205,7 +4277,7 @@ var CaptureIntegrity = class {
3205
4277
  return first.run.registry;
3206
4278
  })];
3207
4279
  }
3208
- #select(evidence, entries, options, attributed) {
4280
+ #select(entries, options, producers) {
3209
4281
  const selectors = [...new Set(entries.flatMap((entry) => {
3210
4282
  const parts = resolveCaptureOwner(entry).split(":");
3211
4283
  return parts.map((_part, index) => parts.slice(0, index + 1).join(":"));
@@ -3230,19 +4302,16 @@ var CaptureIntegrity = class {
3230
4302
  const scoped = entries.filter((entry) => matchesCaptureSelector(resolveCaptureOwner(entry), options.selector) && (options.portfolio === void 0 || entry.portfolio === options.portfolio));
3231
4303
  if (scoped.length === 0) throw new CaptureError(`Empty selector; ${describeCaptureFault("selector", options.selector, "a declared selector with destinations in the selected portfolio", ["all", ...selectors])}`, { code: "USAGE" });
3232
4304
  if (options.variants.length === 0) throw new CaptureError(`Invalid capture selection; ${describeCaptureFault("selection.variants", options.variants, "a nonempty selected variant list", [...new Set(scoped.map((entry) => entry.variant))])}`, { code: "USAGE" });
3233
- const variants = [...new Set(attributed ? entries.map((entry) => this.#producer(entry, evidence)) : entries.map((entry) => entry.variant))];
4305
+ const variants = [...new Set(producers === void 0 ? entries.map((entry) => entry.variant) : entries.map((entry) => requireCaptureProducer(entry, producers)))];
3234
4306
  const unknown = options.variants.find((variant) => !variants.includes(variant));
3235
- if (unknown !== void 0) throw new CaptureError(`Unknown or unattested selected variant; ${describeCaptureFault("selection.variants", unknown, "an attested registry variant", variants)}`, { code: "USAGE" });
3236
- const selected = scoped.filter((entry) => options.variants.includes(attributed ? this.#producer(entry, evidence) : entry.variant) && (options.state === void 0 || entry.state === options.state) && (options.case === void 0 || entry.case === options.case));
4307
+ if (unknown !== void 0) throw new CaptureError(`Unknown or unattested selected variant; ${describeCaptureFault("selection.variants", unknown, "an attested registry variant", variants)}`, {
4308
+ code: "REGISTRY",
4309
+ context: { variant: unknown }
4310
+ });
4311
+ const selected = scoped.filter((entry) => options.variants.includes(producers === void 0 ? entry.variant : requireCaptureProducer(entry, producers)) && (options.state === void 0 || entry.state === options.state) && (options.case === void 0 || entry.case === options.case));
3237
4312
  if (selected.length === 0) throw new CaptureError(`Empty selection or state outside selector/case; ${describeCaptureFault("selection.state", options.state, "a state in the selected selector/case", [...new Set(scoped.map((entry) => entry.state))])}; ${describeCaptureFault("selection.case", options.case, "a case in the selected selector", [...new Set(scoped.map((entry) => entry.case))])}`, { code: "USAGE" });
3238
4313
  return selected;
3239
4314
  }
3240
- #producer(destination, evidence) {
3241
- const sources = [...evidence.registry.receipts, ...evidence.runs.map((entry) => entry.run)];
3242
- const variants = [...new Set(sources.filter((source) => source.registry.some((entry) => describeCaptureDestination(entry) === describeCaptureDestination(destination))).map((source) => source.variant))];
3243
- if (variants.length !== 1 || variants[0] === void 0) throw new CaptureError("Destination has no unique producing variant", { code: "EVIDENCE" });
3244
- return variants[0];
3245
- }
3246
4315
  #reportPath(args, paths) {
3247
4316
  const outputs = args.filter((argument) => argument.startsWith("--outputFile.json="));
3248
4317
  if (outputs.length !== 1 || outputs[0] === void 0) throw new CaptureError("Request has no unique JSON reporter path", { code: "HOST" });
@@ -3394,6 +4463,7 @@ var CaptureInvocation = class {
3394
4463
  }
3395
4464
  async release() {
3396
4465
  const failures = [];
4466
+ const kept = [];
3397
4467
  try {
3398
4468
  if (this.#termination !== void 0) await this.#termination;
3399
4469
  failures.push(...await settleCaptureShutdown(() => this.retract(), [...this.#children].map((child) => () => this.#stop(child))));
@@ -3412,7 +4482,10 @@ var CaptureInvocation = class {
3412
4482
  }
3413
4483
  if (this.#owner(marker.value).id !== this.id) return;
3414
4484
  if (this.#unconfirmed.size > 0) {
3415
- this.#record();
4485
+ kept.push(`ownership marker retained: ${this.#lock}`);
4486
+ const record = attempt(() => this.#record());
4487
+ if (record.success) kept.push(`child record: ${record.value}`);
4488
+ else failures.push(record.error);
3416
4489
  return;
3417
4490
  }
3418
4491
  this.#remove(deadline);
@@ -3421,7 +4494,7 @@ var CaptureInvocation = class {
3421
4494
  else if (!removal.success) failures.push(removal.error);
3422
4495
  }
3423
4496
  }
3424
- if (failures.length > 0 || this.#unconfirmed.size > 0) throw new CaptureError(`Capture shutdown failed${this.#unconfirmed.size === 0 ? "" : `; child termination was not confirmed for process ${[...this.#unconfirmed].join(", ")}; ownership marker retained: ${this.#lock}; child record: ${resolve(this.#directory, CAPTURE_SURVIVORS_FILE)}`}`, {
4497
+ if (failures.length > 0 || this.#unconfirmed.size > 0) throw new CaptureError(`Capture shutdown failed${this.#unconfirmed.size === 0 ? "" : `; child termination was not confirmed for process ${[...this.#unconfirmed].join(", ")}`}${kept.map((entry) => `; ${entry}`).join("")}`, {
3425
4498
  code: "STAGE",
3426
4499
  cause: new AggregateError(failures)
3427
4500
  });
@@ -3433,15 +4506,21 @@ var CaptureInvocation = class {
3433
4506
  for (const name of readdirSync(requests)) {
3434
4507
  const pid = readCaptureRequestOwner(name);
3435
4508
  if (pid === void 0 || pid === process.pid) continue;
3436
- if (!readCaptureRunning(pid)) rmSync(resolve(requests, name), { force: true });
4509
+ if (this.#alive(pid) === false) attempt(() => rmSync(resolve(requests, name), { force: true }));
3437
4510
  }
3438
4511
  }
3439
4512
  holders() {
3440
4513
  const requests = resolve(this.#options.root, this.#options.requests);
3441
4514
  return [...new Set(readdirSync(requests).flatMap((name) => {
3442
4515
  const pid = readCaptureRequestOwner(name);
3443
- return pid === void 0 || pid === process.pid && this.#lease !== void 0 || !readCaptureRunning(pid) ? [] : [pid];
3444
- }))];
4516
+ return pid === void 0 || pid === process.pid && this.#lease !== void 0 ? [] : [pid];
4517
+ }))].flatMap((pid) => {
4518
+ const alive = this.#alive(pid);
4519
+ return alive === false ? [] : [{
4520
+ pid,
4521
+ inspected: alive === true
4522
+ }];
4523
+ });
3445
4524
  }
3446
4525
  publish(request) {
3447
4526
  this.#claim();
@@ -3476,16 +4555,13 @@ var CaptureInvocation = class {
3476
4555
  try {
3477
4556
  mkdirSync(this.#directory, { recursive: true });
3478
4557
  writeFileSync(log, "");
3479
- const environment = Object.fromEntries(Object.entries(process.env).filter(([name]) => name.toLowerCase() !== "CAPTURE".toLowerCase() && name.toLowerCase() !== "CAPTURE_REQUESTS".toLowerCase()));
3480
4558
  const session = createDuplex({
3481
4559
  command: {
3482
4560
  file: process.execPath,
3483
4561
  arguments: args,
3484
- isolated: true,
3485
4562
  environment: {
3486
- ...environment,
3487
4563
  [CAPTURE_REQUESTS_FLAG]: resolve(this.#options.root, this.#options.requests),
3488
- ...capture ? { [CAPTURE_FLAG]: "1" } : {}
4564
+ [CAPTURE_FLAG]: capture ? "1" : void 0
3489
4565
  }
3490
4566
  },
3491
4567
  workspace: this.#options.root,
@@ -3597,9 +4673,10 @@ var CaptureInvocation = class {
3597
4673
  try {
3598
4674
  if (this.#options.ownership?.write === void 0) writeFileSync(file, text, { flag: "wx" });
3599
4675
  else this.#options.ownership.write(file, text);
4676
+ return file;
3600
4677
  } catch (error) {
3601
4678
  const code = error instanceof Error && "code" in error ? String(error.code) : describeCaptureError(error);
3602
- if (code === "EEXIST") return;
4679
+ if (code === "EEXIST") return file;
3603
4680
  if (code === "ENOENT" && retry) {
3604
4681
  mkdirSync(this.#directory, { recursive: true });
3605
4682
  return this.#record(false);
@@ -3623,9 +4700,9 @@ var CaptureInvocation = class {
3623
4700
  }
3624
4701
  #backoff(deadline, error) {
3625
4702
  const left = deadline - performance.now();
3626
- if (left <= 0) throw new CaptureError(`Capture ownership marker is temporarily unavailable (${error instanceof Error && "code" in error ? String(error.code) : "contention"}): ${this.#lock}; rerun after serializing capture commands`, {
4703
+ if (left <= 0) throw new CaptureError(error === void 0 ? `Capture ownership marker kept changing until the deadline: ${this.#lock}; rerun after serializing capture commands` : `Capture ownership marker is temporarily unavailable (${error instanceof Error && "code" in error ? String(error.code) : describeCaptureError(error)}): ${this.#lock}; rerun after serializing capture commands`, {
3627
4704
  code: "STAGE",
3628
- cause: error
4705
+ ...error === void 0 ? {} : { cause: error }
3629
4706
  });
3630
4707
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Math.min(10, left));
3631
4708
  }
@@ -3640,7 +4717,7 @@ var CaptureInvocation = class {
3640
4717
  for (const name of readdirSync(requests)) {
3641
4718
  if (!name.startsWith(`.capture-owner.`) || !name.endsWith(".tmp")) continue;
3642
4719
  const [pid] = name.slice(CAPTURE_OWNER_FILE.length + 1).split(".");
3643
- if (pid !== void 0 && /^\d+$/u.test(pid) && Number.isSafeInteger(Number(pid)) && Number(pid) > 0 && !readCaptureRunning(Number(pid))) attempt(() => rmSync(resolve(requests, name), { force: true }));
4720
+ if (pid !== void 0 && /^\d+$/u.test(pid) && Number.isSafeInteger(Number(pid)) && Number(pid) > 0 && this.#alive(Number(pid)) === false) attempt(() => rmSync(resolve(requests, name), { force: true }));
3644
4721
  }
3645
4722
  const temporary = `${this.#lock}.${String(process.pid)}.${this.id}.tmp`;
3646
4723
  try {
@@ -3665,7 +4742,7 @@ var CaptureInvocation = class {
3665
4742
  cause: error
3666
4743
  });
3667
4744
  } finally {
3668
- rmSync(temporary, { force: true });
4745
+ attempt(() => rmSync(temporary, { force: true }));
3669
4746
  }
3670
4747
  }
3671
4748
  #acquire(temporary, deadline) {
@@ -3692,7 +4769,7 @@ var CaptureInvocation = class {
3692
4769
  });
3693
4770
  }
3694
4771
  const owner = attempt(() => this.#owner(marker.value));
3695
- const alive = owner.success ? (this.#options.ownership?.alive ?? readCaptureRunning)(owner.value.pid) : void 0;
4772
+ const alive = owner.success ? this.#alive(owner.value.pid) : void 0;
3696
4773
  if (!owner.success) this.#backoff(deadline);
3697
4774
  const confirmed = attempt(() => this.#read(deadline));
3698
4775
  if (!confirmed.success) {
@@ -3711,7 +4788,10 @@ var CaptureInvocation = class {
3711
4788
  return this.#acquire(temporary, deadline);
3712
4789
  }
3713
4790
  if (!owner.success) throw owner.error;
3714
- this.#refuse(owner.value, alive === true);
4791
+ this.#refuse(owner.value, alive);
4792
+ }
4793
+ #alive(pid) {
4794
+ return (this.#options.ownership?.alive ?? inspectProcess)(pid);
3715
4795
  }
3716
4796
  #owner(marker) {
3717
4797
  if (marker === "") throw new CaptureError(`Capture ownership marker is empty; confirm no capture process or surviving child is running and inspect this file: ${this.#lock}; its holder cannot be established`, { code: "STAGE" });
@@ -3723,15 +4803,18 @@ var CaptureInvocation = class {
3723
4803
  };
3724
4804
  }
3725
4805
  #refuse(holder, alive) {
3726
- if (!alive) throw new CaptureError(`Capture ownership process ${String(holder.pid)} is not running; invocation ${preview(holder.id)}. ${this.#survivors(holder)} Confirm no capture process or surviving child is running and re-read ${this.#lock} to confirm it still names pid ${String(holder.pid)} before you delete this file and rerun`, { code: "STAGE" });
4806
+ if (alive === false) throw new CaptureError(`Capture ownership process ${String(holder.pid)} is not running; invocation ${preview(holder.id)}. ${this.#survivors(holder)} Confirm no capture process or surviving child is running and re-read ${this.#lock} to confirm it still names pid ${String(holder.pid)} before you delete this file and rerun`, { code: "STAGE" });
4807
+ if (alive === void 0) throw new CaptureError(`Capture ownership process ${String(holder.pid)} could not be inspected; invocation ${preview(holder.id)}; serialize capture commands. Confirm no capture process or surviving child is running and re-read ${this.#lock} to confirm it still names pid ${String(holder.pid)} before deleting`, { code: "STAGE" });
3727
4808
  throw new CaptureError(`Another runner holds this workspace (process ${preview(holder.pid)}); invocation ${preview(holder.id)}; serialize capture commands. If this pid is not a capture run, confirm no capture process or surviving child is running and re-read ${this.#lock} to confirm it still names pid ${String(holder.pid)} before deleting`, { code: "STAGE" });
3728
4809
  }
3729
4810
  #survivors(holder) {
4811
+ if (!/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/u.test(holder.id)) return `Invocation ${preview(holder.id)} is not an invocation id; no child record is read.`;
3730
4812
  const file = resolve(this.#options.root, this.#options.requests, CAPTURE_RUNS_DIRECTORY, holder.id, CAPTURE_SURVIVORS_FILE);
3731
4813
  try {
3732
4814
  const record = parseJSON(this.#options.ownership?.read === void 0 ? readFileSync(file, "utf8") : this.#options.ownership.read(file));
3733
4815
  if (!isRecord(record) || record.pid !== holder.pid || record.id !== holder.id || typeof record.command !== "string" || record.command === "" || typeof record.at !== "string" || !Number.isFinite(Date.parse(record.at)) || !Array.isArray(record.children) || !record.children.every((pid) => typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0)) return `Child record could not be read (EINVAL): ${file}.`;
3734
- return `Unconfirmed child processes: ${record.children.join(", ")}; stop them before deleting. Child record: ${file}.`;
4816
+ const omitted = record.children.length - 16;
4817
+ return `Unconfirmed child processes: ${[...record.children.slice(0, 16), ...omitted > 0 ? [`… ${String(omitted)} more`] : []].join(", ")}; stop them before deleting. Child record: ${file}.`;
3735
4818
  } catch (error) {
3736
4819
  const code = error instanceof SyntaxError ? "EINVAL" : error instanceof Error && "code" in error ? String(error.code) : describeCaptureError(error);
3737
4820
  return code === "ENOENT" ? `No child record exists at ${file}.` : `Child record could not be read (${code}): ${file}.`;
@@ -3808,7 +4891,7 @@ var CapturePreflight = class {
3808
4891
  if (!isCapturePath(resolveCaptureRelative(root, config))) throw new CaptureError("Reader config must be a contained repository path", { code: "USAGE" });
3809
4892
  requireCaptureSelection(selection.selector, [], loaded.map((entry) => entry.project), [], selection.portfolio);
3810
4893
  const primary = requireCaptureProjects(loaded.map((entry) => entry.project));
3811
- const standalone = primary.standalone.find((entry) => selection.portfolio === entry.portfolio || selection.selector === entry.portfolio || selection.selector.startsWith(`${entry.portfolio}:`));
4894
+ const standalone = resolveCaptureStandalone(primary.standalone, selection.selector, selection.portfolio);
3812
4895
  const options = buildCaptureIntegrityOptions(root, primary, standalone);
3813
4896
  requireCaptureSelection(selection.selector, selection.variants ?? [], loaded.map((entry) => entry.project), readCaptureVariants(root, resolve(root, options.directory, CAPTURE_REGISTRY_FILE)));
3814
4897
  const integrity = new CaptureIntegrity(options);
@@ -3901,22 +4984,8 @@ var CapturePreflight = class {
3901
4984
  async execute() {
3902
4985
  try {
3903
4986
  const result = await this.check();
3904
- const issues = result.issues;
3905
- this.#stdout(`${CAPTURE_REPORT_LINES.preflight} ${JSON.stringify({
3906
- selection: result.selection,
3907
- freshness: result.freshness,
3908
- mixed: result.mixed,
3909
- issues,
3910
- identical: collectCaptureIdentical(result.images),
3911
- sizes: result.images.map(({ entry, picture, size }) => ({
3912
- file: entry.file,
3913
- width: picture.width,
3914
- height: picture.height,
3915
- bytes: size
3916
- })),
3917
- acceptance: false
3918
- })}\n`);
3919
- return issues.length > 0 || result.freshness.entries.some((entry) => entry.status !== "current") ? CAPTURE_EXIT.failed : CAPTURE_EXIT.passed;
4987
+ this.#stdout(`${CAPTURE_REPORT_LINES.preflight} ${JSON.stringify(buildCaptureReaderReport(result))}\n`);
4988
+ return result.issues.length > 0 || result.freshness.entries.some((entry) => entry.status !== "current") ? CAPTURE_EXIT.failed : CAPTURE_EXIT.passed;
3920
4989
  } catch (error) {
3921
4990
  this.#stderr(`${describeCaptureError(error)}\n`);
3922
4991
  return resolveCaptureExit(error);
@@ -4004,14 +5073,14 @@ var CapturePreflight = class {
4004
5073
  issues: [describeCaptureError(outcome.error)]
4005
5074
  };
4006
5075
  const artifact = outcome.value;
4007
- const lines = artifact.text.split(/\r\n|\n/u);
5076
+ const lines = readCaptureArtifact(artifact.text);
4008
5077
  return {
4009
5078
  entry,
4010
5079
  artifact,
4011
5080
  issues: [
4012
5081
  ...artifact.run.passed.includes(location.value.case) && artifact.run.entries.some((emitted) => resolveCaptureKey(emitted) === resolveCaptureKey(entry)) ? [] : [`Judged record does not cover ${entry.file}: ${artifact.record}`],
4013
- ...lines.includes(`record=${artifact.record}`) ? [] : [`Judged journey artifact does not cover its record: ${artifact.file}`],
4014
- ...lines.includes(`case-ran=${location.value.case}`) ? [] : [`Judged journey artifact does not cover ${location.value.case}: ${artifact.file}`]
5082
+ ...lines.records.includes(artifact.record) ? [] : [`Judged journey artifact does not cover its record: ${artifact.file}`],
5083
+ ...lines.cases.includes(location.value.case) ? [] : [`Judged journey artifact does not cover ${location.value.case}: ${artifact.file}`]
4015
5084
  ]
4016
5085
  };
4017
5086
  });
@@ -4024,9 +5093,7 @@ var CapturePreflight = class {
4024
5093
  #manifest(directory) {
4025
5094
  const file = resolve(this.#options.root, directory, CAPTURE_MANIFEST_FILE);
4026
5095
  if (!existsSync(file)) return void 0;
4027
- const manifest = parseJSON(readFileSync(file, "utf8"));
4028
- if (!isCaptureStoredManifest(manifest)) throw new CaptureError("Invalid stamped manifest schema", { code: "EVIDENCE" });
4029
- return manifest;
5096
+ return readCaptureManifest(parseJSON(readFileSync(file, "utf8")), `${directory}/${CAPTURE_MANIFEST_FILE}`);
4030
5097
  }
4031
5098
  #locate(entry, stored, producers, directory) {
4032
5099
  const stamp = stored?.entries[resolveCaptureKey(entry)];
@@ -4078,14 +5145,16 @@ var CapturePreflight = class {
4078
5145
  * requires, so it cannot stamp through the integrity engine. It reads the wrapper through the same
4079
5146
  * discovery the runner uses, takes the same invocation entity, request file, and Vitest child, and runs
4080
5147
  * every selected producing variant in one stage, one child that receives each variant's project, with
4081
- * the `all` selector and no capture variable. It reads the stage's reporter once and each variant's
5148
+ * the `all` selector and no capture variable. The stage passes no tag filter, so it runs the whole
5149
+ * suite, which stands in for the consumer's complete test run. It reads the stage's reporter once and each variant's
4082
5150
  * final record, takes each project's input population before and after, and builds one receipt per
4083
5151
  * variant, all naming the one reporter, through `buildCaptureRegistry`. The registry is written to a
4084
5152
  * candidate beside its target, read back through the integrity engine, and only then renamed into
4085
5153
  * place, so a registry the engine would refuse never replaces a good one. With `--variant`, the
4086
5154
  * existing registry's receipts for the other declared variants are kept. It never widens a scoped
4087
5155
  * run into a refresh and refuses while another runner holds a request file in the request directory.
4088
- * Before any stage, it reads the inherited manifest and lookup journal and refuses an unsupported
5156
+ * Before any stage, it reads the inherited manifest and lookup journal: it refuses a document of
5157
+ * another version with that refusal's own removal and refresh commands alone, and an unsupported
4089
5158
  * schema with the file to inspect and repair.
4090
5159
  *
4091
5160
  * @example
@@ -4171,14 +5240,14 @@ var CaptureRegistrar = class {
4171
5240
  });
4172
5241
  this.#inherit(options);
4173
5242
  const holders = invocation.holders();
4174
- if (holders.length > 0) throw new CaptureError(`Another runner holds this workspace (process ${holders.join(", ")}); the registry refresh starts only while no runner is mid-stage`, {
5243
+ if (holders.length > 0) throw new CaptureError(`${describeCaptureHolders(holders, this.#options.requests)}; the registry refresh starts only while no runner is mid-stage`, {
4175
5244
  code: "STAGE",
4176
- context: { holders }
5245
+ context: { holders: holders.map((holder) => holder.pid) }
4177
5246
  });
4178
5247
  const retained = parsed.variants.length === 0 ? [] : this.#retain(target, variants, declared);
4179
5248
  if (retained.length > 0) buildCaptureRegistry(retained);
4180
5249
  if (invocation.interrupted) return CAPTURE_EXIT.failed;
4181
- const imports = await this.#stage(invocation, parsed, projects, primary, selected);
5250
+ const imports = await this.#stage(invocation, parsed, primary, selected);
4182
5251
  if (invocation.interrupted) return CAPTURE_EXIT.failed;
4183
5252
  const registry = buildCaptureRegistry([...retained, ...imports]);
4184
5253
  const path = resolve(root, candidate);
@@ -4203,13 +5272,16 @@ var CaptureRegistrar = class {
4203
5272
  return CAPTURE_EXIT.passed;
4204
5273
  }
4205
5274
  #inherit(options) {
4206
- for (const [file, guard] of [[options.manifest, isCaptureStoredManifest], [options.lookups, isCaptureLookupJournal]]) {
5275
+ for (const file of [options.manifest, options.lookups]) {
4207
5276
  const path = resolve(options.root, file);
4208
5277
  try {
4209
5278
  requireCaptureContained(options.root, path);
4210
5279
  if (!existsSync(path)) continue;
4211
- if (!guard(parseJSON(readFileSync(path, "utf8")))) throw new CaptureError("Invalid inherited evidence schema", { code: "EVIDENCE" });
5280
+ const value = parseJSON(readFileSync(path, "utf8"));
5281
+ if (file === options.manifest) readCaptureManifest(value, file);
5282
+ else readCaptureLookupJournal(value, file);
4212
5283
  } catch (error) {
5284
+ if (matchesCaptureVersionRefusal(error)) throw error;
4213
5285
  throw new CaptureError(`Cannot refresh the registry with inherited evidence at ${JSON.stringify(file)}: ${describeCaptureError(error)}; inspect and repair this file before retrying`, {
4214
5286
  code: "EVIDENCE",
4215
5287
  cause: error,
@@ -4218,9 +5290,8 @@ var CaptureRegistrar = class {
4218
5290
  }
4219
5291
  }
4220
5292
  }
4221
- async #stage(invocation, parsed, projects, primary, selected) {
5293
+ async #stage(invocation, parsed, primary, selected) {
4222
5294
  const { root } = this.#options;
4223
- const selectors = [...new Set(projects.flatMap((candidate) => candidate.tags))].filter((tag) => tag.startsWith(CAPTURE_OWNER_PREFIX)).map((tag) => tag.slice(CAPTURE_OWNER_PREFIX.length));
4224
5295
  const stage = CAPTURE_REGISTRY_STAGE;
4225
5296
  const variants = selected.map((project) => project.variant);
4226
5297
  const reportFile = resolve(invocation.directory, `${stage}.json`);
@@ -4230,13 +5301,14 @@ var CaptureRegistrar = class {
4230
5301
  entry: resolve(root, CAPTURE_VITEST_ENTRY),
4231
5302
  config: parsed.config,
4232
5303
  report: reportFile,
5304
+ progress: resolve(invocation.directory, `${stage}${CAPTURE_PROGRESS_SUFFIX}`),
5305
+ ...parsed.bail === void 0 ? {} : { bail: parsed.bail },
4233
5306
  projects: selected.map((project) => project.name),
4234
- filter: buildCaptureFilter("journey", "all", selectors),
4235
5307
  final: primary.final,
4236
5308
  ...parsed.mode === void 0 ? {} : { mode: parsed.mode }
4237
5309
  });
4238
5310
  const request = {
4239
- version: 1,
5311
+ version: CAPTURE_VERSION,
4240
5312
  id: invocation.id,
4241
5313
  stage,
4242
5314
  config: resolveCaptureRelative(root, parsed.config),
@@ -4403,60 +5475,69 @@ var CaptureRunner = class {
4403
5475
  stderr: this.#stderr
4404
5476
  });
4405
5477
  invocation.attach();
5478
+ const invocations = [invocation];
5479
+ const reports = [];
4406
5480
  const argumentsResult = attempt(() => readCaptureArguments(argv, command, root, config));
5481
+ const described = await this.#describe(invocation, argumentsResult).then((description) => success(description), (error) => failure(error));
5482
+ const result = isFailure(described) ? described : await this.#dispatch(invocation, invocations, reports, described.value.parsed, described.value.projects).then((code) => success(code), (error) => failure(error));
4407
5483
  try {
4408
- invocation.prepare();
4409
- if (!argumentsResult.success) throw argumentsResult.error;
4410
- const parsed = argumentsResult.value;
4411
- const projects = (await new CaptureDiscovery({
4412
- root,
4413
- config: parsed.config,
4414
- invocation,
4415
- ...parsed.mode === void 0 ? {} : { mode: parsed.mode },
4416
- ...this.#options.deadline === void 0 ? {} : { deadline: this.#options.deadline }
4417
- }).describe()).projects.map((entry) => entry.project);
4418
- if (parsed.selector !== void 0) requireCaptureSelection(parsed.selector, [], projects, [], parsed.portfolio);
4419
- if (command !== "stale" && parsed.variants.length > 0) resolveCaptureVariants(parsed.variants, projects);
4420
- if (command !== "stale" && parsed.case !== void 0) this.#case(requireCaptureProjects(projects), parsed.case, parsed.selector);
4421
- if (command !== "stale" && parsed.changed !== void 0) {
4422
- await invocation.release();
4423
- invocation.attach();
4424
- const code = await this.#changed(invocation, command, parsed, projects);
4425
- if (code === 64) rmSync(invocation.directory, {
4426
- recursive: true,
4427
- force: true
4428
- });
4429
- return code;
4430
- }
4431
- return command === "stale" ? await this.#check(parsed, projects) : await this.#run(invocation, command, parsed, projects);
4432
- } catch (error) {
4433
- if (resolveCaptureExit(error) === 64) rmSync(invocation.directory, {
5484
+ const code = isSuccess(result) ? result.value : resolveCaptureExit(result.error);
5485
+ if (code === CAPTURE_EXIT.usage) rmSync(invocation.directory, {
4434
5486
  recursive: true,
4435
5487
  force: true
4436
5488
  });
4437
- const ran = Object.values(CAPTURE_STAGES).filter((stage) => invocation.launched(resolve(invocation.directory, `${command}-${stage}.log`)));
4438
- const next = renderCaptureCommand(command, {
4439
- config: argumentsResult.success ? argumentsResult.value.config : resolve(root, config),
4440
- variants: []
4441
- }, "all", root);
4442
- this.#stderr(`${describeCaptureError(error)}\n${ran.length === 0 ? "No execution child ran; the command was refused before execution." : `Execution stopped after stages: ${ran.join(", ")}; no later stage ran.`}\nNEXT ${next}\n`);
4443
- return resolveCaptureExit(error);
5489
+ this.#conclude(result, invocations, reports, argumentsResult.success ? argumentsResult.value : void 0, isSuccess(described) ? described.value.projects : []);
5490
+ return code;
4444
5491
  } finally {
4445
5492
  await invocation.release().catch((error) => this.#stderr(`Capture cleanup failed: ${describeCaptureError(error)}\n`));
4446
5493
  }
4447
5494
  }
4448
- async #changed(discovery, command, parsed, projects) {
5495
+ async #describe(invocation, argumentsResult) {
5496
+ const { root } = this.#options;
5497
+ invocation.prepare();
5498
+ if (!argumentsResult.success) throw argumentsResult.error;
5499
+ const parsed = argumentsResult.value;
5500
+ return {
5501
+ parsed,
5502
+ projects: (await new CaptureDiscovery({
5503
+ root,
5504
+ config: parsed.config,
5505
+ invocation,
5506
+ ...parsed.mode === void 0 ? {} : { mode: parsed.mode },
5507
+ ...this.#options.deadline === void 0 ? {} : { deadline: this.#options.deadline }
5508
+ }).describe()).projects.map((entry) => entry.project)
5509
+ };
5510
+ }
5511
+ async #dispatch(invocation, invocations, reports, parsed, projects) {
5512
+ const { command } = this.#options;
5513
+ if (parsed.selector !== void 0) requireCaptureSelection(parsed.selector, [], projects, [], parsed.portfolio);
5514
+ if (command !== "stale" && parsed.variants.length > 0) resolveCaptureVariants(parsed.variants, projects);
5515
+ if (command !== "stale" && parsed.changed === void 0) this.#scope(parsed.selector, collectCaptureOwners(projects));
5516
+ if (command !== "stale" && parsed.case !== void 0) this.#case(requireCaptureProjects(projects), parsed.case, parsed.selector);
5517
+ if (command !== "stale" && parsed.changed !== void 0) {
5518
+ await invocation.release();
5519
+ invocation.attach();
5520
+ return await this.#changed(invocation, invocations, reports, command, parsed, projects);
5521
+ }
5522
+ return command === "stale" ? await this.#check(parsed, projects, reports) : await this.#run(invocation, command, parsed, projects, reports);
5523
+ }
5524
+ #conclude(result, invocations, reports, parsed, projects) {
5525
+ const { command } = this.#options;
5526
+ const lines = reports.length > 0 || isSuccess(result) || parsed === void 0 ? reports : this.#recover(result.error, parsed, parsed.selector, invocations.some((entry) => entry.interrupted), projects);
5527
+ const next = [...new Set(lines)].map((line) => `NEXT ${line}\n`).join("");
5528
+ if (reports.length > 0 && next !== "") this.#stdout(next);
5529
+ if (isSuccess(result)) return;
5530
+ const ran = Object.values(CAPTURE_STAGES).filter((stage) => invocations.some((entry) => entry.launched(resolve(entry.directory, `${command}-${stage}.log`))));
5531
+ this.#stderr(`${describeCaptureError(result.error)}\n${ran.length === 0 ? "No execution child ran; the command was refused before execution." : `Execution stopped after stages: ${ran.join(", ")}; no later stage ran.`}\n${reports.length > 0 ? "" : next}`);
5532
+ }
5533
+ async #changed(discovery, invocations, reports, command, parsed, projects) {
4449
5534
  const { root, requests } = this.#options;
4450
5535
  const primary = requireCaptureProjects(projects);
4451
5536
  const plan = this.#changes(parsed, primary);
4452
5537
  for (const change of plan.changes) this.#stdout(`CHANGE ${JSON.stringify(change)}\n`);
4453
5538
  const commands = plan.owners.map((owner) => renderCaptureCommand(command, parsed, owner, root));
4454
5539
  const shared = plan.changes.filter((change) => change.classification === "shared");
4455
- const complete = renderCaptureCommand("journey", {
4456
- config: parsed.config,
4457
- variants: parsed.variants,
4458
- ...parsed.mode === void 0 ? {} : { mode: parsed.mode }
4459
- }, "all", root);
5540
+ const complete = this.#complete(parsed);
4460
5541
  for (const next of commands) this.#stdout(`COMMAND ${next}\n`);
4461
5542
  const variants = resolveCaptureVariants(parsed.variants, projects);
4462
5543
  if (shared.length > 0) {
@@ -4468,7 +5549,7 @@ var CaptureRunner = class {
4468
5549
  notrun: plan.owners,
4469
5550
  reason: "shared inputs require an explicit journey selection"
4470
5551
  })}\n`);
4471
- for (const next of [...commands, complete]) this.#stdout(`NEXT ${next}\n`);
5552
+ reports.push(...commands, complete);
4472
5553
  return CAPTURE_EXIT.usage;
4473
5554
  }
4474
5555
  if (plan.owners.length === 0) {
@@ -4478,10 +5559,11 @@ var CaptureRunner = class {
4478
5559
  failed: [],
4479
5560
  notrun: [],
4480
5561
  reason: "only outside paths or no changed paths"
4481
- })}\nNEXT ${complete}\n`);
5562
+ })}\n`);
5563
+ reports.push(complete);
4482
5564
  return parsed.plan ? CAPTURE_EXIT.passed : CAPTURE_EXIT.failed;
4483
5565
  }
4484
- const selectors = [...new Set(projects.flatMap((project) => project.tags))].filter((tag) => tag.startsWith(CAPTURE_OWNER_PREFIX)).map((tag) => tag.slice(CAPTURE_OWNER_PREFIX.length));
5566
+ const selectors = collectCaptureOwners(projects);
4485
5567
  for (const owner of plan.owners) {
4486
5568
  const fault = describeCaptureSelectorFault(owner, selectors);
4487
5569
  if (fault !== void 0) throw new CaptureError(fault, { code: "HOST" });
@@ -4496,10 +5578,11 @@ var CaptureRunner = class {
4496
5578
  notrun: plan.owners,
4497
5579
  reason: "--plan starts no execution child"
4498
5580
  })}\n`);
4499
- for (const next of commands) this.#stdout(`NEXT ${next}\n`);
5581
+ reports.push(...commands);
4500
5582
  return CAPTURE_EXIT.passed;
4501
5583
  }
4502
5584
  const outcomes = [];
5585
+ const recorded = [];
4503
5586
  for (const owner of plan.owners) {
4504
5587
  if (discovery.interrupted) break;
4505
5588
  const invocation = new CaptureInvocation({
@@ -4509,16 +5592,24 @@ var CaptureRunner = class {
4509
5592
  stdout: this.#stdout,
4510
5593
  stderr: this.#stderr
4511
5594
  });
5595
+ invocations.push(invocation);
4512
5596
  invocation.attach();
5597
+ const owned = {
5598
+ ...parsed,
5599
+ selector: owner
5600
+ };
5601
+ const lines = [];
4513
5602
  try {
4514
- invocation.prepare();
4515
- const code = await this.#run(invocation, command, {
4516
- ...parsed,
4517
- selector: owner
4518
- }, projects).catch((error) => {
5603
+ const code = await Promise.resolve().then(async () => {
5604
+ invocation.prepare();
5605
+ return await this.#run(invocation, command, owned, projects, lines);
5606
+ }).catch((error) => {
5607
+ if (matchesCaptureVersionRefusal(error)) throw error;
4519
5608
  this.#stderr(`${describeCaptureError(error)}\n`);
5609
+ if (lines.length === 0) lines.push(...this.#recover(error, owned, owner, false, projects));
4520
5610
  return resolveCaptureExit(error);
4521
5611
  });
5612
+ if (code !== CAPTURE_EXIT.passed) recorded.push(...lines);
4522
5613
  outcomes.push({
4523
5614
  owner,
4524
5615
  code,
@@ -4538,10 +5629,18 @@ var CaptureRunner = class {
4538
5629
  notrun,
4539
5630
  reason: discovery.interrupted ? "interrupted" : failed.length > 0 ? "stopped at the first red owner" : "every selected owner passed"
4540
5631
  })}\n`);
4541
- for (const owner of [.../* @__PURE__ */ new Set([...failed.map((outcome) => outcome.owner), ...notrun])]) this.#stdout(`NEXT ${renderCaptureCommand(command, parsed, owner, root)}\n`);
4542
- if (failed.length === 0 && notrun.length === 0) this.#stdout(`NEXT ${complete}\n`);
5632
+ reports.push(...failed.length === 0 && notrun.length === 0 ? [complete] : [...recorded, ...notrun.map((owner) => renderCaptureCommand(command, parsed, owner, root))]);
4543
5633
  return failed.at(0)?.code ?? (discovery.interrupted ? CAPTURE_EXIT.failed : CAPTURE_EXIT.passed);
4544
5634
  }
5635
+ #scope(selector, selectors) {
5636
+ if (selector === void 0) throw new CaptureError(this.#usage(selectors), { code: "USAGE" });
5637
+ const fault = describeCaptureSelectorFault(selector, selectors);
5638
+ if (fault !== void 0) throw new CaptureError(fault, {
5639
+ code: "USAGE",
5640
+ context: { selector }
5641
+ });
5642
+ return selector;
5643
+ }
4545
5644
  #case(primary, name, selector) {
4546
5645
  const { root } = this.#options;
4547
5646
  const titles = readCaptureTitles(root, resolve(root, primary.directory, CAPTURE_REGISTRY_FILE), selector);
@@ -4552,31 +5651,18 @@ var CaptureRunner = class {
4552
5651
  if (parsed.changed === void 0) throw new CaptureError("Missing value: --changed", { code: "USAGE" });
4553
5652
  return this.#integrity(primary).changed(parsed.changed);
4554
5653
  } catch (error) {
4555
- const command = renderCaptureCommand("journey", {
4556
- config: parsed.config,
4557
- variants: []
4558
- }, "all", this.#options.root);
4559
- const registry = renderCaptureCommand("registry", {
4560
- config: parsed.config,
4561
- variants: []
4562
- }, void 0, this.#options.root);
4563
- throw new CaptureError(`${describeCaptureError(error)}\nNo owner ran; changed selection was refused.\n${isCaptureError(error) && error.code === "EVIDENCE" ? `NEXT ${registry}\n` : ""}NEXT ${command}`, {
5654
+ if (matchesCaptureVersionRefusal(error)) throw error;
5655
+ throw new CaptureError(`${describeCaptureError(error)}\nNo owner ran; changed selection was refused.`, {
4564
5656
  code: isCaptureError(error) ? error.code : "EVIDENCE",
4565
5657
  cause: error
4566
5658
  });
4567
5659
  }
4568
5660
  }
4569
- async #run(invocation, command, parsed, projects) {
5661
+ async #run(invocation, command, parsed, projects, reports) {
4570
5662
  const { root } = this.#options;
4571
5663
  const primary = requireCaptureProjects(projects);
4572
- const selectors = [...new Set(projects.flatMap((project) => project.tags))].filter((tag) => tag.startsWith(CAPTURE_OWNER_PREFIX)).map((tag) => tag.slice(CAPTURE_OWNER_PREFIX.length));
4573
- const selector = parsed.selector;
4574
- if (selector === void 0) throw new CaptureError(this.#usage(selectors), { code: "USAGE" });
4575
- const fault = describeCaptureSelectorFault(selector, selectors);
4576
- if (fault !== void 0) throw new CaptureError(fault, {
4577
- code: "USAGE",
4578
- context: { selector }
4579
- });
5664
+ const selectors = collectCaptureOwners(projects);
5665
+ const selector = this.#scope(parsed.selector, selectors);
4580
5666
  const variants = resolveCaptureVariants(parsed.variants, projects);
4581
5667
  const integrity = this.#integrity(primary);
4582
5668
  const selected = await this.#resolve(integrity, parsed, selector, variants);
@@ -4590,38 +5676,38 @@ var CaptureRunner = class {
4590
5676
  final: primary.final,
4591
5677
  directory: resolveCaptureRelative(root, primary.directory),
4592
5678
  config: resolveCaptureRelative(root, parsed.config),
4593
- ...parsed.mode === void 0 ? {} : { mode: parsed.mode }
5679
+ ...parsed.mode === void 0 ? {} : { mode: parsed.mode },
5680
+ ...parsed.bail === void 0 ? {} : { bail: parsed.bail }
4594
5681
  };
4595
5682
  const outcomes = [];
4596
5683
  const stages = resolveCaptureStages(variants, primary.first, command);
4597
5684
  const completed = [];
4598
- try {
4599
- for (const stage of stages) {
4600
- if (invocation.interrupted) return CAPTURE_EXIT.failed;
4601
- outcomes.push(...await this.#stage(invocation, integrity, plan, stage));
4602
- completed.push(stage);
4603
- }
4604
- for (const outcome of outcomes) this.#stdout(`${outcome.project}: ${String(outcome.count)} owner-bearing passed cases\n`);
4605
- if (outcomes.every((outcome) => outcome.count === 0)) throw new CaptureError("Empty selected workload: no requested project held applicable work", { code: "STAGE" });
4606
- return CAPTURE_EXIT.passed;
4607
- } finally {
4608
- const ran = stages.filter((stage) => invocation.launched(resolve(invocation.directory, `${command}-${stage.name}.log`)));
4609
- const notrun = stages.filter((stage) => !ran.includes(stage));
4610
- const failed = ran.filter((stage) => !completed.includes(stage));
4611
- const passed = completed.length === stages.length && outcomes.some((outcome) => outcome.count > 0);
4612
- this.#stdout(`STAGES ${JSON.stringify({
4613
- selector,
4614
- run: ran.map((stage) => stage.name),
4615
- passed: completed.map((stage) => stage.name),
4616
- failed: failed.map((stage) => stage.name),
4617
- notrun: notrun.map((stage) => stage.name),
4618
- reason: invocation.interrupted ? "interrupted; no later stage ran" : passed ? "selected workload passed" : failed.length > 0 ? "stage failed; no later stage ran" : notrun.length > 0 ? "refused before execution" : "empty selected workload"
4619
- })}\n`);
4620
- this.#stdout(`NEXT ${renderCaptureCommand(passed ? "journey" : command, passed ? {
4621
- config: parsed.config,
4622
- variants: []
4623
- } : parsed, passed ? "all" : selector, root)}\n`);
5685
+ const result = await this.#stages(invocation, integrity, plan, stages, outcomes, completed).then((code) => success(code), (error) => failure(error));
5686
+ const ran = stages.filter((stage) => invocation.launched(resolve(invocation.directory, `${command}-${stage.name}.log`)));
5687
+ const notrun = stages.filter((stage) => !ran.includes(stage));
5688
+ const failed = ran.filter((stage) => !completed.includes(stage));
5689
+ const passed = completed.length === stages.length && outcomes.some((outcome) => outcome.count > 0);
5690
+ this.#stdout(`STAGES ${JSON.stringify({
5691
+ selector,
5692
+ run: ran.map((stage) => stage.name),
5693
+ passed: completed.map((stage) => stage.name),
5694
+ failed: failed.map((stage) => stage.name),
5695
+ notrun: notrun.map((stage) => stage.name),
5696
+ reason: invocation.interrupted ? "interrupted; no later stage ran" : passed ? "selected workload passed" : failed.length > 0 ? "stage failed; no later stage ran" : notrun.length > 0 ? "refused before execution" : "empty selected workload"
5697
+ })}\n`);
5698
+ reports.push(...passed ? command === "journey" && selector === "all" && parsed.case === void 0 ? [] : [this.#complete(parsed)] : this.#recover(isFailure(result) ? result.error : void 0, parsed, selector, failed.length > 0 || invocation.interrupted, projects));
5699
+ if (isFailure(result)) throw result.error;
5700
+ return result.value;
5701
+ }
5702
+ async #stages(invocation, integrity, plan, stages, outcomes, completed) {
5703
+ for (const stage of stages) {
5704
+ if (invocation.interrupted) return CAPTURE_EXIT.failed;
5705
+ outcomes.push(...await this.#stage(invocation, integrity, plan, stage));
5706
+ completed.push(stage);
4624
5707
  }
5708
+ for (const outcome of outcomes) this.#stdout(`${outcome.project}: ${String(outcome.count)} owner-bearing passed cases\n`);
5709
+ if (outcomes.every((outcome) => outcome.count === 0)) throw new CaptureError("Empty selected workload: no requested project held applicable work", { code: "SELECTION" });
5710
+ return CAPTURE_EXIT.passed;
4625
5711
  }
4626
5712
  async #stage(invocation, integrity, plan, stage) {
4627
5713
  const { root } = this.#options;
@@ -4632,6 +5718,8 @@ var CaptureRunner = class {
4632
5718
  entry: resolve(root, CAPTURE_VITEST_ENTRY),
4633
5719
  config: resolve(root, plan.config),
4634
5720
  report,
5721
+ progress: resolve(invocation.directory, `${stage.name}${CAPTURE_PROGRESS_SUFFIX}`),
5722
+ ...plan.bail === void 0 ? {} : { bail: plan.bail },
4635
5723
  projects: selected.map((project) => project.name),
4636
5724
  filter: plan.filter,
4637
5725
  ...plan.mode === void 0 ? {} : { mode: plan.mode },
@@ -4640,7 +5728,7 @@ var CaptureRunner = class {
4640
5728
  final: plan.final
4641
5729
  });
4642
5730
  const request = {
4643
- version: 1,
5731
+ version: CAPTURE_VERSION,
4644
5732
  id: invocation.id,
4645
5733
  stage: stage.name,
4646
5734
  config: plan.config,
@@ -4716,11 +5804,11 @@ var CaptureRunner = class {
4716
5804
  const create = this.#options.integrity;
4717
5805
  return create === void 0 ? new CaptureIntegrity(options) : create(options);
4718
5806
  }
4719
- async #check(parsed, projects) {
5807
+ async #check(parsed, projects, reports) {
4720
5808
  const selector = parsed.selector;
4721
5809
  if (selector === void 0) throw new CaptureError(`Usage: capture ${CAPTURE_COMMAND_NAMES.stale} <selector> [--variant <output>] [--state <state>] [--case <full name>] [--portfolio <name>]`, { code: "USAGE" });
4722
5810
  const primary = requireCaptureProjects(projects);
4723
- const standalone = primary.standalone.find((root) => parsed.portfolio === root.portfolio || selector === root.portfolio || selector.startsWith(`${root.portfolio}:`));
5811
+ const standalone = resolveCaptureStandalone(primary.standalone, selector, parsed.portfolio);
4724
5812
  requireCaptureSelection(selector, parsed.variants, projects, readCaptureVariants(this.#options.root, resolve(this.#options.root, standalone?.directory ?? primary.directory, CAPTURE_REGISTRY_FILE)));
4725
5813
  const result = await this.#integrity(primary, standalone).check({
4726
5814
  selector,
@@ -4734,8 +5822,36 @@ var CaptureRunner = class {
4734
5822
  command: "stale",
4735
5823
  ...result
4736
5824
  })}\n`);
5825
+ if (standalone === void 0 && result.entries.some((entry) => CAPTURE_STATUS_RECOVERIES[entry.status] === "capture")) reports.push(renderCaptureCommand("capture", {
5826
+ config: parsed.config,
5827
+ variants: [],
5828
+ ...parsed.mode === void 0 ? {} : { mode: parsed.mode },
5829
+ ...parsed.case === void 0 ? {} : { case: parsed.case }
5830
+ }, selector, this.#options.root));
4737
5831
  return result.entries.every((entry) => entry.status === "current") ? CAPTURE_EXIT.passed : CAPTURE_EXIT.failed;
4738
5832
  }
5833
+ #recover(error, parsed, selector, unfinished, projects) {
5834
+ if (matchesCaptureVersionRefusal(error)) return [];
5835
+ const { command, root } = this.#options;
5836
+ const recovery = isCaptureError(error) ? CAPTURE_RECOVERIES[error.code] : void 0;
5837
+ const standalone = command === "stale" && selector !== void 0 && resolveCaptureStandalone(projects.flatMap((project) => project.standalone), selector, parsed.portfolio) !== void 0;
5838
+ return [
5839
+ ...recovery === "registry" && !standalone ? [renderCaptureCommand("registry", {
5840
+ config: parsed.config,
5841
+ variants: [],
5842
+ ...parsed.mode === void 0 ? {} : { mode: parsed.mode }
5843
+ }, void 0, root)] : [],
5844
+ ...recovery === "journey" && selector !== void 0 ? [renderCaptureCommand("journey", parsed, selector, root)] : [],
5845
+ ...unfinished && selector !== void 0 ? [renderCaptureCommand(command, parsed, selector, root)] : []
5846
+ ];
5847
+ }
5848
+ #complete(parsed) {
5849
+ return renderCaptureCommand("journey", {
5850
+ config: parsed.config,
5851
+ variants: parsed.variants,
5852
+ ...parsed.mode === void 0 ? {} : { mode: parsed.mode }
5853
+ }, "all", this.#options.root);
5854
+ }
4739
5855
  #usage(selectors) {
4740
5856
  const { command } = this.#options;
4741
5857
  const state = command === "capture" ? " [--state <name>]" : "";
@@ -4751,8 +5867,8 @@ var CaptureRunner = class {
4751
5867
  * selection through `CapturePreflight`, so it judges the same population the preflight does and
4752
5868
  * keeps its refusals. It writes the sheets, an index of every cell, and a notes document into a new
4753
5869
  * directory that is contained in the workspace, has an existing parent, and lies outside every
4754
- * selected capture directory. A frame whose image cannot be read shows as a red mark and is indexed
4755
- * as `missing`.
5870
+ * selected capture directory. A frame whose image cannot be read shows as a red mark with no source
5871
+ * size, and its index cell carries the freshness the engine classified, `missing` for an absent file.
4756
5872
  *
4757
5873
  * @example
4758
5874
  * ```ts
@@ -4801,23 +5917,31 @@ var CaptureSheets = class {
4801
5917
  await invocation.release().catch((error) => this.#stderr(`Capture cleanup failed: ${describeCaptureError(error)}\n`));
4802
5918
  }
4803
5919
  const result = await new CapturePreflight(reader).check();
4804
- const sheets = splitCapturePages(splitCapturePages(this.#groups(result), CAPTURE_SHEET.pairs).map((pair) => ({
4805
- groups: pair,
4806
- picture: composeCapturePictures(pair.map((entry) => entry.picture), false, CAPTURE_SHEET.gap)
4807
- })), CAPTURE_SHEET.rows).map((page, index) => ({
4808
- file: `${CAPTURE_SHEET_FILES.prefix}${String(index + 1).padStart(CAPTURE_SHEET_FILES.digits, "0")}.png`,
4809
- rows: page,
4810
- picture: composeCapturePictures(page.map((row) => row.picture), true, CAPTURE_SHEET.gap)
4811
- }));
5920
+ const sheets = splitCaptureSheets(splitCapturePages(this.#groups(result), CAPTURE_SHEET.pairs).map((pair) => ({
5921
+ pair,
5922
+ ...computeCaptureComposite(pair.map((group) => computeCaptureComposite(group.cells.map((cell) => cell.picture), false)), false, CAPTURE_SHEET.gap)
5923
+ })), CAPTURE_SHEET.rows, CAPTURE_SHEET.gap).map((page, index) => {
5924
+ const rows = page.map(({ pair }) => {
5925
+ const groups = pair.map((group) => ({
5926
+ ...group,
5927
+ picture: composeCapturePictures(group.cells.map((cell) => cell.picture), false)
5928
+ }));
5929
+ return {
5930
+ groups,
5931
+ picture: composeCapturePictures(groups.map((group) => group.picture), false, CAPTURE_SHEET.gap)
5932
+ };
5933
+ });
5934
+ return {
5935
+ file: `${CAPTURE_SHEET_FILES.prefix}${String(index + 1).padStart(CAPTURE_SHEET_FILES.digits, "0")}.png`,
5936
+ rows,
5937
+ picture: composeCapturePictures(rows.map((row) => row.picture), true, CAPTURE_SHEET.gap)
5938
+ };
5939
+ });
4812
5940
  const output = this.#output(result);
4813
5941
  mkdirSync(output);
4814
5942
  for (const sheet of sheets) writeFileSync(resolve(output, sheet.file), encodeCapturePicture(sheet.picture));
4815
5943
  const index = {
4816
- selection: result.selection,
4817
- freshness: result.freshness,
4818
- mixed: result.mixed,
4819
- issues: result.issues,
4820
- acceptance: false,
5944
+ ...buildCaptureReaderReport(result),
4821
5945
  sheets: sheets.map((sheet) => ({
4822
5946
  file: sheet.file,
4823
5947
  width: sheet.picture.width,
@@ -4857,30 +5981,28 @@ var CaptureSheets = class {
4857
5981
  }
4858
5982
  #groups(result) {
4859
5983
  return [...new Set(result.selection.entries.map((entry) => resolveCaptureSheetIdentity(entry)))].map((identity) => {
4860
- const cells = result.selection.entries.filter((entry) => resolveCaptureSheetIdentity(entry) === identity).map((entry) => {
4861
- const image = result.images.find((candidate) => candidate.entry.file === entry.file);
4862
- const factor = image === void 0 ? 1 : Math.max(1, Math.ceil(image.picture.width / CAPTURE_SHEET.cell));
4863
- return {
4864
- entry,
4865
- picture: image === void 0 ? {
4866
- width: CAPTURE_SHEET.mark.width,
4867
- height: CAPTURE_SHEET.mark.height,
4868
- pixels: Uint8Array.from({ length: CAPTURE_SHEET.mark.width * CAPTURE_SHEET.mark.height * 3 }, (_, index) => index % 3 === 0 ? CAPTURE_SHEET.mark.present : CAPTURE_SHEET.mark.absent)
4869
- } : image.thumbnail,
4870
- source: image === void 0 ? void 0 : {
4871
- width: image.picture.width,
4872
- height: image.picture.height,
4873
- bytes: image.size
4874
- },
4875
- factor,
4876
- clipped: image !== void 0 && Math.ceil(image.picture.height / factor) > CAPTURE_SHEET.limit,
4877
- freshness: result.freshness.entries.find((candidate) => candidate.file === entry.file)
4878
- };
4879
- });
4880
5984
  return {
4881
5985
  identity,
4882
- cells,
4883
- picture: composeCapturePictures(cells.map((cell) => cell.picture), false)
5986
+ cells: result.selection.entries.filter((entry) => resolveCaptureSheetIdentity(entry) === identity).map((entry) => {
5987
+ const image = result.images.find((candidate) => candidate.entry.file === entry.file);
5988
+ const factor = image === void 0 ? 1 : Math.max(1, Math.ceil(image.picture.width / CAPTURE_SHEET.cell));
5989
+ return {
5990
+ entry,
5991
+ picture: image === void 0 ? {
5992
+ width: CAPTURE_SHEET.mark.width,
5993
+ height: CAPTURE_SHEET.mark.height,
5994
+ pixels: Uint8Array.from({ length: CAPTURE_SHEET.mark.width * CAPTURE_SHEET.mark.height * 3 }, (_, index) => index % 3 === 0 ? CAPTURE_SHEET.mark.present : CAPTURE_SHEET.mark.absent)
5995
+ } : image.thumbnail,
5996
+ source: image === void 0 ? void 0 : {
5997
+ width: image.picture.width,
5998
+ height: image.picture.height,
5999
+ bytes: image.size
6000
+ },
6001
+ factor,
6002
+ clipped: image !== void 0 && Math.ceil(image.picture.height / factor) > CAPTURE_SHEET.limit,
6003
+ freshness: result.freshness.entries.find((candidate) => candidate.file === entry.file)
6004
+ };
6005
+ })
4884
6006
  };
4885
6007
  });
4886
6008
  }
@@ -4915,9 +6037,10 @@ var CaptureSheets = class {
4915
6037
  *
4916
6038
  * @remarks
4917
6039
  * The executable's whole behaviour: it reads the subcommand, hands the rest of the command line to
4918
- * the runner, the registry refresh, the preflight, or the contact sheets, and turns a refused
4919
- * usage into exit 64 and any other capture refusal into exit 1, writing the refusal to its error
4920
- * writer. An error that is not a capture refusal propagates.
6040
+ * the runner, the registry refresh, the preflight, or the contact sheets, or prints the progress of
6041
+ * the stage that ran last, and turns a refused usage into exit 64 and any other capture refusal
6042
+ * into exit 1, writing the refusal to its error writer. An error that is not a capture refusal
6043
+ * propagates.
4921
6044
  *
4922
6045
  * @example
4923
6046
  * ```ts
@@ -4969,6 +6092,13 @@ var CaptureCLI = class {
4969
6092
  stdout: this.#stdout,
4970
6093
  stderr: this.#stderr
4971
6094
  }).execute();
6095
+ case "progress": {
6096
+ const usage = "Usage: capture progress";
6097
+ const { positionals } = readCaptureOptions(argv, CAPTURE_COMMAND_OPTIONS.progress, usage);
6098
+ if (positionals.length > 0) throw new CaptureError(`Unexpected argument ${JSON.stringify(positionals[0]?.slice(0, 80))}: the progress command takes no argument. ${usage}`, { code: "USAGE" });
6099
+ this.#stdout(`${renderCaptureProgress(readCaptureProgress(root, CAPTURE_DEFAULTS.requests))}\n`);
6100
+ return CAPTURE_EXIT.passed;
6101
+ }
4972
6102
  case "preflight": {
4973
6103
  const { reader } = readCaptureReaderArguments(argv, root, CAPTURE_DEFAULTS, "preflight");
4974
6104
  return await new CapturePreflight({
@@ -5126,6 +6256,6 @@ function createCaptureRegistrar(options) {
5126
6256
  function createCaptureCLI(options = {}) {
5127
6257
  return new CaptureCLI(options);
5128
6258
  }
5129
- export { CAPTURE_COMMAND_NAMES, CAPTURE_COMMAND_OPTIONS, CAPTURE_DEFAULTS, CAPTURE_DISCOVERY, CAPTURE_EXIT, CAPTURE_FLAG, CAPTURE_FLAG_VALUE, CAPTURE_MESSAGE_LIMIT, CAPTURE_MINIMUM_IMAGE, CAPTURE_OWNER_BACKOFF, CAPTURE_OWNER_FILE, CAPTURE_OWNER_PREFIX, CAPTURE_OWNER_TIMEOUT, CAPTURE_PNG_LIMITS, CAPTURE_REFUSAL_LIMIT, CAPTURE_REGISTRY_LINE, CAPTURE_REGISTRY_STAGE, CAPTURE_REPORT_LINES, CAPTURE_REQUESTS_FLAG, CAPTURE_RUNS_DIRECTORY, CAPTURE_SHEET, CAPTURE_SHEET_FILES, CAPTURE_STAGES, CAPTURE_SUBCOMMANDS, CAPTURE_SURVIVORS_FILE, CAPTURE_TAG_OPERATORS, CAPTURE_USAGE, CAPTURE_VITEST_ENTRY, CaptureCLI, CaptureDiscovery, CaptureIntegrity, CaptureInvocation, CapturePreflight, CaptureRegistrar, CaptureRunner, CaptureSheets, answerCaptureDiscovery, buildCaptureArguments, buildCaptureChangePlan, buildCaptureDigest, buildCaptureDiscoveryConfig, buildCaptureFilter, buildCaptureIntegrityOptions, buildCaptureLookupJournal, buildCaptureRegistry, buildCaptureRequestRefusal, collectCaptureErrors, collectCaptureIdentical, composeCapturePictures, computeCaptureHash, computeRegistryDigest, createCaptureCLI, createCaptureDiscovery, createCaptureIntegrity, createCapturePreflight, createCaptureRegistrar, createCaptureRunner, createCaptureSheets, decodeCapturePicture, describeCaptureFault, describeCaptureMembers, describeCaptureOutput, describeCapturePortfolios, describeCaptureSelectorFault, encodeCaptureChunk, encodeCapturePicture, encodeCaptureWord, escapeCapturePattern, inflateCaptureStream, matchesCaptureFile, matchesCaptureSignature, matchesCaptureTransient, mergeCaptureLookups, normalizeSlashes, predictCaptureByte, readCaptureAncestor, readCaptureArguments, readCaptureChunks, readCaptureDescription, readCaptureEntry, readCaptureImage, readCaptureInputs, readCaptureLookups, readCaptureOptions, readCapturePortfolios, readCaptureProject, readCaptureReaderArguments, readCaptureRegistryArguments, readCaptureRequest, readCaptureRequestOwner, readCaptureRunning, readCaptureSeparator, readCaptureTitles, readCaptureVariants, readCaptureViewport, renderCaptureCommand, requireCaptureArgument, requireCaptureContained, requireCaptureImageSize, requireCaptureProjects, requireCaptureSelection, resolveCaptureExit, resolveCapturePhysical, resolveCaptureRelative, resolveCaptureRequests, resolveCaptureSheetIdentity, resolveCaptureStages, resolveCaptureVariants, resolveCaptureWrapperProject, scanCaptureFrames, settleCaptureShutdown, shrinkCapturePicture, splitCapturePages, unfilterCaptureRow, writeCaptureDocument };
6259
+ export { CAPTURE_COMMAND_NAMES, CAPTURE_COMMAND_OPTIONS, CAPTURE_DEFAULTS, CAPTURE_DISCOVERY, CAPTURE_EXIT, CAPTURE_FLAG, CAPTURE_FLAG_VALUE, CAPTURE_MESSAGE_LIMIT, CAPTURE_MINIMUM_IMAGE, CAPTURE_OWNER_BACKOFF, CAPTURE_OWNER_FILE, CAPTURE_OWNER_TIMEOUT, CAPTURE_PID_LIMIT, CAPTURE_PNG_LIMITS, CAPTURE_PROGRESS_SUFFIX, CAPTURE_RECOVERIES, CAPTURE_REFUSAL_LIMIT, CAPTURE_REGISTRY_LINE, CAPTURE_REGISTRY_STAGE, CAPTURE_REPORT_LINES, CAPTURE_REQUESTS_FLAG, CAPTURE_RUNS_DIRECTORY, CAPTURE_SHEET, CAPTURE_SHEET_FILES, CAPTURE_STAGES, CAPTURE_STATUS_RECOVERIES, CAPTURE_SUBCOMMANDS, CAPTURE_SURVIVORS_FILE, CAPTURE_TAG_OPERATORS, CAPTURE_USAGE, CAPTURE_VITEST_ENTRY, CAPTURE_WRAPPER_PREFIXES, CaptureCLI, CaptureDiscovery, CaptureIntegrity, CaptureInvocation, CapturePreflight, CaptureRegistrar, CaptureRunner, CaptureSheets, answerCaptureDiscovery, buildCaptureArguments, buildCaptureChangePlan, buildCaptureDigest, buildCaptureDiscoveryConfig, buildCaptureFilter, buildCaptureIntegrityOptions, buildCaptureLookupJournal, buildCaptureManifestDocument, buildCaptureOverride, buildCaptureReaderReport, buildCaptureRegistry, buildCaptureRequestRefusal, buildCaptureTable, buildCaptureWrapper, collectCaptureErrors, collectCaptureIdentical, collectCaptureOwners, collectCaptureProducers, composeCapturePictures, computeCaptureComposite, computeCaptureHash, computeCaptureMatchKey, computeCaptureTableKey, computeRegistryDigest, createCaptureCLI, createCaptureDiscovery, createCaptureIntegrity, createCapturePreflight, createCaptureRegistrar, createCaptureRunner, createCaptureSheets, decodeCapturePicture, describeCaptureChunk, describeCaptureFault, describeCaptureHolders, describeCaptureMembers, describeCaptureOutput, describeCapturePortfolios, describeCaptureSelectorFault, encodeCaptureChunk, encodeCapturePicture, encodeCaptureWord, escapeCapturePattern, filterCaptureInputs, inflateCaptureStream, matchesCaptureFile, matchesCaptureLimits, matchesCaptureSignature, matchesCaptureTransient, matchesCaptureVersionRefusal, mergeCaptureLookups, normalizeSlashes, predictCaptureByte, readCaptureAncestor, readCaptureArguments, readCaptureChunks, readCaptureDescription, readCaptureEntry, readCaptureFrames, readCaptureImage, readCaptureInputs, readCaptureListing, readCaptureLookupJournal, readCaptureLookups, readCaptureManifest, readCaptureOptions, readCapturePortfolios, readCaptureProgress, readCaptureProject, readCaptureReaderArguments, readCaptureRegistryArguments, readCaptureRequest, readCaptureRequestOwner, readCaptureSeparator, readCaptureTable, readCaptureTitles, readCaptureVariants, readCaptureViewport, renderCaptureCommand, renderCaptureProgress, requireCaptureArgument, requireCaptureContained, requireCaptureImageSize, requireCaptureProducer, requireCaptureProjects, requireCaptureSelection, requireCaptureTableEntry, requireCaptureVersion, resolveCaptureExit, resolveCapturePhysical, resolveCaptureRegistryFault, resolveCaptureRelative, resolveCaptureRequests, resolveCaptureSheetIdentity, resolveCaptureStages, resolveCaptureStandalone, resolveCaptureVariants, resolveCaptureWrapperProject, scanCaptureChunks, scanCaptureFrames, settleCaptureShutdown, shrinkCapturePicture, splitCapturePages, splitCaptureSheets, sumCaptureBlock, sumCaptureRow, unfilterCaptureRow, writeCaptureDocument };
5130
6260
 
5131
6261
  //# sourceMappingURL=index.js.map