@bridge_gpt/mcp-server 0.2.72 → 0.2.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +3 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-permissions.js +27 -0
  5. package/build/ci-system-detection.js +50 -0
  6. package/build/ci-trigger-adapters.js +631 -0
  7. package/build/ci-trigger-install.js +106 -0
  8. package/build/codex-launcher-pin.js +33 -2
  9. package/build/codex-skill-adapter.js +3 -1
  10. package/build/command-host.js +33 -0
  11. package/build/commands.generated.js +7 -6
  12. package/build/conductor/bridge-api-client.js +842 -35
  13. package/build/conductor/bring-up-facts.js +18 -5
  14. package/build/conductor/command-drift-production.js +42 -17
  15. package/build/conductor/command-drift.js +47 -0
  16. package/build/conductor/declare-blocked.js +554 -0
  17. package/build/conductor/doctor.js +106 -21
  18. package/build/conductor/driver-commands.js +141 -0
  19. package/build/conductor/driver-guard.js +277 -0
  20. package/build/conductor/driver-lapse.js +321 -0
  21. package/build/conductor/driver-register.js +176 -0
  22. package/build/conductor/driver-release.js +174 -0
  23. package/build/conductor/driver-session-state.js +315 -0
  24. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  25. package/build/conductor/epic-implementer-cli.js +166 -15
  26. package/build/conductor/epic-server-database.js +162 -0
  27. package/build/conductor/epic-server-guidance.js +278 -0
  28. package/build/conductor/epic-server-journal.js +239 -0
  29. package/build/conductor/epic-server-processes.js +324 -0
  30. package/build/conductor/epic-server-recipe.js +397 -0
  31. package/build/conductor/epic-server-runtime.js +1207 -0
  32. package/build/conductor/epic-server-sfcc.js +107 -0
  33. package/build/conductor/epic-server-state.js +427 -0
  34. package/build/conductor/epic-server.js +594 -0
  35. package/build/conductor/gate-discovery.js +150 -5
  36. package/build/conductor/gate-settings-review.js +224 -4
  37. package/build/conductor/launch-need-probes.js +6 -53
  38. package/build/conductor/launch-plan.js +313 -156
  39. package/build/conductor/prerequisite-inputs.js +879 -45
  40. package/build/conductor/readiness-assessment.js +16 -1
  41. package/build/conductor/readiness-cli.js +20 -9
  42. package/build/conductor/readiness-prerequisites.js +28 -9
  43. package/build/conductor/readiness-sections.js +133 -126
  44. package/build/conductor/readiness.js +1 -1
  45. package/build/conductor/recovery-cli.js +13 -2
  46. package/build/conductor/tools.js +6 -5
  47. package/build/conductor/wait-run-attention.js +2 -2
  48. package/build/conductor/wait-run-cli.js +208 -22
  49. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  50. package/build/conductor/worker-setup-tally.js +27 -0
  51. package/build/credential-store.js +71 -1
  52. package/build/dependency-install-declarations.js +55 -0
  53. package/build/docs.generated.js +2 -2
  54. package/build/doctor.js +54 -3
  55. package/build/drive-epic-help.js +21 -2
  56. package/build/drive-epic.js +1811 -351
  57. package/build/engine-paths.js +20 -0
  58. package/build/epic-branch-ci-summary.js +140 -0
  59. package/build/epic-capability-statement.js +107 -0
  60. package/build/epic-ci-workflow-drift.js +30 -15
  61. package/build/epic-ci-workflow-install.js +110 -42
  62. package/build/epic-ci-workflow-v2.js +274 -0
  63. package/build/epic-ci-workflow.js +38 -12
  64. package/build/epic-implementer-bin.js +2101 -44
  65. package/build/epic-launch-context.js +607 -0
  66. package/build/epic-server-record.js +273 -0
  67. package/build/epic-shared/bridge-client.js +11 -3
  68. package/build/escalation-reachability.js +43 -0
  69. package/build/executor/ci-fix-test-runs.js +334 -0
  70. package/build/executor/completion-contract.js +8 -1
  71. package/build/executor/env.js +59 -22
  72. package/build/executor/epic-server-context.js +141 -0
  73. package/build/executor/gate-qualification-job.js +127 -26
  74. package/build/executor/http-client.js +52 -5
  75. package/build/executor/job-runner.js +423 -69
  76. package/build/executor/observation.js +8 -0
  77. package/build/executor/pre-pr-checks.js +363 -0
  78. package/build/executor/prompt-spec.js +114 -2
  79. package/build/executor/reconcile-overlap-job.js +5 -3
  80. package/build/executor/required-work-diagnostics.js +4 -2
  81. package/build/executor/required-work-ledger.js +936 -38
  82. package/build/executor/results.js +58 -0
  83. package/build/executor/terminal-mutation.js +8 -0
  84. package/build/executor/worker-command.js +72 -3
  85. package/build/executor/worker-database-config.js +281 -0
  86. package/build/executor/worker-database-target.js +16 -12
  87. package/build/executor/worker-database.js +320 -101
  88. package/build/executor/worker-finalization.js +7 -1
  89. package/build/executor/worker-resources.js +25 -3
  90. package/build/executor/worker-verification-guidance.js +18 -3
  91. package/build/executor/worktree.js +20 -1
  92. package/build/executor-launch.js +54 -2
  93. package/build/generated-assets-catalog.js +2 -2
  94. package/build/index.js +664 -335
  95. package/build/init.js +26 -11
  96. package/build/install-bridge-conductor-answers.js +465 -0
  97. package/build/install-bridge-conductor-apply.js +259 -0
  98. package/build/install-bridge-conductor-assessment.js +895 -0
  99. package/build/install-bridge-conductor-compact.js +161 -0
  100. package/build/install-bridge-conductor-contracts.js +63 -0
  101. package/build/install-bridge-conductor-gate.js +1197 -196
  102. package/build/install-bridge-conductor-setup.js +535 -79
  103. package/build/install-bridge-conductor.js +2885 -560
  104. package/build/install-bridge.js +199 -21
  105. package/build/install-maintenance.js +26 -3
  106. package/build/launcher-config-inspection.js +162 -1
  107. package/build/mcp-grant-candidates.js +767 -0
  108. package/build/mcp-grant-doctor.js +63 -0
  109. package/build/mcp-grant.js +288 -0
  110. package/build/mcp-host-targets.js +8 -0
  111. package/build/mcp-identity.js +23 -0
  112. package/build/mcp-invoke.js +126 -13
  113. package/build/mcp-presets.js +107 -0
  114. package/build/mcp-provisioning.js +134 -2
  115. package/build/mcp-registration-doctor.js +31 -2
  116. package/build/mcp-server-invocation.js +6 -1
  117. package/build/merge-workflow-install.js +234 -109
  118. package/build/pipelines.generated.js +5 -5
  119. package/build/plan-discovery.js +97 -4
  120. package/build/plan-execution-ledger.js +100 -7
  121. package/build/plan-generation-io.js +262 -0
  122. package/build/plan-generation.js +424 -0
  123. package/build/plane/build-freshness.js +6 -1
  124. package/build/plane/cli.js +75 -9
  125. package/build/plane/plane-freshness.js +17 -0
  126. package/build/plane/preflight.js +50 -10
  127. package/build/plane/shutdown.js +19 -0
  128. package/build/plane/terminal-run-cleanup.js +18 -4
  129. package/build/printed-remedy-commands.js +206 -12
  130. package/build/readiness-check.js +77 -0
  131. package/build/readiness-prerequisites.generated.js +122 -14
  132. package/build/readme.generated.js +1 -1
  133. package/build/repository-state-paths.js +38 -0
  134. package/build/run-unit-tests-launcher.js +8 -1
  135. package/build/setup-epic.js +1190 -196
  136. package/build/setup-progress.js +44 -0
  137. package/build/setup-question.js +122 -4
  138. package/build/third-party-mcp-targets.js +30 -0
  139. package/build/ticket-delivery-enrollment.js +9 -0
  140. package/build/upgrade-cli.js +85 -2
  141. package/build/v2-readiness-requirements.js +28 -1
  142. package/build/version.generated.js +3 -3
  143. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  144. package/docs/epic-implementer/getting-started.md +3 -1
  145. package/docs/epic-implementer/self-hosting.md +14 -1
  146. package/package.json +2 -2
@@ -1,32 +1,59 @@
1
1
  /**
2
- * `epic-implementer prerequisite-inputs` — write the private scanner input files
3
- * for a `/drive-epic-run` prerequisite scan (BAPI-1557).
2
+ * `epic-implementer prerequisite-inputs` — the private scanner inputs, the local
3
+ * result cache, and the scan claims for a `/drive-epic-run` prerequisite scan
4
+ * (BAPI-1557, BAPI-1597).
4
5
  *
5
- * WHAT IT DOES. The driver passes the epic key and its validated, ordered child
6
+ * LOOKUP MODE. The driver passes the epic key and its validated, ordered child
6
7
  * keys. For each child the command reads the stored epic and child descriptions
7
- * through the shared Bridge API client and writes one deterministic file,
8
- * `~/.local/state/bapi-conductor-runs/<EPIC>/prerequisite-input-<CHILD>.txt`,
9
- * that holds the epic description (for context) and that one child's description.
10
- * A scanner agent then reads only its own file.
8
+ * through the shared Bridge API client and builds one deterministic input
9
+ * (`Epic: ...` + the epic description, then `Child: ...` + the child description).
10
+ * It hashes that input together with the packaged scanner agent and the cache
11
+ * schema version, and reports one status per child:
12
+ *
13
+ * - `cached` a validated result for exactly this input is on disk; reuse it.
14
+ * - `in_flight` another process holds a live scan claim; wait for its deadline.
15
+ * - `scan_needed` this process now holds the claim; the private input file
16
+ * `~/.local/state/bapi-conductor-runs/<EPIC>/prerequisite-input-<CHILD>.txt`
17
+ * was written, and the scanner may run until the claim deadline.
18
+ * - `failed` a closed per-child reason; no scanner may run for this child.
19
+ *
20
+ * RECORD MODE (`--record`). The session pipes the scanner's block on stdin. The
21
+ * command is fully local: it resolves no access and reads no ticket. It rechecks
22
+ * the on-disk input against the supplied hash, checks that the claim is still the
23
+ * live one, validates the block itself, and writes a cache entry only for a
24
+ * timely, drop-free, verified result. A matching claim is released, except after
25
+ * invalid scanner output: that keeps the claim until its original deadline so one
26
+ * corrected result can be recorded with the same claim.
11
27
  *
12
28
  * WHAT IT IS NOT. It changes nothing on the server and decides nothing: it does
13
- * not derive run membership, skip decisions, or order. It reads stored tickets
14
- * (a read-only route) and writes local files only inside a private directory.
29
+ * not derive run membership, skip decisions, or order, and it never blocks a
30
+ * launch. Every cache, claim, and record problem is a closed, advisory outcome.
15
31
  *
16
- * PRIVACY. Descriptions and raw upstream content never reach stdout, stderr,
17
- * logs, argv, or error text. A per-child failure reports only a closed reason.
18
- * Access comes only from the shared resolver, never from this module.
32
+ * CACHE IDENTITY. An entry is valid for exactly one input hash:
33
+ * SHA-256 of the canonical JSON of `{agentVersion, input, schemaVersion}`, where
34
+ * `agentVersion` is the SHA-256 of the canonical JSON of the whole packaged
35
+ * scanner `{body, frontmatter}` entry. Age never invalidates an entry. A changed
36
+ * description, scanner, or schema version changes the hash, which is the whole
37
+ * invalidation rule.
19
38
  *
20
- * EXIT CODES. Per-child failures (including all children failing) exit 0 with a
21
- * closed reason per child. Exit 1 with one bounded stderr line is reserved for an
22
- * invalid call, an access failure, an epic-read failure, or a run directory that
23
- * cannot be made private.
39
+ * PRIVACY. Descriptions, evidence, and raw scanner output never reach stdout
40
+ * (except validated items in the explicit JSON result), stderr, logs, argv, or
41
+ * error text. Failures report only closed reasons. Access comes only from the
42
+ * shared resolver, never from this module.
43
+ *
44
+ * EXIT CODES. Lookup: per-child failures (including all children failing) exit 0
45
+ * with a closed reason per child; exit 1 with one bounded stderr line is reserved
46
+ * for an invalid call, an access failure, an epic-read failure, or a run directory
47
+ * that cannot be made private. Record: every content, validation, local-state,
48
+ * claim, and cache-write refusal exits 0 with `not cached: <closed reason>`; exit
49
+ * 1 is reserved for an invalid invocation (bad flags, missing or oversized stdin).
24
50
  */
25
- import { randomBytes } from "node:crypto";
51
+ import { createHash, randomBytes } from "node:crypto";
26
52
  import { constants as fsConstants } from "node:fs";
27
53
  import { lstat, mkdir, open, rename, unlink, chmod } from "node:fs/promises";
28
54
  import os from "node:os";
29
55
  import path from "node:path";
56
+ import { AGENTS } from "../agents.generated.js";
30
57
  import { ConductorBridgeApiError, fetchStoredTicket, resolveConductorBridgeApiAccess, } from "./bridge-api-client.js";
31
58
  import { ConductorValidationError } from "./errors.js";
32
59
  import { writeJsonDocument } from "./json-output.js";
@@ -39,32 +66,80 @@ export const PREREQUISITE_INPUT_KEY_PATTERN = /^[A-Z][A-Z0-9_]{0,19}-[0-9]+$/;
39
66
  export const PREREQUISITE_INPUT_WRAP_LIMIT = 1000;
40
67
  /** A completed input larger than this many UTF-8 bytes is refused. */
41
68
  export const PREREQUISITE_INPUT_MAX_BYTES = 98_304;
69
+ /** The cache-entry and claim-marker schema version; part of every input hash. */
70
+ export const PREREQUISITE_CACHE_SCHEMA_VERSION = 1;
71
+ /** How long one scan claim lives: five minutes, in milliseconds. */
72
+ export const PREREQUISITE_SCAN_DEADLINE_MS = 5 * 60 * 1000;
73
+ /** The most items one child may carry, counted across all three shapes. */
74
+ export const PREREQUISITE_MAX_ITEMS = 20;
75
+ /** The longest `requirement` or `evidence`, in Unicode code points. */
76
+ export const PREREQUISITE_TEXT_MAX_CHARS = 200;
77
+ /** The longest `env` name. */
78
+ export const PREREQUISITE_ENV_MAX_CHARS = 64;
79
+ /** The largest scanner block read from stdin, in UTF-8 bytes. */
80
+ export const PREREQUISITE_STDIN_MAX_BYTES = 65_536;
81
+ /** The key of the packaged scanner agent in the generated bundle. */
82
+ export const PREREQUISITE_SCANNER_AGENT = "epic-prerequisite-scanner";
42
83
  /** Fixed run-state root, relative to the home directory. */
43
84
  const RUN_STATE_SEGMENTS = [".local", "state", "bapi-conductor-runs"];
44
85
  const MAX_ERROR_CHARS = 200;
86
+ const MAX_MARKER_BYTES = 4096;
87
+ const MAX_CACHE_BYTES = 65_536;
88
+ const LOCK_ATTEMPTS = 50;
89
+ const LOCK_WAIT_MS = 20;
90
+ const LOCK_STALE_MS = 10_000;
45
91
  const UNEXPECTED_FAILURE_MESSAGE = "prerequisite-inputs failed unexpectedly; no scanner input was reported.";
92
+ const HASH_PATTERN = /^[0-9a-f]{64}$/;
93
+ const CLAIM_ID_PATTERN = /^[A-Za-z0-9_-]{8,64}$/;
94
+ const ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
95
+ const ISO_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;
46
96
  // ---------------------------------------------------------------------------
47
97
  // Usage and argument parsing
48
98
  // ---------------------------------------------------------------------------
49
99
  export function getPrerequisiteInputsUsage() {
50
100
  return [
51
101
  "Usage: epic-implementer prerequisite-inputs --epic-key <KEY> --child <KEY> [--child <KEY> ...] [--json]",
102
+ " epic-implementer prerequisite-inputs --record --epic-key <KEY> --child <KEY> --input-hash <SHA256> --claim-id <ID> [--json] < scanner-block",
52
103
  "",
53
- "Reads stored ticket descriptions and writes one private local scanner input file per",
54
- "child under ~/.local/state/bapi-conductor-runs/<EPIC>/. Changes nothing on the server.",
104
+ "Lookup mode reads stored ticket descriptions and, per child, reports a status. A",
105
+ "private local scanner input file is written under",
106
+ "~/.local/state/bapi-conductor-runs/<EPIC>/ only when a scan is needed.",
107
+ "Changes nothing on the server.",
55
108
  "",
56
109
  "Options:",
57
- " --epic-key <KEY> The epic whose description gives context (required)",
58
- " --child <KEY> A child ticket, repeated, in the order to report (at least one)",
59
- " --json Print one JSON document",
110
+ " --epic-key <KEY> The epic whose description gives context (required)",
111
+ " --child <KEY> A child ticket, repeated, in the order to report (at least one;",
112
+ " exactly one with --record)",
113
+ " --record Record a scanner result. Fully local: resolves no access and",
114
+ " reads no ticket. The scanner's block is read from stdin, never argv",
115
+ " --input-hash <HASH> With --record: the input hash the claim was issued for",
116
+ " --claim-id <ID> With --record: the claim id the claim was issued with",
117
+ " --json Print one JSON document",
118
+ "",
119
+ "Lookup statuses, one per child:",
120
+ " cached A validated result for this exact input is stored; reuse it.",
121
+ " in_flight A live scan claim exists; wait until its absolute deadline.",
122
+ " scan_needed You hold the claim: scan the printed input path, then record the result",
123
+ " before the deadline (five minutes). A result after it is ignored.",
124
+ " failed `input over size cap`, `input rewrite failed`, or `claim unavailable`.",
125
+ "A cache or claim file that cannot be trusted adds the warning `cache unavailable` and",
126
+ "is treated as a miss. Cache age never invalidates an entry; a changed input, scanner,",
127
+ "or schema version does.",
60
128
  "",
61
- "Each child prints its written path, or the reason `input over size cap` or",
62
- "`input rewrite failed`. Per-child failures exit 0. Invalid calls, access failures,",
63
- "an unreadable epic, or a directory that cannot be made private exit 1 with one line",
64
- "on stderr. Descriptions never appear in output.",
129
+ "Record mode caches only a timely, verified result with no dropped item (an explicit",
130
+ "`none` counts). Otherwise it prints `not cached: <reason>`. It releases a matching",
131
+ "claim for `scanner timed out`, `scanner failed`, `item dropped: evidence not in",
132
+ "input`, `input changed`, or `cache unavailable`. `invalid scanner output` keeps the",
133
+ "claim until its original deadline, so one corrected result can use the same claim.",
134
+ "",
135
+ "Exit codes. Lookup: per-child failures exit 0. Invalid calls, access failures, an",
136
+ "unreadable epic, or a directory that cannot be made private exit 1 with one line on",
137
+ "stderr. Record: every refusal after a valid invocation exits 0; exit 1 is only for an",
138
+ "invalid invocation (bad flags, missing or oversized stdin). Descriptions, evidence,",
139
+ "and scanner output never appear in argv, logs, or human-readable output.",
65
140
  "",
66
141
  "Example:",
67
- " epic-implementer prerequisite-inputs --epic-key EPIC-1 --child EPIC-2 --child EPIC-3",
142
+ " epic-implementer prerequisite-inputs --epic-key EPIC-1 --child EPIC-2 --child EPIC-3 --json",
68
143
  ].join("\n");
69
144
  }
70
145
  /** Parse flags. Every message is fixed text: argv content is never echoed. */
@@ -72,16 +147,29 @@ export function parsePrerequisiteInputsArgs(argv) {
72
147
  let epicKey;
73
148
  const children = [];
74
149
  let json = false;
150
+ let record = false;
151
+ let inputHash;
152
+ let claimId;
75
153
  for (let i = 0; i < argv.length; i += 1) {
76
154
  const token = argv[i];
77
155
  if (token === "-h" || token === "--help") {
78
- return { help: true, epicKey: "", children: [], json: false };
156
+ return { help: true, record: false, epicKey: "", children: [], json: false };
79
157
  }
80
158
  if (token === "--json") {
81
159
  json = true;
82
160
  continue;
83
161
  }
84
- if (token !== "--epic-key" && token !== "--child") {
162
+ if (token === "--record") {
163
+ if (record) {
164
+ throw new ConductorValidationError('Flag "--record" may be given only once.');
165
+ }
166
+ record = true;
167
+ continue;
168
+ }
169
+ if (token !== "--epic-key" &&
170
+ token !== "--child" &&
171
+ token !== "--input-hash" &&
172
+ token !== "--claim-id") {
85
173
  throw new ConductorValidationError('Unknown or malformed prerequisite-inputs argument. Run "epic-implementer prerequisite-inputs --help" for usage.');
86
174
  }
87
175
  const value = argv[i + 1];
@@ -89,6 +177,26 @@ export function parsePrerequisiteInputsArgs(argv) {
89
177
  throw new ConductorValidationError(`Flag "${token}" requires a value.`);
90
178
  }
91
179
  i += 1;
180
+ if (token === "--input-hash") {
181
+ if (inputHash !== undefined) {
182
+ throw new ConductorValidationError('Flag "--input-hash" may be given only once.');
183
+ }
184
+ if (!HASH_PATTERN.test(value)) {
185
+ throw new ConductorValidationError('Flag "--input-hash" requires a lowercase SHA-256 hex digest.');
186
+ }
187
+ inputHash = value;
188
+ continue;
189
+ }
190
+ if (token === "--claim-id") {
191
+ if (claimId !== undefined) {
192
+ throw new ConductorValidationError('Flag "--claim-id" may be given only once.');
193
+ }
194
+ if (!CLAIM_ID_PATTERN.test(value)) {
195
+ throw new ConductorValidationError('Flag "--claim-id" requires a valid claim id.');
196
+ }
197
+ claimId = value;
198
+ continue;
199
+ }
92
200
  if (!PREREQUISITE_INPUT_KEY_PATTERN.test(value)) {
93
201
  throw new ConductorValidationError(`Flag "${token}" requires a valid ticket key.`);
94
202
  }
@@ -111,7 +219,21 @@ export function parsePrerequisiteInputsArgs(argv) {
111
219
  if (children.length === 0) {
112
220
  throw new ConductorValidationError('At least one "--child" is required.');
113
221
  }
114
- return { help: false, epicKey, children, json };
222
+ if (record) {
223
+ if (children.length !== 1) {
224
+ throw new ConductorValidationError('Record mode requires exactly one "--child".');
225
+ }
226
+ if (inputHash === undefined) {
227
+ throw new ConductorValidationError('Record mode requires "--input-hash".');
228
+ }
229
+ if (claimId === undefined) {
230
+ throw new ConductorValidationError('Record mode requires "--claim-id".');
231
+ }
232
+ }
233
+ else if (inputHash !== undefined || claimId !== undefined) {
234
+ throw new ConductorValidationError('Flags "--input-hash" and "--claim-id" require "--record".');
235
+ }
236
+ return { help: false, record, epicKey, children, json, inputHash, claimId };
115
237
  }
116
238
  // ---------------------------------------------------------------------------
117
239
  // Content
@@ -175,14 +297,217 @@ export function formatPrerequisiteInput(epicKey, epicDescription, childKey, chil
175
297
  wrapDescription(childDescription) +
176
298
  "\n");
177
299
  }
178
- /** The one stdout document for a result list. */
300
+ function hash12(inputHash) {
301
+ return inputHash.slice(0, 12);
302
+ }
303
+ /**
304
+ * The lookup result list. Human output names statuses and short hash prefixes
305
+ * only: never a requirement, evidence, description, or scanner text. The JSON
306
+ * document is the one place validated cached items are echoed.
307
+ */
179
308
  export function formatPrerequisiteInputResults(results, json) {
180
309
  if (json)
181
310
  return JSON.stringify({ results });
182
311
  return results
183
- .map((r) => ("path" in r ? `${r.child}: ${r.path}` : `${r.child}: ${r.reason}`))
312
+ .map((r) => {
313
+ switch (r.status) {
314
+ case "cached":
315
+ return `${r.child}: cached (input ${hash12(r.inputHash)}, ${r.items.length} items)`;
316
+ case "in_flight":
317
+ return `${r.child}: in flight (input ${hash12(r.inputHash)}, deadline ${r.deadline})`;
318
+ case "scan_needed":
319
+ return `${r.child}: scan needed: ${r.path} (input ${hash12(r.inputHash)}, claim ${r.claimId}, deadline ${r.deadline})`;
320
+ case "failed":
321
+ return `${r.child}: ${r.reason}`;
322
+ }
323
+ })
184
324
  .join("\n");
185
325
  }
326
+ /** The one stdout document for a record result. Human output holds no item text. */
327
+ export function formatPrerequisiteRecordResult(result, json) {
328
+ if (json)
329
+ return JSON.stringify({ results: [result] });
330
+ if (result.status === "cached") {
331
+ return `${result.child}: cached (input ${hash12(result.inputHash)}, ${result.items.length} items)`;
332
+ }
333
+ return `${result.child}: not cached: ${result.reason}`;
334
+ }
335
+ // ---------------------------------------------------------------------------
336
+ // Canonical hashing
337
+ // ---------------------------------------------------------------------------
338
+ /**
339
+ * Compact JSON with every object's keys sorted recursively and array order
340
+ * preserved. Narrowly scoped to plain JSON values: `undefined` object members are
341
+ * omitted, as `JSON.stringify` omits them.
342
+ */
343
+ export function canonicalJson(value) {
344
+ if (value === null || typeof value !== "object") {
345
+ const text = JSON.stringify(value);
346
+ if (text === undefined)
347
+ throw new TypeError("value is not canonical JSON");
348
+ return text;
349
+ }
350
+ if (Array.isArray(value)) {
351
+ return `[${value.map((entry) => canonicalJson(entry === undefined ? null : entry)).join(",")}]`;
352
+ }
353
+ const record = value;
354
+ const members = Object.keys(record)
355
+ .filter((key) => record[key] !== undefined)
356
+ .sort()
357
+ .map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`);
358
+ return `{${members.join(",")}}`;
359
+ }
360
+ /** Lowercase hex SHA-256 of the UTF-8 bytes of `text`. */
361
+ export function sha256Hex(text) {
362
+ return createHash("sha256").update(text, "utf8").digest("hex");
363
+ }
364
+ /** SHA-256 of the canonical JSON of the complete packaged `{body, frontmatter}` entry. */
365
+ export function computeAgentVersion(entry) {
366
+ return sha256Hex(canonicalJson(entry));
367
+ }
368
+ /**
369
+ * SHA-256 of the canonical JSON of `{agentVersion, input, schemaVersion}`. The
370
+ * input is the exact formatted bytes: no trimming, newline conversion, or other
371
+ * normalization happens here.
372
+ */
373
+ export function computeInputHash(agentVersion, input, schemaVersion = PREREQUISITE_CACHE_SCHEMA_VERSION) {
374
+ return sha256Hex(canonicalJson({ agentVersion, input, schemaVersion }));
375
+ }
376
+ function resolveAgentVersion(deps) {
377
+ const entry = "agentEntry" in deps ? deps.agentEntry : AGENTS[PREREQUISITE_SCANNER_AGENT];
378
+ if (entry === undefined || entry === null)
379
+ throw new Error("scanner agent entry unavailable");
380
+ return computeAgentVersion(entry);
381
+ }
382
+ // ---------------------------------------------------------------------------
383
+ // Scanner-block validation
384
+ // ---------------------------------------------------------------------------
385
+ const CLASSIC_KEYS = ["requirement", "dependents", "class", "env", "uncertain", "evidence"];
386
+ const NOT_MEASURABLE_KEYS = ["requirement", "dependents", "class", "measurable", "uncertain", "evidence"];
387
+ const WORKER_RUNTIME_KEYS = ["requirement", "dependents", "category", "uncertain", "evidence"];
388
+ function codePointLength(text) {
389
+ return Array.from(text).length;
390
+ }
391
+ function sameKeys(actual, expected) {
392
+ return actual.length === expected.length && expected.every((key) => actual.includes(key));
393
+ }
394
+ /**
395
+ * Validate one item's fields against the child and the exact input. Returns the
396
+ * typed item, or `undefined` when any constraint fails. Evidence is only checked
397
+ * for shape here; whether it occurs in the input is the caller's separate,
398
+ * non-fatal drop rule.
399
+ */
400
+ function validateItemFields(fields, child, input) {
401
+ const keys = Object.keys(fields);
402
+ const text = (key) => {
403
+ const value = fields[key];
404
+ return typeof value === "string" ? value : undefined;
405
+ };
406
+ const requirement = text("requirement");
407
+ const dependents = text("dependents");
408
+ const uncertain = text("uncertain");
409
+ const evidence = text("evidence");
410
+ if (requirement === undefined || dependents === undefined || uncertain === undefined || evidence === undefined) {
411
+ return undefined;
412
+ }
413
+ if (requirement.length === 0 || codePointLength(requirement) > PREREQUISITE_TEXT_MAX_CHARS)
414
+ return undefined;
415
+ if (requirement.includes("`") || /[\r\n]/.test(requirement))
416
+ return undefined;
417
+ if (dependents !== child)
418
+ return undefined;
419
+ if (uncertain !== "yes" && uncertain !== "no")
420
+ return undefined;
421
+ if (evidence.length === 0 || codePointLength(evidence) > PREREQUISITE_TEXT_MAX_CHARS)
422
+ return undefined;
423
+ if (/[\r\n]/.test(evidence))
424
+ return undefined;
425
+ if (sameKeys(keys, WORKER_RUNTIME_KEYS)) {
426
+ if (fields.category !== "worker-runtime")
427
+ return undefined;
428
+ return { requirement, dependents, category: "worker-runtime", uncertain, evidence };
429
+ }
430
+ const classValue = text("class");
431
+ if (classValue !== "core" && classValue !== "minor")
432
+ return undefined;
433
+ if (sameKeys(keys, CLASSIC_KEYS)) {
434
+ const env = text("env");
435
+ if (env === undefined || !ENV_NAME_PATTERN.test(env) || env.length > PREREQUISITE_ENV_MAX_CHARS) {
436
+ return undefined;
437
+ }
438
+ // The name must occur verbatim in this child's exact private input.
439
+ if (!input.includes(env))
440
+ return undefined;
441
+ return { requirement, dependents, class: classValue, env, uncertain, evidence };
442
+ }
443
+ if (sameKeys(keys, NOT_MEASURABLE_KEYS)) {
444
+ if (fields.measurable !== "no")
445
+ return undefined;
446
+ return { requirement, dependents, class: classValue, measurable: "no", uncertain, evidence };
447
+ }
448
+ return undefined;
449
+ }
450
+ const FIELD_LINE = /^([a-z]+): ?(.*)$/;
451
+ /**
452
+ * Parse and validate one scanner reply for `child` against the exact `input`.
453
+ *
454
+ * The reply must be exactly one complete fenced `prerequisites` block and nothing
455
+ * else. Its body is explicit `none`, one `not verified: <reason>` line, or at most
456
+ * twenty items. Any structural defect in any item invalidates the whole child.
457
+ * Only after every item is structurally valid are items whose evidence is not a
458
+ * literal substring of the input dropped, and the drops are counted, never
459
+ * described.
460
+ */
461
+ export function validateScannerBlock(text, child, input) {
462
+ const normalized = text.replace(/\r\n/g, "\n").trim();
463
+ const fenced = /^(`{3,})prerequisites\n([\s\S]*?)\n\1$/.exec(normalized);
464
+ if (fenced === null)
465
+ return { kind: "invalid" };
466
+ const body = fenced[2];
467
+ if (body === "none")
468
+ return { kind: "items", items: [], dropped: 0 };
469
+ const failure = /^not verified: (.{1,200})$/.exec(body);
470
+ if (failure !== null && !body.includes("\n")) {
471
+ return {
472
+ kind: "failure",
473
+ reason: failure[1].trim() === "scanner timed out" ? "scanner timed out" : "scanner failed",
474
+ };
475
+ }
476
+ const parsed = [];
477
+ let current;
478
+ for (const line of body.split("\n")) {
479
+ let fieldText;
480
+ if (line.startsWith("- ")) {
481
+ current = {};
482
+ parsed.push(current);
483
+ fieldText = line.slice(2);
484
+ }
485
+ else if (line.startsWith(" ") && current !== undefined) {
486
+ fieldText = line.slice(2);
487
+ }
488
+ else {
489
+ return { kind: "invalid" };
490
+ }
491
+ const match = FIELD_LINE.exec(fieldText);
492
+ if (match === null || current === undefined)
493
+ return { kind: "invalid" };
494
+ const [, key, rawValue] = match;
495
+ if (Object.prototype.hasOwnProperty.call(current, key))
496
+ return { kind: "invalid" };
497
+ current[key] = rawValue.trim();
498
+ }
499
+ if (parsed.length === 0 || parsed.length > PREREQUISITE_MAX_ITEMS)
500
+ return { kind: "invalid" };
501
+ const valid = [];
502
+ for (const fields of parsed) {
503
+ const item = validateItemFields(fields, child, input);
504
+ if (item === undefined)
505
+ return { kind: "invalid" };
506
+ valid.push(item);
507
+ }
508
+ const kept = valid.filter((item) => input.includes(item.evidence));
509
+ return { kind: "items", items: kept, dropped: valid.length - kept.length };
510
+ }
186
511
  // ---------------------------------------------------------------------------
187
512
  // Filesystem
188
513
  // ---------------------------------------------------------------------------
@@ -206,6 +531,14 @@ function defaultFs() {
206
531
  close: () => handle.close(),
207
532
  };
208
533
  },
534
+ openRead: async (p) => {
535
+ const handle = await open(p, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
536
+ return {
537
+ stat: () => handle.stat(),
538
+ readFile: (encoding) => handle.readFile({ encoding }),
539
+ close: () => handle.close(),
540
+ };
541
+ },
209
542
  rename: (from, to) => rename(from, to),
210
543
  unlink: (p) => unlink(p),
211
544
  };
@@ -295,6 +628,280 @@ async function writePrivateFileAtomically(fs, dir, targetName, content, uid, isW
295
628
  }
296
629
  }
297
630
  }
631
+ function errorCode(err) {
632
+ return err?.code;
633
+ }
634
+ function isMissingEntry(err) {
635
+ return errorCode(err) === "ENOENT" || (err instanceof Error && err.message === "ENOENT");
636
+ }
637
+ function isExistingEntry(err) {
638
+ return errorCode(err) === "EEXIST" || (err instanceof Error && err.message === "EEXIST");
639
+ }
640
+ /**
641
+ * Read a private regular file without following a symlink. A missing entry is
642
+ * `absent`. A symlink, a non-regular file, a foreign owner, a mode other than
643
+ * 0600 (outside Windows), an oversized file, or any read failure is `unsafe`.
644
+ * Nothing is chmodded or followed.
645
+ */
646
+ async function readPrivateText(fs, target, maxBytes, uid, isWindows) {
647
+ try {
648
+ let entry;
649
+ try {
650
+ entry = await fs.lstat(target);
651
+ }
652
+ catch (err) {
653
+ return isMissingEntry(err) ? { kind: "absent" } : { kind: "unsafe" };
654
+ }
655
+ if (entry.isSymbolicLink() || entry.isDirectory())
656
+ return { kind: "unsafe" };
657
+ const handle = await fs.openRead(target);
658
+ try {
659
+ const info = await handle.stat();
660
+ if (!info.isFile() || info.size > maxBytes)
661
+ return { kind: "unsafe" };
662
+ if (!isWindows && (uid === undefined || info.uid !== uid || (info.mode & 0o777) !== 0o600)) {
663
+ return { kind: "unsafe" };
664
+ }
665
+ const text = await handle.readFile("utf8");
666
+ if (Buffer.byteLength(text, "utf8") > maxBytes)
667
+ return { kind: "unsafe" };
668
+ return { kind: "ok", text, mtimeMs: info.mtimeMs ?? entry.mtimeMs };
669
+ }
670
+ finally {
671
+ await handle.close();
672
+ }
673
+ }
674
+ catch {
675
+ return { kind: "unsafe" };
676
+ }
677
+ }
678
+ const inputFileName = (child) => `prerequisite-input-${child}.txt`;
679
+ const cacheFileName = (child, inputHash) => `prerequisite-cache-${child}-${inputHash}.json`;
680
+ const markerFileName = (child, inputHash) => `prerequisite-claim-${child}-${inputHash}.json`;
681
+ const lockFileName = (child, inputHash) => `.prerequisite-claim-${child}-${inputHash}.lock`;
682
+ /**
683
+ * Read the cache entry for exactly `inputHash`. Absent is an ordinary miss; an
684
+ * entry that is unsafe, unreadable, corrupt, or no longer valid against the
685
+ * current input is a miss carrying `cache unavailable`. Every stored item is
686
+ * revalidated against this input, so a corrupt entry cannot bypass record-mode
687
+ * validation.
688
+ */
689
+ async function readCacheEntry(ctx, child, inputHash, input) {
690
+ const read = await readPrivateText(ctx.fs, path.join(ctx.runDir, cacheFileName(child, inputHash)), MAX_CACHE_BYTES, ctx.uid, ctx.isWindows);
691
+ if (read.kind === "absent")
692
+ return { kind: "miss" };
693
+ const unavailable = { kind: "miss", warning: "cache unavailable" };
694
+ if (read.kind === "unsafe")
695
+ return unavailable;
696
+ let doc;
697
+ try {
698
+ doc = JSON.parse(read.text);
699
+ }
700
+ catch {
701
+ return unavailable;
702
+ }
703
+ if (typeof doc !== "object" || doc === null || Array.isArray(doc))
704
+ return unavailable;
705
+ const entry = doc;
706
+ if (!sameKeys(Object.keys(entry), ["schemaVersion", "inputHash", "items", "recordedAt"]))
707
+ return unavailable;
708
+ if (entry.schemaVersion !== PREREQUISITE_CACHE_SCHEMA_VERSION)
709
+ return unavailable;
710
+ if (entry.inputHash !== inputHash)
711
+ return unavailable;
712
+ if (typeof entry.recordedAt !== "string" ||
713
+ !ISO_TIMESTAMP_PATTERN.test(entry.recordedAt) ||
714
+ Number.isNaN(Date.parse(entry.recordedAt))) {
715
+ return unavailable;
716
+ }
717
+ if (!Array.isArray(entry.items) || entry.items.length > PREREQUISITE_MAX_ITEMS)
718
+ return unavailable;
719
+ const items = [];
720
+ for (const raw of entry.items) {
721
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
722
+ return unavailable;
723
+ const item = validateItemFields(raw, child, input);
724
+ if (item === undefined || !input.includes(item.evidence))
725
+ return unavailable;
726
+ items.push(item);
727
+ }
728
+ return { kind: "hit", items };
729
+ }
730
+ async function writeCacheEntry(ctx, child, inputHash, items) {
731
+ const content = JSON.stringify({
732
+ schemaVersion: PREREQUISITE_CACHE_SCHEMA_VERSION,
733
+ inputHash,
734
+ items,
735
+ recordedAt: new Date(ctx.now()).toISOString(),
736
+ });
737
+ try {
738
+ await writePrivateFileAtomically(ctx.fs, ctx.runDir, cacheFileName(child, inputHash), content, ctx.uid, ctx.isWindows, ctx.suffixOf());
739
+ return true;
740
+ }
741
+ catch {
742
+ return false;
743
+ }
744
+ }
745
+ /**
746
+ * Read a claim marker. A marker that is a safe regular file but cannot be parsed
747
+ * (for example one a concurrent creator has not finished writing) is ruled by its
748
+ * modification time: it lives until `mtime + the claim window`.
749
+ */
750
+ async function readMarker(ctx, child, inputHash) {
751
+ const read = await readPrivateText(ctx.fs, path.join(ctx.runDir, markerFileName(child, inputHash)), MAX_MARKER_BYTES, ctx.uid, ctx.isWindows);
752
+ if (read.kind !== "ok")
753
+ return read;
754
+ try {
755
+ const doc = JSON.parse(read.text);
756
+ if (doc !== null &&
757
+ typeof doc === "object" &&
758
+ doc.schemaVersion === PREREQUISITE_CACHE_SCHEMA_VERSION &&
759
+ doc.inputHash === inputHash &&
760
+ typeof doc.claimId === "string" &&
761
+ CLAIM_ID_PATTERN.test(doc.claimId) &&
762
+ typeof doc.deadline === "string" &&
763
+ ISO_TIMESTAMP_PATTERN.test(doc.deadline) &&
764
+ !Number.isNaN(Date.parse(doc.deadline))) {
765
+ return { kind: "marker", marker: { claimId: doc.claimId, deadlineMs: Date.parse(doc.deadline) } };
766
+ }
767
+ }
768
+ catch {
769
+ // fall through to the modification-time rule
770
+ }
771
+ const base = read.mtimeMs ?? ctx.now();
772
+ return { kind: "marker", marker: { claimId: "", deadlineMs: base + PREREQUISITE_SCAN_DEADLINE_MS } };
773
+ }
774
+ /**
775
+ * Run `fn` while holding the child/hash mutation lock, so retiring a stale marker,
776
+ * clearing a matched one, and committing a record cannot interleave across
777
+ * processes. The lock never replaces the exclusive marker create as the authority
778
+ * on who owns a scan; it only makes read-then-mutate sequences safe. A lock older
779
+ * than ten seconds is treated as abandoned. Returns `undefined` when the lock
780
+ * cannot be taken.
781
+ */
782
+ async function withClaimLock(ctx, child, inputHash, fn) {
783
+ const lockPath = path.join(ctx.runDir, lockFileName(child, inputHash));
784
+ let held = false;
785
+ for (let attempt = 0; attempt < LOCK_ATTEMPTS && !held; attempt += 1) {
786
+ try {
787
+ const handle = await ctx.fs.openExclusive(lockPath, 0o600);
788
+ await handle.close();
789
+ held = true;
790
+ }
791
+ catch (err) {
792
+ if (!isExistingEntry(err))
793
+ return undefined;
794
+ try {
795
+ const entry = await ctx.fs.lstat(lockPath);
796
+ if (entry.isSymbolicLink() ||
797
+ (entry.mtimeMs !== undefined && ctx.now() - entry.mtimeMs > LOCK_STALE_MS)) {
798
+ await ctx.fs.unlink(lockPath);
799
+ continue;
800
+ }
801
+ }
802
+ catch {
803
+ // The holder released it between our attempts; try again at once.
804
+ continue;
805
+ }
806
+ await ctx.sleep(LOCK_WAIT_MS);
807
+ }
808
+ }
809
+ if (!held)
810
+ return undefined;
811
+ try {
812
+ return { value: await fn() };
813
+ }
814
+ finally {
815
+ try {
816
+ await ctx.fs.unlink(lockPath);
817
+ }
818
+ catch {
819
+ // best effort; a leftover lock goes stale
820
+ }
821
+ }
822
+ }
823
+ /**
824
+ * Try to become the one scanner for `child`/`inputHash`. Exclusive no-follow
825
+ * creation of the marker is the ownership authority. On `EEXIST` the existing
826
+ * marker decides: live means `in_flight`; expired or unreadable-but-regular is
827
+ * retired under the lock and one replacement create is attempted.
828
+ */
829
+ async function acquireClaim(ctx, child, inputHash) {
830
+ const markerPath = path.join(ctx.runDir, markerFileName(child, inputHash));
831
+ const tryCreate = async () => {
832
+ const claimId = ctx.randomClaimId();
833
+ const deadlineMs = ctx.now() + PREREQUISITE_SCAN_DEADLINE_MS;
834
+ let handle;
835
+ try {
836
+ handle = await ctx.fs.openExclusive(markerPath, 0o600);
837
+ }
838
+ catch (err) {
839
+ if (isExistingEntry(err))
840
+ return "exists";
841
+ return { kind: "unavailable" };
842
+ }
843
+ try {
844
+ try {
845
+ if (!ctx.isWindows)
846
+ await handle.chmod(0o600);
847
+ await handle.writeFile(JSON.stringify({
848
+ schemaVersion: PREREQUISITE_CACHE_SCHEMA_VERSION,
849
+ inputHash,
850
+ claimId,
851
+ deadline: new Date(deadlineMs).toISOString(),
852
+ }), "utf8");
853
+ await handle.sync();
854
+ }
855
+ finally {
856
+ await handle.close();
857
+ }
858
+ }
859
+ catch {
860
+ // A half-written marker we created is ours to remove; nothing else is touched.
861
+ try {
862
+ await ctx.fs.unlink(markerPath);
863
+ }
864
+ catch {
865
+ // best effort
866
+ }
867
+ return { kind: "unavailable" };
868
+ }
869
+ return { kind: "claimed", claimId, deadlineMs };
870
+ };
871
+ const first = await tryCreate();
872
+ if (first !== "exists")
873
+ return first;
874
+ const locked = await withClaimLock(ctx, child, inputHash, async () => {
875
+ const read = await readMarker(ctx, child, inputHash);
876
+ if (read.kind === "unsafe")
877
+ return { kind: "unavailable" };
878
+ if (read.kind === "marker") {
879
+ if (read.marker.deadlineMs > ctx.now())
880
+ return { kind: "in_flight", deadlineMs: read.marker.deadlineMs };
881
+ try {
882
+ await ctx.fs.unlink(markerPath);
883
+ }
884
+ catch {
885
+ return { kind: "unavailable" };
886
+ }
887
+ }
888
+ const second = await tryCreate();
889
+ return second === "exists" ? { kind: "unavailable" } : second;
890
+ });
891
+ return locked === undefined ? { kind: "unavailable" } : locked.value;
892
+ }
893
+ /** Remove the marker only if it still carries `claimId`. Call under the lock. */
894
+ async function clearOwnedMarker(ctx, child, inputHash, claimId) {
895
+ const read = await readMarker(ctx, child, inputHash);
896
+ if (read.kind === "marker" && read.marker.claimId === claimId) {
897
+ try {
898
+ await ctx.fs.unlink(path.join(ctx.runDir, markerFileName(child, inputHash)));
899
+ }
900
+ catch {
901
+ // best effort; an expired marker is retired by the next lookup
902
+ }
903
+ }
904
+ }
298
905
  // ---------------------------------------------------------------------------
299
906
  // Command
300
907
  // ---------------------------------------------------------------------------
@@ -303,6 +910,200 @@ function boundedLine(text) {
303
910
  const single = text.replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim();
304
911
  return single.length > MAX_ERROR_CHARS ? `${single.slice(0, MAX_ERROR_CHARS - 1)}…` : single;
305
912
  }
913
+ async function defaultReadStdin(maxBytes) {
914
+ if (process.stdin.isTTY)
915
+ return { kind: "missing" };
916
+ const chunks = [];
917
+ let total = 0;
918
+ for await (const chunk of process.stdin) {
919
+ const buffer = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
920
+ total += buffer.length;
921
+ if (total > maxBytes)
922
+ return { kind: "too_large" };
923
+ chunks.push(buffer);
924
+ }
925
+ if (total === 0)
926
+ return { kind: "missing" };
927
+ return { kind: "ok", text: Buffer.concat(chunks).toString("utf8") };
928
+ }
929
+ /** Look up one child: cached, in flight, scan needed, or a closed failure. */
930
+ async function lookupChild(ctx, agentVersion, child, content) {
931
+ if (Buffer.byteLength(content, "utf8") > PREREQUISITE_INPUT_MAX_BYTES) {
932
+ return { child, status: "failed", reason: "input over size cap" };
933
+ }
934
+ const inputHash = computeInputHash(agentVersion, content);
935
+ const warnings = [];
936
+ const cached = await readCacheEntry(ctx, child, inputHash, content);
937
+ if (cached.kind === "hit")
938
+ return { child, status: "cached", inputHash, items: cached.items };
939
+ if (cached.warning !== undefined)
940
+ warnings.push(cached.warning);
941
+ const claim = await acquireClaim(ctx, child, inputHash);
942
+ if (claim.kind === "unavailable") {
943
+ return { child, status: "failed", reason: "claim unavailable", inputHash };
944
+ }
945
+ if (claim.kind === "in_flight") {
946
+ return {
947
+ child,
948
+ status: "in_flight",
949
+ inputHash,
950
+ deadline: new Date(claim.deadlineMs).toISOString(),
951
+ ...(warnings.length > 0 ? { warnings } : {}),
952
+ };
953
+ }
954
+ let written;
955
+ try {
956
+ written = await writePrivateFileAtomically(ctx.fs, ctx.runDir, inputFileName(child), content, ctx.uid, ctx.isWindows, ctx.suffixOf());
957
+ }
958
+ catch {
959
+ // We hold the claim but cannot give the scanner an input: release it.
960
+ await withClaimLock(ctx, child, inputHash, () => clearOwnedMarker(ctx, child, inputHash, claim.claimId));
961
+ return { child, status: "failed", reason: "input rewrite failed", inputHash };
962
+ }
963
+ return {
964
+ child,
965
+ status: "scan_needed",
966
+ inputHash,
967
+ path: written,
968
+ claimId: claim.claimId,
969
+ deadline: new Date(claim.deadlineMs).toISOString(),
970
+ ...(warnings.length > 0 ? { warnings } : {}),
971
+ };
972
+ }
973
+ function notCached(child, inputHash, reason, extra = {}) {
974
+ return {
975
+ child,
976
+ status: "not_cached",
977
+ reason,
978
+ inputHash,
979
+ verified: extra.verified ?? false,
980
+ ...(extra.items !== undefined ? { items: extra.items } : {}),
981
+ ...(extra.dropped !== undefined ? { dropped: extra.dropped } : {}),
982
+ };
983
+ }
984
+ /**
985
+ * Record one scanner result. Fully local; never throws for a refusal. The marker
986
+ * for the supplied hash is released whenever it still carries the supplied claim,
987
+ * except for `invalid scanner output`, which keeps it until its original deadline.
988
+ */
989
+ async function recordResult(ctx, deps, parsed, stdinText) {
990
+ const child = parsed.children[0];
991
+ const suppliedHash = parsed.inputHash;
992
+ const claimId = parsed.claimId;
993
+ const locked = await withClaimLock(ctx, child, suppliedHash, async () => {
994
+ try {
995
+ const marker = await readMarker(ctx, child, suppliedHash);
996
+ const owned = marker.kind === "marker" && marker.marker.claimId === claimId;
997
+ const timely = marker.kind === "marker" && owned && marker.marker.deadlineMs >= ctx.now();
998
+ const release = async () => {
999
+ if (owned)
1000
+ await clearOwnedMarker(ctx, child, suppliedHash, claimId);
1001
+ };
1002
+ // The on-disk input, bound to this epic and child, must still hash to the
1003
+ // supplied hash.
1004
+ const inputRead = await readPrivateText(ctx.fs, path.join(ctx.runDir, inputFileName(child)), PREREQUISITE_INPUT_MAX_BYTES, ctx.uid, ctx.isWindows);
1005
+ if (inputRead.kind !== "ok") {
1006
+ await release();
1007
+ return notCached(child, suppliedHash, "cache unavailable");
1008
+ }
1009
+ const input = inputRead.text;
1010
+ let recomputed;
1011
+ try {
1012
+ recomputed = computeInputHash(resolveAgentVersion(deps), input);
1013
+ }
1014
+ catch {
1015
+ await release();
1016
+ return notCached(child, suppliedHash, "cache unavailable");
1017
+ }
1018
+ if (recomputed !== suppliedHash ||
1019
+ !input.startsWith(`Epic: ${parsed.epicKey}\n`) ||
1020
+ !input.includes(`\n\nChild: ${child}\n`)) {
1021
+ await release();
1022
+ return notCached(child, suppliedHash, "input changed");
1023
+ }
1024
+ if (!timely) {
1025
+ await release();
1026
+ return notCached(child, suppliedHash, "scanner timed out");
1027
+ }
1028
+ const outcome = validateScannerBlock(stdinText, child, input);
1029
+ if (outcome.kind === "invalid") {
1030
+ return notCached(child, suppliedHash, "invalid scanner output");
1031
+ }
1032
+ if (outcome.kind === "failure") {
1033
+ await release();
1034
+ return notCached(child, suppliedHash, outcome.reason);
1035
+ }
1036
+ if (outcome.dropped > 0) {
1037
+ await release();
1038
+ return notCached(child, suppliedHash, "item dropped: evidence not in input", {
1039
+ verified: outcome.items.length > 0,
1040
+ ...(outcome.items.length > 0 ? { items: outcome.items } : {}),
1041
+ dropped: outcome.dropped,
1042
+ });
1043
+ }
1044
+ const wrote = await writeCacheEntry(ctx, child, suppliedHash, outcome.items);
1045
+ await release();
1046
+ if (!wrote)
1047
+ return notCached(child, suppliedHash, "cache unavailable");
1048
+ return { child, status: "cached", inputHash: suppliedHash, items: outcome.items };
1049
+ }
1050
+ catch {
1051
+ return notCached(child, suppliedHash, "cache unavailable");
1052
+ }
1053
+ });
1054
+ return locked === undefined ? notCached(child, suppliedHash, "cache unavailable") : locked.value;
1055
+ }
1056
+ /**
1057
+ * BAPI-1596 — a read-only view of the validated cache for the given children, for
1058
+ * the launch preview. It is lookup mode without its side effects: it reads the stored
1059
+ * descriptions through the supplied `fetchTicket`, hashes each child's exact input
1060
+ * the same way lookup mode does, and revalidates a stored entry through
1061
+ * {@link readCacheEntry}. It takes no scan claim, creates no directory, writes no
1062
+ * file, and never reports a scan as needed. A child with no valid entry (a miss, a
1063
+ * changed description, an unreadable or corrupt entry, an oversize input, a failed
1064
+ * ticket read) is simply absent from the result. Only a failure that affects every
1065
+ * child (an epic read failure, an unavailable scanner entry, bad keys) is
1066
+ * `unavailable`. Descriptions and evidence never leave this function except as
1067
+ * validated items.
1068
+ */
1069
+ export async function readCachedPrerequisites(input, deps = {}) {
1070
+ try {
1071
+ if (!PREREQUISITE_INPUT_KEY_PATTERN.test(input.epicKey))
1072
+ return { kind: "unavailable" };
1073
+ if (!input.children.every((child) => PREREQUISITE_INPUT_KEY_PATTERN.test(child)))
1074
+ return { kind: "unavailable" };
1075
+ const agentVersion = resolveAgentVersion(deps);
1076
+ const uid = deps.getuid ? deps.getuid() : typeof process.getuid === "function" ? process.getuid() : undefined;
1077
+ const ctx = {
1078
+ fs: deps.fs ?? defaultFs(),
1079
+ runDir: path.join((deps.homedir ?? os.homedir)(), ...RUN_STATE_SEGMENTS, input.epicKey),
1080
+ uid,
1081
+ isWindows: process.platform === "win32",
1082
+ now: () => Date.now(),
1083
+ sleep: async () => undefined,
1084
+ randomClaimId: () => "",
1085
+ suffixOf: () => "",
1086
+ };
1087
+ const epic = await input.fetchTicket(input.epicKey);
1088
+ const found = await Promise.all(input.children.map(async (child) => {
1089
+ try {
1090
+ const ticket = await input.fetchTicket(child);
1091
+ const content = formatPrerequisiteInput(input.epicKey, epic.description, child, ticket.description);
1092
+ if (Buffer.byteLength(content, "utf8") > PREREQUISITE_INPUT_MAX_BYTES)
1093
+ return null;
1094
+ const cached = await readCacheEntry(ctx, child, computeInputHash(agentVersion, content), content);
1095
+ return cached.kind === "hit" ? { child, items: cached.items } : null;
1096
+ }
1097
+ catch {
1098
+ return null;
1099
+ }
1100
+ }));
1101
+ return { kind: "entries", entries: found.filter((entry) => entry !== null) };
1102
+ }
1103
+ catch {
1104
+ return { kind: "unavailable" };
1105
+ }
1106
+ }
306
1107
  /** Run `prerequisite-inputs`; returns the process exit code. */
307
1108
  export async function runPrerequisiteInputsCommand(argv, deps = {}) {
308
1109
  const writeStdout = deps.writeStdout ?? ((text) => writeJsonDocument(text));
@@ -324,6 +1125,43 @@ export async function runPrerequisiteInputsCommand(argv, deps = {}) {
324
1125
  return 0;
325
1126
  return fail("prerequisite-inputs: the help text could not be written to stdout.");
326
1127
  }
1128
+ const fs = deps.fs ?? defaultFs();
1129
+ const isWindows = process.platform === "win32";
1130
+ const uid = deps.getuid ? deps.getuid() : typeof process.getuid === "function" ? process.getuid() : undefined;
1131
+ const home = (deps.homedir ?? os.homedir)();
1132
+ const runDir = path.join(home, ...RUN_STATE_SEGMENTS, parsed.epicKey);
1133
+ const ctx = {
1134
+ fs,
1135
+ runDir,
1136
+ uid,
1137
+ isWindows,
1138
+ now: deps.now ?? (() => Date.now()),
1139
+ sleep: deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
1140
+ randomClaimId: deps.randomClaimId ?? (() => randomBytes(16).toString("hex")),
1141
+ suffixOf: deps.randomSuffix ?? (() => randomBytes(8).toString("hex")),
1142
+ };
1143
+ if (parsed.record) {
1144
+ // Record mode is fully local: dispatched before access resolution, before any
1145
+ // ticket read, and before any other remote operation.
1146
+ const stdin = await (deps.readStdin ?? defaultReadStdin)(PREREQUISITE_STDIN_MAX_BYTES);
1147
+ if (stdin.kind === "missing") {
1148
+ return fail("prerequisite-inputs: record mode requires the scanner block on stdin.");
1149
+ }
1150
+ if (stdin.kind === "too_large") {
1151
+ return fail("prerequisite-inputs: the scanner block on stdin is larger than the allowed size.");
1152
+ }
1153
+ let result;
1154
+ try {
1155
+ await ensurePrivateRunDirectory(fs, runDir, uid, isWindows);
1156
+ result = await recordResult(ctx, deps, parsed, stdin.text);
1157
+ }
1158
+ catch {
1159
+ result = notCached(parsed.children[0], parsed.inputHash, "cache unavailable");
1160
+ }
1161
+ if (await writeStdout(formatPrerequisiteRecordResult(result, parsed.json)))
1162
+ return 0;
1163
+ return fail("prerequisite-inputs: the result could not be written to stdout.");
1164
+ }
327
1165
  const resolveAccess = deps.resolveAccess ?? (() => resolveConductorBridgeApiAccess());
328
1166
  const accessResult = await resolveAccess();
329
1167
  if (!accessResult.ok) {
@@ -341,32 +1179,28 @@ export async function runPrerequisiteInputsCommand(argv, deps = {}) {
341
1179
  const detail = err instanceof ConductorBridgeApiError ? ` (${err.message})` : "";
342
1180
  return fail(`prerequisite-inputs: the epic ticket could not be read${detail}.`);
343
1181
  }
344
- const fs = deps.fs ?? defaultFs();
345
- const isWindows = process.platform === "win32";
346
- const uid = deps.getuid ? deps.getuid() : typeof process.getuid === "function" ? process.getuid() : undefined;
347
- const home = (deps.homedir ?? os.homedir)();
348
- const runDir = path.join(home, ...RUN_STATE_SEGMENTS, parsed.epicKey);
349
1182
  try {
350
1183
  await ensurePrivateRunDirectory(fs, runDir, uid, isWindows);
351
1184
  }
352
1185
  catch {
353
1186
  return fail("prerequisite-inputs: the run directory could not be made private.");
354
1187
  }
355
- const suffixOf = deps.randomSuffix ?? (() => randomBytes(8).toString("hex"));
1188
+ let agentVersion;
1189
+ try {
1190
+ agentVersion = resolveAgentVersion(deps);
1191
+ }
1192
+ catch {
1193
+ return fail(UNEXPECTED_FAILURE_MESSAGE);
1194
+ }
356
1195
  const results = [];
357
1196
  for (const child of parsed.children) {
358
1197
  try {
359
1198
  const ticket = await fetchTicket(access, child);
360
1199
  const content = formatPrerequisiteInput(parsed.epicKey, epic.description, child, ticket.description);
361
- if (Buffer.byteLength(content, "utf8") > PREREQUISITE_INPUT_MAX_BYTES) {
362
- results.push({ child, reason: "input over size cap" });
363
- continue;
364
- }
365
- const written = await writePrivateFileAtomically(fs, runDir, `prerequisite-input-${child}.txt`, content, uid, isWindows, suffixOf());
366
- results.push({ child, path: written });
1200
+ results.push(await lookupChild(ctx, agentVersion, child, content));
367
1201
  }
368
1202
  catch {
369
- results.push({ child, reason: "input rewrite failed" });
1203
+ results.push({ child, status: "failed", reason: "input rewrite failed" });
370
1204
  }
371
1205
  }
372
1206
  if (await writeStdout(formatPrerequisiteInputResults(results, parsed.json)))