@bridge_gpt/mcp-server 0.2.72 → 0.2.74

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 (181) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +15 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-config.js +7 -1
  5. package/build/bridge-permissions.js +30 -0
  6. package/build/ci-system-detection.js +50 -0
  7. package/build/ci-trigger-adapters.js +631 -0
  8. package/build/ci-trigger-install.js +106 -0
  9. package/build/codex-launcher-pin.js +33 -2
  10. package/build/codex-skill-adapter.js +3 -1
  11. package/build/command-host.js +33 -0
  12. package/build/command-provisioning.js +4 -3
  13. package/build/commands.generated.js +7 -6
  14. package/build/conductor/bridge-api-client.js +867 -35
  15. package/build/conductor/bring-up-facts.js +18 -5
  16. package/build/conductor/command-drift-production.js +42 -17
  17. package/build/conductor/command-drift.js +48 -1
  18. package/build/conductor/declare-blocked.js +554 -0
  19. package/build/conductor/declared-extras.js +335 -0
  20. package/build/conductor/doctor.js +108 -21
  21. package/build/conductor/driver-commands.js +141 -0
  22. package/build/conductor/driver-guard.js +277 -0
  23. package/build/conductor/driver-lapse.js +321 -0
  24. package/build/conductor/driver-pass-output.js +104 -0
  25. package/build/conductor/driver-pass.js +571 -0
  26. package/build/conductor/driver-register.js +176 -0
  27. package/build/conductor/driver-release.js +174 -0
  28. package/build/conductor/driver-session-state.js +315 -0
  29. package/build/conductor/epic-branch-ci-inspection.js +281 -43
  30. package/build/conductor/epic-implementer-cli.js +199 -15
  31. package/build/conductor/epic-server-database.js +162 -0
  32. package/build/conductor/epic-server-guidance.js +278 -0
  33. package/build/conductor/epic-server-journal.js +239 -0
  34. package/build/conductor/epic-server-processes.js +324 -0
  35. package/build/conductor/epic-server-recipe.js +397 -0
  36. package/build/conductor/epic-server-runtime.js +1207 -0
  37. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  38. package/build/conductor/epic-server-sfcc.js +85 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +647 -0
  41. package/build/conductor/gate-discovery.js +196 -11
  42. package/build/conductor/gate-settings-review.js +261 -4
  43. package/build/conductor/launch-need-probes.js +6 -53
  44. package/build/conductor/launch-plan.js +313 -156
  45. package/build/conductor/prerequisite-inputs.js +879 -45
  46. package/build/conductor/readiness-assessment.js +16 -1
  47. package/build/conductor/readiness-cli.js +20 -9
  48. package/build/conductor/readiness-prerequisites.js +28 -9
  49. package/build/conductor/readiness-sections.js +133 -126
  50. package/build/conductor/readiness.js +1 -1
  51. package/build/conductor/recovery-cli.js +13 -2
  52. package/build/conductor/tools.js +6 -5
  53. package/build/conductor/wait-run-attention.js +2 -2
  54. package/build/conductor/wait-run-cli.js +208 -22
  55. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  56. package/build/conductor/worker-setup-tally.js +27 -0
  57. package/build/credential-delivery.js +280 -0
  58. package/build/credential-launch-safety.js +142 -0
  59. package/build/credential-materialization.js +91 -16
  60. package/build/credential-references-node-deps.js +29 -0
  61. package/build/credential-references.js +1394 -0
  62. package/build/credential-references.test-fixtures.js +211 -0
  63. package/build/credential-scan-conventions.js +145 -0
  64. package/build/credential-scan.js +517 -0
  65. package/build/credential-store.js +121 -1
  66. package/build/credentials-cli.js +252 -3
  67. package/build/dependency-install-declarations.js +102 -1
  68. package/build/docs.generated.js +10 -3
  69. package/build/doctor.js +95 -3
  70. package/build/drive-epic-help.js +21 -2
  71. package/build/drive-epic.js +2095 -375
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +157 -0
  74. package/build/epic-capability-statement.js +175 -0
  75. package/build/epic-ci-workflow-drift.js +77 -23
  76. package/build/epic-ci-workflow-install.js +137 -44
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow-v3.js +273 -0
  79. package/build/epic-ci-workflow.js +165 -18
  80. package/build/epic-implementer-bin.js +2204 -56
  81. package/build/epic-launch-context.js +702 -0
  82. package/build/epic-server-record.js +288 -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/completion-contract.js +8 -1
  87. package/build/executor/credential-delivery-step.js +168 -0
  88. package/build/executor/deps.js +3 -1
  89. package/build/executor/env.js +98 -23
  90. package/build/executor/epic-server-context.js +157 -0
  91. package/build/executor/gate-qualification-job.js +127 -26
  92. package/build/executor/guarded-fast-forward-push.js +13 -8
  93. package/build/executor/http-client.js +52 -5
  94. package/build/executor/job-runner.js +577 -81
  95. package/build/executor/observation.js +8 -0
  96. package/build/executor/permissions.js +85 -3
  97. package/build/executor/pre-pr-checks.js +363 -0
  98. package/build/executor/prompt-spec.js +149 -3
  99. package/build/executor/reconcile-overlap-job.js +5 -3
  100. package/build/executor/required-work-diagnostics.js +4 -2
  101. package/build/executor/required-work-ledger.js +936 -38
  102. package/build/executor/results.js +58 -0
  103. package/build/executor/terminal-mutation.js +8 -0
  104. package/build/executor/worker-command.js +72 -3
  105. package/build/executor/worker-database-config.js +281 -0
  106. package/build/executor/worker-database-target.js +16 -12
  107. package/build/executor/worker-database.js +320 -101
  108. package/build/executor/worker-finalization.js +7 -1
  109. package/build/executor/worker-resources.js +25 -3
  110. package/build/executor/worker-verification-guidance.js +18 -3
  111. package/build/executor/worktree.js +20 -1
  112. package/build/executor-launch.js +58 -4
  113. package/build/generated-assets-catalog.js +2 -2
  114. package/build/git-exclude-lock.js +187 -0
  115. package/build/index.js +824 -366
  116. package/build/init.js +26 -11
  117. package/build/install-bridge-conductor-answers.js +528 -0
  118. package/build/install-bridge-conductor-apply.js +288 -0
  119. package/build/install-bridge-conductor-assessment.js +1222 -0
  120. package/build/install-bridge-conductor-compact.js +186 -0
  121. package/build/install-bridge-conductor-contracts.js +72 -0
  122. package/build/install-bridge-conductor-gate.js +1312 -198
  123. package/build/install-bridge-conductor-setup.js +577 -83
  124. package/build/install-bridge-conductor.js +3381 -544
  125. package/build/install-bridge.js +280 -25
  126. package/build/install-doctor.js +38 -8
  127. package/build/install-maintenance.js +26 -3
  128. package/build/install-sfcc-detection.js +120 -0
  129. package/build/install-sfcc-setup.js +185 -0
  130. package/build/launcher-config-inspection.js +162 -1
  131. package/build/mcp-grant-candidates.js +779 -0
  132. package/build/mcp-grant-doctor.js +63 -0
  133. package/build/mcp-grant.js +288 -0
  134. package/build/mcp-host-targets.js +8 -0
  135. package/build/mcp-identity.js +23 -0
  136. package/build/mcp-invoke.js +292 -15
  137. package/build/mcp-presets.js +107 -0
  138. package/build/mcp-provisioning.js +155 -6
  139. package/build/mcp-registration-doctor.js +31 -2
  140. package/build/mcp-server-invocation.js +19 -1
  141. package/build/merge-workflow-install.js +243 -110
  142. package/build/pipelines.generated.js +7 -6
  143. package/build/plan-discovery.js +97 -4
  144. package/build/plan-execution-ledger.js +100 -7
  145. package/build/plan-generation-io.js +262 -0
  146. package/build/plan-generation.js +424 -0
  147. package/build/plane/build-freshness.js +6 -1
  148. package/build/plane/cli.js +75 -9
  149. package/build/plane/plane-freshness.js +17 -0
  150. package/build/plane/preflight.js +50 -10
  151. package/build/plane/shutdown.js +19 -0
  152. package/build/plane/status.js +8 -2
  153. package/build/plane/terminal-run-cleanup.js +18 -4
  154. package/build/printed-remedy-commands.js +211 -12
  155. package/build/project-root.js +40 -0
  156. package/build/readiness-check.js +77 -0
  157. package/build/readiness-prerequisites.generated.js +122 -14
  158. package/build/readme.generated.js +1 -1
  159. package/build/repository-state-paths.js +41 -0
  160. package/build/repository-toolchains.js +6 -3
  161. package/build/run-unit-tests-launcher.js +8 -1
  162. package/build/setup-epic.js +1305 -210
  163. package/build/setup-progress.js +44 -0
  164. package/build/setup-question.js +122 -4
  165. package/build/sfcc/credentials.js +3 -2
  166. package/build/sfcc/hostname.js +98 -2
  167. package/build/sfcc/tool-wrapper.js +6 -95
  168. package/build/start-tickets.js +193 -29
  169. package/build/test-support/executor-source-files.js +200 -0
  170. package/build/testing-config-client.js +25 -2
  171. package/build/third-party-mcp-targets.js +63 -2
  172. package/build/ticket-delivery-enrollment.js +9 -0
  173. package/build/upgrade-cli.js +85 -2
  174. package/build/v2-readiness-requirements.js +28 -1
  175. package/build/version.generated.js +3 -3
  176. package/build/with-credentials.js +208 -0
  177. package/build/worktree-credential-delivery.js +340 -0
  178. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  179. package/docs/epic-implementer/getting-started.md +3 -1
  180. package/docs/epic-implementer/self-hosting.md +14 -1
  181. 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
@@ -321,8 +323,12 @@ export function validateWorkerEnvDeclarations(raw, taken = new Set()) {
321
323
  * carries no credential and never the operator's database. Built here so the
322
324
  * job runner never constructs a worker environment itself.
323
325
  */
324
- export function buildDependencyInstallEnv(parentEnv, payload) {
325
- return buildExecutorBaseWorkerEnv(parentEnv, { ...payloadWorkerEnvOption(payload), legacyNotice: false });
326
+ export function buildDependencyInstallEnv(parentEnv, payload, databaseOption = {}) {
327
+ return buildExecutorBaseWorkerEnv(parentEnv, {
328
+ ...payloadWorkerEnvOption(payload),
329
+ ...databaseOption,
330
+ legacyNotice: false,
331
+ });
326
332
  }
327
333
  /**
328
334
  * BAPI-1551 — the `{ dependencyInstall }` option a job payload implies: present
@@ -335,6 +341,18 @@ export function payloadDependencyInstallOption(payload) {
335
341
  return {};
336
342
  return { dependencyInstall: payload.dependency_install };
337
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
+ }
338
356
  /** BAPI-1551 — the `{ ciDatabase }` option, present exactly when the payload owns `ci_database`. */
339
357
  export function payloadCiDatabaseOption(payload) {
340
358
  if (typeof payload !== "object" || payload === null || Array.isArray(payload))
@@ -560,6 +578,35 @@ export function isExecutorEnvKeyAllowed(key) {
560
578
  return false;
561
579
  return true;
562
580
  }
581
+ /** Printed in place of a declared credential name that is not a safe variable name. */
582
+ const DECLARED_CREDENTIAL_UNPRINTABLE_NAME = "(unprintable name)";
583
+ /**
584
+ * BAPI-1647: admit approved credential variables into `env` (mutated). Returns
585
+ * the names-only outcome. A warning names only the variable.
586
+ */
587
+ export function admitDeclaredCredentialEnv(env, declared, warn = (message) => console.error(message)) {
588
+ const outcome = { admitted: [], dropped: [] };
589
+ const taken = new Set(Object.keys(env));
590
+ for (const [name, value] of Object.entries(declared)) {
591
+ if (typeof value !== "string")
592
+ continue;
593
+ const printable = WORKER_ENV_NAME_PATTERN.test(name) ? name : DECLARED_CREDENTIAL_UNPRINTABLE_NAME;
594
+ if (!WORKER_ENV_NAME_PATTERN.test(name) || isWorkerEnvNameReserved(name)) {
595
+ outcome.dropped.push({ name: printable, reason: "reserved_name" });
596
+ warn(`executor: credential variable ${printable} dropped: the name is reserved for the worker environment`);
597
+ continue;
598
+ }
599
+ if (taken.has(name)) {
600
+ outcome.dropped.push({ name, reason: "name_collision" });
601
+ warn(`executor: credential variable ${name} dropped: the worker environment already sets it`);
602
+ continue;
603
+ }
604
+ env[name] = value;
605
+ taken.add(name);
606
+ outcome.admitted.push(name);
607
+ }
608
+ return outcome;
609
+ }
563
610
  /** True when the options object owns a `workerEnv` property (value irrelevant). */
564
611
  export function hasWorkerEnvOption(options) {
565
612
  return options !== undefined && Object.prototype.hasOwnProperty.call(options, "workerEnv");
@@ -574,22 +621,41 @@ export function buildExecutorBaseWorkerEnv(parentEnv, options = {}) {
574
621
  env[key] = value;
575
622
  }
576
623
  }
624
+ // BAPI-1598 — no executor database setting is ever inherited. The allowlist
625
+ // already omits these, so this sweep only keeps that true if the allowlist grows.
626
+ for (const key of Object.keys(env)) {
627
+ if (key === "DATABASE_URL" || key.startsWith("POSTGRES_") || key.startsWith("PG"))
628
+ delete env[key];
629
+ }
577
630
  env.BRIDGE_SKIP_PREPUSH = "1";
578
631
  env.MAX_MCP_OUTPUT_TOKENS = "50000";
579
- // BAPI-1019 — the sentinel database target, set for EVERY job type and every
580
- // adapter, from constants and never from `parentEnv`. Set here rather than in
581
- // an adapter because "a worker cannot name a real database" is a property of
582
- // being a worker, not of being a Claude worker.
583
- env.DATABASE_URL = WORKER_SENTINEL_DATABASE_URL;
584
- env.POSTGRES_DATABASE = WORKER_SENTINEL_DATABASE_NAME;
585
- env.POSTGRES_DB = WORKER_SENTINEL_DATABASE_NAME;
586
- env.PGDATABASE = WORKER_SENTINEL_DATABASE_NAME;
587
- // BAPI-1479 — a provisioned job database replaces the four sentinel keys
588
- // TOGETHER and adds the loopback role keys. Validated before anything is set, so
589
- // an invalid name throws rather than leaving a half-pointed environment.
632
+ // BAPI-1019/BAPI-1598 — the database destination, from the validated
633
+ // declaration and never from `parentEnv`. A declaration that lists protected
634
+ // databases gets the sentinel in every configured URL alias and the component
635
+ // variables, so a worker cannot name a real database. An absent declaration, or
636
+ // one with no protected names, adds nothing. A provisioned job database then
637
+ // replaces the sentinel TOGETHER with the loopback role keys; its name is
638
+ // validated before anything is set, so an invalid name throws rather than
639
+ // leaving a half-pointed environment.
640
+ let databaseEnv = {};
641
+ const databaseConfig = options.workerDatabaseConfig;
642
+ if (databaseConfig !== undefined && databaseConfig.protectedDatabases.length > 0) {
643
+ for (const alias of databaseConfig.envNames)
644
+ databaseEnv[alias] = WORKER_SENTINEL_DATABASE_URL;
645
+ databaseEnv.POSTGRES_DATABASE = WORKER_SENTINEL_DATABASE_NAME;
646
+ databaseEnv.POSTGRES_DB = WORKER_SENTINEL_DATABASE_NAME;
647
+ databaseEnv.PGDATABASE = WORKER_SENTINEL_DATABASE_NAME;
648
+ }
590
649
  if (options.workerDatabase !== undefined) {
591
- Object.assign(env, buildWorkerDatabaseEnv(options.workerDatabase));
650
+ if (databaseConfig?.workerRole === undefined) {
651
+ throw new Error("worker database target requires a validated worker_database declaration");
652
+ }
653
+ databaseEnv = buildWorkerDatabaseEnv(options.workerDatabase, {
654
+ role: databaseConfig.workerRole,
655
+ envNames: databaseConfig.envNames,
656
+ });
592
657
  }
658
+ Object.assign(env, databaseEnv);
593
659
  // BAPI-1479 — CI's throwaway test values, from constants and never from
594
660
  // `parentEnv`, for every job type and every adapter. BAPI-1521: only when the
595
661
  // payload did not carry a `worker_env` declaration at all. A present declaration
@@ -655,17 +721,26 @@ export function buildExecutorBaseWorkerEnv(parentEnv, options = {}) {
655
721
  env[name] = value;
656
722
  }
657
723
  }
658
- // Nothing agent-specific is added here, and deliberately nothing secret. An
724
+ // BAPI-1598 — the final database assignments, after every permitted declaration
725
+ // and legacy fill, so neither can overwrite the protected destination.
726
+ Object.assign(env, databaseEnv);
727
+ // BAPI-1647 — approved sandbox credential variables, after everything the
728
+ // executor owns, so a declared credential can never replace an executor key,
729
+ // a `worker_env` declaration, or the database destination. Absent or empty
730
+ // adds nothing and reports nothing.
731
+ if (options.declaredCredentialEnv !== undefined && Object.keys(options.declaredCredentialEnv).length > 0) {
732
+ const outcome = admitDeclaredCredentialEnv(env, options.declaredCredentialEnv);
733
+ options.onDeclaredCredentialEnv?.(outcome);
734
+ }
735
+ // Nothing agent-specific is added here, and nothing ambient or secret beyond
736
+ // the owner-approved sandbox credentials admitted above. An
659
737
  // adapter that needs to forward an operator-owned credential declares it as a
660
738
  // passthrough and copies it onto the object this function returns; see
661
739
  // `buildClaudeWorkerEnv`. Keeping the base free of every credential is what
662
740
  // makes "which secrets can reach a worker?" answerable per adapter instead of
663
741
  // 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";
742
+ // BAPI-1598 — no implicit `ENVIRONMENT`. A repository that needs one declares
743
+ // it in `worker_env` (bridge-api declares `ENVIRONMENT=LOCAL`).
669
744
  return env;
670
745
  }
671
746
  /**
@@ -0,0 +1,157 @@
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`, and the run id becomes `BRIDGE_EPIC_SERVER_RUN_ID`
15
+ * (what `sfcc-upload` addresses). No local state is read, and no sandbox id,
16
+ * credential, or credential reference reaches the worker.
17
+ * - Upload capability is separate from the browser target (BAPI-1669): a `local`
18
+ * context carries `sfccUpload: true` when the record also approves a sandbox.
19
+ * - no record, an unusable record, or `none`: disabled, even with an approved
20
+ * sandbox (its UI steps hand off; the driver still uploads). Nothing is injected,
21
+ * so the spawn environment, the prompt, and `.mcp.json` are byte-identical to
22
+ * a repository that never opted in.
23
+ *
24
+ * Every read is bounded and every failure is swallowed into `disabled` or
25
+ * `local_unavailable`. Nothing here can fail a job, write run state, add a gate,
26
+ * park a ticket, or block a spawn. The browser origin restriction itself is the
27
+ * `mcp-invoke` shim's, derived from `BRIDGE_EPIC_SERVER_URL`; it is not
28
+ * recomputed here.
29
+ */
30
+ import { lstat, readFile } from "node:fs/promises";
31
+ import os from "node:os";
32
+ import { readEpicServerRecord } from "../epic-server-record.js";
33
+ import { boundedResult, createDefaultEpicServerStateFs, findEpicServerRunPaths, isValidEpicRunId, readEpicServerLiveState, EPIC_SERVER_RUN_ID_ENV, EPIC_SERVER_URL_ENV, } from "../conductor/epic-server-state.js";
34
+ import { createDefaultEpicServerProcessDeps, readProcessStartTime } from "../conductor/epic-server-processes.js";
35
+ import { EPIC_SERVER_DEFAULT_TIMING } from "../conductor/epic-server-recipe.js";
36
+ import { SFCC_UPLOAD_WORKER_COMMAND_SECONDS } from "../conductor/epic-server-sfcc.js";
37
+ /** The whole optional read is bounded by this. */
38
+ export const EPIC_SERVER_CONTEXT_BUDGET_MS = 3_000;
39
+ /**
40
+ * The live-state read finishes this much before the whole budget, so a hung
41
+ * helper probe resolves "local, unavailable" (the record DID select local mode)
42
+ * instead of losing the race to the outer `disabled` timeout.
43
+ */
44
+ const LIVE_STATE_MARGIN_MS = 250;
45
+ export function createDefaultEpicServerContextDeps(env) {
46
+ const proc = createDefaultEpicServerProcessDeps();
47
+ return {
48
+ readRecord: (repoName) => readEpicServerRecord(repoName, { env, homedir: os.homedir, readFile: (p) => readFile(p, "utf8"), lstat: (p) => lstat(p) }),
49
+ homedir: os.homedir,
50
+ tmpdir: os.tmpdir,
51
+ fs: createDefaultEpicServerStateFs(),
52
+ identity: async (pid) => {
53
+ const startedAt = await readProcessStartTime(pid, proc);
54
+ return startedAt === null ? null : { startedAt };
55
+ },
56
+ };
57
+ }
58
+ async function readContext(repoName, epicRunId, deps, deadline) {
59
+ const record = await deps.readRecord(repoName);
60
+ if (record.state !== "ok")
61
+ return { kind: "disabled" };
62
+ const mode = record.record.mode;
63
+ if (mode === "none")
64
+ return { kind: "disabled" };
65
+ if (mode === "sfcc_shared_active") {
66
+ const origin = record.record.sfcc?.storefront_origin;
67
+ return typeof origin === "string" && origin.length > 0
68
+ ? { kind: "sfcc", origin, runId: isValidEpicRunId(epicRunId) ? epicRunId : null }
69
+ : { kind: "disabled" };
70
+ }
71
+ const sfccUpload = record.record.sfcc !== undefined ? { sfccUpload: true } : {};
72
+ if (!isValidEpicRunId(epicRunId))
73
+ return { kind: "disabled" };
74
+ const paths = await findEpicServerRunPaths(deps.homedir(), epicRunId, deps.fs, deps.tmpdir());
75
+ if (paths === null)
76
+ return { kind: "local_unavailable", runId: epicRunId, ...sfccUpload };
77
+ 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) });
78
+ return live.state === "live"
79
+ ? {
80
+ kind: "local_live",
81
+ url: live.value.url,
82
+ runId: epicRunId,
83
+ turnWaitSeconds: live.value.turn_wait_seconds,
84
+ turnBuildSeconds: live.value.turn_build_seconds,
85
+ ...sfccUpload,
86
+ }
87
+ : { kind: "local_unavailable", runId: epicRunId, ...sfccUpload };
88
+ }
89
+ /**
90
+ * Read the worker's epic-server context. Never throws and never exceeds the
91
+ * budget: a slow or failed local read degrades to `local_unavailable` only after
92
+ * the record selected local mode, and to `disabled` otherwise.
93
+ */
94
+ export async function readEpicServerWorkerContext(repoName, epicRunId, deps) {
95
+ if (typeof epicRunId !== "string" || epicRunId.length === 0)
96
+ return { kind: "disabled" };
97
+ const deadline = Date.now() + EPIC_SERVER_CONTEXT_BUDGET_MS;
98
+ const work = readContext(repoName, epicRunId, deps, deadline).catch(() => ({ kind: "disabled" }));
99
+ return boundedResult(work, EPIC_SERVER_CONTEXT_BUDGET_MS, { kind: "disabled" });
100
+ }
101
+ /**
102
+ * Claude Code caps a foreground Bash command at 600 s unless this names a higher
103
+ * ceiling (milliseconds). `turn acquire` can legitimately take longer: a worker
104
+ * queued behind a held lease waits, then gets its own rebuild budget.
105
+ */
106
+ export const EPIC_SERVER_BASH_MAX_TIMEOUT_ENV = "BASH_MAX_TIMEOUT_MS";
107
+ /** Slack the client allows past the queue wait and rebuild budget. */
108
+ const EPIC_SERVER_ACQUIRE_SLACK_SECONDS = 60;
109
+ /**
110
+ * The longest one `turn acquire` command can take before it prints, in seconds:
111
+ * the running helper's turn wait plus its rebuild budget, plus slack. A context
112
+ * with no live helper uses the default timing, which is what a helper that starts
113
+ * later is most likely to run with. The prompt states this number and the spawn
114
+ * env raises the harness ceiling to it, so the two always agree.
115
+ */
116
+ export function epicServerAcquireCommandSeconds(context) {
117
+ const timing = context.kind === "local_live"
118
+ ? { wait: context.turnWaitSeconds, build: context.turnBuildSeconds }
119
+ : { wait: EPIC_SERVER_DEFAULT_TIMING.acquire_wait_seconds, build: EPIC_SERVER_DEFAULT_TIMING.proof_seconds };
120
+ return timing.wait + timing.build + EPIC_SERVER_ACQUIRE_SLACK_SECONDS;
121
+ }
122
+ /**
123
+ * Inject the trusted epic-server keys AFTER the worker environment builder ran,
124
+ * like the job tag. Any ambient copy is removed first. Local contexts also raise
125
+ * the harness command ceiling to {@link epicServerAcquireCommandSeconds}. `disabled` returns the
126
+ * environment unchanged (the same object), so a repository without an opt-in is
127
+ * byte-identical.
128
+ */
129
+ export function withEpicServerEnv(env, context) {
130
+ if (context.kind === "disabled")
131
+ return env;
132
+ const next = { ...env };
133
+ delete next[EPIC_SERVER_URL_ENV];
134
+ delete next[EPIC_SERVER_RUN_ID_ENV];
135
+ if (context.kind === "local_live" || context.kind === "local_unavailable") {
136
+ if (context.kind === "local_live")
137
+ next[EPIC_SERVER_URL_ENV] = context.url;
138
+ next[EPIC_SERVER_RUN_ID_ENV] = context.runId;
139
+ // Raise only the ceiling, never the default: the prompt names an explicit
140
+ // timeout for `turn acquire`, and every other command keeps the harness
141
+ // default. A higher ceiling already in the env is kept.
142
+ // A local context with an approved sandbox also runs `sfcc-upload`: take the larger ceiling.
143
+ const needed = Math.max(epicServerAcquireCommandSeconds(context), context.sfccUpload === true ? SFCC_UPLOAD_WORKER_COMMAND_SECONDS : 0) * 1000;
144
+ const current = Number(next[EPIC_SERVER_BASH_MAX_TIMEOUT_ENV]);
145
+ next[EPIC_SERVER_BASH_MAX_TIMEOUT_ENV] = String(Number.isSafeInteger(current) && current > needed ? current : needed);
146
+ }
147
+ else {
148
+ next[EPIC_SERVER_URL_ENV] = context.origin;
149
+ if (context.runId !== null && isValidEpicRunId(context.runId))
150
+ next[EPIC_SERVER_RUN_ID_ENV] = context.runId;
151
+ // An upload can take up to the worker command ceiling; keep any higher value.
152
+ const needed = SFCC_UPLOAD_WORKER_COMMAND_SECONDS * 1000;
153
+ const current = Number(next[EPIC_SERVER_BASH_MAX_TIMEOUT_ENV]);
154
+ next[EPIC_SERVER_BASH_MAX_TIMEOUT_ENV] = String(Number.isSafeInteger(current) && current > needed ? current : needed);
155
+ }
156
+ return next;
157
+ }
@@ -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
  }
@@ -12,9 +12,14 @@ export function isSafePublicationBranch(branch) {
12
12
  /** No command text, remote URL, or environment escapes this closed outcome. */
13
13
  export async function guardedFastForwardPush(input) {
14
14
  const refuse = (reason) => ({ status: "refused", reason });
15
- if (!isSafePublicationBranch(input.branch) || !SHA.test(input.expectedOriginSha) ||
15
+ const creating = input.expectedOriginSha === null;
16
+ // Ordinary publication needs a remote SHA and no create-only input; create-only needs a local start SHA and no remote SHA.
17
+ const baseSha = creating ? input.createOnly?.startSha : input.expectedOriginSha;
18
+ if (!isSafePublicationBranch(input.branch) || baseSha === undefined || baseSha === null || !SHA.test(baseSha) ||
19
+ (creating ? input.createOnly === undefined : input.createOnly !== undefined) ||
16
20
  input.trustedExcludedShas?.some(sha => !SHA.test(sha)) ||
17
- (input.candidateSha !== undefined && (!SHA.test(input.candidateSha) || input.candidateSha === input.expectedOriginSha)))
21
+ (creating && input.candidateSha === undefined) ||
22
+ (input.candidateSha !== undefined && (!SHA.test(input.candidateSha) || input.candidateSha.toLowerCase() === baseSha.toLowerCase())))
18
23
  return refuse("invalid_input");
19
24
  let timedOut = false;
20
25
  const git = async (args) => {
@@ -36,10 +41,10 @@ export async function guardedFastForwardPush(input) {
36
41
  const candidate = head.stdout.trim().toLowerCase();
37
42
  if (head.exitCode !== 0 || !SHA.test(candidate))
38
43
  return refuse("ancestry_unknown");
39
- if (candidate === input.expectedOriginSha.toLowerCase() ||
44
+ if (candidate === baseSha.toLowerCase() ||
40
45
  (input.candidateSha !== undefined && candidate !== input.candidateSha.toLowerCase()))
41
46
  return refuse("invalid_input");
42
- const ancestor = await git(["merge-base", "--is-ancestor", input.expectedOriginSha, "HEAD"]);
47
+ const ancestor = await git(["merge-base", "--is-ancestor", baseSha, "HEAD"]);
43
48
  if (ancestor.exitCode === 1)
44
49
  return refuse("not_fast_forward");
45
50
  if (ancestor.exitCode !== 0)
@@ -49,7 +54,7 @@ export async function guardedFastForwardPush(input) {
49
54
  (await git(["merge-base", "--is-ancestor", sha, "HEAD"])).exitCode !== 0)
50
55
  return refuse("range_unreadable");
51
56
  }
52
- const range = await git(["rev-list", "HEAD", `^${input.expectedOriginSha}`, ...(input.trustedExcludedShas ?? []).map(sha => `^${sha}`)]);
57
+ const range = await git(["rev-list", "HEAD", `^${baseSha}`, ...(input.trustedExcludedShas ?? []).map(sha => `^${sha}`)]);
53
58
  const commits = range.stdout.trim().split(/\s+/);
54
59
  if (range.exitCode !== 0 || commits.length === 0 || commits.some(sha => !SHA.test(sha)))
55
60
  return refuse("range_unreadable");
@@ -105,7 +110,7 @@ export async function guardedFastForwardPush(input) {
105
110
  return refuse("timeout");
106
111
  const destination = `refs/heads/${input.branch}`;
107
112
  const push = await git(["push", "--no-verify", "--porcelain",
108
- `--force-with-lease=${destination}:${input.expectedOriginSha}`, "origin", `HEAD:${destination}`]);
113
+ `--force-with-lease=${destination}:${creating ? "" : baseSha}`, "origin", `HEAD:${destination}`]);
109
114
  const text = `${push.stdout}\n${push.stderr}`;
110
115
  if (timedOut || push.exitCode === 124 || /timed out|timeout/i.test(text))
111
116
  return refuse("timeout");
@@ -117,11 +122,11 @@ export async function guardedFastForwardPush(input) {
117
122
  return refuse("remote_rejected");
118
123
  const update = push.stdout.split("\n").some(line => {
119
124
  const parts = line.split("\t");
120
- return parts[0] === " " && parts[1] === `HEAD:${destination}`;
125
+ return parts[0] === (creating ? "*" : " ") && parts[1] === `HEAD:${destination}`;
121
126
  });
122
127
  if (!update)
123
128
  return refuse("lease_rejected");
124
- return { status: "published", from_sha: input.expectedOriginSha.toLowerCase(), to_sha: candidate };
129
+ return { status: "published", from_sha: baseSha.toLowerCase(), to_sha: candidate };
125
130
  }
126
131
  catch {
127
132
  return refuse(timedOut || input.remainingMs() <= 0 ? "timeout" : "remote_rejected");