@bridge_gpt/mcp-server 0.2.70 → 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 (134) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +29 -4
  3. package/build/agent-notes.js +171 -95
  4. package/build/agent-registry.js +5 -5
  5. package/build/agents.generated.js +12 -2
  6. package/build/bounded-wait.js +9 -1
  7. package/build/bridge-permissions.js +17 -5
  8. package/build/bridge-worktree-inspection.js +237 -0
  9. package/build/check-evidence.js +6 -0
  10. package/build/claude-review-workflow.js +1 -1
  11. package/build/cli-help.js +6 -0
  12. package/build/codex-auto-recovery.js +126 -0
  13. package/build/codex-skill-adapter.js +2 -0
  14. package/build/commands.generated.js +5 -5
  15. package/build/conductor/bridge-api-client.js +776 -23
  16. package/build/conductor/command-drift-production.js +7 -2
  17. package/build/conductor/doctor.js +93 -13
  18. package/build/conductor/epic-implementer-cli.js +55 -2
  19. package/build/conductor/gate-discovery.js +659 -19
  20. package/build/conductor/gate-settings-review.js +751 -0
  21. package/build/conductor/git-hooks-uninstall.js +112 -0
  22. package/build/conductor/git-hooks.js +81 -15
  23. package/build/conductor/guided-repair.js +10 -1
  24. package/build/conductor/install-doctor.js +2 -4
  25. package/build/conductor/launch-need-probes.js +16 -11
  26. package/build/conductor/launch-plan.js +185 -0
  27. package/build/conductor/local-merge.js +12 -1
  28. package/build/conductor/merge-execution-contract.js +1 -1
  29. package/build/conductor/merged-child-check.js +2 -1
  30. package/build/conductor/precheck-timings.js +14 -0
  31. package/build/conductor/prerequisite-inputs.js +379 -0
  32. package/build/conductor/preview-observations.js +10 -0
  33. package/build/conductor/readiness-assessment.js +78 -0
  34. package/build/conductor/readiness-cli.js +10 -0
  35. package/build/conductor/readiness-prerequisites.js +53 -0
  36. package/build/conductor/readiness-sections.js +25 -9
  37. package/build/conductor/readiness.js +20 -2
  38. package/build/conductor/recovery-cli.js +281 -14
  39. package/build/conductor/recovery-operations.js +78 -5
  40. package/build/conductor/repair-contract.js +33 -0
  41. package/build/conductor/tools.js +34 -3
  42. package/build/conductor/wait-run-attention.js +115 -0
  43. package/build/conductor/wait-run-cli.js +96 -3
  44. package/build/conductor/worker-database-doctor-inspector.js +1 -0
  45. package/build/credential-store.js +25 -20
  46. package/build/dependency-install-declarations.js +157 -0
  47. package/build/docs.generated.js +4 -4
  48. package/build/doctor.js +37 -5
  49. package/build/drive-epic-help.js +2 -2
  50. package/build/drive-epic.js +240 -56
  51. package/build/epic-ci-workflow-drift.js +71 -23
  52. package/build/epic-ci-workflow-install.js +83 -26
  53. package/build/epic-ci-workflow-v1.js +132 -0
  54. package/build/epic-ci-workflow.js +174 -13
  55. package/build/epic-implementer-bin.js +119 -44
  56. package/build/epic-launch-profile.js +1 -1
  57. package/build/executor/ci-rerun-job.js +220 -14
  58. package/build/executor/cli.js +2 -0
  59. package/build/executor/completion-contract.js +16 -0
  60. package/build/executor/credentials.js +1 -1
  61. package/build/executor/delivery-observations.js +113 -0
  62. package/build/executor/delivery-outcome.js +30 -0
  63. package/build/executor/dependency-refresh-runner.js +132 -0
  64. package/build/executor/dependency-refresh.js +530 -0
  65. package/build/executor/deps.js +4 -0
  66. package/build/executor/env.js +274 -5
  67. package/build/executor/gate-qualification-job.js +20 -5
  68. package/build/executor/harness-coverage.js +19 -0
  69. package/build/executor/http-client.js +35 -1
  70. package/build/executor/index.js +2 -1
  71. package/build/executor/install-preflight.js +1 -1
  72. package/build/executor/job-runner.js +355 -36
  73. package/build/executor/likely-tests.js +100 -98
  74. package/build/executor/preflight.js +5 -0
  75. package/build/executor/process-containment.js +18 -0
  76. package/build/executor/prompt-spec.js +84 -15
  77. package/build/executor/reconcile-overlap-job.js +6 -1
  78. package/build/executor/required-verification.js +28 -0
  79. package/build/executor/required-work-diagnostics.js +30 -0
  80. package/build/executor/required-work-ledger.js +19 -1
  81. package/build/executor/results.js +42 -0
  82. package/build/executor/service-discovery.js +42 -0
  83. package/build/executor/service-lifecycle.js +109 -2
  84. package/build/executor/service-uninstall.js +205 -0
  85. package/build/executor/service-unit.js +5 -3
  86. package/build/executor/test-clock.js +3 -0
  87. package/build/executor/verification-hints.js +179 -0
  88. package/build/executor/worker-command.js +188 -1
  89. package/build/executor/worker-database.js +299 -40
  90. package/build/executor/worker-finalization.js +65 -10
  91. package/build/executor/worker-guard-hook.js +10 -2
  92. package/build/executor/worker-resources.js +12 -1
  93. package/build/executor/worker-verification-guidance.js +64 -0
  94. package/build/executor/worktree-inspection.js +42 -0
  95. package/build/github-sign-in.js +1 -1
  96. package/build/index.js +767 -310
  97. package/build/init.js +3 -3
  98. package/build/install-bridge-conductor-gate.js +416 -41
  99. package/build/install-bridge-conductor-setup.js +135 -32
  100. package/build/install-bridge-conductor.js +769 -353
  101. package/build/install-bridge.js +419 -124
  102. package/build/install-maintenance.js +104 -0
  103. package/build/install-reexec.js +1 -1
  104. package/build/local-cleanup.js +59 -0
  105. package/build/mcp-install-state.js +68 -2
  106. package/build/merge-workflow-install.js +22 -2
  107. package/build/package-script-semantics.js +10 -0
  108. package/build/pipeline-utils.js +1 -1
  109. package/build/pipelines.generated.js +6 -6
  110. package/build/plan-execution-ledger.js +171 -10
  111. package/build/plane/plane-freshness.js +12 -9
  112. package/build/plane/preflight.js +19 -0
  113. package/build/plane/terminal-run-cleanup.js +5 -1
  114. package/build/plane/terminal-run-status.js +4 -0
  115. package/build/printed-remedy-commands.js +31 -4
  116. package/build/readiness-check.js +1 -78
  117. package/build/readiness-prerequisites.generated.js +199 -0
  118. package/build/readme.generated.js +1 -1
  119. package/build/repository-toolchains.js +623 -0
  120. package/build/setup-change-policy.js +32 -0
  121. package/build/setup-epic.js +26 -9
  122. package/build/setup-question.js +62 -0
  123. package/build/start-tickets.js +4 -0
  124. package/build/test-command-detection.js +61 -80
  125. package/build/test-support/notes-fs.js +40 -0
  126. package/build/ticket-delivery-artifacts.js +7 -0
  127. package/build/ticket-delivery-enrollment.js +80 -4
  128. package/build/ticket-delivery-run-scope.js +128 -0
  129. package/build/version.generated.js +3 -3
  130. package/build/worker-guard-hook-bin.js +2 -2
  131. package/build/worktrees.js +105 -0
  132. package/docs/EPIC-IMPLEMENTER.md +43 -0
  133. package/docs/epic-implementer/getting-started.md +95 -14
  134. package/package.json +2 -2
@@ -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"),