@bridge_gpt/mcp-server 0.2.71 → 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.
- package/README.md +55 -17
- package/build/agent-launchers/claude-executor-adapter.js +22 -3
- package/build/agent-notes.js +171 -95
- package/build/agents.generated.js +7 -7
- package/build/bridge-permissions.js +31 -0
- package/build/bridge-worktree-inspection.js +237 -0
- package/build/check-evidence.js +6 -0
- package/build/ci-system-detection.js +50 -0
- package/build/ci-trigger-adapters.js +631 -0
- package/build/ci-trigger-install.js +106 -0
- package/build/claude-review-workflow.js +1 -1
- package/build/cli-help.js +6 -0
- package/build/codex-auto-recovery.js +126 -0
- package/build/codex-launcher-pin.js +33 -2
- package/build/codex-skill-adapter.js +5 -1
- package/build/command-host.js +33 -0
- package/build/commands.generated.js +7 -6
- package/build/conductor/bridge-api-client.js +1352 -50
- package/build/conductor/bring-up-facts.js +18 -5
- package/build/conductor/command-drift-production.js +42 -17
- package/build/conductor/command-drift.js +47 -0
- package/build/conductor/declare-blocked.js +554 -0
- package/build/conductor/doctor.js +187 -28
- package/build/conductor/driver-commands.js +141 -0
- package/build/conductor/driver-guard.js +277 -0
- package/build/conductor/driver-lapse.js +321 -0
- package/build/conductor/driver-register.js +176 -0
- package/build/conductor/driver-release.js +174 -0
- package/build/conductor/driver-session-state.js +315 -0
- package/build/conductor/epic-branch-ci-inspection.js +222 -29
- package/build/conductor/epic-implementer-cli.js +213 -13
- package/build/conductor/epic-server-database.js +162 -0
- package/build/conductor/epic-server-guidance.js +278 -0
- package/build/conductor/epic-server-journal.js +239 -0
- package/build/conductor/epic-server-processes.js +324 -0
- package/build/conductor/epic-server-recipe.js +397 -0
- package/build/conductor/epic-server-runtime.js +1207 -0
- package/build/conductor/epic-server-sfcc.js +107 -0
- package/build/conductor/epic-server-state.js +427 -0
- package/build/conductor/epic-server.js +594 -0
- package/build/conductor/gate-discovery.js +281 -10
- package/build/conductor/gate-settings-review.js +525 -5
- package/build/conductor/git-hooks-uninstall.js +112 -0
- package/build/conductor/git-hooks.js +81 -15
- package/build/conductor/guided-repair.js +10 -1
- package/build/conductor/install-doctor.js +2 -4
- package/build/conductor/launch-need-probes.js +6 -53
- package/build/conductor/launch-plan.js +318 -121
- package/build/conductor/local-merge.js +12 -1
- package/build/conductor/merge-execution-contract.js +1 -1
- package/build/conductor/merged-child-check.js +2 -1
- package/build/conductor/prerequisite-inputs.js +1213 -0
- package/build/conductor/readiness-assessment.js +93 -0
- package/build/conductor/readiness-cli.js +30 -9
- package/build/conductor/readiness-prerequisites.js +77 -5
- package/build/conductor/readiness-sections.js +146 -126
- package/build/conductor/readiness.js +21 -3
- package/build/conductor/recovery-cli.js +236 -15
- package/build/conductor/recovery-operations.js +34 -4
- package/build/conductor/repair-contract.js +33 -0
- package/build/conductor/tools.js +36 -4
- package/build/conductor/wait-run-attention.js +115 -0
- package/build/conductor/wait-run-cli.js +300 -21
- package/build/conductor/worker-database-doctor-inspector.js +34 -2
- package/build/conductor/worker-setup-tally.js +27 -0
- package/build/credential-store.js +96 -21
- package/build/dependency-install-declarations.js +212 -0
- package/build/docs.generated.js +4 -4
- package/build/doctor.js +91 -8
- package/build/drive-epic-help.js +23 -4
- package/build/drive-epic.js +1841 -340
- package/build/engine-paths.js +20 -0
- package/build/epic-branch-ci-summary.js +140 -0
- package/build/epic-capability-statement.js +107 -0
- package/build/epic-ci-workflow-drift.js +30 -15
- package/build/epic-ci-workflow-install.js +110 -42
- package/build/epic-ci-workflow-v2.js +274 -0
- package/build/epic-ci-workflow.js +38 -12
- package/build/epic-implementer-bin.js +2184 -52
- package/build/epic-launch-context.js +607 -0
- package/build/epic-launch-profile.js +1 -1
- package/build/epic-server-record.js +273 -0
- package/build/epic-shared/bridge-client.js +11 -3
- package/build/escalation-reachability.js +43 -0
- package/build/executor/ci-fix-test-runs.js +334 -0
- package/build/executor/cli.js +2 -0
- package/build/executor/completion-contract.js +24 -1
- package/build/executor/credentials.js +1 -1
- package/build/executor/delivery-observations.js +113 -0
- package/build/executor/delivery-outcome.js +30 -0
- package/build/executor/dependency-refresh-runner.js +132 -0
- package/build/executor/dependency-refresh.js +530 -0
- package/build/executor/deps.js +4 -0
- package/build/executor/env.js +119 -17
- package/build/executor/epic-server-context.js +141 -0
- package/build/executor/gate-qualification-job.js +127 -26
- package/build/executor/harness-coverage.js +19 -0
- package/build/executor/http-client.js +87 -6
- package/build/executor/index.js +2 -1
- package/build/executor/install-preflight.js +1 -1
- package/build/executor/job-runner.js +659 -87
- package/build/executor/likely-tests.js +94 -97
- package/build/executor/observation.js +8 -0
- package/build/executor/pre-pr-checks.js +363 -0
- package/build/executor/prompt-spec.js +127 -5
- package/build/executor/reconcile-overlap-job.js +5 -3
- package/build/executor/required-verification.js +28 -0
- package/build/executor/required-work-diagnostics.js +32 -0
- package/build/executor/required-work-ledger.js +955 -39
- package/build/executor/results.js +100 -0
- package/build/executor/service-discovery.js +42 -0
- package/build/executor/service-lifecycle.js +109 -2
- package/build/executor/service-uninstall.js +205 -0
- package/build/executor/service-unit.js +5 -3
- package/build/executor/terminal-mutation.js +8 -0
- package/build/executor/test-clock.js +3 -0
- package/build/executor/verification-hints.js +179 -0
- package/build/executor/worker-command.js +126 -5
- package/build/executor/worker-database-config.js +281 -0
- package/build/executor/worker-database-target.js +16 -12
- package/build/executor/worker-database.js +575 -116
- package/build/executor/worker-finalization.js +71 -10
- package/build/executor/worker-guard-hook.js +10 -2
- package/build/executor/worker-resources.js +25 -3
- package/build/executor/worker-verification-guidance.js +55 -5
- package/build/executor/worktree-inspection.js +42 -0
- package/build/executor/worktree.js +20 -1
- package/build/executor-launch.js +54 -2
- package/build/generated-assets-catalog.js +2 -2
- package/build/github-sign-in.js +1 -1
- package/build/index.js +1111 -381
- package/build/init.js +29 -14
- package/build/install-bridge-conductor-answers.js +465 -0
- package/build/install-bridge-conductor-apply.js +259 -0
- package/build/install-bridge-conductor-assessment.js +895 -0
- package/build/install-bridge-conductor-compact.js +161 -0
- package/build/install-bridge-conductor-contracts.js +63 -0
- package/build/install-bridge-conductor-gate.js +1383 -188
- package/build/install-bridge-conductor-setup.js +637 -92
- package/build/install-bridge-conductor.js +3163 -740
- package/build/install-bridge.js +601 -128
- package/build/install-maintenance.js +127 -0
- package/build/install-reexec.js +1 -1
- package/build/launcher-config-inspection.js +162 -1
- package/build/local-cleanup.js +59 -0
- package/build/mcp-grant-candidates.js +767 -0
- package/build/mcp-grant-doctor.js +63 -0
- package/build/mcp-grant.js +288 -0
- package/build/mcp-host-targets.js +8 -0
- package/build/mcp-identity.js +23 -0
- package/build/mcp-install-state.js +68 -2
- package/build/mcp-invoke.js +126 -13
- package/build/mcp-presets.js +107 -0
- package/build/mcp-provisioning.js +134 -2
- package/build/mcp-registration-doctor.js +31 -2
- package/build/mcp-server-invocation.js +6 -1
- package/build/merge-workflow-install.js +236 -111
- package/build/package-script-semantics.js +10 -0
- package/build/pipeline-utils.js +1 -1
- package/build/pipelines.generated.js +6 -6
- package/build/plan-discovery.js +97 -4
- package/build/plan-execution-ledger.js +248 -9
- package/build/plan-generation-io.js +262 -0
- package/build/plan-generation.js +424 -0
- package/build/plane/build-freshness.js +6 -1
- package/build/plane/cli.js +75 -9
- package/build/plane/plane-freshness.js +23 -7
- package/build/plane/preflight.js +50 -10
- package/build/plane/shutdown.js +19 -0
- package/build/plane/terminal-run-cleanup.js +23 -5
- package/build/plane/terminal-run-status.js +4 -0
- package/build/printed-remedy-commands.js +229 -15
- package/build/readiness-check.js +1 -1
- package/build/readiness-prerequisites.generated.js +311 -4
- package/build/readme.generated.js +1 -1
- package/build/repository-state-paths.js +38 -0
- package/build/repository-toolchains.js +50 -8
- package/build/run-unit-tests-launcher.js +8 -1
- package/build/setup-change-policy.js +32 -0
- package/build/setup-epic.js +1192 -198
- package/build/setup-progress.js +44 -0
- package/build/setup-question.js +180 -0
- package/build/start-tickets.js +4 -0
- package/build/test-command-detection.js +32 -88
- package/build/test-support/notes-fs.js +40 -0
- package/build/third-party-mcp-targets.js +30 -0
- package/build/ticket-delivery-enrollment.js +30 -8
- package/build/ticket-delivery-run-scope.js +128 -0
- package/build/upgrade-cli.js +85 -2
- package/build/v2-readiness-requirements.js +28 -1
- package/build/version.generated.js +3 -3
- package/build/worker-guard-hook-bin.js +2 -2
- package/build/worktrees.js +105 -0
- package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
- package/docs/EPIC-IMPLEMENTER.md +5 -0
- package/docs/epic-implementer/getting-started.md +42 -15
- package/docs/epic-implementer/self-hosting.md +14 -1
- package/package.json +2 -2
|
@@ -0,0 +1,1213 @@
|
|
|
1
|
+
/**
|
|
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).
|
|
5
|
+
*
|
|
6
|
+
* LOOKUP MODE. The driver passes the epic key and its validated, ordered child
|
|
7
|
+
* keys. For each child the command reads the stored epic and child descriptions
|
|
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.
|
|
27
|
+
*
|
|
28
|
+
* WHAT IT IS NOT. It changes nothing on the server and decides nothing: it does
|
|
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.
|
|
31
|
+
*
|
|
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.
|
|
38
|
+
*
|
|
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).
|
|
50
|
+
*/
|
|
51
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
52
|
+
import { constants as fsConstants } from "node:fs";
|
|
53
|
+
import { lstat, mkdir, open, rename, unlink, chmod } from "node:fs/promises";
|
|
54
|
+
import os from "node:os";
|
|
55
|
+
import path from "node:path";
|
|
56
|
+
import { AGENTS } from "../agents.generated.js";
|
|
57
|
+
import { ConductorBridgeApiError, fetchStoredTicket, resolveConductorBridgeApiAccess, } from "./bridge-api-client.js";
|
|
58
|
+
import { ConductorValidationError } from "./errors.js";
|
|
59
|
+
import { writeJsonDocument } from "./json-output.js";
|
|
60
|
+
// ---------------------------------------------------------------------------
|
|
61
|
+
// Constants
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
/** Ticket-key shape every key argument must match. */
|
|
64
|
+
export const PREREQUISITE_INPUT_KEY_PATTERN = /^[A-Z][A-Z0-9_]{0,19}-[0-9]+$/;
|
|
65
|
+
/** A line longer than this many Unicode code points is wrapped at a space or tab. */
|
|
66
|
+
export const PREREQUISITE_INPUT_WRAP_LIMIT = 1000;
|
|
67
|
+
/** A completed input larger than this many UTF-8 bytes is refused. */
|
|
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";
|
|
83
|
+
/** Fixed run-state root, relative to the home directory. */
|
|
84
|
+
const RUN_STATE_SEGMENTS = [".local", "state", "bapi-conductor-runs"];
|
|
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;
|
|
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$/;
|
|
96
|
+
// ---------------------------------------------------------------------------
|
|
97
|
+
// Usage and argument parsing
|
|
98
|
+
// ---------------------------------------------------------------------------
|
|
99
|
+
export function getPrerequisiteInputsUsage() {
|
|
100
|
+
return [
|
|
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",
|
|
103
|
+
"",
|
|
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.",
|
|
108
|
+
"",
|
|
109
|
+
"Options:",
|
|
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.",
|
|
128
|
+
"",
|
|
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.",
|
|
140
|
+
"",
|
|
141
|
+
"Example:",
|
|
142
|
+
" epic-implementer prerequisite-inputs --epic-key EPIC-1 --child EPIC-2 --child EPIC-3 --json",
|
|
143
|
+
].join("\n");
|
|
144
|
+
}
|
|
145
|
+
/** Parse flags. Every message is fixed text: argv content is never echoed. */
|
|
146
|
+
export function parsePrerequisiteInputsArgs(argv) {
|
|
147
|
+
let epicKey;
|
|
148
|
+
const children = [];
|
|
149
|
+
let json = false;
|
|
150
|
+
let record = false;
|
|
151
|
+
let inputHash;
|
|
152
|
+
let claimId;
|
|
153
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
154
|
+
const token = argv[i];
|
|
155
|
+
if (token === "-h" || token === "--help") {
|
|
156
|
+
return { help: true, record: false, epicKey: "", children: [], json: false };
|
|
157
|
+
}
|
|
158
|
+
if (token === "--json") {
|
|
159
|
+
json = true;
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
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") {
|
|
173
|
+
throw new ConductorValidationError('Unknown or malformed prerequisite-inputs argument. Run "epic-implementer prerequisite-inputs --help" for usage.');
|
|
174
|
+
}
|
|
175
|
+
const value = argv[i + 1];
|
|
176
|
+
if (value === undefined || value.startsWith("--")) {
|
|
177
|
+
throw new ConductorValidationError(`Flag "${token}" requires a value.`);
|
|
178
|
+
}
|
|
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
|
+
}
|
|
200
|
+
if (!PREREQUISITE_INPUT_KEY_PATTERN.test(value)) {
|
|
201
|
+
throw new ConductorValidationError(`Flag "${token}" requires a valid ticket key.`);
|
|
202
|
+
}
|
|
203
|
+
if (token === "--epic-key") {
|
|
204
|
+
if (epicKey !== undefined) {
|
|
205
|
+
throw new ConductorValidationError('Flag "--epic-key" may be given only once.');
|
|
206
|
+
}
|
|
207
|
+
epicKey = value;
|
|
208
|
+
}
|
|
209
|
+
else {
|
|
210
|
+
if (children.includes(value)) {
|
|
211
|
+
throw new ConductorValidationError('Flag "--child" may not repeat a ticket key.');
|
|
212
|
+
}
|
|
213
|
+
children.push(value);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (epicKey === undefined) {
|
|
217
|
+
throw new ConductorValidationError('Flag "--epic-key" is required.');
|
|
218
|
+
}
|
|
219
|
+
if (children.length === 0) {
|
|
220
|
+
throw new ConductorValidationError('At least one "--child" is required.');
|
|
221
|
+
}
|
|
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 };
|
|
237
|
+
}
|
|
238
|
+
// ---------------------------------------------------------------------------
|
|
239
|
+
// Content
|
|
240
|
+
// ---------------------------------------------------------------------------
|
|
241
|
+
/**
|
|
242
|
+
* Wrap long lines, and change nothing else.
|
|
243
|
+
*
|
|
244
|
+
* Counting Unicode code points, a line longer than the limit has the last ASCII
|
|
245
|
+
* space or tab at or before the limit replaced by LF, and the remainder is
|
|
246
|
+
* handled the same way. Position zero is never a break, and a token with no
|
|
247
|
+
* eligible space or tab at or before the limit stays whole on its own line, with
|
|
248
|
+
* wrapping resuming at the first space or tab after it. Existing newlines (and the CR in a CRLF),
|
|
249
|
+
* multibyte whitespace, and every other character pass through untouched: no
|
|
250
|
+
* trimming, normalization, summarizing, or truncation.
|
|
251
|
+
*/
|
|
252
|
+
export function wrapDescription(text, limit = PREREQUISITE_INPUT_WRAP_LIMIT) {
|
|
253
|
+
return text
|
|
254
|
+
.split("\n")
|
|
255
|
+
.map((line) => wrapLine(line, limit))
|
|
256
|
+
.join("\n");
|
|
257
|
+
}
|
|
258
|
+
function wrapLine(line, limit) {
|
|
259
|
+
let rest = Array.from(line);
|
|
260
|
+
if (rest.length <= limit)
|
|
261
|
+
return line;
|
|
262
|
+
const out = [];
|
|
263
|
+
while (rest.length > limit) {
|
|
264
|
+
let breakAt = -1;
|
|
265
|
+
for (let i = Math.min(limit, rest.length - 1); i >= 1; i -= 1) {
|
|
266
|
+
if (rest[i] === " " || rest[i] === "\t") {
|
|
267
|
+
breakAt = i;
|
|
268
|
+
break;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (breakAt < 0) {
|
|
272
|
+
// An unbreakable run longer than the limit stays whole on its own line;
|
|
273
|
+
// wrapping resumes at the first ASCII space or tab after it.
|
|
274
|
+
for (let i = limit + 1; i < rest.length; i += 1) {
|
|
275
|
+
if (rest[i] === " " || rest[i] === "\t") {
|
|
276
|
+
breakAt = i;
|
|
277
|
+
break;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
if (breakAt < 0)
|
|
282
|
+
break;
|
|
283
|
+
out.push(rest.slice(0, breakAt).join(""));
|
|
284
|
+
rest = rest.slice(breakAt + 1);
|
|
285
|
+
}
|
|
286
|
+
out.push(rest.join(""));
|
|
287
|
+
return out.join("\n");
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* The exact file layout: `Epic: <EPIC>\n` + epic segment + `\n\nChild: <CHILD>\n` +
|
|
291
|
+
* child segment + `\n`, each segment the wrapped description.
|
|
292
|
+
*/
|
|
293
|
+
export function formatPrerequisiteInput(epicKey, epicDescription, childKey, childDescription) {
|
|
294
|
+
return (`Epic: ${epicKey}\n` +
|
|
295
|
+
wrapDescription(epicDescription) +
|
|
296
|
+
`\n\nChild: ${childKey}\n` +
|
|
297
|
+
wrapDescription(childDescription) +
|
|
298
|
+
"\n");
|
|
299
|
+
}
|
|
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
|
+
*/
|
|
308
|
+
export function formatPrerequisiteInputResults(results, json) {
|
|
309
|
+
if (json)
|
|
310
|
+
return JSON.stringify({ results });
|
|
311
|
+
return results
|
|
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
|
+
})
|
|
324
|
+
.join("\n");
|
|
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
|
+
}
|
|
511
|
+
// ---------------------------------------------------------------------------
|
|
512
|
+
// Filesystem
|
|
513
|
+
// ---------------------------------------------------------------------------
|
|
514
|
+
function defaultFs() {
|
|
515
|
+
return {
|
|
516
|
+
mkdir: async (dir, mode) => {
|
|
517
|
+
await mkdir(dir, { recursive: true, mode });
|
|
518
|
+
},
|
|
519
|
+
lstat: (p) => lstat(p),
|
|
520
|
+
chmod: (p, mode) => chmod(p, mode),
|
|
521
|
+
openExclusive: async (p, mode) => {
|
|
522
|
+
// O_NOFOLLOW is absent on Windows; the exclusive create still refuses an
|
|
523
|
+
// existing name there.
|
|
524
|
+
const flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | (fsConstants.O_NOFOLLOW ?? 0);
|
|
525
|
+
const handle = await open(p, flags, mode);
|
|
526
|
+
return {
|
|
527
|
+
stat: () => handle.stat(),
|
|
528
|
+
chmod: (m) => handle.chmod(m),
|
|
529
|
+
writeFile: (data, encoding) => handle.writeFile(data, encoding),
|
|
530
|
+
sync: () => handle.sync(),
|
|
531
|
+
close: () => handle.close(),
|
|
532
|
+
};
|
|
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
|
+
},
|
|
542
|
+
rename: (from, to) => rename(from, to),
|
|
543
|
+
unlink: (p) => unlink(p),
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
class PrivateDirectoryError extends Error {
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* Create the run directory at mode 0700 and prove it is a real directory (not a
|
|
550
|
+
* symlink) owned by the current user whose mode is exactly 0700.
|
|
551
|
+
*/
|
|
552
|
+
async function ensurePrivateRunDirectory(fs, dir, uid, isWindows) {
|
|
553
|
+
try {
|
|
554
|
+
await fs.mkdir(dir, 0o700);
|
|
555
|
+
let info = await fs.lstat(dir);
|
|
556
|
+
if (info.isSymbolicLink() || !info.isDirectory())
|
|
557
|
+
throw new PrivateDirectoryError();
|
|
558
|
+
if (isWindows)
|
|
559
|
+
return;
|
|
560
|
+
if (uid === undefined || info.uid !== uid)
|
|
561
|
+
throw new PrivateDirectoryError();
|
|
562
|
+
if ((info.mode & 0o777) !== 0o700) {
|
|
563
|
+
await fs.chmod(dir, 0o700);
|
|
564
|
+
info = await fs.lstat(dir);
|
|
565
|
+
if (info.isSymbolicLink() || !info.isDirectory() || info.uid !== uid) {
|
|
566
|
+
throw new PrivateDirectoryError();
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
if ((info.mode & 0o777) !== 0o700)
|
|
570
|
+
throw new PrivateDirectoryError();
|
|
571
|
+
}
|
|
572
|
+
catch {
|
|
573
|
+
throw new PrivateDirectoryError();
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Write `content` to `target` through an exclusively created, mode-0600 temporary
|
|
578
|
+
* file in the same verified directory, then rename it over the target. The rename
|
|
579
|
+
* replaces a symlinked target rather than writing through it.
|
|
580
|
+
*/
|
|
581
|
+
async function writePrivateFileAtomically(fs, dir, targetName, content, uid, isWindows, suffix) {
|
|
582
|
+
const target = path.join(dir, targetName);
|
|
583
|
+
const temp = path.join(dir, `.${targetName}.${suffix}.tmp`);
|
|
584
|
+
let created = false;
|
|
585
|
+
// A target that is already a symlink is refused outright: it is never followed,
|
|
586
|
+
// never replaced, and never reported as a success. A missing target is fine.
|
|
587
|
+
let existing;
|
|
588
|
+
try {
|
|
589
|
+
existing = await fs.lstat(target);
|
|
590
|
+
}
|
|
591
|
+
catch {
|
|
592
|
+
// No readable target entry: nothing to refuse. A genuine access problem
|
|
593
|
+
// surfaces from the exclusive create or the rename below.
|
|
594
|
+
existing = undefined;
|
|
595
|
+
}
|
|
596
|
+
if (existing?.isSymbolicLink())
|
|
597
|
+
throw new Error("target is a symlink");
|
|
598
|
+
try {
|
|
599
|
+
const handle = await fs.openExclusive(temp, 0o600);
|
|
600
|
+
created = true;
|
|
601
|
+
try {
|
|
602
|
+
if (!isWindows)
|
|
603
|
+
await handle.chmod(0o600);
|
|
604
|
+
const info = await handle.stat();
|
|
605
|
+
if (!info.isFile())
|
|
606
|
+
throw new Error("not a regular file");
|
|
607
|
+
if (!isWindows && (uid === undefined || info.uid !== uid || (info.mode & 0o777) !== 0o600)) {
|
|
608
|
+
throw new Error("unverified temporary file");
|
|
609
|
+
}
|
|
610
|
+
await handle.writeFile(content, "utf8");
|
|
611
|
+
await handle.sync();
|
|
612
|
+
}
|
|
613
|
+
finally {
|
|
614
|
+
await handle.close();
|
|
615
|
+
}
|
|
616
|
+
await fs.rename(temp, target);
|
|
617
|
+
created = false;
|
|
618
|
+
return target;
|
|
619
|
+
}
|
|
620
|
+
finally {
|
|
621
|
+
if (created) {
|
|
622
|
+
try {
|
|
623
|
+
await fs.unlink(temp);
|
|
624
|
+
}
|
|
625
|
+
catch {
|
|
626
|
+
// best effort; the name is unique and holds no secret beyond the input
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
}
|
|
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
|
+
}
|
|
905
|
+
// ---------------------------------------------------------------------------
|
|
906
|
+
// Command
|
|
907
|
+
// ---------------------------------------------------------------------------
|
|
908
|
+
function boundedLine(text) {
|
|
909
|
+
// eslint-disable-next-line no-control-regex
|
|
910
|
+
const single = text.replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim();
|
|
911
|
+
return single.length > MAX_ERROR_CHARS ? `${single.slice(0, MAX_ERROR_CHARS - 1)}…` : single;
|
|
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
|
+
}
|
|
1107
|
+
/** Run `prerequisite-inputs`; returns the process exit code. */
|
|
1108
|
+
export async function runPrerequisiteInputsCommand(argv, deps = {}) {
|
|
1109
|
+
const writeStdout = deps.writeStdout ?? ((text) => writeJsonDocument(text));
|
|
1110
|
+
const writeStderr = deps.writeStderr ?? ((line) => console.error(line));
|
|
1111
|
+
const fail = (message) => {
|
|
1112
|
+
writeStderr(`Error: ${boundedLine(message)}`);
|
|
1113
|
+
return 1;
|
|
1114
|
+
};
|
|
1115
|
+
try {
|
|
1116
|
+
let parsed;
|
|
1117
|
+
try {
|
|
1118
|
+
parsed = parsePrerequisiteInputsArgs(argv);
|
|
1119
|
+
}
|
|
1120
|
+
catch (err) {
|
|
1121
|
+
return fail(err instanceof ConductorValidationError ? err.message : UNEXPECTED_FAILURE_MESSAGE);
|
|
1122
|
+
}
|
|
1123
|
+
if (parsed.help) {
|
|
1124
|
+
if (await writeStdout(getPrerequisiteInputsUsage()))
|
|
1125
|
+
return 0;
|
|
1126
|
+
return fail("prerequisite-inputs: the help text could not be written to stdout.");
|
|
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
|
+
}
|
|
1165
|
+
const resolveAccess = deps.resolveAccess ?? (() => resolveConductorBridgeApiAccess());
|
|
1166
|
+
const accessResult = await resolveAccess();
|
|
1167
|
+
if (!accessResult.ok) {
|
|
1168
|
+
// The shared resolver's messages are fixed, secret-free text.
|
|
1169
|
+
return fail(`prerequisite-inputs: ${accessResult.error}`);
|
|
1170
|
+
}
|
|
1171
|
+
const access = accessResult.access;
|
|
1172
|
+
const fetchTicket = deps.fetchTicket ?? fetchStoredTicket;
|
|
1173
|
+
// Read the epic once. Failing here is a whole-command failure.
|
|
1174
|
+
let epic;
|
|
1175
|
+
try {
|
|
1176
|
+
epic = await fetchTicket(access, parsed.epicKey);
|
|
1177
|
+
}
|
|
1178
|
+
catch (err) {
|
|
1179
|
+
const detail = err instanceof ConductorBridgeApiError ? ` (${err.message})` : "";
|
|
1180
|
+
return fail(`prerequisite-inputs: the epic ticket could not be read${detail}.`);
|
|
1181
|
+
}
|
|
1182
|
+
try {
|
|
1183
|
+
await ensurePrivateRunDirectory(fs, runDir, uid, isWindows);
|
|
1184
|
+
}
|
|
1185
|
+
catch {
|
|
1186
|
+
return fail("prerequisite-inputs: the run directory could not be made private.");
|
|
1187
|
+
}
|
|
1188
|
+
let agentVersion;
|
|
1189
|
+
try {
|
|
1190
|
+
agentVersion = resolveAgentVersion(deps);
|
|
1191
|
+
}
|
|
1192
|
+
catch {
|
|
1193
|
+
return fail(UNEXPECTED_FAILURE_MESSAGE);
|
|
1194
|
+
}
|
|
1195
|
+
const results = [];
|
|
1196
|
+
for (const child of parsed.children) {
|
|
1197
|
+
try {
|
|
1198
|
+
const ticket = await fetchTicket(access, child);
|
|
1199
|
+
const content = formatPrerequisiteInput(parsed.epicKey, epic.description, child, ticket.description);
|
|
1200
|
+
results.push(await lookupChild(ctx, agentVersion, child, content));
|
|
1201
|
+
}
|
|
1202
|
+
catch {
|
|
1203
|
+
results.push({ child, status: "failed", reason: "input rewrite failed" });
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
if (await writeStdout(formatPrerequisiteInputResults(results, parsed.json)))
|
|
1207
|
+
return 0;
|
|
1208
|
+
return fail("prerequisite-inputs: the result could not be written to stdout.");
|
|
1209
|
+
}
|
|
1210
|
+
catch {
|
|
1211
|
+
return fail(UNEXPECTED_FAILURE_MESSAGE);
|
|
1212
|
+
}
|
|
1213
|
+
}
|