@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
@@ -518,7 +518,7 @@ const MAX_HOLD_BLOCKERS_IN_MESSAGE = 8;
518
518
  * worker HEAD equal to it; and an origin tip equal to both. Anything less is not
519
519
  * server confirmation, and the caller falls through to its existing checks.
520
520
  */
521
- function confirmedDeliveryHold(delivery, workerHeadSha, originSha) {
521
+ function confirmedDeliveryState(delivery, workerHeadSha, originSha) {
522
522
  if (!delivery || delivery.bound !== true || delivery.unavailable === true)
523
523
  return null;
524
524
  if (typeof delivery.attemptId !== "string" || !delivery.attemptId)
@@ -537,6 +537,26 @@ function confirmedDeliveryHold(delivery, workerHeadSha, originSha) {
537
537
  blockers: (delivery.blockers ?? []).map((b) => typeof b.step_id === "number" ? { kind: b.kind, step_id: b.step_id } : { kind: b.kind }),
538
538
  };
539
539
  }
540
+ /**
541
+ * BAPI-1563: the hold the server confirmed for THIS head, or null. Only an actual
542
+ * server hold outcome (`blocked`, `verification_failed`, `evidence_missing_or_stale`)
543
+ * is a hold. `awaiting_post_pr` and `complete` PERMIT publication and success, so
544
+ * they are never translated into a required-check or required-work failure here;
545
+ * a missing pull request is judged separately by {@link confirmedAwaitingWithoutPr}.
546
+ */
547
+ function confirmedDeliveryHold(delivery, workerHeadSha, originSha) {
548
+ const state = confirmedDeliveryState(delivery, workerHeadSha, originSha);
549
+ return state !== null && DELIVERY_HOLD_OUTCOMES.has(state.outcome) ? state : null;
550
+ }
551
+ /**
552
+ * BAPI-1426: an `awaiting_post_pr` attempt confirmed at THIS head. Its remaining
553
+ * work needs a pull request, so it is a hold only while none is attached. This is
554
+ * about the missing PR, not about verification: with a PR it is a success path.
555
+ */
556
+ function confirmedAwaitingWithoutPr(delivery, workerHeadSha, originSha) {
557
+ const state = confirmedDeliveryState(delivery, workerHeadSha, originSha);
558
+ return state !== null && state.outcome === "awaiting_post_pr" ? state : null;
559
+ }
540
560
  /**
541
561
  * BAPI-1426: the intentional checkpoint a managed ticket ends with when the
542
562
  * server holds its delivery. This is a `/fail`, never a success, and it never
@@ -547,7 +567,7 @@ function confirmedDeliveryHold(delivery, workerHeadSha, originSha) {
547
567
  * The message carries only public identifiers, the closed outcome token, a
548
568
  * truncated head, and blocker kinds with step ids — never evidence text.
549
569
  */
550
- function deliveryHoldFailure(job, branch, hold) {
570
+ function deliveryHoldFailure(job, branch, hold, observedPr) {
551
571
  const label = job.ticket_key ? `${job.ticket_key} (job ${job.id})` : `job ${job.id}`;
552
572
  const shown = hold.blockers.slice(0, MAX_HOLD_BLOCKERS_IN_MESSAGE);
553
573
  const blockerText = shown.length
@@ -567,8 +587,19 @@ function deliveryHoldFailure(job, branch, hold) {
567
587
  classification: "clean_exit",
568
588
  last_commit_sha: hold.preserved_head_sha,
569
589
  telemetry,
590
+ // BAPI-1563: a hold still reports the pull request the executor discovered.
591
+ ...(observedPr ? { observed_pr: observedPr } : {}),
570
592
  };
571
593
  }
594
+ /** BAPI-1563: the discovered pull request as a wire fact, or undefined when not fully known. */
595
+ function observedPrOf(pr) {
596
+ if (!pr.found || typeof pr.prNumber !== "number" || !Number.isInteger(pr.prNumber) || pr.prNumber <= 0) {
597
+ return undefined;
598
+ }
599
+ if (pr.headRefOid === null || !FULL_SHA_RE.test(pr.headRefOid) || pr.baseRef === null)
600
+ return undefined;
601
+ return { number: pr.prNumber, head_sha: pr.headRefOid, base_ref: pr.baseRef };
602
+ }
572
603
  /**
573
604
  * BAPI-1426: the delivery hold a finalization failure carries, or null. Read
574
605
  * from the failure's own structured marker, never from its message.
@@ -747,11 +778,36 @@ export async function validateWorkerFinalization(input) {
747
778
  // is attached, and before the attachment contract can call it missing.
748
779
  // BAPI-1516: a `ci_fix` is never a delivery hold, even when an outcome reaches
749
780
  // this seam directly; its success rests on the attachment contract below.
750
- const hold = job.job_type === "ci_fix"
751
- ? undefined
752
- : confirmedDeliveryHold(input.deliveryOutcome, trimmedHeadSha, remoteSha);
753
- if (hold && DELIVERY_HOLD_OUTCOMES.has(hold.outcome)) {
754
- return { ok: false, failure: deliveryHoldFailure(job, trimmedBranch, hold) };
781
+ const observedPr = observedPrOf(pr);
782
+ if (observedPr && input.onObservedPr) {
783
+ try {
784
+ input.onObservedPr({ number: observedPr.number, headSha: observedPr.head_sha, baseRef: observedPr.base_ref });
785
+ }
786
+ catch {
787
+ /* observational only */
788
+ }
789
+ }
790
+ // BAPI-1563: the verdict acted on is a FRESH one, read after the final head is
791
+ // proven on origin and the PR has been discovered. A failed or absent refresh
792
+ // keeps the earlier read; it never invents a verdict.
793
+ let deliveryOutcome = input.deliveryOutcome;
794
+ if (job.job_type !== "ci_fix" && input.refreshDeliveryOutcome) {
795
+ try {
796
+ const fresh = await input.refreshDeliveryOutcome();
797
+ if (fresh !== undefined)
798
+ deliveryOutcome = fresh;
799
+ }
800
+ catch {
801
+ /* keep the earlier read */
802
+ }
803
+ }
804
+ const hold = job.job_type === "ci_fix" ? null : confirmedDeliveryHold(deliveryOutcome, trimmedHeadSha, remoteSha);
805
+ // BAPI-1590: a hold with an attached PR at exactly the proven origin tip is not a
806
+ // dead end. Fall through to the unchanged PR contract and let the server judge the
807
+ // report; a missing PR or a different PR head keeps the hold failure.
808
+ const heldAtMatchingPr = hold !== null && observedPr !== undefined && observedPr.head_sha.toLowerCase() === remoteSha.toLowerCase();
809
+ if (hold && !heldAtMatchingPr) {
810
+ return { ok: false, failure: deliveryHoldFailure(job, trimmedBranch, hold, observedPr) };
755
811
  }
756
812
  let contract = evaluatePrContract(pr, trimmedHeadSha, covered);
757
813
  for (let attempt = 1; attempt < attempts && !contract.ok && contract.retryable; attempt++) {
@@ -761,12 +817,13 @@ export async function validateWorkerFinalization(input) {
761
817
  }
762
818
  // BAPI-1426: post-PR work needs a pull request. While neither the provider nor
763
819
  // the server shows one, a confirmed `awaiting_post_pr` attempt is a hold too.
820
+ const awaitingHold = job.job_type === "ci_fix" ? null : confirmedAwaitingWithoutPr(deliveryOutcome, trimmedHeadSha, remoteSha);
764
821
  if (!contract.ok &&
765
822
  contract.unverified !== true &&
766
823
  !pr.found &&
767
- hold?.outcome === "awaiting_post_pr" &&
768
- input.deliveryOutcome?.prNumber == null) {
769
- return { ok: false, failure: deliveryHoldFailure(job, trimmedBranch, hold) };
824
+ awaitingHold !== null &&
825
+ deliveryOutcome?.prNumber == null) {
826
+ return { ok: false, failure: deliveryHoldFailure(job, trimmedBranch, awaitingHold) };
770
827
  }
771
828
  if (!contract.ok && contract.unverified === true) {
772
829
  return {
@@ -784,6 +841,10 @@ export async function validateWorkerFinalization(input) {
784
841
  ok: true,
785
842
  prUrl: pr.url ?? undefined,
786
843
  prNumber: pr.prNumber,
844
+ // Only when a fresh assessment was requested, so the legacy success shape is unchanged.
845
+ ...(input.refreshDeliveryOutcome !== undefined && deliveryOutcome !== undefined ? { deliveryOutcome } : {}),
846
+ // BAPI-1590: only after the PR contract above succeeded for the hold let through.
847
+ ...(heldAtMatchingPr && hold ? { heldAtOpenPr: hold } : {}),
787
848
  // BAPI-1311: the verified origin tip — proven equal to the worker's HEAD above
788
849
  // whenever that HEAD was known. Only for a caller that asked for it.
789
850
  ...(input.exposePushedHead === true ? { pushedHeadSha: remoteSha } : {}),
@@ -111,6 +111,12 @@ export function renderWorkerGuardReason(category, family, form) {
111
111
  "made outside the worker. Do not run regenerate-plan or call its route; record the " +
112
112
  "step escalated with its reason and continue.");
113
113
  }
114
+ if (category === "operator-verb" && family === "acknowledge-gaps") {
115
+ return (`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). ` +
116
+ "Acknowledging the run's carried-gap list is the run owner's decision, made " +
117
+ "outside the worker. Do not run acknowledge-gaps or call its route; record what " +
118
+ "you could not verify in your phase result and continue.");
119
+ }
114
120
  if (category === "operator-verb") {
115
121
  return (`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). ` +
116
122
  "Resolving a verification hand-off is the run owner's decision, made outside the " +
@@ -1012,9 +1018,11 @@ function isClaudeWorkflowPrintLaunch(segment) {
1012
1018
  /**
1013
1019
  * The operator-only subcommands a worker may never run, and their route segments.
1014
1020
  * BAPI-1532 adds `regenerate-plan` beside `resolve-handoff`, with its own family so
1015
- * the denial names the verb that was attempted.
1021
+ * the denial names the verb that was attempted. BAPI-1562 adds `acknowledge-gaps`,
1022
+ * the owner's one acknowledgement of the run's carried-gap list (route segment
1023
+ * `/acknowledge-gaps`), the same way.
1016
1024
  */
1017
- const OPERATOR_ONLY_VERBS = ["resolve-handoff", "regenerate-plan"];
1025
+ const OPERATOR_ONLY_VERBS = ["resolve-handoff", "regenerate-plan", "acknowledge-gaps"];
1018
1026
  /** The packaged MCP-server package token after `npx` (any version suffix). */
1019
1027
  const BRIDGE_PACKAGE_TOKEN = /^@bridge_gpt\/mcp-server(?:@\S+)?$/;
1020
1028
  /** Package runners whose package argument launches the packaged CLI. */
@@ -19,6 +19,10 @@ import { resolveExecutorStateDir } from "./job-log-registry.js";
19
19
  import { hostIdentityDigest } from "./process-containment.js";
20
20
  import { createDefaultWorkerCliLauncherDeps, createWorkerCliLauncher, } from "./worker-cli-launcher.js";
21
21
  import { createDefaultWorkerDatabaseDeps, dropWorkerDatabase, provisionWorkerDatabase, sweepOrphanedWorkerDatabases, } from "./worker-database.js";
22
+ /** Retain reasons that mean an executor-owned database may still exist. */
23
+ const OWNED_RETAIN_REASONS = new Set([
24
+ "owner_alive", "owner_unknown", "ownership_changed", "drop_failed",
25
+ ]);
22
26
  /**
23
27
  * The production worker resources, bound to this executor process: its pid, its
24
28
  * host identity, its state directory, and the operator checkout it runs from
@@ -35,12 +39,13 @@ export function createProductionWorkerResources(input) {
35
39
  // Built lazily, once: constructing the deps touches nothing, but there is no
36
40
  // reason to do even that for an executor that never claims a worker job.
37
41
  let databaseDeps;
38
- const dbDeps = () => (databaseDeps ??= createDefaultWorkerDatabaseDeps({ stateDir, env: input.env }));
42
+ const dbDeps = () => (databaseDeps ??= input.databaseDeps ?? createDefaultWorkerDatabaseDeps({ stateDir, env: input.env }));
39
43
  let launcherDeps;
40
44
  const cliDeps = () => (launcherDeps ??= createDefaultWorkerCliLauncherDeps({ stateDir }));
41
45
  return {
42
46
  provisionDatabase: (request) => provisionWorkerDatabase({
43
47
  jobId: request.jobId,
48
+ config: request.config,
44
49
  operatorRepositoryRoot: input.cwd,
45
50
  worktreePath: request.worktreePath,
46
51
  executorPid,
@@ -51,8 +56,25 @@ export function createProductionWorkerResources(input) {
51
56
  ? { workerEnv: request.workerEnv }
52
57
  : {}),
53
58
  }, dbDeps()),
54
- dropDatabase: (target) => dropWorkerDatabase(target, dbDeps()),
59
+ dropDatabase: (target, role) => dropWorkerDatabase(target, dbDeps(), { role }),
55
60
  createLauncher: ({ jobId }) => createWorkerCliLauncher({ jobId }, cliDeps()),
56
- sweepOrphanedDatabases: (signal) => sweepOrphanedWorkerDatabases({ hostDigest, executorPid, signal }, dbDeps()),
61
+ sweepOrphanedDatabases: async (signal) => {
62
+ const deps = dbDeps();
63
+ // The marker is the only thing that justifies a Postgres connection at
64
+ // startup. Absent: this host never provisioned, so there is nothing to sweep.
65
+ // Unreadable: the answer is unknown, so nothing is swept and the marker stays.
66
+ const marker = (await deps.hostState?.read()) ?? { state: "absent" };
67
+ if (marker.state === "absent")
68
+ return { kind: "completed", dropped: [], retained: [] };
69
+ if (marker.state === "unreadable")
70
+ return { kind: "unavailable", category: "boundary_unknown" };
71
+ const result = await sweepOrphanedWorkerDatabases({ role: marker.role, hostDigest, executorPid, signal }, deps);
72
+ // Clear only once the sweep proves no owned database remains. A foreign,
73
+ // comment-less, or malformed database is not ours and does not hold the marker.
74
+ if (result.kind === "completed" && !result.retained.some((entry) => OWNED_RETAIN_REASONS.has(entry.reason))) {
75
+ await deps.hostState?.clear().catch(() => undefined);
76
+ }
77
+ return result;
78
+ },
57
79
  };
58
80
  }
@@ -1,5 +1,37 @@
1
1
  /** Agent-neutral trusted starter context, appended after payload interpolation. */
2
2
  import { MCP_PACKAGE_NAME } from "../mcp-identity.js";
3
+ import { EPIC_WORKAROUNDS_DIR } from "../epic-workarounds-path.js";
4
+ /**
5
+ * BAPI-1552: the `preexisting_at_base` exception, shared by the launch
6
+ * instruction and the continuation test-invocation guidance so they cannot drift.
7
+ * Added only when the run allows hand-offs. SINGLE-LINE and free of semicolons,
8
+ * quote characters, and apostrophes, because it travels in the launch prompt.
9
+ * It names no repository path beyond the paired workaround record.
10
+ *
11
+ * The order matters. The paired record is committed first, so the failing step is
12
+ * rerun and the base reproduction collected at the final committed head, which is
13
+ * the head the phase result is recorded at. The base SHA is the merge-base of
14
+ * that head and the base branch, which is what the server re-checks against the
15
+ * provider. The worker owns the temporary worktree from creation to removal.
16
+ */
17
+ export function renderPreexistingAtBaseGuidance(record) {
18
+ const path = record ?? `${EPIC_WORKAROUNDS_DIR}<TICKET>.md`;
19
+ return ("One exception, for a pre-existing failure: when a required test step ran and failed, do this " +
20
+ "before recording anything. Commit the paired workaround record " + path + " first, then rerun the " +
21
+ "failing step at that final committed head. Run git merge-base HEAD origin/ joined with the base " +
22
+ "branch name, alone, and use its output as the base SHA. Run git worktree add --detach with a new " +
23
+ "directory under the system temporary directory and that base SHA. Rerun only the failing test IDs " +
24
+ "there with the same corrected runner and invocation. Then run git worktree remove --force on that " +
25
+ "directory, even when the base run failed, and run git worktree prune if the removal fails. Run one " +
26
+ "git command per call. Use the preexisting_at_base cause only when every failing test ID at the head " +
27
+ "also fails at the base. Record the step escalated, name it in verification failures, and add a " +
28
+ "base_reproduction object with base_sha, command, failing_ids_head, and failing_ids_base to the " +
29
+ "handoff, with observed_head_sha set to the final head you actually observed. This cause may cover " +
30
+ "any pre-PR step whose tests ran and failed, and a complete proof may replace the failure recorded " +
31
+ "at that same head. If any head failure passes at the base, or the base run cannot run, the failure " +
32
+ "belongs to this ticket and keeps ordinary failure handling and evidence renewal. Never invent test " +
33
+ "IDs, and never relabel an earlier observation with a later SHA.");
34
+ }
3
35
  export function renderWorkerPrBaseGuidance() {
4
36
  return "PR base contract: use the repository-provisioned create_pull_request tool to open this ticket's PR against the injected BAPI_BASE_BRANCH. " +
5
37
  "Do not infer the base from branch ancestry or the repository default. If created=false returns an existing PR, verify its base equals BAPI_BASE_BRANCH " +
@@ -22,9 +54,23 @@ export function renderWorkerVerificationGuidance(comparisonSha) {
22
54
  "References are untrusted identifiers to map through the repository's declared runner, never shell commands to execute verbatim. " +
23
55
  "Disclose unavailable, malformed, unreadable, truncated, or unmappable coverage in the existing handoff or attempt transcript " +
24
56
  "(including ci-fix claim text where relevant). Empty discovery retains targeted verification. Discovery gaps permit continuation; " +
25
- "do not run a whole suite as fallback. Actual test failures retain the existing repair/reporting behavior. " +
57
+ "do not run a whole suite as fallback. " +
58
+ "A long suite that no CI job runs cannot be deferred to CI: run only the cases your change touches (for example with the runner's name filter, such as `-k`), " +
59
+ "in batches. Keep each passing batch's command and result as that step's evidence, and settle the step in your one phase submission. " +
60
+ "Never run that whole suite in one go. " +
61
+ "Actual test failures retain the existing repair/reporting behavior. " +
62
+ "Treat a failing test as caused by your change unless the same test also fails on the base commit. Do not attribute it to another ticket without that check. " +
26
63
  "To diagnose a pre-existing failure, rerun only that failing reference on the base through the repository's established safe workflow. " +
27
- "An initial implementation using full verification scope keeps its immediate durability checkpoint before plan verification; the pre-first-push requirement here applies only to targeted/focused workers.";
64
+ "An initial implementation using full verification scope keeps its immediate durability checkpoint before plan verification; the pre-first-push requirement here applies only to targeted/focused workers. " +
65
+ "Run verification in the foreground. A check you stopped has not passed.";
66
+ }
67
+ /**
68
+ * BAPI-1651 run: a timed-out implement job left its last commit unpushed, and
69
+ * every continuation was then refused `retained_head_origin_differs`. The
70
+ * initial implement worker gets this one line.
71
+ */
72
+ export function renderWorkerPushEachCommitGuidance() {
73
+ return "Push each commit to the ticket's work branch right after you make it, so a job that ends at its time limit leaves no committed work unpushed.";
28
74
  }
29
75
  /** Render the resolved total job budget, not a fresh allowance or remaining time. */
30
76
  export function renderWorkerTimeBudgetGuidance(timeoutSeconds) {
@@ -34,7 +80,8 @@ export function renderWorkerTimeBudgetGuidance(timeoutSeconds) {
34
80
  return "## TIME BUDGET ##\n" + budget + " " +
35
81
  "Preparation and executor work consume this same total budget; this is not a fresh worker allowance or measured remaining time. " +
36
82
  "Local verification must leave room for commit, push, the single renewal pass, and `.conductor/result.json`. " +
37
- "Do not start a verification command that cannot finish within the remaining budget.";
83
+ "Do not start a verification command that cannot finish within the remaining budget. " +
84
+ "Prefer foreground verification. Stopping a task does not make its check pass.";
38
85
  }
39
86
  /**
40
87
  * BAPI-1533: the compact test-invocation rule a PUSHING continuation worker gets
@@ -50,7 +97,10 @@ export function renderWorkerTimeBudgetGuidance(timeoutSeconds) {
50
97
  * AC-7 acceptance needs the second release's deployed server, published MCP
51
98
  * package, and rebuilt executors. There is no runtime version gate.
52
99
  */
53
- export function renderWorkerTestInvocationGuidance() {
100
+ export function renderWorkerTestInvocationGuidance(handoffEnabled) {
101
+ // BAPI-1552: the pre-existing failure exception, only when the run allows
102
+ // hand-offs. Without it the text is exactly the BAPI-1533 rule.
103
+ const preexisting = handoffEnabled === true ? " " + renderPreexistingAtBaseGuidance() : "";
54
104
  return ("Test invocation rule: a requested test selector that collects zero tests is an invocation error, " +
55
105
  "never a pass and never proof of a missing capability. Rerun every affected test-running step from the " +
56
106
  "repository root with the repository's declared runner, and record the exact command and its output as " +
@@ -63,7 +113,7 @@ export function renderWorkerTestInvocationGuidance() {
63
113
  "SHA both ran against, and that SHA must equal the head the phase result is recorded at. A hand-off " +
64
114
  "counts only at the head it observed, so a step that failed at one head can be handed off only from a " +
65
115
  "new head. Failed assertions, application errors, unfinished work, and unclear failures keep their " +
66
- "existing blocker or escalation handling.");
116
+ "existing blocker or escalation handling." + preexisting);
67
117
  }
68
118
  export function renderWorkerPushAndCommitGuidance(rebase = false) {
69
119
  return "\n\n## PUSH AND COMMIT PROCEDURE ##\n" +
@@ -9,6 +9,48 @@
9
9
  */
10
10
  import path from "node:path";
11
11
  import { BranchMismatch, ExecutorNamedError } from "./job-errors.js";
12
+ /** Parse --porcelain -z without trimming paths or interpreting Git quoting. */
13
+ export function parseGitWorktreePorcelainZ(output) {
14
+ const result = [];
15
+ let current;
16
+ for (const field of output.split("\0")) {
17
+ if (field.startsWith("worktree ")) {
18
+ if (current)
19
+ result.push(current);
20
+ current = { path: field.slice(9), detached: false, bare: false };
21
+ }
22
+ else if (current) {
23
+ if (field.startsWith("HEAD "))
24
+ current.head = field.slice(5);
25
+ else if (field.startsWith("branch ")) {
26
+ current.branchRef = field.slice(7);
27
+ current.branch = current.branchRef.replace(/^refs\/heads\//, "");
28
+ }
29
+ else if (field === "detached")
30
+ current.detached = true;
31
+ else if (field === "bare")
32
+ current.bare = true;
33
+ else if (field === "locked" || field.startsWith("locked "))
34
+ current.locked = field.slice(7) || "locked";
35
+ else if (field === "prunable" || field.startsWith("prunable "))
36
+ current.prunable = field.slice(9) || "prunable";
37
+ }
38
+ }
39
+ if (current)
40
+ result.push(current);
41
+ return result;
42
+ }
43
+ export async function observeGitWorktrees(run, cwd) {
44
+ try {
45
+ const result = await run("git", ["worktree", "list", "--porcelain", "-z"], { cwd });
46
+ if (result.exitCode !== 0 || !result.stdout.startsWith("worktree ") || !result.stdout.endsWith("\0"))
47
+ return { state: "unavailable" };
48
+ return { state: "observed", value: parseGitWorktreePorcelainZ(result.stdout) };
49
+ }
50
+ catch {
51
+ return { state: "unavailable" };
52
+ }
53
+ }
12
54
  /** Return the Node `path` API matching a platform (`win32` vs POSIX). */
13
55
  export function pathApiForExecutorPlatform(platform) {
14
56
  return platform === "win32" ? path.win32 : path.posix;
@@ -62,7 +62,7 @@ export async function configureExecutorBranch(worktreePath, branch, deps) {
62
62
  (pushUrls.length === 1 && pushUrls[0] !== urls[0]))
63
63
  return failure;
64
64
  for (const [key, value] of [[`branch.${branch}.remote`, "origin"], [`branch.${branch}.merge`, `refs/heads/${branch}`]]) {
65
- if ((await deps.runCommand("git", ["config", "--local", key, value], { cwd: worktreePath })).exitCode !== 0)
65
+ if (!await writeLocalConfigWithLockRetry(worktreePath, key, value, deps))
66
66
  return failure;
67
67
  }
68
68
  return null;
@@ -71,6 +71,25 @@ export async function configureExecutorBranch(worktreePath, branch, deps) {
71
71
  return failure;
72
72
  }
73
73
  }
74
+ /** Total attempts for one `git config --local` write that hits git's config lock. */
75
+ export const CONFIG_LOCK_WRITE_ATTEMPTS = 4;
76
+ /**
77
+ * Write one local config value. Executors that claim jobs in the same second
78
+ * share one `.git/config`, so git can refuse a write with "could not lock config
79
+ * file". Only that failure is retried, a bounded number of times, after a short
80
+ * random delay. Any other failure returns false at once.
81
+ */
82
+ async function writeLocalConfigWithLockRetry(worktreePath, key, value, deps) {
83
+ for (let attempt = 1;; attempt += 1) {
84
+ const result = await deps.runCommand("git", ["config", "--local", key, value], { cwd: worktreePath });
85
+ if (result.exitCode === 0)
86
+ return true;
87
+ const lockFailure = /could not lock config file/i.test(result.stderr ?? "");
88
+ if (!lockFailure || attempt >= CONFIG_LOCK_WRITE_ATTEMPTS)
89
+ return false;
90
+ await deps.sleep(50 + Math.floor(Math.random() * 200));
91
+ }
92
+ }
74
93
  /**
75
94
  * BAPI-941: emit the per-spawn `claude-review` workflow-drift advisory for an
76
95
  * executor worker. Returns `void` and swallows everything — a diagnostic that
@@ -43,6 +43,7 @@
43
43
  * that executor instance's own heartbeat is fresh. Anything short of that and
44
44
  * uncertain is refused rather than signalled or duplicated.
45
45
  */
46
+ import { PARALLEL_LIMIT_CHANGE_ADVISORY } from "./conductor/launch-plan.js";
46
47
  import { spawn as nodeSpawn } from "node:child_process";
47
48
  import { mkdir, open, readFile, stat, unlink } from "node:fs/promises";
48
49
  import os from "node:os";
@@ -228,6 +229,9 @@ export function runExecutorArgs(args) {
228
229
  "--executor-id",
229
230
  args.executorId,
230
231
  "--exit-when-run-terminal",
232
+ ...(args.maxConcurrent !== undefined && args.maxConcurrent > 1
233
+ ? ["--max-concurrent", String(args.maxConcurrent)]
234
+ : []),
231
235
  ];
232
236
  }
233
237
  /**
@@ -289,6 +293,15 @@ export function parseRunExecutorRecord(raw) {
289
293
  }
290
294
  if (!isValidExecutorEpicRunId(r.epicRunId))
291
295
  return null;
296
+ // BAPI-1581 — absent reads as 1; a present value must be the positive integer
297
+ // the executor's own `--max-concurrent` accepts, else the record is untrusted.
298
+ let maxConcurrent = 1;
299
+ if (r.maxConcurrent !== undefined) {
300
+ if (typeof r.maxConcurrent !== "number" || !Number.isInteger(r.maxConcurrent) || r.maxConcurrent < 1) {
301
+ return null;
302
+ }
303
+ maxConcurrent = r.maxConcurrent;
304
+ }
292
305
  return {
293
306
  version: RUN_EXECUTOR_RECORD_VERSION,
294
307
  pid: r.pid,
@@ -297,8 +310,25 @@ export function parseRunExecutorRecord(raw) {
297
310
  baseUrl: r.baseUrl,
298
311
  startedAt: r.startedAt,
299
312
  logPath: r.logPath,
313
+ maxConcurrent,
300
314
  };
301
315
  }
316
+ /**
317
+ * BAPI-1581 — explain a reused executor whose capacity differs from the run's
318
+ * stored limit. Returns `undefined` when they match or no limit was requested.
319
+ * Never an action: a running executor is not stopped, resized, or restarted.
320
+ */
321
+ export function describeReusedExecutorCapacity(actual, requested) {
322
+ if (requested === undefined || requested === actual)
323
+ return undefined;
324
+ if (actual < requested) {
325
+ return (`The reused executor serves ${actual} job${actual === 1 ? "" : "s"} at a time while the run limit is ` +
326
+ `${requested}. ${PARALLEL_LIMIT_CHANGE_ADVISORY} To get higher local capacity, stop this executor ` +
327
+ "and run drive-epic again.");
328
+ }
329
+ return (`The reused executor can serve ${actual} jobs at a time while the run limit is ${requested}; ` +
330
+ "the queue admits only the run limit, so the extra slots stay idle.");
331
+ }
302
332
  /**
303
333
  * Is the recorded pid still THIS executor?
304
334
  *
@@ -497,6 +527,7 @@ export async function ensureRunExecutor(args, deps) {
497
527
  epicRunId,
498
528
  baseUrl: access.baseUrl,
499
529
  executorId,
530
+ ...(args.maxConcurrent !== undefined ? { maxConcurrent: args.maxConcurrent } : {}),
500
531
  });
501
532
  const fail = (reason, message, executorMayBeRunning = false) => ({
502
533
  ok: false,
@@ -563,6 +594,10 @@ export async function ensureRunExecutor(args, deps) {
563
594
  pid: existing.pid,
564
595
  logPath: existing.logPath,
565
596
  recordPath: paths.record,
597
+ ...((existing.maxConcurrent ?? 1) > 1 ? { maxConcurrent: existing.maxConcurrent } : {}),
598
+ ...(describeReusedExecutorCapacity(existing.maxConcurrent ?? 1, args.maxConcurrent) !== undefined
599
+ ? { capacityNotice: describeReusedExecutorCapacity(existing.maxConcurrent ?? 1, args.maxConcurrent) }
600
+ : {}),
566
601
  };
567
602
  }
568
603
  return fail("existing-executor-unconfirmed", `an executor for run ${epicRunId} is already running (pid ${existing.pid}), but its ` +
@@ -606,7 +641,13 @@ export async function ensureRunExecutor(args, deps) {
606
641
  paths.log,
607
642
  deps.nodeExecutable,
608
643
  prepared.entrypoint,
609
- ...runExecutorArgs({ repoName, epicRunId, baseUrl: access.baseUrl, executorId }),
644
+ ...runExecutorArgs({
645
+ repoName,
646
+ epicRunId,
647
+ baseUrl: access.baseUrl,
648
+ executorId,
649
+ ...(args.maxConcurrent !== undefined ? { maxConcurrent: args.maxConcurrent } : {}),
650
+ }),
610
651
  ], { cwd: prepared.repoRoot, env: childEnv, detached: true });
611
652
  }
612
653
  catch {
@@ -627,6 +668,9 @@ export async function ensureRunExecutor(args, deps) {
627
668
  baseUrl: access.baseUrl,
628
669
  startedAt: new Date(spawnedAtMs).toISOString(),
629
670
  logPath: paths.log,
671
+ // BAPI-1581 — the actual capacity of the process just spawned; omitted at 1,
672
+ // which an absent key already means, so a legacy record stays byte-identical.
673
+ ...(args.maxConcurrent !== undefined && args.maxConcurrent > 1 ? { maxConcurrent: args.maxConcurrent } : {}),
630
674
  };
631
675
  try {
632
676
  await deps.writeFile(paths.record, `${JSON.stringify(record, null, 2)}\n`);
@@ -651,7 +695,15 @@ export async function ensureRunExecutor(args, deps) {
651
695
  ? `the executor (pid ${pid}) exited before it sent a heartbeat`
652
696
  : `no heartbeat from the executor (pid ${pid}) arrived within ${timeoutSeconds}s`, !exited);
653
697
  }
654
- return { ok: true, outcome: "started", executorId, pid, logPath: paths.log, recordPath: paths.record };
698
+ return {
699
+ ok: true,
700
+ outcome: "started",
701
+ executorId,
702
+ pid,
703
+ logPath: paths.log,
704
+ recordPath: paths.record,
705
+ ...((record.maxConcurrent ?? 1) > 1 ? { maxConcurrent: record.maxConcurrent } : {}),
706
+ };
655
707
  }
656
708
  finally {
657
709
  try {
@@ -1,7 +1,7 @@
1
1
  import { COMMANDS } from "./commands.generated.js";
2
2
  import { AGENTS } from "./agents.generated.js";
3
3
  import { DOCS, DOC_METADATA } from "./docs.generated.js";
4
- import { renderCommandForHost } from "./command-host.js";
4
+ import { renderCommandForHost, stripClaudeOnlyFrontmatter } from "./command-host.js";
5
5
  import { codexSkillAssets } from "./codex-skill-adapter.js";
6
6
  import { reconstructAgentMarkdown, translateAgentToCopilot, translateCommandToCopilot } from "./agent-utils.js";
7
7
  export const WORKFLOW_HOSTS = ["claude", "cursor", "codex", "copilot"];
@@ -23,7 +23,7 @@ export function buildPackagedAssetCatalog() {
23
23
  try {
24
24
  add(`.claude/commands/${filename}`, renderCommandForHost(filename, content, "claude-code"), "command", ["claude"], [workflow]);
25
25
  add(`.cursor/commands/${filename}`, renderCommandForHost(filename, content, "cursor"), "command", ["cursor"], [workflow]);
26
- const copilot = translateCommandToCopilot(filename, content);
26
+ const copilot = translateCommandToCopilot(filename, stripClaudeOnlyFrontmatter(content));
27
27
  add(`.github/prompts/${workflow}.prompt.md`, copilot.prompt, "prompt", ["copilot"], [workflow]);
28
28
  add(`.github/skills/${workflow}/SKILL.md`, copilot.skill, "skill", ["copilot"], [workflow]);
29
29
  }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Read-only GitHub CLI sign-in check (BAPI-1461), shared by `install conductor`
2
+ * Read-only GitHub CLI sign-in check (BAPI-1461), shared by `install epic-implementer`
3
3
  * and `doctor`.
4
4
  *
5
5
  * It runs exactly one command, `gh auth status`, bounded to ten seconds with