@bridge_gpt/mcp-server 0.2.71 → 0.2.72

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 (116) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +19 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +4 -4
  5. package/build/bridge-permissions.js +4 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/claude-review-workflow.js +1 -1
  9. package/build/cli-help.js +6 -0
  10. package/build/codex-auto-recovery.js +126 -0
  11. package/build/codex-skill-adapter.js +2 -0
  12. package/build/commands.generated.js +5 -5
  13. package/build/conductor/bridge-api-client.js +518 -23
  14. package/build/conductor/doctor.js +84 -10
  15. package/build/conductor/epic-implementer-cli.js +51 -2
  16. package/build/conductor/gate-discovery.js +136 -10
  17. package/build/conductor/gate-settings-review.js +305 -5
  18. package/build/conductor/git-hooks-uninstall.js +112 -0
  19. package/build/conductor/git-hooks.js +81 -15
  20. package/build/conductor/guided-repair.js +10 -1
  21. package/build/conductor/install-doctor.js +2 -4
  22. package/build/conductor/launch-plan.js +42 -2
  23. package/build/conductor/local-merge.js +12 -1
  24. package/build/conductor/merge-execution-contract.js +1 -1
  25. package/build/conductor/merged-child-check.js +2 -1
  26. package/build/conductor/prerequisite-inputs.js +379 -0
  27. package/build/conductor/readiness-assessment.js +78 -0
  28. package/build/conductor/readiness-cli.js +10 -0
  29. package/build/conductor/readiness-prerequisites.js +53 -0
  30. package/build/conductor/readiness-sections.js +21 -8
  31. package/build/conductor/readiness.js +20 -2
  32. package/build/conductor/recovery-cli.js +223 -13
  33. package/build/conductor/recovery-operations.js +34 -4
  34. package/build/conductor/repair-contract.js +33 -0
  35. package/build/conductor/tools.js +34 -3
  36. package/build/conductor/wait-run-attention.js +115 -0
  37. package/build/conductor/wait-run-cli.js +96 -3
  38. package/build/conductor/worker-database-doctor-inspector.js +1 -0
  39. package/build/credential-store.js +25 -20
  40. package/build/dependency-install-declarations.js +157 -0
  41. package/build/docs.generated.js +4 -4
  42. package/build/doctor.js +37 -5
  43. package/build/drive-epic-help.js +2 -2
  44. package/build/drive-epic.js +52 -11
  45. package/build/epic-implementer-bin.js +118 -43
  46. package/build/epic-launch-profile.js +1 -1
  47. package/build/executor/cli.js +2 -0
  48. package/build/executor/completion-contract.js +16 -0
  49. package/build/executor/credentials.js +1 -1
  50. package/build/executor/delivery-observations.js +113 -0
  51. package/build/executor/delivery-outcome.js +30 -0
  52. package/build/executor/dependency-refresh-runner.js +132 -0
  53. package/build/executor/dependency-refresh.js +530 -0
  54. package/build/executor/deps.js +4 -0
  55. package/build/executor/env.js +67 -2
  56. package/build/executor/harness-coverage.js +19 -0
  57. package/build/executor/http-client.js +35 -1
  58. package/build/executor/index.js +2 -1
  59. package/build/executor/install-preflight.js +1 -1
  60. package/build/executor/job-runner.js +246 -28
  61. package/build/executor/likely-tests.js +94 -97
  62. package/build/executor/prompt-spec.js +13 -3
  63. package/build/executor/required-verification.js +28 -0
  64. package/build/executor/required-work-diagnostics.js +30 -0
  65. package/build/executor/required-work-ledger.js +19 -1
  66. package/build/executor/results.js +42 -0
  67. package/build/executor/service-discovery.js +42 -0
  68. package/build/executor/service-lifecycle.js +109 -2
  69. package/build/executor/service-uninstall.js +205 -0
  70. package/build/executor/service-unit.js +5 -3
  71. package/build/executor/test-clock.js +3 -0
  72. package/build/executor/verification-hints.js +179 -0
  73. package/build/executor/worker-command.js +54 -2
  74. package/build/executor/worker-database.js +271 -31
  75. package/build/executor/worker-finalization.js +65 -10
  76. package/build/executor/worker-guard-hook.js +10 -2
  77. package/build/executor/worker-verification-guidance.js +37 -2
  78. package/build/executor/worktree-inspection.js +42 -0
  79. package/build/github-sign-in.js +1 -1
  80. package/build/index.js +679 -278
  81. package/build/init.js +3 -3
  82. package/build/install-bridge-conductor-gate.js +236 -42
  83. package/build/install-bridge-conductor-setup.js +115 -26
  84. package/build/install-bridge-conductor.js +448 -350
  85. package/build/install-bridge.js +418 -123
  86. package/build/install-maintenance.js +104 -0
  87. package/build/install-reexec.js +1 -1
  88. package/build/local-cleanup.js +59 -0
  89. package/build/mcp-install-state.js +68 -2
  90. package/build/merge-workflow-install.js +2 -2
  91. package/build/package-script-semantics.js +10 -0
  92. package/build/pipeline-utils.js +1 -1
  93. package/build/pipelines.generated.js +5 -5
  94. package/build/plan-execution-ledger.js +148 -2
  95. package/build/plane/plane-freshness.js +6 -7
  96. package/build/plane/terminal-run-cleanup.js +5 -1
  97. package/build/plane/terminal-run-status.js +4 -0
  98. package/build/printed-remedy-commands.js +24 -4
  99. package/build/readiness-check.js +1 -78
  100. package/build/readiness-prerequisites.generated.js +199 -0
  101. package/build/readme.generated.js +1 -1
  102. package/build/repository-toolchains.js +50 -8
  103. package/build/setup-change-policy.js +32 -0
  104. package/build/setup-epic.js +2 -2
  105. package/build/setup-question.js +62 -0
  106. package/build/start-tickets.js +4 -0
  107. package/build/test-command-detection.js +32 -88
  108. package/build/test-support/notes-fs.js +40 -0
  109. package/build/ticket-delivery-enrollment.js +21 -8
  110. package/build/ticket-delivery-run-scope.js +128 -0
  111. package/build/version.generated.js +3 -3
  112. package/build/worker-guard-hook-bin.js +2 -2
  113. package/build/worktrees.js +105 -0
  114. package/docs/EPIC-IMPLEMENTER.md +5 -0
  115. package/docs/epic-implementer/getting-started.md +40 -15
  116. package/package.json +1 -1
@@ -0,0 +1,530 @@
1
+ /**
2
+ * BAPI-1551 — the executor's fail-open dependency refresh.
3
+ *
4
+ * Before a worker job spawns, each owner-confirmed `dependency_install` entry is
5
+ * checked: when the SHA-256 over the entry's canonical `{cwd, argv, lockfiles}`
6
+ * and its lockfiles' bytes differs from the marker an earlier job wrote, the
7
+ * declared argv runs in `<worktree>/<cwd>`. Every failure is fail-open: the
8
+ * worker still spawns, and the prompt's LOCAL ENVIRONMENT LIMITS block names the
9
+ * entry whose dependencies may be stale. Only the existing interruptions (lease
10
+ * loss, server stop, job timeout, executor shutdown) end a job here, and the
11
+ * caller reports them through their existing outcomes.
12
+ *
13
+ * Where it runs, and why it is safe:
14
+ *
15
+ * - Only inside the job's own worktree. The real worktree path must differ from
16
+ * the real main checkout (`deps.cwd`); otherwise every entry is `unreadable`.
17
+ * The `cwd` and each lockfile are resolved through a contained no-follow walk,
18
+ * so a symlink or an out-of-tree path is refused, never followed.
19
+ * - Two workers never share a worktree: the worktree lock (`worktree-lock.ts`)
20
+ * refuses a second job in a locked tree.
21
+ * - The marker lives in the worktree's PRIVATE git directory
22
+ * (`git rev-parse --absolute-git-dir`, never `--git-common-dir`):
23
+ * `<git-dir>/bridge/dependency-refresh/<sha256(cwd, sorted lockfiles)>.json`,
24
+ * holding `{version: 1, hash}`. Never in the working tree: Worktrunk's
25
+ * `copy-ignored` copies ignored working-tree files, so a marker there could be
26
+ * copied in from the main checkout beside a stale `node_modules` and wrongly
27
+ * skip the install. An unresolvable git directory installs without a marker.
28
+ *
29
+ * Worktrunk facts (wt v0.48.0, `wt step copy-ignored --help`, confirmed locally):
30
+ *
31
+ * - `copy-ignored` uses a copy-on-write reflink where the filesystem supports it
32
+ * and a plain per-file copy otherwise. It never hard-links, so rewriting a
33
+ * dependency file in one worktree never changes the main checkout. The
34
+ * shared-inode guard below is a defensive check for other tooling, not for
35
+ * Worktrunk.
36
+ * - It SKIPS destination files that already exist (unless `--force`), so a late
37
+ * copy cannot overwrite what an install wrote, but it can still add files into
38
+ * a directory an install just recreated.
39
+ * - It publishes no completion signal. `post-start` hooks run in the BACKGROUND
40
+ * after `wt switch` returns (see `env-file-guard.ts`). A live probe showed the
41
+ * pipeline runs as a `wt hook run-pipeline` process whose cwd is the real path
42
+ * of the new worktree. So the refresh first waits, within its own budget, until
43
+ * no such process (or a `step copy-ignored` one) has its cwd in the worktree.
44
+ * When that cannot be established — an unsupported platform, a probe error, or
45
+ * the budget running out — no entry installs or writes a marker; each gets the
46
+ * `copy_uncertain` stale line instead.
47
+ *
48
+ * Trust: containment protects the DECLARED PATHS only. The install argv and any
49
+ * lifecycle scripts it runs are administrator-confirmed repository code. They run
50
+ * with the sentinel worker environment (no credentials), but they are not
51
+ * sandboxed.
52
+ *
53
+ * Logging: one line per entry with the job id, the validated `cwd`, a closed
54
+ * outcome, and an optional closed marker status. Never the argv, the install
55
+ * output, an environment value, or the hash.
56
+ */
57
+ import { createHash } from "node:crypto";
58
+ import { execFile } from "node:child_process";
59
+ import { constants } from "node:fs";
60
+ import { lstat, open, readdir, readFile, readlink, realpath, rename, unlink, mkdir, writeFile } from "node:fs/promises";
61
+ import path from "node:path";
62
+ import { dependencyInstallEntryIdentity, } from "../dependency-install-declarations.js";
63
+ import { runDependencyInstall } from "./dependency-refresh-runner.js";
64
+ /** The cap on one job's whole refresh (all entries, copy wait, hashing, installs). */
65
+ export const DEPENDENCY_REFRESH_MAX_MS = 600_000;
66
+ /** Job time kept back for the worker itself; below it the refresh is skipped. */
67
+ export const DEPENDENCY_REFRESH_JOB_MARGIN_MS = 30_000;
68
+ /** How often the copy-readiness probe re-checks a running background copy. */
69
+ export const DEPENDENCY_REFRESH_COPY_POLL_MS = 1_000;
70
+ /** Files sampled by the shared-inode guard. */
71
+ export const DEPENDENCY_REFRESH_INODE_SAMPLE = 64;
72
+ const GIT_PROBE_TIMEOUT_MS = 10_000;
73
+ const PROBE_TIMEOUT_MS = 10_000;
74
+ const PROBE_MAX_BUFFER = 4 * 1024 * 1024;
75
+ const HASH_CHUNK_BYTES = 64 * 1024;
76
+ const MARKER_VERSION = 1;
77
+ const MARKER_MAX_BYTES = 4 * 1024;
78
+ const STALE_FOR = {
79
+ failed: "install_failed",
80
+ timeout: "install_failed",
81
+ unreadable: "lockfile_unreadable",
82
+ no_budget: "no_budget",
83
+ copy_uncertain: "copy_uncertain",
84
+ shared_inode: "shared_inode",
85
+ marker_uncleared: "marker_uncleared",
86
+ };
87
+ /** The refresh budget for `remainingMs` of job time: never above the cap, `<= 0` means none. */
88
+ export function dependencyRefreshBudgetMs(remainingMs) {
89
+ return Math.min(DEPENDENCY_REFRESH_MAX_MS, remainingMs - DEPENDENCY_REFRESH_JOB_MARGIN_MS);
90
+ }
91
+ // ---------------------------------------------------------------------------
92
+ // Bounded, shell-free probes
93
+ // ---------------------------------------------------------------------------
94
+ function boundedExec(file, args, cwd, timeoutMs) {
95
+ return new Promise((resolve, reject) => {
96
+ execFile(file, args, {
97
+ cwd, shell: false, timeout: Math.max(1, timeoutMs), maxBuffer: PROBE_MAX_BUFFER, encoding: "utf8",
98
+ }, (error, stdout) => {
99
+ if (error)
100
+ reject(new Error("probe_failed"));
101
+ else
102
+ resolve(stdout);
103
+ });
104
+ });
105
+ }
106
+ /** The real private git-directory resolver. `null` when it cannot be resolved. */
107
+ export const resolvePrivateGitDir = async (worktreeRealPath, timeoutMs) => {
108
+ try {
109
+ const out = (await boundedExec("git", ["rev-parse", "--absolute-git-dir"], worktreeRealPath, Math.min(GIT_PROBE_TIMEOUT_MS, timeoutMs))).trim();
110
+ if (!out || !path.isAbsolute(out) || /[\r\n\0]/.test(out))
111
+ return null;
112
+ return out;
113
+ }
114
+ catch {
115
+ return null;
116
+ }
117
+ };
118
+ const BACKGROUND_COPY_COMMANDS = ["hook run-pipeline", "step copy-ignored"];
119
+ /**
120
+ * macOS system tools by absolute path: an executor's `PATH` need not include
121
+ * `/usr/sbin` (where `lsof` lives), and a bare name would also let a `PATH`
122
+ * entry shadow the system tool.
123
+ */
124
+ const DARWIN_PS = "/bin/ps";
125
+ const DARWIN_LSOF = "/usr/sbin/lsof";
126
+ function isWithin(root, candidate) {
127
+ const relative = path.relative(root, candidate);
128
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
129
+ }
130
+ /**
131
+ * The real copy-readiness probe: is a Worktrunk background pipeline (or a
132
+ * `copy-ignored` step) running with its cwd inside the worktree? macOS reads
133
+ * process cwds with `lsof`, Linux with `/proc/<pid>/cwd`. Anything else, or any
134
+ * error, is `unknown`.
135
+ */
136
+ export function createCopyReadinessProbe(platform = process.platform) {
137
+ return async (worktreeRealPath) => {
138
+ try {
139
+ if (platform === "darwin") {
140
+ const listing = await boundedExec(DARWIN_PS, ["-axo", "pid=,command="], undefined, PROBE_TIMEOUT_MS);
141
+ const pids = [];
142
+ for (const line of listing.split("\n")) {
143
+ const match = /^\s*(\d+)\s+(.*)$/.exec(line);
144
+ if (!match)
145
+ continue;
146
+ const pid = Number(match[1]);
147
+ if (pid === process.pid)
148
+ continue;
149
+ if (BACKGROUND_COPY_COMMANDS.some((c) => match[2].includes(c)))
150
+ pids.push(pid);
151
+ }
152
+ for (const pid of pids) {
153
+ let out;
154
+ try {
155
+ out = await boundedExec(DARWIN_LSOF, ["-a", "-p", String(pid), "-d", "cwd", "-Fn"], undefined, PROBE_TIMEOUT_MS);
156
+ }
157
+ catch {
158
+ // `lsof` exits nonzero when the process already exited: re-check it is gone.
159
+ const still = await boundedExec(DARWIN_PS, ["-o", "pid=", "-p", String(pid)], undefined, PROBE_TIMEOUT_MS)
160
+ .then((t) => t.trim().length > 0, () => false);
161
+ if (still)
162
+ return "unknown";
163
+ continue;
164
+ }
165
+ const cwdLine = out.split("\n").find((l) => l.startsWith("n"));
166
+ if (cwdLine === undefined)
167
+ return "unknown";
168
+ if (isWithin(worktreeRealPath, cwdLine.slice(1)))
169
+ return "running";
170
+ }
171
+ return "idle";
172
+ }
173
+ if (platform === "linux") {
174
+ const entries = await readdir("/proc");
175
+ for (const name of entries) {
176
+ if (!/^\d+$/.test(name) || Number(name) === process.pid)
177
+ continue;
178
+ let command;
179
+ try {
180
+ command = (await readFile(`/proc/${name}/cmdline`, "utf8")).split("\0").join(" ");
181
+ }
182
+ catch {
183
+ continue;
184
+ }
185
+ if (!BACKGROUND_COPY_COMMANDS.some((c) => command.includes(c)))
186
+ continue;
187
+ let cwd;
188
+ try {
189
+ cwd = await readlink(`/proc/${name}/cwd`);
190
+ }
191
+ catch (error) {
192
+ if (error.code === "ENOENT")
193
+ continue;
194
+ return "unknown";
195
+ }
196
+ if (isWithin(worktreeRealPath, cwd))
197
+ return "running";
198
+ }
199
+ return "idle";
200
+ }
201
+ return "unknown";
202
+ }
203
+ catch {
204
+ return "unknown";
205
+ }
206
+ };
207
+ }
208
+ /**
209
+ * The real shared-inode guard: sample up to {@link DEPENDENCY_REFRESH_INODE_SAMPLE}
210
+ * files under the cwd's git-ignored entries (no symlink followed) and report
211
+ * `true` when one has more than one link AND the main checkout's file at the same
212
+ * relative path is the same inode. Any sampling error skips the guard.
213
+ */
214
+ export const checkSharedInodes = async ({ cwdRealPath, worktreeRealPath, mainCheckoutRealPath }) => {
215
+ let listing;
216
+ try {
217
+ listing = await boundedExec("git", ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"], cwdRealPath, GIT_PROBE_TIMEOUT_MS);
218
+ }
219
+ catch {
220
+ return false;
221
+ }
222
+ const queue = listing.split("\0").filter(Boolean)
223
+ .filter((p) => !path.isAbsolute(p) && !p.split("/").includes(".."))
224
+ .map((p) => path.join(cwdRealPath, p));
225
+ let sampled = 0;
226
+ while (queue.length > 0 && sampled < DEPENDENCY_REFRESH_INODE_SAMPLE) {
227
+ const candidate = queue.shift();
228
+ try {
229
+ const info = await lstat(candidate);
230
+ if (info.isSymbolicLink())
231
+ continue;
232
+ if (info.isDirectory()) {
233
+ const children = (await readdir(candidate)).sort().slice(0, DEPENDENCY_REFRESH_INODE_SAMPLE);
234
+ for (const child of children)
235
+ queue.push(path.join(candidate, child));
236
+ continue;
237
+ }
238
+ if (!info.isFile())
239
+ continue;
240
+ sampled += 1;
241
+ if (info.nlink <= 1)
242
+ continue;
243
+ const relative = path.relative(worktreeRealPath, candidate);
244
+ if (relative.startsWith("..") || path.isAbsolute(relative))
245
+ continue;
246
+ const twin = await lstat(path.join(mainCheckoutRealPath, relative)).catch(() => null);
247
+ if (twin && !twin.isSymbolicLink() && twin.dev === info.dev && twin.ino === info.ino)
248
+ return true;
249
+ }
250
+ catch {
251
+ continue;
252
+ }
253
+ }
254
+ return false;
255
+ };
256
+ // ---------------------------------------------------------------------------
257
+ // Contained reads and hashing
258
+ // ---------------------------------------------------------------------------
259
+ /** Resolve `relative` under `root` with no symlink anywhere; return the absolute path. */
260
+ async function containedPath(root, relative, want) {
261
+ if (relative === ".") {
262
+ if (want !== "directory")
263
+ throw new Error("kind");
264
+ return root;
265
+ }
266
+ let current = root;
267
+ const parts = relative.split("/");
268
+ for (let index = 0; index < parts.length; index++) {
269
+ const part = parts[index];
270
+ if (part === "" || part === "." || part === "..")
271
+ throw new Error("invalid_path");
272
+ current = path.join(current, part);
273
+ const info = await lstat(current);
274
+ if (info.isSymbolicLink())
275
+ throw new Error("symlink");
276
+ const last = index === parts.length - 1;
277
+ if (!last && !info.isDirectory())
278
+ throw new Error("ancestor");
279
+ if (last && (want === "directory" ? !info.isDirectory() : !info.isFile()))
280
+ throw new Error("kind");
281
+ }
282
+ if (!isWithin(root, current))
283
+ throw new Error("outside");
284
+ return current;
285
+ }
286
+ class BudgetExhausted extends Error {
287
+ }
288
+ function frame(hash, bytes) {
289
+ const length = Buffer.alloc(8);
290
+ length.writeBigUInt64BE(BigInt(bytes.length));
291
+ hash.update(length);
292
+ hash.update(bytes);
293
+ }
294
+ async function hashEntry(root, entry, deadline, now) {
295
+ const hash = createHash("sha256");
296
+ frame(hash, Buffer.from(JSON.stringify({ cwd: entry.cwd, argv: entry.argv, lockfiles: entry.lockfiles }), "utf8"));
297
+ for (const lockfile of entry.lockfiles) {
298
+ const absolute = await containedPath(root, lockfile, "file");
299
+ const handle = await open(absolute, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
300
+ try {
301
+ const info = await handle.stat();
302
+ if (!info.isFile())
303
+ throw new Error("not_regular");
304
+ frame(hash, Buffer.from(lockfile, "utf8"));
305
+ const content = createHash("sha256");
306
+ const buffer = Buffer.alloc(HASH_CHUNK_BYTES);
307
+ let total = 0;
308
+ for (;;) {
309
+ if (now() >= deadline)
310
+ throw new BudgetExhausted();
311
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
312
+ if (bytesRead === 0)
313
+ break;
314
+ content.update(buffer.subarray(0, bytesRead));
315
+ total += bytesRead;
316
+ }
317
+ frame(hash, Buffer.from(`${total}:${content.digest("hex")}`, "utf8"));
318
+ }
319
+ finally {
320
+ await handle.close();
321
+ }
322
+ }
323
+ return hash.digest("hex");
324
+ }
325
+ // ---------------------------------------------------------------------------
326
+ // Markers
327
+ // ---------------------------------------------------------------------------
328
+ function markerPath(gitDir, entry) {
329
+ const name = createHash("sha256").update(dependencyInstallEntryIdentity(entry), "utf8").digest("hex");
330
+ return path.join(gitDir, "bridge", "dependency-refresh", `${name}.json`);
331
+ }
332
+ async function readMarker(file) {
333
+ let info;
334
+ try {
335
+ info = await lstat(file);
336
+ }
337
+ catch (error) {
338
+ // ENOTDIR: an ancestor is not a directory, so no marker can exist there.
339
+ return isAbsentPathError(error) ? { kind: "absent" } : { kind: "failed" };
340
+ }
341
+ if (!info.isFile() || info.size > MARKER_MAX_BYTES)
342
+ return { kind: "malformed" };
343
+ try {
344
+ const parsed = JSON.parse(await readFile(file, "utf8"));
345
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
346
+ const doc = parsed;
347
+ if (doc.version === MARKER_VERSION && typeof doc.hash === "string" && /^[0-9a-f]{64}$/.test(doc.hash)) {
348
+ return { kind: "hash", hash: doc.hash };
349
+ }
350
+ }
351
+ return { kind: "malformed" };
352
+ }
353
+ catch (error) {
354
+ return error instanceof SyntaxError ? { kind: "malformed" } : { kind: "failed" };
355
+ }
356
+ }
357
+ async function deleteMarker(file) {
358
+ try {
359
+ await unlink(file);
360
+ return true;
361
+ }
362
+ catch (error) {
363
+ return isAbsentPathError(error);
364
+ }
365
+ }
366
+ function isAbsentPathError(error) {
367
+ const code = error.code;
368
+ return code === "ENOENT" || code === "ENOTDIR";
369
+ }
370
+ async function writeMarker(file, hash) {
371
+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
372
+ try {
373
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
374
+ await writeFile(temporary, JSON.stringify({ version: MARKER_VERSION, hash }), { encoding: "utf8", mode: 0o600, flag: "wx" });
375
+ await rename(temporary, file);
376
+ return true;
377
+ }
378
+ catch {
379
+ await unlink(temporary).catch(() => undefined);
380
+ return false;
381
+ }
382
+ }
383
+ // ---------------------------------------------------------------------------
384
+ // The refresh
385
+ // ---------------------------------------------------------------------------
386
+ /**
387
+ * Refresh every admitted entry, in declaration order, within one budget.
388
+ * Never throws. A caller signal stops it (`cancelled: true`), terminating any
389
+ * running install first.
390
+ */
391
+ export async function refreshDeclaredDependencies(options) {
392
+ const results = [];
393
+ const log = (message) => { try {
394
+ options.log(message);
395
+ }
396
+ catch { /* sink */ } };
397
+ const settle = (entry, outcome, markerStatus) => {
398
+ results.push({ cwd: entry.cwd, outcome, ...(markerStatus ? { markerStatus } : {}) });
399
+ log(`executor: dependency refresh job ${options.jobId} cwd ${entry.cwd}: ${outcome}` +
400
+ (markerStatus ? ` (${markerStatus})` : ""));
401
+ };
402
+ const finish = (cancelled) => ({
403
+ entries: results,
404
+ stale: results.flatMap((r) => {
405
+ const reason = STALE_FOR[r.outcome];
406
+ return reason ? [{ cwd: r.cwd, reason }] : [];
407
+ }),
408
+ cancelled,
409
+ });
410
+ const settleRest = (from, outcome) => {
411
+ for (const entry of options.entries.slice(from))
412
+ settle(entry, outcome);
413
+ };
414
+ const cancelled = () => options.signal?.aborted === true;
415
+ try {
416
+ const now = options.now;
417
+ const budget = dependencyRefreshBudgetMs(options.remainingMs);
418
+ if (budget <= 0) {
419
+ settleRest(0, "no_budget");
420
+ return finish(false);
421
+ }
422
+ const deadline = now() + budget;
423
+ // Isolation: never the main checkout, and both real paths must resolve.
424
+ let worktreeReal;
425
+ let mainReal;
426
+ try {
427
+ worktreeReal = await realpath(options.worktreePath);
428
+ mainReal = await realpath(options.mainCheckoutPath);
429
+ }
430
+ catch {
431
+ settleRest(0, "unreadable");
432
+ return finish(false);
433
+ }
434
+ if (worktreeReal === mainReal || isWithin(worktreeReal, mainReal)) {
435
+ settleRest(0, "unreadable");
436
+ return finish(false);
437
+ }
438
+ // Wait out a background Worktrunk copy, within the same budget.
439
+ const probe = options.copyReadiness ?? createCopyReadinessProbe(options.platform);
440
+ for (;;) {
441
+ if (cancelled())
442
+ return finish(true);
443
+ const state = await probe(worktreeReal);
444
+ if (state === "idle")
445
+ break;
446
+ if (state === "unknown" || now() + DEPENDENCY_REFRESH_COPY_POLL_MS >= deadline) {
447
+ settleRest(0, "copy_uncertain");
448
+ return finish(false);
449
+ }
450
+ await options.sleep(DEPENDENCY_REFRESH_COPY_POLL_MS);
451
+ }
452
+ const gitDir = await (options.resolveGitDir ?? resolvePrivateGitDir)(worktreeReal, Math.max(1, deadline - now()));
453
+ const runInstall = options.runInstall ?? runDependencyInstall;
454
+ const sharedInode = options.sharedInode ?? checkSharedInodes;
455
+ for (let index = 0; index < options.entries.length; index++) {
456
+ const entry = options.entries[index];
457
+ if (cancelled())
458
+ return finish(true);
459
+ if (now() >= deadline) {
460
+ settleRest(index, "no_budget");
461
+ break;
462
+ }
463
+ let cwdReal;
464
+ let hash;
465
+ try {
466
+ cwdReal = await containedPath(worktreeReal, entry.cwd, "directory");
467
+ hash = await hashEntry(worktreeReal, entry, deadline, now);
468
+ }
469
+ catch (error) {
470
+ settle(entry, error instanceof BudgetExhausted ? "no_budget" : "unreadable");
471
+ continue;
472
+ }
473
+ if (await sharedInode({ cwdRealPath: cwdReal, worktreeRealPath: worktreeReal, mainCheckoutRealPath: mainReal })
474
+ .catch(() => false)) {
475
+ settle(entry, "shared_inode");
476
+ continue;
477
+ }
478
+ let marker = null;
479
+ let markerStatus = "marker_unavailable";
480
+ if (gitDir !== null) {
481
+ marker = markerPath(gitDir, entry);
482
+ const read = await readMarker(marker);
483
+ if (read.kind === "hash" && read.hash === hash) {
484
+ settle(entry, "unchanged");
485
+ continue;
486
+ }
487
+ markerStatus = read.kind === "absent" ? "marker_missing"
488
+ : read.kind === "hash" ? "marker_mismatch"
489
+ : read.kind === "malformed" ? "marker_malformed" : "marker_read_failed";
490
+ // A stale marker must be gone BEFORE anything can change the tree.
491
+ if (read.kind !== "absent" && !(await deleteMarker(marker))) {
492
+ settle(entry, "marker_uncleared", "marker_delete_failed");
493
+ continue;
494
+ }
495
+ }
496
+ const timeoutMs = deadline - now();
497
+ if (timeoutMs <= 0) {
498
+ settleRest(index, "no_budget");
499
+ break;
500
+ }
501
+ const run = await runInstall({
502
+ argv: entry.argv, cwd: cwdReal, env: options.env, timeoutMs,
503
+ ...(options.signal ? { signal: options.signal } : {}),
504
+ }).catch(() => ({ outcome: "spawn_failed", outputTail: "" }));
505
+ // The output tail is deliberately dropped: it may echo argv, paths, or tokens.
506
+ if (run.outcome === "cancelled")
507
+ return finish(true);
508
+ if (run.outcome === "timeout") {
509
+ settle(entry, "timeout", markerStatus);
510
+ continue;
511
+ }
512
+ if (run.outcome !== "exit_zero") {
513
+ settle(entry, "failed", markerStatus);
514
+ continue;
515
+ }
516
+ if (marker !== null) {
517
+ settle(entry, "installed", (await writeMarker(marker, hash)) ? "marker_written" : "marker_write_failed");
518
+ }
519
+ else {
520
+ settle(entry, "installed", markerStatus);
521
+ }
522
+ }
523
+ return finish(false);
524
+ }
525
+ catch {
526
+ // Unreachable by construction; fail open for anything not yet settled.
527
+ settleRest(results.length, "unreadable");
528
+ return finish(cancelled());
529
+ }
530
+ }
@@ -14,6 +14,8 @@ import { open, readFile, writeFile, appendFile, mkdir, mkdtemp, chmod, rm, renam
14
14
  import os from "node:os";
15
15
  import { promisify } from "node:util";
16
16
  import { resolveMcpShimInvocationForRuntime } from "../mcp-server-invocation.js";
17
+ import { runDependencyInstall } from "./dependency-refresh-runner.js";
18
+ import { readVerificationHints } from "./verification-hints.js";
17
19
  const execFileAsync = promisify(execFile);
18
20
  /** Bounded subprocess output buffer (bytes). */
19
21
  const MAX_COMMAND_BUFFER = 10 * 1024 * 1024;
@@ -139,6 +141,8 @@ export function createDefaultExecutorDeps() {
139
141
  },
140
142
  };
141
143
  },
144
+ runDependencyInstall,
145
+ readVerificationHints,
142
146
  recordPackagedAssets: recordProvisionedAssets,
143
147
  readFile: (filePath) => readFile(filePath, "utf-8"),
144
148
  writeFile: (filePath, data) => writeFile(filePath, data, "utf-8"),
@@ -75,6 +75,7 @@ import { INDEX_SCOPE_ENV_VAR, validateOptionalIndexScope } from "../index-scope-
75
75
  import { delimiter as PLATFORM_PATH_DELIMITER } from "node:path";
76
76
  import { EPIC_IMPLEMENTER_ENV_PREFIX, EPIC_IMPLEMENTER_NODE_PATH_ENV, LEGACY_EPIC_IMPLEMENTER_ENV_PREFIX, LEGACY_EPIC_IMPLEMENTER_NODE_PATH_ENV, } from "../epic-implementer-env.js";
77
77
  import { buildWorkerDatabaseEnv } from "./worker-database-target.js";
78
+ import { admitDependencyInstallDeclarations, normalizeCiDatabase, } from "../dependency-install-declarations.js";
78
79
  /** Entry rules for a declared worker variable (BAPI-1520), rechecked by the executor. */
79
80
  const MAX_WORKER_ENV_ENTRIES = 32;
80
81
  const MAX_WORKER_ENV_VALUE_BYTES = 1024;
@@ -183,7 +184,7 @@ export const WORKER_SENTINEL_DATABASE_ENV_KEYS = [
183
184
  "PGDATABASE",
184
185
  ];
185
186
  /**
186
- * CI's non-secret test values, injected into EVERY worker environment (BAPI-1479).
187
+ * Four non-secret BGPT_* compatibility values for legacy payloads without worker_env.
187
188
  *
188
189
  * These are the exact literals the Python lane of
189
190
  * `.github/workflows/epic-implementer-ci.yml` sets. They are throwaway CI values,
@@ -203,7 +204,6 @@ export const CI_WORKER_ENV_CONSTANTS = Object.freeze({
203
204
  BGPT_DEMO_SECRET: "test-demo-secret",
204
205
  BGPT_SESSION_SECRET: "test-session-secret",
205
206
  BGPT_INVITE_SECRET: "test-invite-secret",
206
- ENVIRONMENT: "LOCAL",
207
207
  });
208
208
  /**
209
209
  * BAPI-1521 — the ONE reserved-name policy for repository-declared worker
@@ -315,6 +315,66 @@ export function validateWorkerEnvDeclarations(raw, taken = new Set()) {
315
315
  }
316
316
  return accepted;
317
317
  }
318
+ /**
319
+ * BAPI-1551 — the environment a declared dependency install runs with: the
320
+ * sentinel worker environment plus the payload's declared worker variables. It
321
+ * carries no credential and never the operator's database. Built here so the
322
+ * job runner never constructs a worker environment itself.
323
+ */
324
+ export function buildDependencyInstallEnv(parentEnv, payload) {
325
+ return buildExecutorBaseWorkerEnv(parentEnv, { ...payloadWorkerEnvOption(payload), legacyNotice: false });
326
+ }
327
+ /**
328
+ * BAPI-1551 — the `{ dependencyInstall }` option a job payload implies: present
329
+ * exactly when the payload OWNS a `dependency_install` key. Never reads the value.
330
+ */
331
+ export function payloadDependencyInstallOption(payload) {
332
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload))
333
+ return {};
334
+ if (!Object.prototype.hasOwnProperty.call(payload, "dependency_install"))
335
+ return {};
336
+ return { dependencyInstall: payload.dependency_install };
337
+ }
338
+ /** BAPI-1551 — the `{ ciDatabase }` option, present exactly when the payload owns `ci_database`. */
339
+ export function payloadCiDatabaseOption(payload) {
340
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload))
341
+ return {};
342
+ if (!Object.prototype.hasOwnProperty.call(payload, "ci_database"))
343
+ return {};
344
+ return { ciDatabase: payload.ci_database };
345
+ }
346
+ /** BAPI-1551 — the payload's `ci_database`, with anything other than the three values (or absence) read as `unknown`. */
347
+ export function payloadCiDatabase(payload) {
348
+ return normalizeCiDatabase(payloadCiDatabaseOption(payload).ciDatabase);
349
+ }
350
+ /**
351
+ * BAPI-1551 — validate a payload `dependency_install` declaration against the
352
+ * server's entry rules and return the entries safe to run. Never throws: an
353
+ * invalid entry is skipped with a closed reason, logged with its `cwd` only when
354
+ * that `cwd` passed the path rules, and never with an argv item.
355
+ */
356
+ export function validateDependencyInstallDeclarations(raw, errorLog = (message) => console.error(message)) {
357
+ let admitted;
358
+ try {
359
+ admitted = admitDependencyInstallDeclarations(raw);
360
+ }
361
+ catch {
362
+ admitted = { entries: [], skipped: [], notAList: true };
363
+ }
364
+ const log = (message) => { try {
365
+ errorLog(message);
366
+ }
367
+ catch { /* sink */ } };
368
+ if (admitted.notAList) {
369
+ log("executor: dependency_install is present but is not a list; running no dependency refresh");
370
+ return [];
371
+ }
372
+ for (const skip of admitted.skipped) {
373
+ const where = skip.cwd !== undefined ? ` for ${skip.cwd}` : "";
374
+ log(`executor: skipped declared dependency refresh${where}: ${skip.reason}`);
375
+ }
376
+ return admitted.entries;
377
+ }
318
378
  /** Substrings that mark a key as secret-bearing (case-insensitive). */
319
379
  const SECRET_NAME_FRAGMENTS = ["TOKEN", "SECRET", "PASSWORD", "API_KEY"];
320
380
  /** True when `name` looks secret, so a declaration of it needs `committed_literal: true`. */
@@ -601,6 +661,11 @@ export function buildExecutorBaseWorkerEnv(parentEnv, options = {}) {
601
661
  // `buildClaudeWorkerEnv`. Keeping the base free of every credential is what
602
662
  // makes "which secrets can reach a worker?" answerable per adapter instead of
603
663
  // per call site.
664
+ // Loopback worker PostgreSQL has SSL disabled. Apply the compatibility default
665
+ // AFTER validating declarations so ENVIRONMENT remains repository-overridable
666
+ // and an ambient host value can never choose the worker's SSL policy. Alembic
667
+ // uses this same builder, including for empty or legacy declarations.
668
+ env.ENVIRONMENT ??= "LOCAL";
604
669
  return env;
605
670
  }
606
671
  /**
@@ -0,0 +1,19 @@
1
+ /** Validate at each projection boundary; legacy/malformed evidence grants nothing. */
2
+ export function sanitizeHarnessCoverage(value, total) {
3
+ if (typeof value !== "object" || value === null)
4
+ return undefined;
5
+ const c = value;
6
+ const count = (n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
7
+ if (!count(c.total) || (total !== undefined && c.total !== total) || !count(c.ciOwned) || c.ciOwned > c.total)
8
+ return undefined;
9
+ if (c.activity === "unknown") {
10
+ return c.inUse === null && c.covered === null && c.uncovered === null
11
+ ? { total: c.total, activity: "unknown", inUse: null, ciOwned: c.ciOwned, covered: null, uncovered: null }
12
+ : undefined;
13
+ }
14
+ if (c.activity !== "known" || !count(c.inUse) || !count(c.covered) || !count(c.uncovered) ||
15
+ c.inUse > c.total || c.covered + c.uncovered !== c.total ||
16
+ c.covered < Math.max(c.inUse, c.ciOwned) || c.covered > Math.min(c.total, c.inUse + c.ciOwned))
17
+ return undefined;
18
+ return { total: c.total, activity: "known", inUse: c.inUse, ciOwned: c.ciOwned, covered: c.covered, uncovered: c.uncovered };
19
+ }