@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
@@ -69,7 +69,7 @@ export function getConductorUsage() {
69
69
  "Local append-only event ledger for multi-agent coordination, plus run-control",
70
70
  "commands. The ledger commands talk ONLY to the local SQLite store",
71
71
  "(~/.config/bridge/events.db); the run-control commands (stop-run through",
72
- "resolve-handoff), epic-status, readiness, and the read-only wait-run call the Bridge API.",
72
+ "acknowledge-gaps), epic-status, readiness, and the read-only wait-run call the Bridge API.",
73
73
  "",
74
74
  "Commands:",
75
75
  " emit-event Append one semantic event to the ledger",
@@ -86,6 +86,7 @@ export function getConductorUsage() {
86
86
  " Remediations are NOT run automatically; always exits 0.",
87
87
  " purge Delete ALL ledger rows (events, messages, supervisor_projection)",
88
88
  " install-git-hooks Install local, opportunistic, non-blocking git hooks",
89
+ " uninstall-git-hooks Remove Bridge-managed hook text [--dry-run]",
89
90
  " git-hook post-commit Run the post-commit producer (invoked by the installed hook)",
90
91
  " git-hook reference-transaction --phase <p> --stdin-file <f>",
91
92
  " Run the reference-transaction producer (invoked by the hook)",
@@ -144,10 +145,50 @@ export function getConductorUsage() {
144
145
  " Record the OWNER's decision on verification hand-offs (a human decision,",
145
146
  " never automatic). Also remove .bridge/epic-workarounds/<KEY>.md in a new",
146
147
  " epic-head commit: the PR leaves draft only when both holds are clear.",
147
- " wait-run --epic-run-id <id> [--ticket-key <key>] [--since <token>] [--timeout <seconds>] [--json]",
148
+ " acknowledge-gaps --epic-run-id <id> --digest <CURRENT_DIGEST> --reason <text> [--json]",
149
+ " The OWNER's one acknowledgement of the run's carried-gap list, by its",
150
+ " current digest (from the PR report or explain-run). Never run by the",
151
+ " driver or a worker; it verifies, readies and merges nothing.",
152
+ " wait-run --epic-run-id <id> [--ticket-key <key>] [--since <token>] [--timeout <seconds>]",
153
+ " [--until change|attention] [--json] [--watch [--max-minutes <minutes>]]",
148
154
  " Read-only: wait until the run's observable state changes, the run finishes,",
149
155
  " or the window closes (default 110 s; values above 240 are clamped to 240).",
156
+ " --until attention wakes only when a new incident appears (a park, a",
157
+ " needs-human reason, a failed job, a paused/stopped or non-active run).",
158
+ " --watch repeats attention windows under one deadline (--max-minutes,",
159
+ " default 20, at most 60) and prints one result.",
150
160
  " Pass the previous result's token as --since. Changes nothing.",
161
+ " epic-server prove|start --epic <KEY> --epic-run-id <id> --head <SHA>",
162
+ " epic-server status [--epic-run-id <id> [--since <seq>]]",
163
+ " epic-server stop --expect-epic-run-id <id>",
164
+ " The run's one epic server for UI checks (opt-in per repository at setup).",
165
+ " The driver proves the run recipe, starts the detached helper, reads its",
166
+ " journal, and stops ONLY this run's own helper (ownership-verified).",
167
+ " epic-server turn acquire --ticket <KEY> --head <SHA> --wait <seconds>",
168
+ " epic-server turn release --lease <handle>",
169
+ " A worker borrows the epic server at its own head for a bounded turn, then",
170
+ " releases it with the lease handle acquire printed. A timeout or a missing",
171
+ " server prints a no_live_server observation for the hand-off; nothing parks.",
172
+ " prerequisite-inputs --epic-key <KEY> --child <KEY> [--child <KEY> ...] [--json]",
173
+ " Reads stored ticket descriptions and reports, per child, cached, in_flight,",
174
+ " scan_needed (with a private scanner input file under",
175
+ " ~/.local/state/bapi-conductor-runs/<EPIC>/), or a closed failure.",
176
+ " Changes nothing on the server.",
177
+ " prerequisite-inputs --record --epic-key <KEY> --child <KEY> --input-hash <SHA256> --claim-id <ID> [--json]",
178
+ " Fully local: records a scanner result read from stdin (never argv).",
179
+ " driver-register --epic-run-id <id> [--json]",
180
+ " Arm the /drive-epic-run Stop-hook guard for this Claude Code session and",
181
+ " print the exact background waiter. Outside Claude Code it arms nothing.",
182
+ " driver-release --reason owner|done|handoff --epic-run-id <id>",
183
+ " Release this session from supervision: done (run terminal) and handoff",
184
+ " (report published) are checked on the server; owner only on the owner's",
185
+ " explicit instruction. Changes nothing on the run.",
186
+ " driver-guard The /drive-epic-run Stop hook. Reads hook JSON on stdin, decides locally",
187
+ " with no network call, always exits 0. Off switch: BRIDGE_EI_DRIVER_GUARD=off.",
188
+ " declare-blocked --epic-run-id <id> --ticket-key <K>... --entry 1|2|3|4|5|wedge --requirement <text>",
189
+ " [--evidence <text>] [--tried <verbs>] [--alternatives <text>] [--fixer-outcome <text>]",
190
+ " Advisory blocker check: not a blocker yet (run <command>), accepted and",
191
+ " escalated, run-wide blocked, or scope unknown. Never releases supervision.",
151
192
  "",
152
193
  "supervise options:",
153
194
  " --run-id <id> Run/session identifier to supervise (required)",
@@ -249,7 +290,9 @@ export function getConductorUsage() {
249
290
  " --help Print this usage message",
250
291
  "",
251
292
  "epic-status options:",
252
- " --epic-key <KEY> Epic key to fetch the snapshot for (required)",
293
+ " --epic-key <KEY> Epic key to fetch the snapshot for",
294
+ " --epic-run-id <id> Epic run identifier, as the other run commands take it",
295
+ " (pass exactly one of --epic-key or --epic-run-id)",
253
296
  " --json Print compact JSON result",
254
297
  " --help Print this usage message",
255
298
  "",
@@ -258,6 +301,7 @@ export function getConductorUsage() {
258
301
  " epic-implementer approve-plan EPIC-405 --plan-version 2 --json",
259
302
  " epic-implementer epic-status --epic-key EPIC-405",
260
303
  " epic-implementer epic-status --epic-key EPIC-405 --json",
304
+ " epic-implementer epic-status --epic-run-id <id>",
261
305
  "",
262
306
  "stop-run / abandon-run options:",
263
307
  " --epic-run-id <id> Epic run identifier (required)",
@@ -342,6 +386,7 @@ const VALID_COMMANDS = new Set([
342
386
  "readiness",
343
387
  "purge",
344
388
  "install-git-hooks",
389
+ "uninstall-git-hooks",
345
390
  "git-hook",
346
391
  "file-scope-guard",
347
392
  "likely-tests",
@@ -369,10 +414,21 @@ const VALID_COMMANDS = new Set([
369
414
  "rerun-ci",
370
415
  // BAPI-1494: CLI-only owner decision on verification hand-offs — never an MCP tool.
371
416
  "resolve-handoff",
417
+ // BAPI-1562: CLI-only owner acknowledgement of the carried-gap list — never an MCP tool.
418
+ "acknowledge-gaps",
372
419
  // BAPI-1532: CLI-only answer to a named plan failure — never an MCP tool.
373
420
  "regenerate-plan",
374
421
  // BAPI-1469: CLI-only read-only bounded wait on a run's state — never an MCP tool.
375
422
  "wait-run",
423
+ // BAPI-1557: CLI-only stored-ticket reader and private local-state writer — never an MCP tool.
424
+ "prerequisite-inputs",
425
+ // BAPI-1546: CLI-only epic-server helper (driver verbs and worker turns) — never an MCP tool.
426
+ "epic-server",
427
+ // BAPI-1642: CLI-only driver supervision guard and blocker check — never MCP tools.
428
+ "driver-register",
429
+ "driver-release",
430
+ "driver-guard",
431
+ "declare-blocked",
376
432
  // Private, and deliberately ABSENT from the usage text: `__hook-bin` exists as
377
433
  // the bundled-artifact regression guard for BAPI-772 (mirroring `plane
378
434
  // __entrypoint`), not as a supported operator workflow.
@@ -783,6 +839,41 @@ export async function runDoctorCommand(argv, deps = {}) {
783
839
  // BAPI-1479: advisory, read-only worker-database rows; runs under
784
840
  // --no-deny-probe too. A caller's injected inspector wins.
785
841
  inspectWorkerDatabase: createWorkerDatabaseDoctorInspector({ env: deps.env ?? process.env, cwd: process.cwd() }),
842
+ // BAPI-1598: the inspection follows the project's declaration. A read that fails
843
+ // for any reason is `unreadable` (shown as "Couldn't check"), never "unset".
844
+ readWorkerDatabaseConfig: async () => {
845
+ try {
846
+ const { resolveConductorBridgeApiAccess, fetchConductorGateProfile } = await import("./bridge-api-client.js");
847
+ const access = await resolveConductorBridgeApiAccess({ env: deps.env ?? process.env });
848
+ if (!access.ok)
849
+ return { status: "unreadable" };
850
+ const read = await fetchConductorGateProfile(access.access, (url, init) => fetch(url, init));
851
+ if (read.stored_malformed)
852
+ return { status: "unreadable" };
853
+ const declared = read.profile?.worker_database;
854
+ if (!declared)
855
+ return { status: "unset" };
856
+ return {
857
+ status: "configured",
858
+ mode: declared.mode,
859
+ ...(declared.worker_role ? { workerRole: declared.worker_role } : {}),
860
+ protectedDatabases: declared.protected_databases ?? [],
861
+ envNames: declared.env_names ?? [],
862
+ ...(declared.migrate_command
863
+ ? {
864
+ migrateCommand: {
865
+ argv: declared.migrate_command.argv,
866
+ timeoutSeconds: declared.migrate_command.timeout_seconds,
867
+ headCheck: declared.migrate_command.head_check ?? "none",
868
+ },
869
+ }
870
+ : {}),
871
+ };
872
+ }
873
+ catch {
874
+ return { status: "unreadable" };
875
+ }
876
+ },
786
877
  // BAPI-1461: a merge token stored once for this repository counts as
787
878
  // configured — after the bounded capability probe confirms GitHub accepts
788
879
  // it. Doctor runs in the person's own session, so the stored rung applies.
@@ -1170,7 +1261,7 @@ export async function runApprovePlanCommand(argv) {
1170
1261
  // Lazy import keeps the credential/HTTP graph out of commands that never
1171
1262
  // need Bridge API access (doctor, emit-event, etc.).
1172
1263
  const { resolveConductorBridgeApiAccess, approveEpicPlan } = await import("./bridge-api-client.js");
1173
- const accessResult = await resolveConductorBridgeApiAccess();
1264
+ const accessResult = await resolveConductorBridgeApiAccess({ followEpicLaunchProfile: true });
1174
1265
  if (!accessResult.ok) {
1175
1266
  const envelope = { error: "CREDENTIALS_UNAVAILABLE", status: 401, message: accessResult.error };
1176
1267
  if (parsed.json) {
@@ -1186,6 +1277,10 @@ export async function runApprovePlanCommand(argv) {
1186
1277
  epicKey: parsed.epicKey,
1187
1278
  planVersion: parsed.planVersion,
1188
1279
  });
1280
+ if (!result.ok && result.kind === "refused") {
1281
+ throw new ConductorValidationError(`approve-plan refused by the server (${result.error_code}, ` +
1282
+ `predicate ${result.predicate}, reason ${result.reason_code}).`);
1283
+ }
1189
1284
  if (!result.ok) {
1190
1285
  throw new ConductorValidationError(`approve-plan rejected: version drift or monotonic constraint violation ` +
1191
1286
  `(kind: ${result.kind}). Ensure --plan-version is strictly greater than ` +
@@ -1219,22 +1314,35 @@ export async function runApprovePlanCommand(argv) {
1219
1314
  // ---------------------------------------------------------------------------
1220
1315
  // epic-status
1221
1316
  // ---------------------------------------------------------------------------
1222
- const EPIC_STATUS_VALUE_FLAGS = new Set(["--epic-key"]);
1317
+ const EPIC_STATUS_VALUE_FLAGS = new Set(["--epic-key", "--epic-run-id"]);
1223
1318
  const EPIC_STATUS_BOOL_FLAGS = new Set(["--json", "--help"]);
1224
1319
  /**
1225
- * Parse `epic-status` flags. `--epic-key` is required and must be non-empty.
1226
- * Malformed input raises a sanitized {@link ConductorValidationError}.
1320
+ * Parse `epic-status` flags. Exactly one of `--epic-key` or `--epic-run-id` is
1321
+ * required and must be non-empty. The other run-control commands take
1322
+ * `--epic-run-id`, and the state endpoint resolves either a run id or an epic
1323
+ * key, so both name the same run. Malformed input raises a sanitized
1324
+ * {@link ConductorValidationError}.
1227
1325
  */
1228
1326
  export function parseEpicStatusArgs(argv) {
1229
1327
  const { values, bools } = tokenizeFlags(argv, EPIC_STATUS_VALUE_FLAGS, EPIC_STATUS_BOOL_FLAGS);
1230
1328
  if (bools.has("--help")) {
1231
- return { epicKey: "", json: false, help: true };
1329
+ return { epicKey: "", epicRunId: null, json: false, help: true };
1232
1330
  }
1233
1331
  const epicKeyRaw = values.get("--epic-key");
1332
+ const epicRunIdRaw = values.get("--epic-run-id");
1333
+ if (epicKeyRaw !== undefined && epicRunIdRaw !== undefined) {
1334
+ throw new ConductorValidationError('Pass only one of "--epic-key" or "--epic-run-id" to epic-status.');
1335
+ }
1336
+ if (epicRunIdRaw !== undefined) {
1337
+ if (epicRunIdRaw.trim().length === 0) {
1338
+ throw new ConductorValidationError('Flag "--epic-run-id" must be non-empty.');
1339
+ }
1340
+ return { epicKey: "", epicRunId: epicRunIdRaw.trim(), json: bools.has("--json"), help: false };
1341
+ }
1234
1342
  if (epicKeyRaw === undefined || epicKeyRaw.trim().length === 0) {
1235
- throw new ConductorValidationError('Flag "--epic-key" is required for epic-status and must be non-empty.');
1343
+ throw new ConductorValidationError('Flag "--epic-key" (or "--epic-run-id") is required for epic-status and must be non-empty.');
1236
1344
  }
1237
- return { epicKey: epicKeyRaw.trim(), json: bools.has("--json"), help: false };
1345
+ return { epicKey: epicKeyRaw.trim(), epicRunId: null, json: bools.has("--json"), help: false };
1238
1346
  }
1239
1347
  /**
1240
1348
  * Run the `epic-status` command. Resolves Bridge API credentials, calls
@@ -1259,7 +1367,7 @@ export async function runEpicStatusCommand(argv) {
1259
1367
  // Lazy import keeps the credential/HTTP graph out of commands that never
1260
1368
  // need Bridge API access (doctor, emit-event, etc.).
1261
1369
  const { resolveConductorBridgeApiAccess, fetchEpicRunState, ConductorBridgeApiError: BridgeApiError } = await import("./bridge-api-client.js");
1262
- const accessResult = await resolveConductorBridgeApiAccess();
1370
+ const accessResult = await resolveConductorBridgeApiAccess({ followEpicLaunchProfile: true });
1263
1371
  if (!accessResult.ok) {
1264
1372
  if (parsed.json) {
1265
1373
  await writeJsonDocument(JSON.stringify({ ok: false, kind: "unauthorized", error: accessResult.error }));
@@ -1270,7 +1378,7 @@ export async function runEpicStatusCommand(argv) {
1270
1378
  return 1;
1271
1379
  }
1272
1380
  try {
1273
- const state = await fetchEpicRunState(accessResult.access, parsed.epicKey);
1381
+ const state = await fetchEpicRunState(accessResult.access, parsed.epicRunId ?? parsed.epicKey);
1274
1382
  if (parsed.json) {
1275
1383
  return (await writeJsonDocument(JSON.stringify(state))) ? 0 : 1;
1276
1384
  }
@@ -1307,7 +1415,9 @@ export async function runEpicStatusCommand(argv) {
1307
1415
  catch (error) {
1308
1416
  if (error instanceof BridgeApiError && error.status === 404) {
1309
1417
  if (parsed.json) {
1310
- const written = await writeJsonDocument(JSON.stringify({ epic_key: parsed.epicKey, status: "unknown", state: null }));
1418
+ const written = await writeJsonDocument(JSON.stringify(parsed.epicRunId !== null
1419
+ ? { epic_run_id: parsed.epicRunId, status: "unknown", state: null }
1420
+ : { epic_key: parsed.epicKey, status: "unknown", state: null }));
1311
1421
  if (!written)
1312
1422
  return 1;
1313
1423
  }
@@ -1417,6 +1527,11 @@ export async function runPurgeCommand(argv) {
1417
1527
  ].join("\n"));
1418
1528
  return 0;
1419
1529
  }
1530
+ /** BAPI-1551 — the stderr note naming how many leading references are always-run guards. */
1531
+ export function likelyTestsRequiredNote(count) {
1532
+ return `The first ${count} references are this repository's always-run guards. ` +
1533
+ "Run them before you push, whatever you changed.";
1534
+ }
1420
1535
  const LIKELY_TESTS_FAILURE_NOTE = "Likely-tests discovery unavailable: internal discovery failure (not an empty result).\n";
1421
1536
  export async function runLikelyTestsCommand(argv, deps = {}) {
1422
1537
  const stdout = deps.stdout ?? ((text) => { process.stdout.write(text); });
@@ -1445,6 +1560,11 @@ export async function runLikelyTestsCommand(argv, deps = {}) {
1445
1560
  printed += 1;
1446
1561
  }
1447
1562
  }
1563
+ // BAPI-1551 — the always-run guards print first; say so on stderr only, so
1564
+ // stdout stays references and nothing else.
1565
+ const required = (result.required ?? []).filter(validTestReference).length;
1566
+ if (required > 0)
1567
+ stderr(likelyTestsRequiredNote(required) + "\n");
1448
1568
  const failed = result.diagnostics.some(d => d === "git_unavailable" || d === "invalid_arguments");
1449
1569
  for (const diagnostic of new Set(result.diagnostics)) {
1450
1570
  if (diagnostic !== "empty")
@@ -1513,6 +1633,10 @@ export async function runEpicImplementerCli(argv, likelyTestsDeps) {
1513
1633
  return await runPurgeCommand(parsed.argv);
1514
1634
  case "install-git-hooks":
1515
1635
  return runInstallGitHooksCommand(parsed.argv);
1636
+ case "uninstall-git-hooks": {
1637
+ const { runUninstallGitHooksCommand } = await import("./git-hooks-uninstall.js");
1638
+ return runUninstallGitHooksCommand(parsed.argv);
1639
+ }
1516
1640
  case "git-hook":
1517
1641
  return await runGitHookCommand(parsed.argv);
1518
1642
  case CONDUCTOR_HOOK_BIN_ACTION:
@@ -1605,6 +1729,11 @@ export async function runEpicImplementerCli(argv, likelyTestsDeps) {
1605
1729
  const { runResolveHandoffCommand } = await import("./recovery-cli.js");
1606
1730
  return await runResolveHandoffCommand(parsed.argv);
1607
1731
  }
1732
+ case "acknowledge-gaps": {
1733
+ // BAPI-1562: delegates only to the owner's list acknowledgement.
1734
+ const { runAcknowledgeGapsCommand } = await import("./recovery-cli.js");
1735
+ return await runAcknowledgeGapsCommand(parsed.argv);
1736
+ }
1608
1737
  case "regenerate-plan": {
1609
1738
  // BAPI-1532: delegates only to the pinned plan-regeneration operation.
1610
1739
  const { runRegeneratePlanCommand } = await import("./recovery-cli.js");
@@ -1623,6 +1752,77 @@ export async function runEpicImplementerCli(argv, likelyTestsDeps) {
1623
1752
  }
1624
1753
  return await runWaitRunCommand(parsed.argv);
1625
1754
  }
1755
+ case "prerequisite-inputs": {
1756
+ // BAPI-1557: dispatched before any MCP server is built or connected. A
1757
+ // module-load failure gets fixed wording, never exception text.
1758
+ let runPrerequisiteInputsCommand;
1759
+ try {
1760
+ ({ runPrerequisiteInputsCommand } = await import("./prerequisite-inputs.js"));
1761
+ }
1762
+ catch {
1763
+ console.error("Error: prerequisite-inputs could not be loaded; no scanner input was written.");
1764
+ return 1;
1765
+ }
1766
+ return await runPrerequisiteInputsCommand(parsed.argv);
1767
+ }
1768
+ case "epic-server": {
1769
+ // BAPI-1546: dispatched before any MCP server is built or connected. A
1770
+ // module-load failure gets fixed wording, never exception text.
1771
+ let runEpicServerCommand;
1772
+ try {
1773
+ ({ runEpicServerCommand } = await import("./epic-server.js"));
1774
+ }
1775
+ catch {
1776
+ console.error("Error: epic-server could not be loaded; nothing was started or stopped.");
1777
+ return 1;
1778
+ }
1779
+ return await runEpicServerCommand(parsed.argv);
1780
+ }
1781
+ case "driver-guard": {
1782
+ // BAPI-1642: the Stop hook. Its own boundary: a load failure or any
1783
+ // exception allows the stop silently with exit 0, never the general
1784
+ // exit-1 error path below.
1785
+ try {
1786
+ const { runDriverGuardCommand } = await import("./driver-guard.js");
1787
+ return await runDriverGuardCommand(parsed.argv);
1788
+ }
1789
+ catch {
1790
+ return 0;
1791
+ }
1792
+ }
1793
+ case "driver-register": {
1794
+ let runDriverRegisterCommand;
1795
+ try {
1796
+ ({ runDriverRegisterCommand } = await import("./driver-register.js"));
1797
+ }
1798
+ catch {
1799
+ console.error("Error: driver-register could not be loaded; the driver guard is not armed.");
1800
+ return 1;
1801
+ }
1802
+ return await runDriverRegisterCommand(parsed.argv);
1803
+ }
1804
+ case "driver-release": {
1805
+ let runDriverReleaseCommand;
1806
+ try {
1807
+ ({ runDriverReleaseCommand } = await import("./driver-release.js"));
1808
+ }
1809
+ catch {
1810
+ console.error("Error: driver-release could not be loaded; nothing was released.");
1811
+ return 1;
1812
+ }
1813
+ return await runDriverReleaseCommand(parsed.argv);
1814
+ }
1815
+ case "declare-blocked": {
1816
+ let runDeclareBlockedCommand;
1817
+ try {
1818
+ ({ runDeclareBlockedCommand } = await import("./declare-blocked.js"));
1819
+ }
1820
+ catch {
1821
+ console.error("Error: declare-blocked could not be loaded; nothing was escalated. Supervision continues.");
1822
+ return 1;
1823
+ }
1824
+ return await runDeclareBlockedCommand(parsed.argv);
1825
+ }
1626
1826
  default:
1627
1827
  console.error('Error: Unknown command. Run "epic-implementer --help" for usage.');
1628
1828
  return 1;
@@ -0,0 +1,162 @@
1
+ /**
2
+ * The epic-server helper's OPTIONAL per-turn database (BAPI-1546).
3
+ *
4
+ * Created only when the validated recipe asks for one (`database.kind:
5
+ * disposable_postgres`). It uses its own name prefix (`bridge_epic_server_`) and
6
+ * its own ownership comment, so the executor's orphan sweep, which lists only
7
+ * the exact `bridge_worker_job_` prefix, never lists or drops it mid-turn.
8
+ *
9
+ * Migration is never run here: it is the recipe's own `migrate` step, so the
10
+ * packaged helper carries no migration tool assumption. This adapter only
11
+ * creates, comments, drops, and sweeps.
12
+ *
13
+ * The ownership comment names the run, the helper pid, a DIGEST of the helper's
14
+ * instance nonce (never the nonce itself), and the turn generation. On start the
15
+ * helper sweeps only its own run's leftovers whose recorded helper pid is
16
+ * definitively dead (or is itself, from an earlier turn). Anything ambiguous,
17
+ * malformed, or another run's is left alone.
18
+ */
19
+ import { createHash, randomBytes } from "node:crypto";
20
+ import { EPIC_SERVER_DATABASE_PREFIX, createEpicServerDatabase, dropEpicServerDatabase, isValidEpicServerDatabaseName, listEpicServerDatabases, } from "../executor/worker-database.js";
21
+ import { WORKER_DATABASE_HOST, WORKER_DATABASE_PORT } from "../executor/worker-database-target.js";
22
+ export const EPIC_SERVER_DATABASE_METADATA_VERSION = 1;
23
+ const KEYS = ["v", "kind", "runId", "helperPid", "nonceDigest", "generation", "createdAt"];
24
+ const RUN_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{7,63}$/;
25
+ const DIGEST_RE = /^[0-9a-f]{64}$/;
26
+ /** The digest recorded instead of the nonce. */
27
+ export function instanceNonceDigest(nonce) {
28
+ return createHash("sha256").update(`epic-server:${nonce}`).digest("hex");
29
+ }
30
+ export function encodeEpicServerDatabaseMetadata(metadata) {
31
+ return JSON.stringify({
32
+ v: metadata.v,
33
+ kind: metadata.kind,
34
+ runId: metadata.runId,
35
+ helperPid: metadata.helperPid,
36
+ nonceDigest: metadata.nonceDigest,
37
+ generation: metadata.generation,
38
+ createdAt: metadata.createdAt,
39
+ });
40
+ }
41
+ /** Strict parser: exactly the known keys, each well-formed. Anything else is null. */
42
+ export function parseEpicServerDatabaseMetadata(comment) {
43
+ if (typeof comment !== "string" || comment.length > 512)
44
+ return null;
45
+ let raw;
46
+ try {
47
+ raw = JSON.parse(comment);
48
+ }
49
+ catch {
50
+ return null;
51
+ }
52
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
53
+ return null;
54
+ const doc = raw;
55
+ const keys = Object.keys(doc);
56
+ if (keys.length !== KEYS.length || !KEYS.every((k) => keys.includes(k)))
57
+ return null;
58
+ if (doc.v !== EPIC_SERVER_DATABASE_METADATA_VERSION || doc.kind !== "epic_server")
59
+ return null;
60
+ if (typeof doc.runId !== "string" || !RUN_ID_RE.test(doc.runId))
61
+ return null;
62
+ if (typeof doc.helperPid !== "number" || !Number.isSafeInteger(doc.helperPid) || doc.helperPid <= 1)
63
+ return null;
64
+ if (typeof doc.nonceDigest !== "string" || !DIGEST_RE.test(doc.nonceDigest))
65
+ return null;
66
+ if (typeof doc.generation !== "number" || !Number.isSafeInteger(doc.generation) || doc.generation < 0)
67
+ return null;
68
+ if (typeof doc.createdAt !== "string" || Number.isNaN(Date.parse(doc.createdAt)))
69
+ return null;
70
+ return {
71
+ v: EPIC_SERVER_DATABASE_METADATA_VERSION,
72
+ kind: "epic_server",
73
+ runId: doc.runId,
74
+ helperPid: doc.helperPid,
75
+ nonceDigest: doc.nonceDigest,
76
+ generation: doc.generation,
77
+ createdAt: doc.createdAt,
78
+ };
79
+ }
80
+ /** `bridge_epic_server_<run12>_g<gen>_<hex8>`, within the identifier limit. */
81
+ export function buildEpicServerDatabaseName(runId, generation, suffix) {
82
+ const run = runId.toLowerCase().replace(/[^a-z0-9]/g, "").slice(0, 12);
83
+ if (run.length === 0 || !/^[0-9a-f]{4,16}$/.test(suffix) || !Number.isSafeInteger(generation) || generation < 0)
84
+ return null;
85
+ const name = `${EPIC_SERVER_DATABASE_PREFIX}${run}_g${generation}_${suffix}`;
86
+ return isValidEpicServerDatabaseName(name) ? name : null;
87
+ }
88
+ /**
89
+ * Create the turn's database and record ownership BEFORE exposing its settings.
90
+ * The settings name only this database, on loopback, as the recipe's role.
91
+ */
92
+ export async function provisionTurnDatabase(owner, role, budgetMs, deps) {
93
+ const suffix = (deps.randomSuffix ?? (() => randomBytes(4).toString("hex")))();
94
+ const name = buildEpicServerDatabaseName(owner.runId, owner.generation, suffix);
95
+ if (name === null)
96
+ return { kind: "unavailable" };
97
+ const comment = encodeEpicServerDatabaseMetadata({
98
+ v: EPIC_SERVER_DATABASE_METADATA_VERSION,
99
+ kind: "epic_server",
100
+ runId: owner.runId,
101
+ helperPid: owner.helperPid,
102
+ nonceDigest: instanceNonceDigest(owner.nonce),
103
+ generation: owner.generation,
104
+ createdAt: deps.now().toISOString(),
105
+ });
106
+ const created = await createEpicServerDatabase(name, role, comment, deps.database, budgetMs);
107
+ if (created.kind !== "ok")
108
+ return created.retained ? { kind: "unavailable", retainedName: name } : { kind: "unavailable" };
109
+ return {
110
+ kind: "ready",
111
+ name,
112
+ settings: { host: WORKER_DATABASE_HOST, port: WORKER_DATABASE_PORT, role, name },
113
+ };
114
+ }
115
+ /** Drop the turn's database. Returns false when the drop could not be confirmed. */
116
+ export async function dropTurnDatabase(name, role, budgetMs, deps) {
117
+ const dropped = await dropEpicServerDatabase(name, role, deps.database, budgetMs);
118
+ return dropped.kind === "ok";
119
+ }
120
+ /**
121
+ * True only when `settings` names the helper's CURRENT per-turn database. The
122
+ * runtime checks this before building any migrate or seed command.
123
+ */
124
+ export function isCurrentTurnDatabase(settings, current) {
125
+ if (settings === null || current === null)
126
+ return false;
127
+ return (isValidEpicServerDatabaseName(settings.name) &&
128
+ settings.name === current.name &&
129
+ settings.role === current.role &&
130
+ settings.host === WORKER_DATABASE_HOST &&
131
+ settings.port === WORKER_DATABASE_PORT);
132
+ }
133
+ /**
134
+ * Drop this run's leftover helper databases whose recorded helper is definitively
135
+ * dead, or is the current helper itself (an earlier turn whose drop failed).
136
+ * Live, unknown, malformed, and other runs' databases are retained untouched.
137
+ */
138
+ export async function sweepOwnLeftoverDatabases(current, role, budgetMs, deps) {
139
+ const result = { dropped: [], retained: [] };
140
+ const listing = await listEpicServerDatabases(role, deps.database, budgetMs);
141
+ if (listing.kind !== "ok")
142
+ return result;
143
+ const currentDigest = instanceNonceDigest(current.nonce);
144
+ for (const row of listing.rows) {
145
+ if (deps.keep?.has(row.name))
146
+ continue;
147
+ const metadata = parseEpicServerDatabaseMetadata(row.comment);
148
+ if (metadata === null || metadata.runId !== current.runId)
149
+ continue;
150
+ const ownEarlierTurn = metadata.helperPid === current.helperPid && metadata.nonceDigest === currentDigest;
151
+ const deadOwner = metadata.helperPid !== current.helperPid && deps.isPidAlive(metadata.helperPid) === false;
152
+ if (!ownEarlierTurn && !deadOwner) {
153
+ result.retained.push(row.name);
154
+ continue;
155
+ }
156
+ if (await dropTurnDatabase(row.name, role, budgetMs, deps))
157
+ result.dropped.push(row.name);
158
+ else
159
+ result.retained.push(row.name);
160
+ }
161
+ return result;
162
+ }