@bridge_gpt/mcp-server 0.2.71 → 0.2.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +22 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +7 -7
  5. package/build/bridge-permissions.js +31 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/ci-system-detection.js +50 -0
  9. package/build/ci-trigger-adapters.js +631 -0
  10. package/build/ci-trigger-install.js +106 -0
  11. package/build/claude-review-workflow.js +1 -1
  12. package/build/cli-help.js +6 -0
  13. package/build/codex-auto-recovery.js +126 -0
  14. package/build/codex-launcher-pin.js +33 -2
  15. package/build/codex-skill-adapter.js +5 -1
  16. package/build/command-host.js +33 -0
  17. package/build/commands.generated.js +7 -6
  18. package/build/conductor/bridge-api-client.js +1352 -50
  19. package/build/conductor/bring-up-facts.js +18 -5
  20. package/build/conductor/command-drift-production.js +42 -17
  21. package/build/conductor/command-drift.js +47 -0
  22. package/build/conductor/declare-blocked.js +554 -0
  23. package/build/conductor/doctor.js +187 -28
  24. package/build/conductor/driver-commands.js +141 -0
  25. package/build/conductor/driver-guard.js +277 -0
  26. package/build/conductor/driver-lapse.js +321 -0
  27. package/build/conductor/driver-register.js +176 -0
  28. package/build/conductor/driver-release.js +174 -0
  29. package/build/conductor/driver-session-state.js +315 -0
  30. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  31. package/build/conductor/epic-implementer-cli.js +213 -13
  32. package/build/conductor/epic-server-database.js +162 -0
  33. package/build/conductor/epic-server-guidance.js +278 -0
  34. package/build/conductor/epic-server-journal.js +239 -0
  35. package/build/conductor/epic-server-processes.js +324 -0
  36. package/build/conductor/epic-server-recipe.js +397 -0
  37. package/build/conductor/epic-server-runtime.js +1207 -0
  38. package/build/conductor/epic-server-sfcc.js +107 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +594 -0
  41. package/build/conductor/gate-discovery.js +281 -10
  42. package/build/conductor/gate-settings-review.js +525 -5
  43. package/build/conductor/git-hooks-uninstall.js +112 -0
  44. package/build/conductor/git-hooks.js +81 -15
  45. package/build/conductor/guided-repair.js +10 -1
  46. package/build/conductor/install-doctor.js +2 -4
  47. package/build/conductor/launch-need-probes.js +6 -53
  48. package/build/conductor/launch-plan.js +318 -121
  49. package/build/conductor/local-merge.js +12 -1
  50. package/build/conductor/merge-execution-contract.js +1 -1
  51. package/build/conductor/merged-child-check.js +2 -1
  52. package/build/conductor/prerequisite-inputs.js +1213 -0
  53. package/build/conductor/readiness-assessment.js +93 -0
  54. package/build/conductor/readiness-cli.js +30 -9
  55. package/build/conductor/readiness-prerequisites.js +77 -5
  56. package/build/conductor/readiness-sections.js +146 -126
  57. package/build/conductor/readiness.js +21 -3
  58. package/build/conductor/recovery-cli.js +236 -15
  59. package/build/conductor/recovery-operations.js +34 -4
  60. package/build/conductor/repair-contract.js +33 -0
  61. package/build/conductor/tools.js +36 -4
  62. package/build/conductor/wait-run-attention.js +115 -0
  63. package/build/conductor/wait-run-cli.js +300 -21
  64. package/build/conductor/worker-database-doctor-inspector.js +34 -2
  65. package/build/conductor/worker-setup-tally.js +27 -0
  66. package/build/credential-store.js +96 -21
  67. package/build/dependency-install-declarations.js +212 -0
  68. package/build/docs.generated.js +4 -4
  69. package/build/doctor.js +91 -8
  70. package/build/drive-epic-help.js +23 -4
  71. package/build/drive-epic.js +1841 -340
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +140 -0
  74. package/build/epic-capability-statement.js +107 -0
  75. package/build/epic-ci-workflow-drift.js +30 -15
  76. package/build/epic-ci-workflow-install.js +110 -42
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow.js +38 -12
  79. package/build/epic-implementer-bin.js +2184 -52
  80. package/build/epic-launch-context.js +607 -0
  81. package/build/epic-launch-profile.js +1 -1
  82. package/build/epic-server-record.js +273 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/cli.js +2 -0
  87. package/build/executor/completion-contract.js +24 -1
  88. package/build/executor/credentials.js +1 -1
  89. package/build/executor/delivery-observations.js +113 -0
  90. package/build/executor/delivery-outcome.js +30 -0
  91. package/build/executor/dependency-refresh-runner.js +132 -0
  92. package/build/executor/dependency-refresh.js +530 -0
  93. package/build/executor/deps.js +4 -0
  94. package/build/executor/env.js +119 -17
  95. package/build/executor/epic-server-context.js +141 -0
  96. package/build/executor/gate-qualification-job.js +127 -26
  97. package/build/executor/harness-coverage.js +19 -0
  98. package/build/executor/http-client.js +87 -6
  99. package/build/executor/index.js +2 -1
  100. package/build/executor/install-preflight.js +1 -1
  101. package/build/executor/job-runner.js +659 -87
  102. package/build/executor/likely-tests.js +94 -97
  103. package/build/executor/observation.js +8 -0
  104. package/build/executor/pre-pr-checks.js +363 -0
  105. package/build/executor/prompt-spec.js +127 -5
  106. package/build/executor/reconcile-overlap-job.js +5 -3
  107. package/build/executor/required-verification.js +28 -0
  108. package/build/executor/required-work-diagnostics.js +32 -0
  109. package/build/executor/required-work-ledger.js +955 -39
  110. package/build/executor/results.js +100 -0
  111. package/build/executor/service-discovery.js +42 -0
  112. package/build/executor/service-lifecycle.js +109 -2
  113. package/build/executor/service-uninstall.js +205 -0
  114. package/build/executor/service-unit.js +5 -3
  115. package/build/executor/terminal-mutation.js +8 -0
  116. package/build/executor/test-clock.js +3 -0
  117. package/build/executor/verification-hints.js +179 -0
  118. package/build/executor/worker-command.js +126 -5
  119. package/build/executor/worker-database-config.js +281 -0
  120. package/build/executor/worker-database-target.js +16 -12
  121. package/build/executor/worker-database.js +575 -116
  122. package/build/executor/worker-finalization.js +71 -10
  123. package/build/executor/worker-guard-hook.js +10 -2
  124. package/build/executor/worker-resources.js +25 -3
  125. package/build/executor/worker-verification-guidance.js +55 -5
  126. package/build/executor/worktree-inspection.js +42 -0
  127. package/build/executor/worktree.js +20 -1
  128. package/build/executor-launch.js +54 -2
  129. package/build/generated-assets-catalog.js +2 -2
  130. package/build/github-sign-in.js +1 -1
  131. package/build/index.js +1111 -381
  132. package/build/init.js +29 -14
  133. package/build/install-bridge-conductor-answers.js +465 -0
  134. package/build/install-bridge-conductor-apply.js +259 -0
  135. package/build/install-bridge-conductor-assessment.js +895 -0
  136. package/build/install-bridge-conductor-compact.js +161 -0
  137. package/build/install-bridge-conductor-contracts.js +63 -0
  138. package/build/install-bridge-conductor-gate.js +1383 -188
  139. package/build/install-bridge-conductor-setup.js +637 -92
  140. package/build/install-bridge-conductor.js +3163 -740
  141. package/build/install-bridge.js +601 -128
  142. package/build/install-maintenance.js +127 -0
  143. package/build/install-reexec.js +1 -1
  144. package/build/launcher-config-inspection.js +162 -1
  145. package/build/local-cleanup.js +59 -0
  146. package/build/mcp-grant-candidates.js +767 -0
  147. package/build/mcp-grant-doctor.js +63 -0
  148. package/build/mcp-grant.js +288 -0
  149. package/build/mcp-host-targets.js +8 -0
  150. package/build/mcp-identity.js +23 -0
  151. package/build/mcp-install-state.js +68 -2
  152. package/build/mcp-invoke.js +126 -13
  153. package/build/mcp-presets.js +107 -0
  154. package/build/mcp-provisioning.js +134 -2
  155. package/build/mcp-registration-doctor.js +31 -2
  156. package/build/mcp-server-invocation.js +6 -1
  157. package/build/merge-workflow-install.js +236 -111
  158. package/build/package-script-semantics.js +10 -0
  159. package/build/pipeline-utils.js +1 -1
  160. package/build/pipelines.generated.js +6 -6
  161. package/build/plan-discovery.js +97 -4
  162. package/build/plan-execution-ledger.js +248 -9
  163. package/build/plan-generation-io.js +262 -0
  164. package/build/plan-generation.js +424 -0
  165. package/build/plane/build-freshness.js +6 -1
  166. package/build/plane/cli.js +75 -9
  167. package/build/plane/plane-freshness.js +23 -7
  168. package/build/plane/preflight.js +50 -10
  169. package/build/plane/shutdown.js +19 -0
  170. package/build/plane/terminal-run-cleanup.js +23 -5
  171. package/build/plane/terminal-run-status.js +4 -0
  172. package/build/printed-remedy-commands.js +229 -15
  173. package/build/readiness-check.js +1 -1
  174. package/build/readiness-prerequisites.generated.js +311 -4
  175. package/build/readme.generated.js +1 -1
  176. package/build/repository-state-paths.js +38 -0
  177. package/build/repository-toolchains.js +50 -8
  178. package/build/run-unit-tests-launcher.js +8 -1
  179. package/build/setup-change-policy.js +32 -0
  180. package/build/setup-epic.js +1192 -198
  181. package/build/setup-progress.js +44 -0
  182. package/build/setup-question.js +180 -0
  183. package/build/start-tickets.js +4 -0
  184. package/build/test-command-detection.js +32 -88
  185. package/build/test-support/notes-fs.js +40 -0
  186. package/build/third-party-mcp-targets.js +30 -0
  187. package/build/ticket-delivery-enrollment.js +30 -8
  188. package/build/ticket-delivery-run-scope.js +128 -0
  189. package/build/upgrade-cli.js +85 -2
  190. package/build/v2-readiness-requirements.js +28 -1
  191. package/build/version.generated.js +3 -3
  192. package/build/worker-guard-hook-bin.js +2 -2
  193. package/build/worktrees.js +105 -0
  194. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  195. package/docs/EPIC-IMPLEMENTER.md +5 -0
  196. package/docs/epic-implementer/getting-started.md +42 -15
  197. package/docs/epic-implementer/self-hosting.md +14 -1
  198. package/package.json +2 -2
@@ -35,9 +35,11 @@
35
35
  * executor must not reach a worker and silently change which configuration —
36
36
  * and which MCP registrations — the CLI resolves.
37
37
  *
38
- * BAPI-1019: this builder also injects four SENTINEL DATABASE literals
39
- * (`DATABASE_URL`, `POSTGRES_DATABASE`, `POSTGRES_DB`, `PGDATABASE`), all naming a
40
- * database that does not exist. Architecture Miss 28 was a worker that ran an
38
+ * BAPI-1019: this builder also injects SENTINEL DATABASE literals (the
39
+ * configured URL aliases, `POSTGRES_DATABASE`, `POSTGRES_DB`, `PGDATABASE`), all
40
+ * naming a database that does not exist. BAPI-1598: only when the job's
41
+ * `worker_database` declaration lists protected databases; an unconfigured
42
+ * project's own runtime defaults are left alone. Architecture Miss 28 was a worker that ran an
41
43
  * allowed `pytest` whose harness truncated the operator's real operational
42
44
  * database; it could name that database because a copied `.env` reached its
43
45
  * worktree and nothing in the worker environment said otherwise. The env-file
@@ -75,6 +77,7 @@ import { INDEX_SCOPE_ENV_VAR, validateOptionalIndexScope } from "../index-scope-
75
77
  import { delimiter as PLATFORM_PATH_DELIMITER } from "node:path";
76
78
  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
79
  import { buildWorkerDatabaseEnv } from "./worker-database-target.js";
80
+ import { admitDependencyInstallDeclarations, normalizeCiDatabase, } from "../dependency-install-declarations.js";
78
81
  /** Entry rules for a declared worker variable (BAPI-1520), rechecked by the executor. */
79
82
  const MAX_WORKER_ENV_ENTRIES = 32;
80
83
  const MAX_WORKER_ENV_VALUE_BYTES = 1024;
@@ -183,7 +186,7 @@ export const WORKER_SENTINEL_DATABASE_ENV_KEYS = [
183
186
  "PGDATABASE",
184
187
  ];
185
188
  /**
186
- * CI's non-secret test values, injected into EVERY worker environment (BAPI-1479).
189
+ * Four non-secret BGPT_* compatibility values for legacy payloads without worker_env.
187
190
  *
188
191
  * These are the exact literals the Python lane of
189
192
  * `.github/workflows/epic-implementer-ci.yml` sets. They are throwaway CI values,
@@ -203,7 +206,6 @@ export const CI_WORKER_ENV_CONSTANTS = Object.freeze({
203
206
  BGPT_DEMO_SECRET: "test-demo-secret",
204
207
  BGPT_SESSION_SECRET: "test-session-secret",
205
208
  BGPT_INVITE_SECRET: "test-invite-secret",
206
- ENVIRONMENT: "LOCAL",
207
209
  });
208
210
  /**
209
211
  * BAPI-1521 — the ONE reserved-name policy for repository-declared worker
@@ -315,6 +317,82 @@ export function validateWorkerEnvDeclarations(raw, taken = new Set()) {
315
317
  }
316
318
  return accepted;
317
319
  }
320
+ /**
321
+ * BAPI-1551 — the environment a declared dependency install runs with: the
322
+ * sentinel worker environment plus the payload's declared worker variables. It
323
+ * carries no credential and never the operator's database. Built here so the
324
+ * job runner never constructs a worker environment itself.
325
+ */
326
+ export function buildDependencyInstallEnv(parentEnv, payload, databaseOption = {}) {
327
+ return buildExecutorBaseWorkerEnv(parentEnv, {
328
+ ...payloadWorkerEnvOption(payload),
329
+ ...databaseOption,
330
+ legacyNotice: false,
331
+ });
332
+ }
333
+ /**
334
+ * BAPI-1551 — the `{ dependencyInstall }` option a job payload implies: present
335
+ * exactly when the payload OWNS a `dependency_install` key. Never reads the value.
336
+ */
337
+ export function payloadDependencyInstallOption(payload) {
338
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload))
339
+ return {};
340
+ if (!Object.prototype.hasOwnProperty.call(payload, "dependency_install"))
341
+ return {};
342
+ return { dependencyInstall: payload.dependency_install };
343
+ }
344
+ /**
345
+ * BAPI-1582 — the `{ prePrChecks }` option a job payload implies: present exactly
346
+ * when the payload OWNS a `pre_pr_checks` key (an inherited or prototype key is
347
+ * absent). Never validates the value; a malformed own value is still present.
348
+ */
349
+ export function payloadPrePrChecksOption(payload) {
350
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload))
351
+ return {};
352
+ if (!Object.prototype.hasOwnProperty.call(payload, "pre_pr_checks"))
353
+ return {};
354
+ return { prePrChecks: payload.pre_pr_checks };
355
+ }
356
+ /** BAPI-1551 — the `{ ciDatabase }` option, present exactly when the payload owns `ci_database`. */
357
+ export function payloadCiDatabaseOption(payload) {
358
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload))
359
+ return {};
360
+ if (!Object.prototype.hasOwnProperty.call(payload, "ci_database"))
361
+ return {};
362
+ return { ciDatabase: payload.ci_database };
363
+ }
364
+ /** BAPI-1551 — the payload's `ci_database`, with anything other than the three values (or absence) read as `unknown`. */
365
+ export function payloadCiDatabase(payload) {
366
+ return normalizeCiDatabase(payloadCiDatabaseOption(payload).ciDatabase);
367
+ }
368
+ /**
369
+ * BAPI-1551 — validate a payload `dependency_install` declaration against the
370
+ * server's entry rules and return the entries safe to run. Never throws: an
371
+ * invalid entry is skipped with a closed reason, logged with its `cwd` only when
372
+ * that `cwd` passed the path rules, and never with an argv item.
373
+ */
374
+ export function validateDependencyInstallDeclarations(raw, errorLog = (message) => console.error(message)) {
375
+ let admitted;
376
+ try {
377
+ admitted = admitDependencyInstallDeclarations(raw);
378
+ }
379
+ catch {
380
+ admitted = { entries: [], skipped: [], notAList: true };
381
+ }
382
+ const log = (message) => { try {
383
+ errorLog(message);
384
+ }
385
+ catch { /* sink */ } };
386
+ if (admitted.notAList) {
387
+ log("executor: dependency_install is present but is not a list; running no dependency refresh");
388
+ return [];
389
+ }
390
+ for (const skip of admitted.skipped) {
391
+ const where = skip.cwd !== undefined ? ` for ${skip.cwd}` : "";
392
+ log(`executor: skipped declared dependency refresh${where}: ${skip.reason}`);
393
+ }
394
+ return admitted.entries;
395
+ }
318
396
  /** Substrings that mark a key as secret-bearing (case-insensitive). */
319
397
  const SECRET_NAME_FRAGMENTS = ["TOKEN", "SECRET", "PASSWORD", "API_KEY"];
320
398
  /** True when `name` looks secret, so a declaration of it needs `committed_literal: true`. */
@@ -514,22 +592,41 @@ export function buildExecutorBaseWorkerEnv(parentEnv, options = {}) {
514
592
  env[key] = value;
515
593
  }
516
594
  }
595
+ // BAPI-1598 — no executor database setting is ever inherited. The allowlist
596
+ // already omits these, so this sweep only keeps that true if the allowlist grows.
597
+ for (const key of Object.keys(env)) {
598
+ if (key === "DATABASE_URL" || key.startsWith("POSTGRES_") || key.startsWith("PG"))
599
+ delete env[key];
600
+ }
517
601
  env.BRIDGE_SKIP_PREPUSH = "1";
518
602
  env.MAX_MCP_OUTPUT_TOKENS = "50000";
519
- // BAPI-1019 — the sentinel database target, set for EVERY job type and every
520
- // adapter, from constants and never from `parentEnv`. Set here rather than in
521
- // an adapter because "a worker cannot name a real database" is a property of
522
- // being a worker, not of being a Claude worker.
523
- env.DATABASE_URL = WORKER_SENTINEL_DATABASE_URL;
524
- env.POSTGRES_DATABASE = WORKER_SENTINEL_DATABASE_NAME;
525
- env.POSTGRES_DB = WORKER_SENTINEL_DATABASE_NAME;
526
- env.PGDATABASE = WORKER_SENTINEL_DATABASE_NAME;
527
- // BAPI-1479 — a provisioned job database replaces the four sentinel keys
528
- // TOGETHER and adds the loopback role keys. Validated before anything is set, so
529
- // an invalid name throws rather than leaving a half-pointed environment.
603
+ // BAPI-1019/BAPI-1598 — the database destination, from the validated
604
+ // declaration and never from `parentEnv`. A declaration that lists protected
605
+ // databases gets the sentinel in every configured URL alias and the component
606
+ // variables, so a worker cannot name a real database. An absent declaration, or
607
+ // one with no protected names, adds nothing. A provisioned job database then
608
+ // replaces the sentinel TOGETHER with the loopback role keys; its name is
609
+ // validated before anything is set, so an invalid name throws rather than
610
+ // leaving a half-pointed environment.
611
+ let databaseEnv = {};
612
+ const databaseConfig = options.workerDatabaseConfig;
613
+ if (databaseConfig !== undefined && databaseConfig.protectedDatabases.length > 0) {
614
+ for (const alias of databaseConfig.envNames)
615
+ databaseEnv[alias] = WORKER_SENTINEL_DATABASE_URL;
616
+ databaseEnv.POSTGRES_DATABASE = WORKER_SENTINEL_DATABASE_NAME;
617
+ databaseEnv.POSTGRES_DB = WORKER_SENTINEL_DATABASE_NAME;
618
+ databaseEnv.PGDATABASE = WORKER_SENTINEL_DATABASE_NAME;
619
+ }
530
620
  if (options.workerDatabase !== undefined) {
531
- Object.assign(env, buildWorkerDatabaseEnv(options.workerDatabase));
621
+ if (databaseConfig?.workerRole === undefined) {
622
+ throw new Error("worker database target requires a validated worker_database declaration");
623
+ }
624
+ databaseEnv = buildWorkerDatabaseEnv(options.workerDatabase, {
625
+ role: databaseConfig.workerRole,
626
+ envNames: databaseConfig.envNames,
627
+ });
532
628
  }
629
+ Object.assign(env, databaseEnv);
533
630
  // BAPI-1479 — CI's throwaway test values, from constants and never from
534
631
  // `parentEnv`, for every job type and every adapter. BAPI-1521: only when the
535
632
  // payload did not carry a `worker_env` declaration at all. A present declaration
@@ -595,12 +692,17 @@ export function buildExecutorBaseWorkerEnv(parentEnv, options = {}) {
595
692
  env[name] = value;
596
693
  }
597
694
  }
695
+ // BAPI-1598 — the final database assignments, after every permitted declaration
696
+ // and legacy fill, so neither can overwrite the protected destination.
697
+ Object.assign(env, databaseEnv);
598
698
  // Nothing agent-specific is added here, and deliberately nothing secret. An
599
699
  // adapter that needs to forward an operator-owned credential declares it as a
600
700
  // passthrough and copies it onto the object this function returns; see
601
701
  // `buildClaudeWorkerEnv`. Keeping the base free of every credential is what
602
702
  // makes "which secrets can reach a worker?" answerable per adapter instead of
603
703
  // per call site.
704
+ // BAPI-1598 — no implicit `ENVIRONMENT`. A repository that needs one declares
705
+ // it in `worker_env` (bridge-api declares `ENVIRONMENT=LOCAL`).
604
706
  return env;
605
707
  }
606
708
  /**
@@ -0,0 +1,141 @@
1
+ /**
2
+ * The executor's read-only, fail-open view of the run's epic server (BAPI-1546).
3
+ *
4
+ * At spawn, an implement-style worker in an epic run gets the browser target the
5
+ * repository owner opted in to, and nothing else:
6
+ *
7
+ * - `local` mode: the helper's live state, accepted only when its pid is alive
8
+ * with the recorded start time and it names THIS run. The served loopback
9
+ * URL becomes `BRIDGE_EPIC_SERVER_URL`, and the run id becomes
10
+ * `BRIDGE_EPIC_SERVER_RUN_ID` (what `turn acquire` addresses). A missing,
11
+ * stale, or unreadable state file is "local, unavailable": the worker still
12
+ * spawns, with no URL, and is told to try one bounded turn.
13
+ * - `sfcc_shared_active` mode: the approved storefront origin becomes
14
+ * `BRIDGE_EPIC_SERVER_URL`. No local state is read, and no sandbox credential
15
+ * or credential reference reaches the worker.
16
+ * - no record, an unusable record, or `none`: disabled. Nothing is injected,
17
+ * so the spawn environment, the prompt, and `.mcp.json` are byte-identical to
18
+ * a repository that never opted in.
19
+ *
20
+ * Every read is bounded and every failure is swallowed into `disabled` or
21
+ * `local_unavailable`. Nothing here can fail a job, write run state, add a gate,
22
+ * park a ticket, or block a spawn. The browser origin restriction itself is the
23
+ * `mcp-invoke` shim's, derived from `BRIDGE_EPIC_SERVER_URL`; it is not
24
+ * recomputed here.
25
+ */
26
+ import { lstat, readFile } from "node:fs/promises";
27
+ import os from "node:os";
28
+ import { readEpicServerRecord } from "../epic-server-record.js";
29
+ import { boundedResult, createDefaultEpicServerStateFs, findEpicServerRunPaths, isValidEpicRunId, readEpicServerLiveState, EPIC_SERVER_RUN_ID_ENV, EPIC_SERVER_URL_ENV, } from "../conductor/epic-server-state.js";
30
+ import { createDefaultEpicServerProcessDeps, readProcessStartTime } from "../conductor/epic-server-processes.js";
31
+ import { EPIC_SERVER_DEFAULT_TIMING } from "../conductor/epic-server-recipe.js";
32
+ /** The whole optional read is bounded by this. */
33
+ export const EPIC_SERVER_CONTEXT_BUDGET_MS = 3_000;
34
+ /**
35
+ * The live-state read finishes this much before the whole budget, so a hung
36
+ * helper probe resolves "local, unavailable" (the record DID select local mode)
37
+ * instead of losing the race to the outer `disabled` timeout.
38
+ */
39
+ const LIVE_STATE_MARGIN_MS = 250;
40
+ export function createDefaultEpicServerContextDeps(env) {
41
+ const proc = createDefaultEpicServerProcessDeps();
42
+ return {
43
+ readRecord: (repoName) => readEpicServerRecord(repoName, { env, homedir: os.homedir, readFile: (p) => readFile(p, "utf8"), lstat: (p) => lstat(p) }),
44
+ homedir: os.homedir,
45
+ tmpdir: os.tmpdir,
46
+ fs: createDefaultEpicServerStateFs(),
47
+ identity: async (pid) => {
48
+ const startedAt = await readProcessStartTime(pid, proc);
49
+ return startedAt === null ? null : { startedAt };
50
+ },
51
+ };
52
+ }
53
+ async function readContext(repoName, epicRunId, deps, deadline) {
54
+ const record = await deps.readRecord(repoName);
55
+ if (record.state !== "ok")
56
+ return { kind: "disabled" };
57
+ const mode = record.record.mode;
58
+ if (mode === "none")
59
+ return { kind: "disabled" };
60
+ if (mode === "sfcc_shared_active") {
61
+ const origin = record.record.sfcc?.storefront_origin;
62
+ return typeof origin === "string" && origin.length > 0 ? { kind: "sfcc", origin } : { kind: "disabled" };
63
+ }
64
+ if (!isValidEpicRunId(epicRunId))
65
+ return { kind: "disabled" };
66
+ const paths = await findEpicServerRunPaths(deps.homedir(), epicRunId, deps.fs, deps.tmpdir());
67
+ if (paths === null)
68
+ return { kind: "local_unavailable", runId: epicRunId };
69
+ const live = await readEpicServerLiveState(paths.state, epicRunId, { fs: deps.fs, probe: { identity: deps.identity }, budgetMs: Math.max(1, deadline - Date.now() - LIVE_STATE_MARGIN_MS) });
70
+ return live.state === "live"
71
+ ? {
72
+ kind: "local_live",
73
+ url: live.value.url,
74
+ runId: epicRunId,
75
+ turnWaitSeconds: live.value.turn_wait_seconds,
76
+ turnBuildSeconds: live.value.turn_build_seconds,
77
+ }
78
+ : { kind: "local_unavailable", runId: epicRunId };
79
+ }
80
+ /**
81
+ * Read the worker's epic-server context. Never throws and never exceeds the
82
+ * budget: a slow or failed local read degrades to `local_unavailable` only after
83
+ * the record selected local mode, and to `disabled` otherwise.
84
+ */
85
+ export async function readEpicServerWorkerContext(repoName, epicRunId, deps) {
86
+ if (typeof epicRunId !== "string" || epicRunId.length === 0)
87
+ return { kind: "disabled" };
88
+ const deadline = Date.now() + EPIC_SERVER_CONTEXT_BUDGET_MS;
89
+ const work = readContext(repoName, epicRunId, deps, deadline).catch(() => ({ kind: "disabled" }));
90
+ return boundedResult(work, EPIC_SERVER_CONTEXT_BUDGET_MS, { kind: "disabled" });
91
+ }
92
+ /**
93
+ * Claude Code caps a foreground Bash command at 600 s unless this names a higher
94
+ * ceiling (milliseconds). `turn acquire` can legitimately take longer: a worker
95
+ * queued behind a held lease waits, then gets its own rebuild budget.
96
+ */
97
+ export const EPIC_SERVER_BASH_MAX_TIMEOUT_ENV = "BASH_MAX_TIMEOUT_MS";
98
+ /** Slack the client allows past the queue wait and rebuild budget. */
99
+ const EPIC_SERVER_ACQUIRE_SLACK_SECONDS = 60;
100
+ /**
101
+ * The longest one `turn acquire` command can take before it prints, in seconds:
102
+ * the running helper's turn wait plus its rebuild budget, plus slack. A context
103
+ * with no live helper uses the default timing, which is what a helper that starts
104
+ * later is most likely to run with. The prompt states this number and the spawn
105
+ * env raises the harness ceiling to it, so the two always agree.
106
+ */
107
+ export function epicServerAcquireCommandSeconds(context) {
108
+ const timing = context.kind === "local_live"
109
+ ? { wait: context.turnWaitSeconds, build: context.turnBuildSeconds }
110
+ : { wait: EPIC_SERVER_DEFAULT_TIMING.acquire_wait_seconds, build: EPIC_SERVER_DEFAULT_TIMING.proof_seconds };
111
+ return timing.wait + timing.build + EPIC_SERVER_ACQUIRE_SLACK_SECONDS;
112
+ }
113
+ /**
114
+ * Inject the trusted epic-server keys AFTER the worker environment builder ran,
115
+ * like the job tag. Any ambient copy is removed first. Local contexts also raise
116
+ * the harness command ceiling to {@link epicServerAcquireCommandSeconds}. `disabled` returns the
117
+ * environment unchanged (the same object), so a repository without an opt-in is
118
+ * byte-identical.
119
+ */
120
+ export function withEpicServerEnv(env, context) {
121
+ if (context.kind === "disabled")
122
+ return env;
123
+ const next = { ...env };
124
+ delete next[EPIC_SERVER_URL_ENV];
125
+ delete next[EPIC_SERVER_RUN_ID_ENV];
126
+ if (context.kind === "local_live" || context.kind === "local_unavailable") {
127
+ if (context.kind === "local_live")
128
+ next[EPIC_SERVER_URL_ENV] = context.url;
129
+ next[EPIC_SERVER_RUN_ID_ENV] = context.runId;
130
+ // Raise only the ceiling, never the default: the prompt names an explicit
131
+ // timeout for `turn acquire`, and every other command keeps the harness
132
+ // default. A higher ceiling already in the env is kept.
133
+ const needed = epicServerAcquireCommandSeconds(context) * 1000;
134
+ const current = Number(next[EPIC_SERVER_BASH_MAX_TIMEOUT_ENV]);
135
+ next[EPIC_SERVER_BASH_MAX_TIMEOUT_ENV] = String(Number.isSafeInteger(current) && current > needed ? current : needed);
136
+ }
137
+ else {
138
+ next[EPIC_SERVER_URL_ENV] = context.origin;
139
+ }
140
+ return next;
141
+ }
@@ -9,7 +9,7 @@
9
9
  * qualification. Like `ci_rerun` it is run-less and deterministic: no worker,
10
10
  * no LLM, no worktrunk worktree, and no fallback to any of those.
11
11
  *
12
- * Five properties are load-bearing:
12
+ * Six properties are load-bearing:
13
13
  *
14
14
  * 1. **Validate before any effect.** Every payload rule in the cross-runtime
15
15
  * contract — shape, bounds, every command digest and identity, the
@@ -43,13 +43,27 @@
43
43
  * A command cut short by shutdown or lost ownership proved nothing about the
44
44
  * gate, so it is reported as an inability (`GateQualificationInterrupted`)
45
45
  * and never recorded as an unqualified gate.
46
+ *
47
+ * 6. **Dependencies are prepared exactly as a worker job would (BAPI-1637).**
48
+ * When the SEALED declaration carries `dependency_install`, the detached
49
+ * checkout is refreshed through the same `refreshDeclaredDependencies()` and
50
+ * install environment the worker pathway uses, after the clean-checkout check
51
+ * and before any command. A completed preparation failure is a COMPLETED job
52
+ * (`outcome: "failed"`, `dependency_preparation: "failed"`, every command
53
+ * `not_run`), distinct from an interruption, which still reports no result. A
54
+ * declaration without the key performs no installation work at all and its
55
+ * result keeps exactly the pre-existing shape (no `dependency_preparation`).
56
+ * Every message and fact stays value-free: no install output, path, argv, or
57
+ * environment value.
46
58
  */
47
59
  import { createHash } from "node:crypto";
48
60
  import { mkdtemp, rm } from "node:fs/promises";
49
61
  import os from "node:os";
50
62
  import path from "node:path";
51
63
  import { validateBranchName } from "../base-ref.js";
52
- import { buildExecutorBaseWorkerEnv } from "./env.js";
64
+ import { parseDependencyInstallStrict, } from "../dependency-install-declarations.js";
65
+ import { refreshDeclaredDependencies } from "./dependency-refresh.js";
66
+ import { buildDependencyInstallEnv, buildExecutorBaseWorkerEnv } from "./env.js";
53
67
  import { ARTIFACT_GIT_TIMEOUT_MS, OWNERSHIP_POLL_MS, canonicalJson, createSupervisedCommandLauncher, preCheckArtifactState, runRequiredVerificationCommands, toCompletionCheckFact, } from "./required-verification.js";
54
68
  import { GATE_QUALIFICATION_CAPABILITY, } from "./types.js";
55
69
  // ---------------------------------------------------------------------------
@@ -210,6 +224,17 @@ export function parseGateQualificationPayload(job) {
210
224
  digests.some((value, index) => value !== commands[index].digest)) {
211
225
  return refuse(MESSAGES.contract);
212
226
  }
227
+ // BAPI-1637: the install declaration is read from the SIGNED body only, with
228
+ // the same whole-list strictness the server applies. The lenient admission the
229
+ // worker pathway uses would silently drop a rejected entry and so run a
230
+ // different declaration from the one the server sealed.
231
+ let dependencyInstallOption = {};
232
+ if (Object.prototype.hasOwnProperty.call(envelope, "dependency_install")) {
233
+ const entries = parseDependencyInstallStrict(envelope.dependency_install);
234
+ if (entries === null)
235
+ return refuse(MESSAGES.contract);
236
+ dependencyInstallOption = { dependencyInstall: entries };
237
+ }
213
238
  // The envelope digest covers the object exactly as received, minus its own
214
239
  // digest key, so any field the server signed is checked byte for byte.
215
240
  const { digest, ...signed } = envelope;
@@ -227,6 +252,7 @@ export function parseGateQualificationPayload(job) {
227
252
  workerEnvOption: Object.prototype.hasOwnProperty.call(envelope, "worker_env")
228
253
  ? { workerEnv: envelope.worker_env }
229
254
  : {},
255
+ dependencyInstallOption,
230
256
  },
231
257
  };
232
258
  }
@@ -313,6 +339,24 @@ function isInterruptionFact(fact) {
313
339
  fact.reason === "executor_cancelled" ||
314
340
  fact.reason === "ownership_lost");
315
341
  }
342
+ /**
343
+ * Fold what was observed into one classification, by fixed precedence:
344
+ * interruption, preparation failure, any `launch_error`/`spawn_failed` fact, any
345
+ * other unsuccessful or not-run fact, then passed. The server derives the same
346
+ * phase from the stored result; the completion envelope carries no `phase`.
347
+ */
348
+ export function foldGateQualificationOutcome(input) {
349
+ if (input.facts.some(isInterruptionFact))
350
+ return "interrupted";
351
+ if (input.preparationFailed === true)
352
+ return "dependency_preparation_failed";
353
+ if (input.facts.some((fact) => fact.outcome === "launch_error" || fact.reason === "spawn_failed")) {
354
+ return "could_not_start";
355
+ }
356
+ if (input.facts.some((fact) => fact.outcome !== "exited_zero"))
357
+ return "ran_and_failed";
358
+ return "passed";
359
+ }
316
360
  /**
317
361
  * Run one `gate_qualification` job.
318
362
  *
@@ -374,9 +418,10 @@ export async function runGateQualificationJob(job, input, deps) {
374
418
  const timeoutMs = input.timeoutSeconds * 1000;
375
419
  const deadlineAtMs = startedAt + Math.max(0, timeoutMs - GATE_QUALIFICATION_DEADLINE_RESERVE_MS);
376
420
  const ownershipHeld = deps.ownershipHeld ?? (() => true);
377
- // Ownership is re-checked WHILE a command runs, not only between commands,
378
- // exactly as the covered lane does: a lost claim terminates the running
379
- // command. The supervisor's own abort (timeout, stop) is chained in too.
421
+ // Ownership is re-checked WHILE preparation and each command run, not only
422
+ // between commands, exactly as the covered lane does: a lost claim terminates
423
+ // the running work. The supervisor's own abort (timeout, stop) is chained in
424
+ // too. One scope covers dependency preparation and verification.
380
425
  const commandAbort = new AbortController();
381
426
  const onOuterAbort = () => commandAbort.abort();
382
427
  if (input.signal.aborted)
@@ -394,10 +439,6 @@ export async function runGateQualificationJob(job, input, deps) {
394
439
  }, OWNERSHIP_POLL_MS);
395
440
  };
396
441
  watchOwnership();
397
- // BAPI-1521 — the effective environment is built here, AFTER the envelope was
398
- // verified and BEFORE any command runs, from the sealed declaration. The
399
- // injected dependencies are never mutated.
400
- const commandEnv = deps.commandEnv ?? buildGateQualificationEnv(deps.baseEnv ?? {}, payload.workerEnvOption);
401
442
  const commands = payload.commands.map((command) => ({
402
443
  identity: command.identity,
403
444
  position: command.position,
@@ -405,20 +446,71 @@ export async function runGateQualificationJob(job, input, deps) {
405
446
  argv: command.argv,
406
447
  timeoutSeconds: command.timeoutSeconds,
407
448
  }));
408
- let facts;
449
+ const dependencyInstall = payload.dependencyInstallOption.dependencyInstall;
450
+ const installDeclared = dependencyInstall !== undefined;
451
+ let preparationFailed = false;
452
+ let facts = [];
409
453
  try {
410
- const run = await runRequiredVerificationCommands({
411
- commands,
412
- worktreePath: dir,
413
- env: commandEnv,
414
- launch: deps.launch,
415
- now: deps.now,
416
- deadlineAtMs,
417
- signal: commandAbort.signal,
418
- ownershipHeld,
419
- onInterruption: "stop",
420
- });
421
- facts = run.facts;
454
+ // BAPI-1637 — dependency preparation, only when the sealed declaration
455
+ // carries entries: after the clean-checkout check, before any command. A
456
+ // declaration without the key (or with an empty list) performs no
457
+ // installation-specific filesystem or process operation.
458
+ if (dependencyInstall !== undefined && dependencyInstall.length > 0) {
459
+ const refresh = deps.refreshDependencies ?? refreshDeclaredDependencies;
460
+ const refreshed = await refresh({
461
+ jobId: "gate-qualification",
462
+ entries: dependencyInstall,
463
+ worktreePath: dir,
464
+ mainCheckoutPath: deps.repoRoot,
465
+ // The install environment is NOT the command environment: it never
466
+ // gains the forced `CI=1` the qualification commands run under.
467
+ env: buildDependencyInstallEnv(deps.baseEnv ?? {}, Object.prototype.hasOwnProperty.call(payload.workerEnvOption, "workerEnv")
468
+ ? { worker_env: payload.workerEnvOption.workerEnv }
469
+ : {}),
470
+ remainingMs: deadlineAtMs - deps.now(),
471
+ now: deps.now,
472
+ sleep: deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
473
+ signal: commandAbort.signal,
474
+ log: (message) => deps.errorLog(message),
475
+ ...(deps.platform ? { platform: deps.platform } : {}),
476
+ ...(deps.runDependencyInstall ? { runInstall: deps.runDependencyInstall } : {}),
477
+ });
478
+ // A cancelled refresh proved nothing about the gate: an inability.
479
+ if (refreshed.cancelled)
480
+ return inability(GATE_QUALIFICATION_INTERRUPTED, MESSAGES.interrupted);
481
+ preparationFailed = refreshed.stale.length > 0;
482
+ }
483
+ if (preparationFailed) {
484
+ // The install did not complete, so nothing was launched. One bounded
485
+ // `not_run` fact per declared command, in declaration order.
486
+ facts = commands.map((command) => ({
487
+ identity: command.identity,
488
+ position: command.position,
489
+ name: command.name,
490
+ outcome: "not_run",
491
+ reason: null,
492
+ durationMs: 0,
493
+ output: "",
494
+ }));
495
+ }
496
+ else {
497
+ // BAPI-1521 — the effective environment is built here, AFTER the envelope
498
+ // was verified and BEFORE any command runs, from the sealed declaration.
499
+ // The injected dependencies are never mutated.
500
+ const commandEnv = deps.commandEnv ?? buildGateQualificationEnv(deps.baseEnv ?? {}, payload.workerEnvOption);
501
+ const run = await runRequiredVerificationCommands({
502
+ commands,
503
+ worktreePath: dir,
504
+ env: commandEnv,
505
+ launch: deps.launch,
506
+ now: deps.now,
507
+ deadlineAtMs,
508
+ signal: commandAbort.signal,
509
+ ownershipHeld,
510
+ onInterruption: "stop",
511
+ });
512
+ facts = run.facts;
513
+ }
422
514
  }
423
515
  finally {
424
516
  if (watchTimer !== undefined)
@@ -433,20 +525,24 @@ export async function runGateQualificationJob(job, input, deps) {
433
525
  }
434
526
  }
435
527
  // 5. An interruption proved nothing about the gate: an inability, never a
436
- // completed "failed" that the server would record as unqualified.
437
- if (facts.some(isInterruptionFact)) {
528
+ // completed "failed" that the server would record as unqualified. A completed
529
+ // preparation failure, by contrast, IS a result.
530
+ const folded = foldGateQualificationOutcome({ facts, preparationFailed });
531
+ if (folded === "interrupted") {
438
532
  return inability(GATE_QUALIFICATION_INTERRUPTED, MESSAGES.interrupted);
439
533
  }
440
534
  const resultFacts = facts.map(toResultFact);
441
- const outcome = resultFacts.every((fact) => fact.outcome === "exited_zero") ? "passed" : "failed";
442
535
  return {
443
536
  ok: true,
444
537
  result: {
445
538
  schema_version: 1,
446
539
  revision: payload.revision,
447
540
  tested_head_sha: sha,
448
- outcome,
541
+ outcome: folded === "passed" ? "passed" : "failed",
449
542
  commands: resultFacts,
543
+ ...(installDeclared
544
+ ? { dependency_preparation: preparationFailed ? "failed" : "ready" }
545
+ : {}),
450
546
  },
451
547
  };
452
548
  }
@@ -510,5 +606,10 @@ export function createProductionGateQualificationDeps(input) {
510
606
  // stderr is the owner's own terminal, so it alone may show output tails.
511
607
  showLocalOutput: options.jobTypes !== undefined && options.jobTypes.length > 0,
512
608
  ownershipHeld: input.ownershipHeld,
609
+ // BAPI-1637: the same install runner, sleep, and platform the worker pathway
610
+ // uses, so a qualification prepares its checkout exactly as a worker would.
611
+ ...(deps.runDependencyInstall ? { runDependencyInstall: deps.runDependencyInstall } : {}),
612
+ sleep: deps.sleep,
613
+ platform: deps.platform,
513
614
  };
514
615
  }
@@ -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
+ }