@aiwg/cli 2026.11.5 → 2026.11.6

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 (150) hide show
  1. package/agentic/code/providers/model-capabilities.v1.json +9 -9
  2. package/bin/aiwg.mjs +6 -4
  3. package/dist/src/activity-log/cli.js +1 -1
  4. package/dist/src/agents/agent-deployer.js +1 -1
  5. package/dist/src/artifacts/audit/types.js +1 -1
  6. package/dist/src/artifacts/discover-facets.js +1 -1
  7. package/dist/src/artifacts/enrichment/prompt.js +1 -1
  8. package/dist/src/artifacts/enrichment/types.js +1 -1
  9. package/dist/src/artifacts/views/definition.js +1 -1
  10. package/dist/src/artifacts/views/types.js +1 -1
  11. package/dist/src/catalog/cli.js +1 -1
  12. package/dist/src/catalog/cli.mjs +1 -1
  13. package/dist/src/catalog/loader.js +1 -1
  14. package/dist/src/catalog/loader.mjs +1 -1
  15. package/dist/src/catalog/types.js +1 -1
  16. package/dist/src/cli/cli-extension-loader.js +19 -5
  17. package/dist/src/cli/cli-extension-paths.js +65 -0
  18. package/dist/src/cli/handlers/best-practices-audit.js +1 -1
  19. package/dist/src/cli/handlers/help.js +3 -4
  20. package/dist/src/cli/handlers/index.js +1 -1
  21. package/dist/src/cli/handlers/marketplace-plugin-search.js +37 -0
  22. package/dist/src/cli/handlers/marketplace.js +3 -1
  23. package/dist/src/cli/handlers/models.js +1 -1
  24. package/dist/src/cli/handlers/ralph-launcher.js +8 -2
  25. package/dist/src/cli/handlers/ralph.js +1 -1
  26. package/dist/src/cli/handlers/runtime-info.js +1 -1
  27. package/dist/src/cli/handlers/scaffolding.js +2 -2
  28. package/dist/src/cli/handlers/script-runner.js +1 -1
  29. package/dist/src/cli/handlers/sdlc-accelerate.js +1 -1
  30. package/dist/src/cli/handlers/subcommands-bundles.js +1 -1
  31. package/dist/src/cli/handlers/subcommands-list-format.js +19 -1
  32. package/dist/src/cli/handlers/types.js +1 -1
  33. package/dist/src/cli/handlers/use.js +2 -2
  34. package/dist/src/cli/handlers/utilities.js +1 -1
  35. package/dist/src/cli/handlers/version.js +1 -1
  36. package/dist/src/cli/handlers/workspace.js +1 -1
  37. package/dist/src/cli/help-generator.js +9 -11
  38. package/dist/src/cli/hooks/builtin/activity-log-hook.js +1 -1
  39. package/dist/src/cli/router.js +1 -1
  40. package/dist/src/cli/workflow-orchestrator.js +1 -1
  41. package/dist/src/config/worker-context.js +37 -7
  42. package/dist/src/config/worker-parallelism.js +11 -0
  43. package/dist/src/contributors/detect.js +1 -1
  44. package/dist/src/contributors/discover.js +1 -1
  45. package/dist/src/contributors/heuristic.js +1 -1
  46. package/dist/src/contributors/index.js +1 -1
  47. package/dist/src/contributors/types.js +1 -1
  48. package/dist/src/contributors/validation.js +1 -1
  49. package/dist/src/effects/worker-delivery.js +83 -0
  50. package/dist/src/extensions/capability-index.js +1 -1
  51. package/dist/src/extensions/commands/definitions.js +2 -2
  52. package/dist/src/extensions/deployment-registration.js +1 -1
  53. package/dist/src/extensions/index.js +1 -1
  54. package/dist/src/extensions/loader.js +1 -1
  55. package/dist/src/extensions/manifest.js +4 -2
  56. package/dist/src/extensions/project-local-activity.js +1 -1
  57. package/dist/src/extensions/project-local-discovery.js +2 -2
  58. package/dist/src/extensions/project-local-doctor.js +7 -3
  59. package/dist/src/extensions/project-local-promote.js +3 -3
  60. package/dist/src/extensions/project-local-remove.js +3 -3
  61. package/dist/src/extensions/project-local-scaffold.js +1 -1
  62. package/dist/src/extensions/registry.js +1 -1
  63. package/dist/src/extensions/shadow-resolver.js +1 -1
  64. package/dist/src/extensions/types.js +1 -1
  65. package/dist/src/extensions/upstream-registry.js +1 -1
  66. package/dist/src/extensions/validation.js +1 -1
  67. package/dist/src/intake/git-history-analyzer.js +1 -1
  68. package/dist/src/kb/cli.js +1 -1
  69. package/dist/src/marketplace/plugin-directory.js +36 -0
  70. package/dist/src/marketplace/plugin-search.js +180 -0
  71. package/dist/src/mcp/cli.mjs +2 -2
  72. package/dist/src/mcp/helpers.mjs +1 -1
  73. package/dist/src/mcp/http-tools.mjs +8 -6
  74. package/dist/src/mcp/http-transport.mjs +3 -1
  75. package/dist/src/mcp/server.mjs +1 -1
  76. package/dist/src/mcp/tools/command-run.mjs +1 -1
  77. package/dist/src/mcp/tools/discovery.mjs +1 -1
  78. package/dist/src/mcp/tools/subsystems.mjs +1 -1
  79. package/dist/src/mcp/tools/worker-invoke.mjs +68 -22
  80. package/dist/src/mcp/tools/worker-local-only-preflight.mjs +79 -0
  81. package/dist/src/mcp/tools/worker-recorded-launch.mjs +26 -0
  82. package/dist/src/mcp/tools/worker-stdin-runtime.mjs +33 -6
  83. package/dist/src/mcp/tools/worker-verify-deliver-schema.mjs +33 -0
  84. package/dist/src/mcp/tools/worker-verify-deliver.mjs +27 -0
  85. package/dist/src/models/catalog-policy.js +2 -2
  86. package/dist/src/models/conductor-data-policy.mjs +83 -14
  87. package/dist/src/models/config-loader.js +2 -2
  88. package/dist/src/models/index.js +2 -2
  89. package/dist/src/models/local-endpoint-models.js +155 -0
  90. package/dist/src/models/model-capabilities.v1.json +9 -9
  91. package/dist/src/models/model-discovery.js +9 -5
  92. package/dist/src/models/opencode-worker-model.mjs +16 -0
  93. package/dist/src/models/resolver.js +2 -2
  94. package/dist/src/models/worker-installation.mjs +5 -3
  95. package/dist/src/models/worker-plan.js +1 -1
  96. package/dist/src/plugin/plugin-installer.js +2 -2
  97. package/dist/src/plugin/registry-validator.js +2 -2
  98. package/dist/src/plugin/skill-command-translator.js +1 -1
  99. package/dist/src/rlm/cache/hash.js +1 -1
  100. package/dist/src/rlm/cache/store.js +1 -1
  101. package/dist/src/rlm/cache/types.js +1 -1
  102. package/dist/src/serve/worker-invocation-preparation.js +13 -0
  103. package/dist/src/serve/worker-invocation.js +21 -6
  104. package/dist/src/skills/run.js +0 -11
  105. package/dist/src/smiths/agentsmith/generator.js +1 -1
  106. package/dist/src/smiths/context-pipeline/index.js +1 -1
  107. package/dist/src/smiths/context-pipeline/provider-policy.js +1 -1
  108. package/dist/src/smiths/context-pipeline/types.js +1 -1
  109. package/dist/src/smiths/mcpsmith/analyzers/cli-analyzer.js +2 -2
  110. package/dist/src/smiths/mcpsmith/generator.js +2 -2
  111. package/dist/src/smiths/mcpsmith/index.js +2 -2
  112. package/dist/src/smiths/mcpsmith/types.js +2 -2
  113. package/dist/src/smiths/skillsmith/collision-detector.js +1 -1
  114. package/dist/src/smiths/skillsmith/namespace-adapter.js +1 -1
  115. package/dist/src/smiths/toolsmith/runtime-discovery.mjs +2 -2
  116. package/dist/src/smiths/toolsmith/types.js +2 -2
  117. package/dist/src/storage/backends/fortemi.js +1 -1
  118. package/dist/src/storage/backends/fs.js +1 -1
  119. package/dist/src/storage/backends/logseq.js +1 -1
  120. package/dist/src/storage/backends/obsidian.js +1 -1
  121. package/dist/src/storage/cli.js +2 -2
  122. package/dist/src/storage/config.js +1 -1
  123. package/dist/src/storage/index.js +1 -1
  124. package/dist/src/storage/subsystem-cli.js +1 -1
  125. package/dist/src/storage/types.js +1 -1
  126. package/dist/src/testing/generators/test-case-generator.js +1 -1
  127. package/dist/src/writing/validation-engine.js +1 -1
  128. package/package.json +11 -1
  129. package/schemas/models/model-catalog.v1.schema.json +6 -3
  130. package/tools/agents/providers/conductor-data-guard.mjs +1 -1
  131. package/tools/ralph-external/lib/mcp-worker-launch.mjs +67 -0
  132. package/tools/ralph-external/lib/opencode-adapter.mjs +9 -7
  133. package/tools/ralph-external/lib/trusted-verification.mjs +1021 -0
  134. package/tools/ralph-external/lib/typed-stop-delivery.mjs +46 -0
  135. package/tools/ralph-external/lib/verification-isolation.mjs +509 -0
  136. package/tools/ralph-external/lib/worker-context.mjs +3 -3
  137. package/tools/ralph-external/lib/worker-delivery-guards.mjs +95 -0
  138. package/tools/ralph-external/lib/worker-delivery-record.mjs +15 -0
  139. package/tools/ralph-external/lib/worker-final.mjs +4 -1
  140. package/tools/ralph-external/lib/worker-isolation-status.mjs +3 -0
  141. package/tools/ralph-external/lib/worker-launch-cli.mjs +8 -0
  142. package/tools/ralph-external/lib/worker-local-only-paths.mjs +45 -0
  143. package/tools/ralph-external/lib/worker-prompt.mjs +4 -1
  144. package/tools/ralph-external/lib/worker-retry-evidence.mjs +2 -1
  145. package/tools/ralph-external/lib/worker-run-directory.mjs +45 -0
  146. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +10 -2
  147. package/tools/ralph-external/lib/worker-verification-cli.mjs +164 -0
  148. package/tools/ralph-external/lib/worktree-preparation.mjs +417 -0
  149. package/tools/ralph-external/session-launcher.mjs +8 -15
  150. package/vscode-extension/schemas/aiwg.config.v1.json +27 -0
@@ -0,0 +1,1021 @@
1
+ /**
2
+ * Tier 0 trusted verification, outside the worker sandbox (FR-OG-039,
3
+ * FR-OG-042, FR-OG-068, #2889 / B-OG-13). Extends Rule 9 step 8 ("Verify
4
+ * independently, outside the worker sandbox") with an executable runner for
5
+ * the behavior that step only described: checks are conductor/policy
6
+ * defined and protected (never read from a worker-writable manifest or
7
+ * script), a check binary must be an explicitly allowlisted, conductor-owned
8
+ * binary outside the worktree (never derived from worktree content), every
9
+ * path is pinned by file descriptor before use so a planted symlink/hardlink
10
+ * or a mid-run swap cannot redirect a later read/spawn, checks run through
11
+ * `verification-isolation.mjs`'s confined `systemd-run --user` path (never
12
+ * with the conductor's own filesystem/network access), and a sandbox
13
+ * permission failure is classified only from a spawn-level errno or this
14
+ * module's own isolation-unavailable signal — never from worker-controlled
15
+ * stdout/stderr text, which a worker can forge in either direction.
16
+ *
17
+ * This module never merges, integrates, or mutates the worktree — it only
18
+ * reads the artifact and runs the supplied protected checks — and it never
19
+ * derives a command from the worktree's own `package.json` (or any other
20
+ * worker-writable manifest): `assertNotPackageScriptInvocation` is kept as
21
+ * defense-in-depth, but the actual protection against worker-controlled
22
+ * check code is `verification-isolation.mjs`'s confinement (checks still
23
+ * run worker code — that is what tests are) plus the binary allowlist
24
+ * (`assertAllowedCheckBinary`), which refuses any check binary that is not
25
+ * both absolute and pre-registered by the conductor outside the worktree.
26
+ * Acceptance binds the exact digest of the artifact *and* a whole-worktree
27
+ * tree digest taken immediately before and after the checks run
28
+ * (schemas/mission-v1.schema.json `$defs/workerDirectVerification`); a
29
+ * later edit, or any mutation that happens *during* the checks, invalidates
30
+ * it.
31
+ */
32
+
33
+ import { createHash } from 'node:crypto';
34
+ import {
35
+ closeSync, constants as fsConstants, fstatSync, lstatSync, openSync,
36
+ readFileSync, readSync, opendirSync, readlinkSync, realpathSync,
37
+ } from 'node:fs';
38
+ import path from 'node:path';
39
+ import { missingRequiredCapabilities, probeVerificationIsolationCapabilities, runConfinedCheck } from './verification-isolation.mjs';
40
+
41
+ export class WorktreeEscapeError extends Error {
42
+ constructor(message) {
43
+ super(message);
44
+ this.name = 'WorktreeEscapeError';
45
+ }
46
+ }
47
+
48
+ export class ProtectedCheckViolationError extends Error {
49
+ constructor(message) {
50
+ super(message);
51
+ this.name = 'ProtectedCheckViolationError';
52
+ }
53
+ }
54
+
55
+ /** M3: a tree digest could not be computed at all (unreadable entry, broken
56
+ * symlink elsewhere in the tree, permission denial, ...). Distinct from a
57
+ * digest MISMATCH (which `verifyWorkerArtifact` reports as `rejected` with a
58
+ * "changed during verification" finding) — this is "we could not establish
59
+ * trust at all," which must also reject, never silently fall back to "we
60
+ * don't know, so treat it as unchanged." */
61
+ export class TreeDigestError extends Error {
62
+ constructor(message) {
63
+ super(message);
64
+ this.name = 'TreeDigestError';
65
+ }
66
+ }
67
+
68
+ // M1 residual: an allowlisted check binary that is itself a general-purpose
69
+ // interpreter (handed a worktree-relative script/path as an argument) is not
70
+ // refused by `assertAllowedCheckBinary` — the interpreter binary legitimately
71
+ // resolves outside the worktree, and running worker-controlled code through
72
+ // it is exactly what a protected check is for. Its safety therefore depends
73
+ // entirely on `verification-isolation.mjs` confinement actually being
74
+ // enforced. When confinement is degraded on this host, a check that both (a)
75
+ // invokes a known interpreter and (b) passes it an argument resolving inside
76
+ // the worktree is refused outright unless the conductor explicitly opts in
77
+ // (`allowWorktreeInterpreterArgs: true`) — see Rule 9 step 8.
78
+ const INTERPRETER_BASENAMES = new Set([
79
+ 'node', 'nodejs', 'node.js', 'python', 'python3', 'python2',
80
+ 'ruby', 'perl', 'sh', 'bash', 'dash', 'ksh', 'zsh', 'env',
81
+ ]);
82
+
83
+ const PACKAGE_MANAGER_BINARIES = new Set(['npm', 'npx', 'yarn', 'pnpm', 'corepack', 'bun']);
84
+ // Any subcommand that can trigger a worker-writable script: explicit script
85
+ // runners (`run`, `test`, `start`, etc.) and install-family commands, which
86
+ // also execute pre/postinstall lifecycle scripts from a worker-writable
87
+ // package.json.
88
+ const SCRIPT_TRIGGERING_ARGS = new Set([
89
+ 'run', 'run-script', 'test', 'start', 'build', 'exec', 'dlx',
90
+ 'install', 'ci', 'i', 'add', 'update', 'rebuild',
91
+ ]);
92
+ // Conductor-supplied env allowlist names must never themselves look like a
93
+ // secret name (m2): a conductor who accidentally allowlists
94
+ // `GITHUB_TOKEN`/`OPENBAO_...` would forward it straight into worker-
95
+ // controlled check code. This is a name-pattern guard, not a value scan.
96
+ const SECRET_LOOKING_ENV_NAME = /TOKEN|SECRET|KEY|PASSWORD|CREDENTIAL/i;
97
+
98
+ // Conductor-owned budget, independent of worker-reported metadata. Tree bounds
99
+ // leave headroom over this repository (13k entries, 124 MB tracked in 2026-10).
100
+ export const MAX_ARTIFACT_BYTES = 10 * 1024 * 1024;
101
+ const ARTIFACT_HASH_CHUNK_BYTES = 64 * 1024;
102
+ export const MAX_TREE_FILE_BYTES = 10 * 1024 * 1024;
103
+ export const MAX_TREE_BYTES = 500 * 1024 * 1024;
104
+ export const MAX_TREE_ENTRIES = 50000;
105
+ const MAX_TREE_DEPTH = 128;
106
+
107
+ /**
108
+ * Refuse any check definition that would end up executing a script a
109
+ * worker could have written (package.json `scripts`, install lifecycle
110
+ * hooks). Defense-in-depth only (M1): the actual protection against
111
+ * worker-controlled check *code* is confinement
112
+ * (`verification-isolation.mjs`) plus `assertAllowedCheckBinary`'s
113
+ * allowlist, because a protected check still legitimately runs worker code
114
+ * (that is what a test run is) — this function exists only to keep an
115
+ * obviously-wrong check definition (an `npm test` style invocation) from
116
+ * ever being accepted as "protected" in the first place.
117
+ */
118
+ export function assertNotPackageScriptInvocation(command, args = []) {
119
+ const base = path.basename(String(command));
120
+ if (!PACKAGE_MANAGER_BINARIES.has(base)) return;
121
+ const hasTrigger = args.some(token => SCRIPT_TRIGGERING_ARGS.has(String(token)));
122
+ // Even a bare `npm` call with no recognized subcommand is refused: package
123
+ // managers accept run-script shorthand (`npm <script>`) that this
124
+ // allowlist cannot enumerate exhaustively, so the only safe default for a
125
+ // "protected check" is to deny every package-manager invocation outright.
126
+ throw new ProtectedCheckViolationError(
127
+ `protected checks must not invoke a package manager (${base}${hasTrigger ? ` ${args.join(' ')}` : ''}): ` +
128
+ 'this would run a script a worker could have edited under conductor authority; ' +
129
+ 'define the check as a direct binary or file invocation instead',
130
+ );
131
+ }
132
+
133
+ function withinRoot(rootReal, candidateReal) {
134
+ const rootWithSep = rootReal.endsWith(path.sep) ? rootReal : rootReal + path.sep;
135
+ return candidateReal === rootReal || candidateReal.startsWith(rootWithSep);
136
+ }
137
+
138
+ /**
139
+ * Resolve `targetPath` to its real (fully symlink-resolved) path WITHOUT
140
+ * any worktree-containment requirement — used for resolving a check
141
+ * *binary*, which by definition (M1) must live outside the worktree.
142
+ * Fails closed on a missing path.
143
+ */
144
+ export function resolveRealpath(targetPath) {
145
+ if (typeof targetPath !== 'string' || !path.isAbsolute(targetPath) || targetPath.includes('\0')) {
146
+ throw new WorktreeEscapeError(`requires an absolute NUL-free path, got ${JSON.stringify(targetPath)}`);
147
+ }
148
+ try {
149
+ return realpathSync(path.resolve(targetPath));
150
+ } catch (error) {
151
+ throw new WorktreeEscapeError(`cannot resolve real path: ${targetPath}: ${error.message}`);
152
+ }
153
+ }
154
+
155
+ /**
156
+ * M1: a protected check's binary must be an absolute, conductor-registered
157
+ * path that resolves OUTSIDE the worktree. A worker-writable binary
158
+ * (anything resolving inside the worktree — `node_modules/.bin/*`, a
159
+ * worker-written `./evil.sh`, `env`, `make` invoked with a worktree-local
160
+ * makefile, etc.) is refused outright, regardless of a denylist match.
161
+ * `allowedCheckBinaries` is the conductor's own fixed list (absolute
162
+ * paths); this function resolves each entry's real path once and compares
163
+ * by exact real-path membership — no prefix/glob matching, so a conductor
164
+ * cannot accidentally allowlist an entire directory the worker controls.
165
+ */
166
+ export function assertAllowedCheckBinary(command, { allowedCheckBinaries = [], worktreeRootReal } = {}) {
167
+ if (typeof command !== 'string' || !path.isAbsolute(command)) {
168
+ throw new ProtectedCheckViolationError(`protected check binary must be an absolute, conductor-defined path, got ${JSON.stringify(command)}`);
169
+ }
170
+ const real = resolveRealpath(command);
171
+ if (worktreeRootReal && withinRoot(worktreeRootReal, real)) {
172
+ throw new ProtectedCheckViolationError(`protected check binary resolves inside the worktree (${real}): a worker-writable binary is never a protected check, regardless of the allowlist`);
173
+ }
174
+ if (!Array.isArray(allowedCheckBinaries) || allowedCheckBinaries.length === 0) {
175
+ throw new ProtectedCheckViolationError('no conductor allowedCheckBinaries were supplied: protected checks are refused by default (fail closed), never derived from the worktree');
176
+ }
177
+ // An allowlist entry that does not resolve on this host (missing binary,
178
+ // different environment) is skipped rather than crashing the whole
179
+ // check: it simply matches nothing, which is the correct "not allowed"
180
+ // outcome for a check that names it, without turning a conductor
181
+ // configuration mismatch into an unrelated WorktreeEscapeError.
182
+ const allowedReal = new Set();
183
+ for (const entry of allowedCheckBinaries) {
184
+ try { allowedReal.add(resolveRealpath(entry)); } catch { /* unresolvable entry: matches nothing */ }
185
+ }
186
+ if (!allowedReal.has(real)) {
187
+ throw new ProtectedCheckViolationError(`protected check binary ${real} is not in the conductor's allowedCheckBinaries list`);
188
+ }
189
+ return real;
190
+ }
191
+
192
+ /**
193
+ * m2: refuse an env allowlist name that looks like a secret, unless the
194
+ * caller explicitly overrides it (`allowSecretLookingNames`). This is a
195
+ * name-pattern guard on the conductor's OWN `envNames` declaration — it
196
+ * cannot inspect values, only catch an accidental
197
+ * `envNames: ['PATH', 'HOME', 'GITHUB_TOKEN']`-style mistake before it ever
198
+ * forwards a credential into worker-controlled check code.
199
+ */
200
+ export function assertNoSecretLookingEnvNames(envNames = [], { allowSecretLookingNames = [] } = {}) {
201
+ const allowed = new Set(allowSecretLookingNames);
202
+ for (const name of envNames) {
203
+ if (SECRET_LOOKING_ENV_NAME.test(name) && !allowed.has(name)) {
204
+ throw new ProtectedCheckViolationError(
205
+ `envNames allowlist contains ${name}, which matches a secret-name pattern (TOKEN/SECRET/KEY/PASSWORD/CREDENTIAL); ` +
206
+ 'protected-check env allowlists are conductor-owned and must never carry secret names — ' +
207
+ 'pass it in allowSecretLookingNames explicitly if this is genuinely intended',
208
+ );
209
+ }
210
+ }
211
+ }
212
+
213
+ /**
214
+ * M1 residual: an allowlisted check binary that is a general-purpose
215
+ * interpreter is not, by itself, evidence that running worker-controlled
216
+ * code through it is safe — that depends entirely on
217
+ * `verification-isolation.mjs` confinement being enforced. `capabilities`
218
+ * must be the live-probed result (`probeVerificationIsolationCapabilities`)
219
+ * for THIS host; when any `REQUIRED_VERIFICATION_CAPABILITIES` capability is
220
+ * not `'enforced'` (or there is no systemd user manager at all) AND the
221
+ * check's own argv references a path resolving inside the worktree, this
222
+ * refuses outright unless `allowWorktreeInterpreterArgs` is explicitly
223
+ * `true`. A non-interpreter binary, a fully-enforced host, or an explicit
224
+ * opt-in all pass through untouched.
225
+ */
226
+ export function assertInterpreterArgsSafeForDegradedConfinement(command, args = [], { worktreeRootReal, capabilities, allowWorktreeInterpreterArgs = false } = {}) {
227
+ if (allowWorktreeInterpreterArgs === true) return;
228
+ const base = path.basename(String(command));
229
+ if (!INTERPRETER_BASENAMES.has(base)) return;
230
+ const degraded = !capabilities || capabilities.mode !== 'systemd-unit' || missingRequiredCapabilities(capabilities).length > 0;
231
+ if (!degraded) return;
232
+ const referencesWorktree = worktreeRootReal && args.some(token => {
233
+ if (typeof token !== 'string' || token.length === 0) return false;
234
+ if (withinRoot(worktreeRootReal, token)) return true;
235
+ if (!path.isAbsolute(token)) return false;
236
+ try { return withinRoot(worktreeRootReal, realpathSync(token)); } catch { return false; }
237
+ });
238
+ if (referencesWorktree) {
239
+ throw new ProtectedCheckViolationError(
240
+ `protected check invokes allowlisted interpreter ${base} with an argument that references the worktree (${args.join(' ')}) while required ` +
241
+ 'confinement capabilities are not enforced on this host: an interpreter check given worker-controlled code depends entirely on the ' +
242
+ 'write/home/network confinement that is currently degraded; pass allowWorktreeInterpreterArgs: true to explicitly accept this residual risk, ' +
243
+ 'or run this check only on a host where confinement is fully enforced',
244
+ );
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Open `targetPath` pinned by file descriptor (B2 TOCTOU fix): resolve its
250
+ * real path once, then open THAT resolved path with `O_NOFOLLOW` so a
251
+ * symlink planted at the resolved location between the resolve and the
252
+ * open fails the open rather than being silently followed. Every
253
+ * subsequent containment check in this call, and every read of the
254
+ * artifact specifically (which stays in this process and keeps using the
255
+ * fd directly — `digestArtifactFd`), operates on the returned fd or on
256
+ * `realPath` taken from it — never on the original path string again — so
257
+ * a swap that happens *after* this call can no longer redirect the
258
+ * validation itself. `realPath` (not the fd) is what a cross-process
259
+ * confined launch receives as its working directory, because
260
+ * `/proc/self/fd/<fd>` only resolves correctly within the SAME process
261
+ * that holds the fd; a `systemd-unit` launch crosses into the systemd user
262
+ * manager and `systemd-executor`, which do not share this process's fd
263
+ * table (confirmed empirically — passing it there is rejected as "a bad
264
+ * unit file setting"). That cross-process string handoff is the one
265
+ * narrow residual TOCTOU window this module cannot close with fd-pinning
266
+ * alone; it is as small as the time between this call returning and
267
+ * `runConfinedCheck` issuing its own request, and it is accepted and
268
+ * documented here rather than silently assumed away.
269
+ *
270
+ * Containment itself is re-derived from the fd via `/proc/self/fd/<fd>`
271
+ * (the kernel's own answer for what this fd actually points at), not from
272
+ * the pre-open realpath, so whatever got opened is what gets checked.
273
+ *
274
+ * m1: a symlink is allowed when its fully-resolved target stays inside
275
+ * `worktreeRootReal` (`node_modules/.bin`, pnpm-style layouts); only a
276
+ * symlink that resolves outside the worktree is denied. A `nlink > 1`
277
+ * regular file is NOT denied here — that check is scoped to the verified
278
+ * artifact only (`assertArtifactPinned`), because legitimate
279
+ * npm/pnpm-installed dependencies are routinely hardlinked from a shared
280
+ * package-manager store and this function is used for general
281
+ * cwd/binary/path resolution, not artifact acceptance.
282
+ *
283
+ * M2: refuses a target whose resolved path crosses a mount boundary
284
+ * relative to the worktree root (`st_dev` mismatch), and refuses a
285
+ * worktree root that has any mount point nested inside it
286
+ * (`/proc/self/mountinfo`) — both would let a conductor-trusted worktree
287
+ * path silently point at filesystem content the worktree preparation step
288
+ * never put there.
289
+ *
290
+ * Returns `{ fd, stat, realPath }`. The caller owns closing `fd`.
291
+ */
292
+ export function openPinnedWithinWorktree(worktreeRootReal, targetPath, { directory = false } = {}) {
293
+ if (typeof targetPath !== 'string' || !path.isAbsolute(targetPath) || targetPath.includes('\0')) {
294
+ throw new WorktreeEscapeError(`worktree-escape check requires an absolute NUL-free path, got ${JSON.stringify(targetPath)}`);
295
+ }
296
+ const literal = path.resolve(targetPath);
297
+ let resolved;
298
+ try {
299
+ resolved = realpathSync(literal);
300
+ } catch (error) {
301
+ throw new WorktreeEscapeError(`cannot resolve real path for worktree-escape check: ${literal}: ${error.message}`);
302
+ }
303
+ const flags = fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK | fsConstants.O_RDONLY | (directory ? fsConstants.O_DIRECTORY : 0);
304
+ let fd;
305
+ try {
306
+ fd = openSync(resolved, flags);
307
+ } catch (error) {
308
+ throw new WorktreeEscapeError(`refusing to open ${literal} -> ${resolved}: ${error.message} (a symlink may have been swapped in after the path was resolved)`);
309
+ }
310
+ try {
311
+ const stat = fstatSync(fd);
312
+ let realPath;
313
+ try {
314
+ realPath = readlinkSync(`/proc/self/fd/${fd}`);
315
+ } catch (error) {
316
+ throw new WorktreeEscapeError(`cannot resolve the pinned file descriptor's own path: ${error.message}`);
317
+ }
318
+ if (!withinRoot(worktreeRootReal, realPath)) {
319
+ throw new WorktreeEscapeError(`pinned path resolves outside the worktree: ${realPath} is not under ${worktreeRootReal}`);
320
+ }
321
+ const rootStat = lstatSync(worktreeRootReal);
322
+ if (stat.dev !== rootStat.dev) {
323
+ throw new WorktreeEscapeError(`pinned path ${realPath} is on a different filesystem/mount (dev ${stat.dev}) than the worktree root (dev ${rootStat.dev}); refusing a mount-boundary crossing`);
324
+ }
325
+ return { fd, stat, realPath };
326
+ } catch (error) {
327
+ closeSync(fd);
328
+ throw error;
329
+ }
330
+ }
331
+
332
+ /**
333
+ * M2: refuse a worktree root that has anything else mounted inside it.
334
+ * Reads `/proc/self/mountinfo` (Linux-only; no-op elsewhere) and throws if
335
+ * any mount point other than the root itself is nested under it — the
336
+ * worktree is expected to be a plain subtree of its own filesystem, never
337
+ * a path with something bind-mounted into it after preparation.
338
+ */
339
+ export function assertNoNestedMounts(worktreeRootReal, { mountinfoText } = {}) {
340
+ if (process.platform !== 'linux' && mountinfoText === undefined) return;
341
+ let mountinfo = mountinfoText;
342
+ if (mountinfo === undefined) try {
343
+ mountinfo = readFileSync('/proc/self/mountinfo', 'utf8');
344
+ } catch (error) {
345
+ // Fail closed: without the mount table a bind mount into the worktree
346
+ // cannot be ruled out.
347
+ throw new WorktreeEscapeError(`cannot read /proc/self/mountinfo to rule out nested mounts: ${error.message}`);
348
+ }
349
+ const rootWithSep = worktreeRootReal.endsWith(path.sep) ? worktreeRootReal : worktreeRootReal + path.sep;
350
+ const nested = [];
351
+ for (const line of mountinfo.split('\n')) {
352
+ const fields = line.split(' ');
353
+ // The kernel octal-escapes space, tab, newline and backslash (\040,
354
+ // \011, \012, \134) in mount points; decode before comparing.
355
+ const mountPoint = fields[4]?.replace(/\\([0-7]{3})/g, (_, octal) => String.fromCharCode(parseInt(octal, 8)));
356
+ if (!mountPoint) continue;
357
+ if (mountPoint !== worktreeRootReal && mountPoint.startsWith(rootWithSep)) nested.push(mountPoint);
358
+ }
359
+ if (nested.length > 0) {
360
+ throw new WorktreeEscapeError(`worktree root has nested mount point(s), refusing: ${nested.join(', ')}`);
361
+ }
362
+ }
363
+
364
+ /** Canonicalize and validate the worktree root itself before using it as a trust boundary. */
365
+ export function resolveWorktreeRoot(worktreeRoot) {
366
+ if (typeof worktreeRoot !== 'string' || !path.isAbsolute(worktreeRoot) || worktreeRoot.includes('\0')) {
367
+ throw new WorktreeEscapeError(`worktree root must be an absolute NUL-free path, got ${JSON.stringify(worktreeRoot)}`);
368
+ }
369
+ // M2: a symlinked worktree root is refused outright (`/proc/self/cwd`
370
+ // style roots, or a root that is itself a symlink) rather than silently
371
+ // canonicalized, so a caller cannot accidentally hand this module a
372
+ // moving target as the trust boundary itself.
373
+ let lst;
374
+ try {
375
+ lst = lstatSync(worktreeRoot);
376
+ } catch (error) {
377
+ throw new WorktreeEscapeError(`cannot stat worktree root: ${worktreeRoot}: ${error.message}`);
378
+ }
379
+ if (lst.isSymbolicLink()) {
380
+ throw new WorktreeEscapeError(`worktree root must not itself be a symlink: ${worktreeRoot}`);
381
+ }
382
+ let real;
383
+ try {
384
+ real = realpathSync(worktreeRoot);
385
+ } catch (error) {
386
+ throw new WorktreeEscapeError(`cannot resolve worktree root: ${worktreeRoot}: ${error.message}`);
387
+ }
388
+ if (real !== worktreeRoot) {
389
+ throw new WorktreeEscapeError(`worktree root has a symlinked ancestor directory: ${worktreeRoot} -> ${real}; refusing a non-canonical root as the trust boundary`);
390
+ }
391
+ assertNoNestedMounts(real);
392
+ return real;
393
+ }
394
+
395
+ /**
396
+ * m1 + B2: validate (and, on success, return the canonical real path for)
397
+ * a path that must stay inside the worktree, WITHOUT pinning a long-lived
398
+ * fd — used by `verifyWorkerArtifact` for the artifact path check where a
399
+ * fresh fd is opened separately for digesting. Kept as a thin wrapper over
400
+ * `openPinnedWithinWorktree` so every path-containment decision in this
401
+ * module goes through the same fd-pinned logic; the fd is opened and
402
+ * immediately closed here since only the validated real path is needed by
403
+ * the caller.
404
+ */
405
+ export function assertWithinWorktree(worktreeRootReal, targetPath) {
406
+ const { fd, realPath } = openPinnedWithinWorktree(worktreeRootReal, targetPath, { directory: false });
407
+ closeSync(fd);
408
+ return realPath;
409
+ }
410
+
411
+ /**
412
+ * An artifact must be a bounded regular file with exactly one hard link.
413
+ * These requirements do not apply to general path/cwd resolution (m1). A
414
+ * freshly checked-out or worker-written artifact is expected to have
415
+ * exactly one hard link; more than one is treated as an escape attempt (a
416
+ * worker-planted hardlink aliasing a file outside the worktree, or a
417
+ * mutable shared dependency) specifically for the thing acceptance is
418
+ * about to bind a digest to.
419
+ */
420
+ export function pinArtifact(worktreeRootReal, artifactPath) {
421
+ const pinned = openPinnedWithinWorktree(worktreeRootReal, artifactPath, { directory: false });
422
+ try {
423
+ if (!pinned.stat.isFile()) {
424
+ throw new WorktreeEscapeError(`verified artifact must be a regular file: ${pinned.realPath}`);
425
+ }
426
+ if (pinned.stat.nlink > 1) {
427
+ throw new WorktreeEscapeError(`refusing a multiply-linked artifact: ${pinned.realPath} (nlink=${pinned.stat.nlink}; the verified artifact is expected to have exactly one hard link)`);
428
+ }
429
+ assertArtifactSize(pinned.stat.size);
430
+ return pinned;
431
+ } catch (error) {
432
+ closeSync(pinned.fd);
433
+ throw error;
434
+ }
435
+ }
436
+
437
+ function assertArtifactSize(size) {
438
+ if (!Number.isSafeInteger(size) || size < 0 || size > MAX_ARTIFACT_BYTES) {
439
+ throw new WorktreeEscapeError(`artifact exceeds maximum size of ${MAX_ARTIFACT_BYTES} bytes (reported size: ${size})`);
440
+ }
441
+ }
442
+
443
+ function digestOf(bytes) {
444
+ return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
445
+ }
446
+
447
+ /** Digest the artifact pinned at `pinned.fd` (read via the fd, never by re-opening the path). */
448
+ export function digestArtifactFd(pinned) {
449
+ const size = pinned.stat.size;
450
+ assertArtifactSize(size);
451
+ const current = fstatSync(pinned.fd);
452
+ assertArtifactSize(current.size);
453
+ if (current.size !== size) throw new WorktreeEscapeError('artifact size changed before hashing');
454
+ const hash = createHash('sha256');
455
+ const buffer = Buffer.alloc(ARTIFACT_HASH_CHUNK_BYTES);
456
+ let offset = 0;
457
+ while (offset < size) {
458
+ const read = readSync(pinned.fd, buffer, 0, Math.min(buffer.length, size - offset), offset);
459
+ if (read === 0) throw new WorktreeEscapeError('artifact truncated during hashing');
460
+ hash.update(buffer.subarray(0, read));
461
+ offset += read;
462
+ }
463
+ // Check EOF without following an indefinitely growing file.
464
+ if (readSync(pinned.fd, buffer, 0, 1, offset) !== 0 || fstatSync(pinned.fd).size !== size) {
465
+ throw new WorktreeEscapeError('artifact size changed during hashing');
466
+ }
467
+ return `sha256:${hash.digest('hex')}`;
468
+ }
469
+
470
+ // M3 (round 2, CRITICAL): the previous implementation ran `git add -A` /
471
+ // `git write-tree` with a disposable `GIT_INDEX_FILE` but otherwise
472
+ // inherited the worktree's own git config and process environment. A
473
+ // worker-controlled `.gitattributes` (`filter=`), `.git/config`
474
+ // (`core.fsmonitor`, `core.hooksPath`, `include`/`includeIf`), or a
475
+ // worker-planted hook executes with CONDUCTOR authority the instant `git
476
+ // add`/`write-tree` runs — confirmed by an independent review spawning a
477
+ // marker-writing filter. Rather than trying to sanitize git's environment
478
+ // and config well enough to be trusted with worker-controlled input (the
479
+ // documented fallback option (b)), this computes the tree digest WITHOUT
480
+ // git at all: a deterministic, content-addressed walk of the real
481
+ // filesystem, opened by file descriptor at every step.
482
+ function digestFileContentsFd(fd, size) {
483
+ if (fstatSync(fd).size !== size) throw new TreeDigestError('tree file size changed before hashing');
484
+ const hash = createHash('sha256');
485
+ const buffer = Buffer.alloc(ARTIFACT_HASH_CHUNK_BYTES);
486
+ let offset = 0;
487
+ while (offset < size) {
488
+ const read = readSync(fd, buffer, 0, Math.min(buffer.length, size - offset), offset);
489
+ if (read === 0) throw new TreeDigestError('tree file truncated during hashing');
490
+ hash.update(buffer.subarray(0, read));
491
+ offset += read;
492
+ }
493
+ if (readSync(fd, buffer, 0, 1, offset) !== 0 || fstatSync(fd).size !== size) {
494
+ throw new TreeDigestError('tree file size changed during hashing');
495
+ }
496
+ return hash.digest('hex');
497
+ }
498
+
499
+ /**
500
+ * Open a child of an already-open directory fd by name, WITHOUT ever
501
+ * re-resolving the parent's path as a string (the openat(2)-equivalent this
502
+ * module uses throughout — `/proc/self/fd/<fd>/<name>` resolves against the
503
+ * kernel's own view of the open directory, not a mutable path, so a rename
504
+ * of an ancestor directory after it was opened cannot redirect this). Never
505
+ * follows a symlink (`O_NOFOLLOW`): a symlinked entry's TYPE is always
506
+ * determined by `lstatSync` first, and only a plain file/directory is ever
507
+ * opened this way.
508
+ */
509
+ function openChildNoFollow(dirFd, name, { directory = false } = {}) {
510
+ const flags = fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK | fsConstants.O_RDONLY | (directory ? fsConstants.O_DIRECTORY : 0);
511
+ return openSync(`/proc/self/fd/${dirFd}/${name}`, flags);
512
+ }
513
+
514
+ function statChildOfDirFd(dirFd, name) {
515
+ return lstatSync(`/proc/self/fd/${dirFd}/${name}`);
516
+ }
517
+
518
+ function listDirFd(dirFd, budget) {
519
+ // Enforce the entry budget before allocating the whole directory listing.
520
+ const directory = opendirSync(`/proc/self/fd/${dirFd}`);
521
+ const names = [];
522
+ try {
523
+ let entry;
524
+ while ((entry = directory.readSync()) !== null) {
525
+ if (++budget.entries > MAX_TREE_ENTRIES) throw new TreeDigestError('tree entry budget exceeded');
526
+ names.push(entry.name);
527
+ }
528
+ } finally { directory.closeSync(); }
529
+ return names.sort();
530
+ }
531
+
532
+ const TREE_DIGEST_EXCLUDED_ENTRIES = new Set(['.git']);
533
+
534
+ /**
535
+ * Recursively walk one already-open directory fd, appending a
536
+ * `{ path, type, ... }` descriptor for every entry to `entries`. Includes
537
+ * UNTRACKED and IGNORED files (there is no git index/gitignore involved at
538
+ * all); excludes only the worktree's own top-level `.git` entry (recorded
539
+ * explicitly, never silently). A symlink's type is taken from `lstat` and
540
+ * its target string is hashed as DATA — the target is never followed, so a
541
+ * symlink to secret content outside the worktree contributes only its own
542
+ * target string to the digest, never that content.
543
+ */
544
+ function walkDirectoryFd(dirFd, relPrefix, entries, budget, depth = 0) {
545
+ if (depth > MAX_TREE_DEPTH) throw new TreeDigestError('tree depth budget exceeded');
546
+ const names = listDirFd(dirFd, budget);
547
+ for (const name of names) {
548
+ if (relPrefix === '' && TREE_DIGEST_EXCLUDED_ENTRIES.has(name)) {
549
+ entries.push({ relPath: name, type: 'excluded' });
550
+ continue;
551
+ }
552
+ const relPath = relPrefix ? `${relPrefix}/${name}` : name;
553
+ let stat;
554
+ try {
555
+ stat = statChildOfDirFd(dirFd, name);
556
+ } catch (error) {
557
+ throw new TreeDigestError(`cannot stat ${relPath}: ${error.message}`);
558
+ }
559
+ if (stat.isSymbolicLink()) {
560
+ let target;
561
+ try {
562
+ target = readlinkSync(`/proc/self/fd/${dirFd}/${name}`);
563
+ } catch (error) {
564
+ throw new TreeDigestError(`cannot read symlink target for ${relPath}: ${error.message}`);
565
+ }
566
+ entries.push({ relPath, type: 'symlink', mode: stat.mode & 0o777, target });
567
+ } else if (stat.isDirectory()) {
568
+ let childFd;
569
+ try {
570
+ childFd = openChildNoFollow(dirFd, name, { directory: true });
571
+ } catch (error) {
572
+ throw new TreeDigestError(`cannot open directory ${relPath}: ${error.message}`);
573
+ }
574
+ try {
575
+ entries.push({ relPath, type: 'dir', mode: stat.mode & 0o777 });
576
+ walkDirectoryFd(childFd, relPath, entries, budget, depth + 1);
577
+ } finally {
578
+ closeSync(childFd);
579
+ }
580
+ } else if (stat.isFile()) {
581
+ let childFd;
582
+ try {
583
+ childFd = openChildNoFollow(dirFd, name);
584
+ } catch (error) {
585
+ throw new TreeDigestError(`cannot open file ${relPath}: ${error.message}`);
586
+ }
587
+ try {
588
+ const openedStat = fstatSync(childFd);
589
+ if (!openedStat.isFile()) throw new TreeDigestError(`file ${relPath} changed to a non-regular file before hashing`);
590
+ if (openedStat.dev !== stat.dev || openedStat.ino !== stat.ino) {
591
+ throw new TreeDigestError(`file ${relPath} identity changed before hashing`);
592
+ }
593
+ if (!Number.isSafeInteger(openedStat.size) || openedStat.size < 0 || openedStat.size > MAX_TREE_FILE_BYTES) {
594
+ throw new TreeDigestError(`tree file ${relPath} exceeds maximum size of ${MAX_TREE_FILE_BYTES} bytes`);
595
+ }
596
+ budget.bytes += openedStat.size;
597
+ if (budget.bytes > MAX_TREE_BYTES) throw new TreeDigestError('tree byte budget exceeded');
598
+ const contentHash = digestFileContentsFd(childFd, openedStat.size);
599
+ entries.push({ relPath, type: 'file', mode: openedStat.mode & 0o777, size: openedStat.size, contentHash });
600
+ } finally {
601
+ closeSync(childFd);
602
+ }
603
+ } else {
604
+ // Device/socket/FIFO: record identity metadata only, never attempt a
605
+ // content read (which could block indefinitely on a FIFO/socket).
606
+ entries.push({ relPath, type: 'other', mode: stat.mode & 0o777 });
607
+ }
608
+ }
609
+ }
610
+
611
+ /**
612
+ * M3: a deterministic, content-addressed digest of the entire worktree
613
+ * tree (`fd-tree:sha256:<hex>`), computed via a pure file-descriptor-pinned
614
+ * walk — no git, no worker-controlled config/filters/hooks/fsmonitor ever
615
+ * executes. Used to bind acceptance to "the tree did not change while the
616
+ * checks ran," not just the single artifact file. Includes untracked AND
617
+ * ignored files; excludes only the worktree's own top-level `.git` entry.
618
+ *
619
+ * THROWS `TreeDigestError` on any failure (unreadable entry, permission
620
+ * denial, a symlink loop surfacing as ELOOP, ...) rather than returning
621
+ * `null` — a digest failure must REJECT verification, never be silently
622
+ * treated as "we don't know, so assume unchanged."
623
+ */
624
+ export function computeWorktreeTreeDigest(worktreeRootReal) {
625
+ let rootFd;
626
+ try {
627
+ rootFd = openSync(worktreeRootReal, fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW | fsConstants.O_RDONLY);
628
+ } catch (error) {
629
+ throw new TreeDigestError(`cannot open worktree root for tree digest: ${error.message}`);
630
+ }
631
+ const entries = [];
632
+ try {
633
+ walkDirectoryFd(rootFd, '', entries, { entries: 0, bytes: 0 });
634
+ } finally {
635
+ closeSync(rootFd);
636
+ }
637
+ entries.sort((a, b) => (a.relPath < b.relPath ? -1 : a.relPath > b.relPath ? 1 : 0));
638
+ const hash = createHash('sha256');
639
+ for (const entry of entries) {
640
+ if (entry.type === 'excluded') { hash.update(`excluded\u0000${entry.relPath}\n`); continue; }
641
+ if (entry.type === 'symlink') { hash.update(`symlink\u0000${entry.relPath}\u0000${entry.mode.toString(8)}\u0000${entry.target}\n`); continue; }
642
+ if (entry.type === 'dir') { hash.update(`dir\u0000${entry.relPath}\u0000${entry.mode.toString(8)}\n`); continue; }
643
+ if (entry.type === 'file') { hash.update(`file\u0000${entry.relPath}\u0000${entry.mode.toString(8)}\u0000${entry.size}\u0000${entry.contentHash}\n`); continue; }
644
+ hash.update(`other\u0000${entry.relPath}\u0000${entry.mode.toString(8)}\n`);
645
+ }
646
+ return `fd-tree:sha256:${hash.digest('hex')}`;
647
+ }
648
+
649
+ /**
650
+ * Run one conductor-defined protected check outside the worker sandbox,
651
+ * through `verification-isolation.mjs`'s confined `systemd-run --user`
652
+ * path. `command`/`args`/`cwd` must come from the conductor's own check
653
+ * definitions, never from worker output or a worker-writable manifest;
654
+ * `command` is additionally required to resolve to an allowlisted binary
655
+ * outside the worktree (M1).
656
+ *
657
+ * Returns a classification distinguishing a sandbox/isolation failure
658
+ * from a real check failure, derived ONLY from a spawn-level errno or this
659
+ * module's own isolation-unavailable signal — NEVER from the check's own
660
+ * stdout/stderr content, which worker-controlled code fully controls and
661
+ * can forge in either direction (B3):
662
+ * - `'passed'` — exit 0.
663
+ * - `'sandbox'` — spawn-level EPERM/EROFS, or confinement was required
664
+ * but unavailable on this host and the caller did not
665
+ * opt into `allowDegradedIsolation`.
666
+ * - `'timeout'` — the check did not finish within `timeoutMs`.
667
+ * - `'failed'` — any other non-zero exit; a real check failure,
668
+ * regardless of what its output says.
669
+ * - `'error'` — the check could not be spawned at all (e.g. ENOENT).
670
+ *
671
+ * `isolation` is always attached to the result (mode + the full degraded-
672
+ * capability list from the live per-host probe), on every classification,
673
+ * so a caller can never read "passed"/"accepted" as "fully isolated"
674
+ * without also seeing what this host could not enforce.
675
+ */
676
+ export function runProtectedCheck({
677
+ id,
678
+ command,
679
+ args = [],
680
+ worktreeRootReal,
681
+ cwd,
682
+ envNames = ['PATH', 'HOME'],
683
+ env = process.env,
684
+ timeoutMs = 60000,
685
+ allowedCheckBinaries = [],
686
+ allowSecretLookingEnvNames = [],
687
+ allowDegradedIsolation = false,
688
+ allowWorktreeInterpreterArgs = false,
689
+ outputDirReal,
690
+ spawn,
691
+ runConfined = runConfinedCheck,
692
+ } = {}) {
693
+ assertNotPackageScriptInvocation(command, args);
694
+ // M1 residual: use the ALLOWLIST-RESOLVED canonical real path for the
695
+ // actual launch, not the original `command` spelling. `command` may be a
696
+ // symlink that was valid (resolved to an allowlisted real path) at the
697
+ // instant `assertAllowedCheckBinary` checked it; launching the original
698
+ // spelling again would re-resolve it a second time at spawn — a window in
699
+ // which the symlink could have been retargeted. Launching the already-
700
+ // resolved real path removes that second resolution entirely.
701
+ const resolvedCommand = assertAllowedCheckBinary(command, { allowedCheckBinaries, worktreeRootReal });
702
+ assertNoSecretLookingEnvNames(envNames, { allowSecretLookingNames: allowSecretLookingEnvNames });
703
+ // M1 residual: an allowlisted interpreter handed a worktree-path argument
704
+ // is only as safe as the confinement it runs under. Refuse outright when
705
+ // confinement is degraded on this host, unless explicitly opted in.
706
+ // `probeVerificationIsolationCapabilities` is cached per-process, so this
707
+ // costs a real probe only once per host per cache TTL, not per check.
708
+ const base = path.basename(resolvedCommand);
709
+ if (INTERPRETER_BASENAMES.has(base) && allowWorktreeInterpreterArgs !== true) {
710
+ const capabilities = spawn ? probeVerificationIsolationCapabilities({ spawn }) : probeVerificationIsolationCapabilities();
711
+ assertInterpreterArgsSafeForDegradedConfinement(resolvedCommand, args, { worktreeRootReal, capabilities, allowWorktreeInterpreterArgs });
712
+ }
713
+ // Pin-validate the cwd (containment, mount-crossing, symlink-swap
714
+ // detection — B2/M2). The fd is held OPEN across the entire confined
715
+ // probe+launch (B2 round 2): closing it immediately after resolving
716
+ // `cwdRealPath`, as the previous version did, left the whole probe+launch
717
+ // duration as an unguarded TOCTOU window. Holding it open lets this
718
+ // function re-verify, the MOMENT the launch returns, that the fd still
719
+ // points at the same real path and the same filesystem/mount as the
720
+ // worktree root — narrowing the residual window to just the handoff
721
+ // between that re-check and the cross-process launch call itself (the
722
+ // one window fd-pinning alone cannot close, documented below and on
723
+ // `openPinnedWithinWorktree`): a confined (`systemd-unit`) launch crosses
724
+ // into the systemd user *manager* and `systemd-executor`, neither of
725
+ // which shares this process's file descriptor table, so
726
+ // `/proc/self/fd/<fd>` cannot be handed to them directly (confirmed
727
+ // empirically — the manager rejects it as "a bad unit file setting"), so
728
+ // the real path STRING is still what is handed onward as `cwd`.
729
+ const pinnedCwd = openPinnedWithinWorktree(worktreeRootReal, cwd ?? worktreeRootReal, { directory: true });
730
+ const cwdRealPath = pinnedCwd.realPath;
731
+ let result;
732
+ try {
733
+ const confinedSpawnOptions = { command: resolvedCommand, args, worktreeRootReal, outputDirReal, envNames, env, timeoutMs, allowDegradedIsolation, cwd: cwdRealPath };
734
+ if (spawn) confinedSpawnOptions.spawn = spawn;
735
+ result = runConfined(confinedSpawnOptions);
736
+ // B2: re-verify, while the fd is STILL open, that the path it is
737
+ // pinned to has not been swapped for a different inode/mount during
738
+ // the probe+launch window that just ran.
739
+ let postLaunchRealPath;
740
+ try {
741
+ postLaunchRealPath = readlinkSync(`/proc/self/fd/${pinnedCwd.fd}`);
742
+ } catch (error) {
743
+ throw new WorktreeEscapeError(`cannot re-verify the pinned cwd after the check ran: ${error.message}`);
744
+ }
745
+ if (postLaunchRealPath !== cwdRealPath) {
746
+ throw new WorktreeEscapeError(`cwd identity changed during the check (was ${cwdRealPath}, now ${postLaunchRealPath}): refusing to trust the result`);
747
+ }
748
+ const postStat = fstatSync(pinnedCwd.fd);
749
+ const rootStat = lstatSync(worktreeRootReal);
750
+ if (postStat.dev !== rootStat.dev) {
751
+ throw new WorktreeEscapeError(`cwd is on a different filesystem/mount after the check ran than the worktree root: refusing to trust the result`);
752
+ }
753
+ assertNoNestedMounts(worktreeRootReal);
754
+ } finally {
755
+ closeSync(pinnedCwd.fd);
756
+ }
757
+ const stdout = String(result.stdout ?? '');
758
+ const stderr = String(result.stderr ?? '');
759
+ const isolation = result.isolation ?? { mode: 'unknown', degraded: [] };
760
+ if (result.error) {
761
+ if (result.error.code === 'ETIMEDOUT') {
762
+ return { id, classification: 'timeout', ok: false, reason: result.error.code, stdout, stderr, isolation };
763
+ }
764
+ if (result.error.code === 'EPERM' || result.error.code === 'EROFS' || result.error.code === 'ISOLATION_UNAVAILABLE') {
765
+ return { id, classification: 'sandbox', ok: false, reason: result.error.code, stdout, stderr, isolation, diagnostic: result.error.message };
766
+ }
767
+ return { id, classification: 'error', ok: false, reason: result.error.code ?? result.error.message, stdout, stderr, isolation };
768
+ }
769
+ if (result.status !== 0) {
770
+ return { id, classification: 'failed', ok: false, reason: `exit ${result.status}`, stdout, stderr, exitCode: result.status, isolation };
771
+ }
772
+ return { id, classification: 'passed', ok: true, stdout, stderr, exitCode: 0, isolation };
773
+ }
774
+
775
+ /**
776
+ * Verify one worker artifact with a fixed set of conductor-defined
777
+ * protected checks, entirely outside the worker sandbox, and return a
778
+ * `workerDirectVerification`-shaped result
779
+ * (schemas/mission-v1.schema.json `$defs/workerDirectVerification`:
780
+ * `status`/`verifierId`/`runnerRef`/`artifactDigest`/`evidence`/`findings`/
781
+ * `controlledContext`), extended with `isolation` (the confinement mode
782
+ * and every degraded capability this host could not enforce, reported
783
+ * unconditionally — never only on failure).
784
+ *
785
+ * Status mapping:
786
+ * - `'rejected'` — a path escape/protected-check violation was caught, at
787
+ * least one check classified `'failed'`/`'error'`/`'timeout'`, or the
788
+ * worktree tree digest changed between the pre- and post-check
789
+ * snapshots (M3: the tree was mutated *during* verification). This is a
790
+ * real-failure or security verdict, not infrastructure noise.
791
+ * - `'blocked'` — no real failure, but at least one check classified
792
+ * `'sandbox'`: the verification environment itself could not run the
793
+ * check (including "confinement was required but unavailable and not
794
+ * explicitly allowed-degraded"), which is infrastructure evidence,
795
+ * never a pass and never promoted to "the code failed."
796
+ * - `'accepted'` — every check passed; `artifactDigest` binds acceptance
797
+ * to the exact bytes verified AFTER the checks ran (re-read via a fresh
798
+ * pinned fd), and `treeDigest` binds it to the whole-worktree tree
799
+ * snapshot taken immediately before and immediately after the checks.
800
+ *
801
+ * This function never deletes, moves, or merges anything — on any
802
+ * non-accepted outcome the worktree and its dirty state are left exactly
803
+ * as found, matching the retention default in
804
+ * `08-security-and-threat-model.md`. There is no "auto-merge" code path:
805
+ * integrating the verified digest elsewhere is a separate, explicit step
806
+ * the caller takes (Rule 9 step 9), never this function.
807
+ */
808
+ /**
809
+ * M3: pin the worktree ROOT itself by file descriptor, independent of the
810
+ * content-level tree digest, so a check that mutates the tree and then
811
+ * restores it byte-for-byte (a "swap-and-restore" — e.g. unmount/remount a
812
+ * different filesystem at the same path, or replace the root directory
813
+ * entry itself) cannot escape detection merely because the pre/post
814
+ * CONTENT digests happen to match. Returns `{ fd, dev, ino }`; the caller
815
+ * holds the fd open across the entire check run and calls
816
+ * `assertRootIdentityUnchanged` afterward, then closes it.
817
+ */
818
+ export function pinRootIdentity(worktreeRootReal) {
819
+ const fd = openSync(worktreeRootReal, fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW | fsConstants.O_RDONLY);
820
+ const stat = fstatSync(fd);
821
+ return { fd, dev: stat.dev, ino: stat.ino };
822
+ }
823
+
824
+ /**
825
+ * M3: re-verify, after the checks have run, that the pinned root fd still
826
+ * resolves to the SAME path and the SAME `dev:ino` identity as a fresh
827
+ * `lstat` of `worktreeRootReal`, and that no mount has appeared inside the
828
+ * root since preparation. Throws `WorktreeEscapeError` on any mismatch.
829
+ */
830
+ export function assertRootIdentityUnchanged(pinnedRoot, worktreeRootReal) {
831
+ let currentPath;
832
+ try {
833
+ currentPath = readlinkSync(`/proc/self/fd/${pinnedRoot.fd}`);
834
+ } catch (error) {
835
+ throw new WorktreeEscapeError(`cannot re-verify the pinned worktree root after checks ran: ${error.message}`);
836
+ }
837
+ if (currentPath !== worktreeRootReal) {
838
+ throw new WorktreeEscapeError(`worktree root identity changed during verification (was ${worktreeRootReal}, now ${currentPath}): refusing to trust the result (swap-and-restore detected)`);
839
+ }
840
+ let freshStat;
841
+ try {
842
+ freshStat = lstatSync(worktreeRootReal);
843
+ } catch (error) {
844
+ throw new WorktreeEscapeError(`cannot re-stat the worktree root after checks ran: ${error.message}`);
845
+ }
846
+ if (freshStat.dev !== pinnedRoot.dev || freshStat.ino !== pinnedRoot.ino) {
847
+ throw new WorktreeEscapeError(`worktree root dev:inode changed during verification (was ${pinnedRoot.dev}:${pinnedRoot.ino}, now ${freshStat.dev}:${freshStat.ino}): refusing to trust the result (swap-and-restore detected)`);
848
+ }
849
+ assertNoNestedMounts(worktreeRootReal);
850
+ }
851
+
852
+ export function verifyWorkerArtifact({
853
+ worktreeRoot,
854
+ artifactPath,
855
+ checks = [],
856
+ allowedCheckBinaries = [],
857
+ outputDirReal,
858
+ verifierId = 'trusted-verification@1',
859
+ runnerRef = null,
860
+ guardArtifact,
861
+ } = {}) {
862
+ let worktreeRootReal;
863
+ try {
864
+ worktreeRootReal = resolveWorktreeRoot(worktreeRoot);
865
+ } catch (error) {
866
+ return rejected(verifierId, runnerRef, [`worktree root invalid: ${error.message}`], 'resolving the worktree root');
867
+ }
868
+
869
+ // M3: pin the root's own identity BEFORE anything else, held open across
870
+ // the entire check run (closed in the `finally` below) so a
871
+ // swap-and-restore of the root itself — not just its content — is
872
+ // independently detectable even if the content-level tree digest is
873
+ // made to match.
874
+ let pinnedRoot;
875
+ try {
876
+ pinnedRoot = pinRootIdentity(worktreeRootReal);
877
+ } catch (error) {
878
+ return rejected(verifierId, runnerRef, [`cannot pin worktree root identity: ${error.message}`], 'pinning the worktree root');
879
+ }
880
+
881
+ try {
882
+ return verifyWorkerArtifactPinned({ worktreeRootReal, artifactPath, checks, allowedCheckBinaries, outputDirReal, verifierId, runnerRef, pinnedRoot, guardArtifact });
883
+ } finally {
884
+ closeSync(pinnedRoot.fd);
885
+ }
886
+ }
887
+
888
+ function verifyWorkerArtifactPinned({ worktreeRootReal, artifactPath, checks, allowedCheckBinaries, outputDirReal, verifierId, runnerRef, pinnedRoot, guardArtifact }) {
889
+ let preCheckArtifact;
890
+ try {
891
+ preCheckArtifact = pinArtifact(worktreeRootReal, artifactPath);
892
+ } catch (error) {
893
+ return rejected(verifierId, runnerRef, [`artifact path escape check failed: ${error.message}`], 'validating the artifact path');
894
+ }
895
+ let preDigest;
896
+ try {
897
+ preDigest = digestArtifactFd(preCheckArtifact);
898
+ } catch (error) {
899
+ closeSync(preCheckArtifact.fd);
900
+ return rejected(verifierId, runnerRef, [`artifact digest failed: ${error.message}`], 'hashing the artifact');
901
+ }
902
+ try { guardArtifact?.(preCheckArtifact, preDigest); }
903
+ finally { closeSync(preCheckArtifact.fd); }
904
+
905
+ // M3: a tree-digest FAILURE must reject, never be silently treated as "we
906
+ // don't know, so assume unchanged" — fail closed before any check runs.
907
+ let preTreeDigest;
908
+ try {
909
+ preTreeDigest = computeWorktreeTreeDigest(worktreeRootReal);
910
+ } catch (error) {
911
+ return rejected(verifierId, runnerRef, [`worktree tree digest (pre-check) could not be computed: ${error.message}`], 'computing the pre-check worktree tree digest');
912
+ }
913
+
914
+ const outcomes = [];
915
+ for (const check of checks) {
916
+ try {
917
+ outcomes.push(runProtectedCheck({ ...check, worktreeRootReal, allowedCheckBinaries, outputDirReal }));
918
+ } catch (error) {
919
+ if (error instanceof ProtectedCheckViolationError || error instanceof WorktreeEscapeError) {
920
+ outcomes.push({ id: check.id, classification: 'rejected-definition', ok: false, reason: error.message, isolation: { mode: 'n/a', degraded: [] } });
921
+ continue;
922
+ }
923
+ throw error;
924
+ }
925
+ }
926
+
927
+ // M3: re-verify the PINNED ROOT's own identity and mount state before
928
+ // trusting anything computed from a fresh read of `worktreeRootReal`
929
+ // below — a swap-and-restore of the root itself is caught here even if
930
+ // it would otherwise leave the content-level tree digest unchanged.
931
+ try {
932
+ assertRootIdentityUnchanged(pinnedRoot, worktreeRootReal);
933
+ } catch (error) {
934
+ return rejected(verifierId, runnerRef, [`worktree root identity check failed after checks ran: ${error.message}`], 're-verifying the worktree root identity after checks');
935
+ }
936
+
937
+ // M3: same fail-closed treatment for the post-check digest — a failure
938
+ // here must also reject, not fall through to "accepted" without ever
939
+ // having proven the tree was untouched.
940
+ let postTreeDigest;
941
+ try {
942
+ postTreeDigest = computeWorktreeTreeDigest(worktreeRootReal);
943
+ } catch (error) {
944
+ return rejected(verifierId, runnerRef, [`worktree tree digest (post-check) could not be computed: ${error.message}`], 'computing the post-check worktree tree digest');
945
+ }
946
+ const treeChangedDuringChecks = preTreeDigest !== postTreeDigest;
947
+
948
+ const allDegraded = outcomes.flatMap(outcome => (outcome.isolation?.degraded ?? []).map(entry => `${outcome.id}: isolation degraded (${entry.capability}): ${entry.reason}`));
949
+
950
+ const findings = outcomes.map(outcome =>
951
+ `${outcome.id}: ${outcome.classification}${outcome.reason ? ` (${outcome.reason})` : ''}`);
952
+ const hasRealFailure = outcomes.some(outcome =>
953
+ ['failed', 'error', 'timeout', 'rejected-definition'].includes(outcome.classification));
954
+ const hasSandboxFailure = outcomes.some(outcome => outcome.classification === 'sandbox');
955
+
956
+ const isolationSummary = {
957
+ mode: outcomes[0]?.isolation?.mode ?? 'n/a',
958
+ degraded: outcomes.flatMap(outcome => outcome.isolation?.degraded ?? []),
959
+ };
960
+
961
+ if (treeChangedDuringChecks) {
962
+ return {
963
+ status: 'rejected', verifierId, runnerRef, artifactDigest: null, evidence: [],
964
+ findings: [...findings, `worktree tree digest changed during verification (pre: ${preTreeDigest}, post: ${postTreeDigest}): the tree was mutated while checks ran`, ...allDegraded],
965
+ controlledContext: 'conductor-controlled check environment, outside worker sandbox',
966
+ isolation: isolationSummary,
967
+ };
968
+ }
969
+ if (hasRealFailure) {
970
+ return {
971
+ status: 'rejected', verifierId, runnerRef, artifactDigest: null, evidence: [],
972
+ findings: [...findings, ...allDegraded],
973
+ controlledContext: 'conductor-controlled check environment, outside worker sandbox',
974
+ isolation: isolationSummary,
975
+ };
976
+ }
977
+ if (hasSandboxFailure) {
978
+ return {
979
+ status: 'blocked', verifierId, runnerRef, artifactDigest: null, evidence: [],
980
+ findings: [...findings, ...allDegraded],
981
+ controlledContext: 'conductor-controlled check environment reported a sandbox/isolation failure, not a code verdict',
982
+ isolation: isolationSummary,
983
+ };
984
+ }
985
+
986
+ // Acceptance re-reads the artifact and re-derives the tree digest AFTER
987
+ // the checks ran (M3): the digest being bound is the post-check state,
988
+ // not a stale pre-check snapshot.
989
+ let postCheckArtifact;
990
+ try {
991
+ postCheckArtifact = pinArtifact(worktreeRootReal, artifactPath);
992
+ } catch (error) {
993
+ return rejected(verifierId, runnerRef, [`artifact path escape check failed after checks ran: ${error.message}`, ...allDegraded], 're-validating the artifact path after checks');
994
+ }
995
+ let postDigest;
996
+ try {
997
+ postDigest = digestArtifactFd(postCheckArtifact);
998
+ } catch (error) {
999
+ return rejected(verifierId, runnerRef, [`artifact digest failed after checks ran: ${error.message}`, ...allDegraded], 'hashing the artifact after checks');
1000
+ } finally {
1001
+ closeSync(postCheckArtifact.fd);
1002
+ }
1003
+ if (postDigest !== preDigest) {
1004
+ return rejected(verifierId, runnerRef, [`artifact changed during verification (pre: ${preDigest}, post: ${postDigest})`, ...allDegraded], 'comparing pre- and post-check artifact digests');
1005
+ }
1006
+
1007
+ const evidence = outcomes.map(outcome => ({
1008
+ ref: outcome.id,
1009
+ digest: digestOf(`${outcome.stdout ?? ''}\u0000${outcome.stderr ?? ''}`),
1010
+ }));
1011
+ return {
1012
+ status: 'accepted', verifierId, runnerRef, artifactDigest: postDigest, treeDigest: postTreeDigest, evidence,
1013
+ findings: findings.length > 0 ? [...findings, ...allDegraded] : ['no protected checks were supplied; artifact path/escape checks passed', ...allDegraded],
1014
+ controlledContext: 'conductor-controlled check environment, outside worker sandbox',
1015
+ isolation: isolationSummary,
1016
+ };
1017
+ }
1018
+
1019
+ function rejected(verifierId, runnerRef, findings, controlledContext) {
1020
+ return { status: 'rejected', verifierId, runnerRef, artifactDigest: null, evidence: [], findings, controlledContext, isolation: { mode: 'n/a', degraded: [] } };
1021
+ }