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