@bridge_gpt/mcp-server 0.2.69 → 0.2.71

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 (164) hide show
  1. package/README.md +140 -292
  2. package/build/agent-launchers/claude-executor-adapter.js +27 -5
  3. package/build/agent-registry.js +5 -5
  4. package/build/agents.generated.js +15 -5
  5. package/build/artifact-diff.js +110 -0
  6. package/build/bin-entrypoint.js +36 -0
  7. package/build/bounded-wait.js +9 -1
  8. package/build/bridge-permissions.js +36 -9
  9. package/build/claude-review-workflow-drift.js +3 -3
  10. package/build/codex-bridge-profile.js +1 -1
  11. package/build/commands.generated.js +6 -6
  12. package/build/conductor/bridge-api-client.js +858 -21
  13. package/build/conductor/bring-up-facts.js +9 -9
  14. package/build/conductor/command-drift-production.js +7 -2
  15. package/build/conductor/doctor.js +472 -18
  16. package/build/conductor/epic-child-continuation.js +54 -3
  17. package/build/conductor/epic-implementer-cli.js +136 -34
  18. package/build/conductor/epic-runtime.js +2 -2
  19. package/build/conductor/epic-state.js +1 -1
  20. package/build/conductor/gate-discovery.js +524 -10
  21. package/build/conductor/gate-settings-review.js +451 -0
  22. package/build/conductor/hook-runtime-qualification.js +1 -1
  23. package/build/conductor/install-doctor.js +4 -2
  24. package/build/conductor/launch-need-probes.js +342 -0
  25. package/build/conductor/launch-plan.js +145 -0
  26. package/build/conductor/local-merge.js +241 -56
  27. package/build/conductor/merge-credential.js +172 -0
  28. package/build/conductor/merge-execution-eligibility.js +1 -1
  29. package/build/conductor/merged-child-check.js +95 -0
  30. package/build/conductor/plan-trim.js +30 -0
  31. package/build/conductor/pr-ci-producer.js +1 -1
  32. package/build/conductor/precheck-timings.js +14 -0
  33. package/build/conductor/preview-observations.js +10 -0
  34. package/build/conductor/readiness-cli.js +11 -6
  35. package/build/conductor/readiness-prerequisites.js +41 -0
  36. package/build/conductor/readiness-sections.js +348 -55
  37. package/build/conductor/readiness.js +99 -87
  38. package/build/conductor/recovery-cli.js +665 -23
  39. package/build/conductor/recovery-operations.js +350 -8
  40. package/build/conductor/repair-contract.js +47 -2
  41. package/build/conductor/repository-workflow-remedy.js +8 -6
  42. package/build/conductor/stored-merge-credential.js +76 -0
  43. package/build/conductor/stored-merge-token-probe.js +28 -0
  44. package/build/conductor/temporary-plan.js +50 -0
  45. package/build/conductor/wait-run-cli.js +759 -0
  46. package/build/conductor/worker-database-doctor-inspector.js +49 -0
  47. package/build/conductor-bin.js +2 -2
  48. package/build/conductor-claude-hook-bin.js +2 -2
  49. package/build/conductor-claude-hook-removed-stub-bin.js +2 -5
  50. package/build/conductor-removed-stub-bin.js +2 -5
  51. package/build/credential-store.js +356 -13
  52. package/build/docs.generated.js +26 -13
  53. package/build/doctor.js +94 -32
  54. package/build/drive-epic-help.js +212 -0
  55. package/build/drive-epic.js +1989 -379
  56. package/build/epic-ci-workflow-drift.js +125 -0
  57. package/build/epic-ci-workflow-install.js +240 -0
  58. package/build/epic-ci-workflow-v1.js +132 -0
  59. package/build/epic-ci-workflow.js +318 -0
  60. package/build/epic-contract-context.js +326 -0
  61. package/build/epic-implementer-bin.js +58 -42
  62. package/build/epic-implementer-claude-hook-bin.js +2 -2
  63. package/build/escalation-reachability.js +134 -0
  64. package/build/executor/ci-rerun-job.js +220 -14
  65. package/build/executor/cleanup-report.js +99 -0
  66. package/build/executor/cli.js +12 -1
  67. package/build/executor/completion-contract.js +66 -11
  68. package/build/executor/completion-supervision.js +99 -0
  69. package/build/executor/delivery-outcome.js +179 -0
  70. package/build/executor/deps.js +3 -0
  71. package/build/executor/env.js +276 -1
  72. package/build/executor/failure-reason-codes.js +126 -0
  73. package/build/executor/gate-qualification-job.js +20 -5
  74. package/build/executor/heartbeat.js +38 -0
  75. package/build/executor/http-client.js +72 -0
  76. package/build/executor/integration-job.js +298 -5
  77. package/build/executor/job-errors.js +36 -6
  78. package/build/executor/job-runner.js +830 -45
  79. package/build/executor/likely-tests.js +42 -3
  80. package/build/executor/merge-job.js +145 -2
  81. package/build/executor/observation.js +73 -4
  82. package/build/executor/permissions.js +193 -97
  83. package/build/executor/preflight.js +19 -3
  84. package/build/executor/process-containment.js +46 -2
  85. package/build/executor/prompt-spec.js +113 -9
  86. package/build/executor/rebase-finalization.js +38 -3
  87. package/build/executor/reconcile-overlap-job.js +41 -8
  88. package/build/executor/required-work-ledger.js +236 -81
  89. package/build/executor/resume-pre-spawn.js +38 -1
  90. package/build/executor/runner.js +91 -3
  91. package/build/executor/test-clock.js +8 -0
  92. package/build/executor/types.js +37 -2
  93. package/build/executor/worker-cli-launcher.js +259 -0
  94. package/build/executor/worker-command.js +177 -5
  95. package/build/executor/worker-database-target.js +91 -0
  96. package/build/executor/worker-database.js +927 -0
  97. package/build/executor/worker-finalization.js +106 -0
  98. package/build/executor/worker-guard-hook.js +203 -0
  99. package/build/executor/worker-resources.js +58 -0
  100. package/build/executor/worker-verification-guidance.js +44 -2
  101. package/build/executor/worktree.js +303 -15
  102. package/build/executor-launch.js +11 -1
  103. package/build/generated-assets-doctor.js +9 -1
  104. package/build/generated-assets-health.js +13 -4
  105. package/build/generated-assets-legacy.js +39 -0
  106. package/build/generated-assets-paths.js +12 -1
  107. package/build/generated-assets-repair.js +4 -1
  108. package/build/generated-assets-test-support.js +12 -0
  109. package/build/github-remote.js +33 -0
  110. package/build/github-sign-in.js +62 -0
  111. package/build/index.js +1133 -546
  112. package/build/init.js +39 -1
  113. package/build/install-bridge-conductor-gate.js +270 -11
  114. package/build/install-bridge-conductor-setup.js +427 -0
  115. package/build/install-bridge-conductor.js +1545 -268
  116. package/build/install-bridge.js +376 -60
  117. package/build/mcp-install-state.js +8 -2
  118. package/build/merge-pull-request.js +6 -0
  119. package/build/merge-workflow-install.js +782 -344
  120. package/build/phase-result-artifacts.js +75 -20
  121. package/build/pipeline-orchestrator.js +247 -4
  122. package/build/pipelines.generated.js +35 -35
  123. package/build/plan-discovery.js +15 -2
  124. package/build/plan-execution-ledger.js +321 -17
  125. package/build/plan-phase-routing.js +48 -13
  126. package/build/plane/cli.js +105 -51
  127. package/build/plane/defaults.js +3 -0
  128. package/build/plane/plane-freshness.js +298 -0
  129. package/build/plane/preflight.js +19 -0
  130. package/build/plane/schema-compatibility.js +137 -0
  131. package/build/plane/shutdown-deps.js +38 -0
  132. package/build/plane/shutdown.js +83 -8
  133. package/build/plane/terminal-run-cleanup.js +303 -0
  134. package/build/printed-remedy-commands.js +33 -4
  135. package/build/readiness-check.js +6 -2
  136. package/build/readiness-prerequisites.generated.js +532 -0
  137. package/build/readme.generated.js +1 -1
  138. package/build/repository-toolchains.js +581 -0
  139. package/build/setup-epic.js +421 -34
  140. package/build/shared-resources.generated.js +5 -0
  141. package/build/start-tickets.js +28 -15
  142. package/build/test-command-detection.js +284 -0
  143. package/build/test-command-validation.js +73 -0
  144. package/build/testing-config-client.js +150 -0
  145. package/build/ticket-delivery-artifacts.js +265 -0
  146. package/build/ticket-delivery-enrollment.js +369 -0
  147. package/build/ticket-delivery.js +205 -0
  148. package/build/ticket-review-summary.js +14 -0
  149. package/build/upgrade-cli.js +13 -0
  150. package/build/v2-readiness-requirements.js +552 -0
  151. package/build/version.generated.js +3 -3
  152. package/build/worker-guard-hook-bin.js +2 -2
  153. package/build/worktree-core.js +22 -7
  154. package/docs/BRIDGE-DIRECTORY-README.md +48 -0
  155. package/docs/EPIC-IMPLEMENTER-INSTALL.md +12 -867
  156. package/docs/EPIC-IMPLEMENTER.md +142 -63
  157. package/docs/epic-implementer/getting-started.md +187 -0
  158. package/docs/epic-implementer/self-hosting.md +133 -0
  159. package/package.json +4 -4
  160. package/pipelines/idea-to-ticket.json +1 -1
  161. package/pipelines/implement-ticket.json +8 -8
  162. package/pipelines/review-ticket.json +2 -2
  163. package/design-assets/favicon/favicon-32x32.png +0 -0
  164. package/design-assets/just-logo-rough-draft.png +0 -0
@@ -1,5 +1,5 @@
1
- /** The pinned operator runbook every remedy below points into. */
2
- export const BRING_UP_RUNBOOK = "docs/epic-implementer/operator-runbook.md";
1
+ /** Where the owner-only bring-up steps these remedies refer to are printed. */
2
+ export const BRING_UP_RUNBOOK = "`drive-epic --help-advanced`";
3
3
  /**
4
4
  * The client-derived refusal vocabulary, IN REFUSAL ORDER.
5
5
  *
@@ -20,20 +20,20 @@ export const BRING_UP_REFUSAL_REASONS = [
20
20
  // ---------------------------------------------------------------------------
21
21
  // Fixed remediations
22
22
  // ---------------------------------------------------------------------------
23
- export const BRING_UP_UNREPORTED_REMEDIATION = "upgrade the Bridge API deploy to a build that reports the bring-up safety facts; " +
24
- "their state is unknown here, not healthy.";
23
+ export const BRING_UP_UNREPORTED_REMEDIATION = "retry later; the server did not report the bring-up safety facts, so their state is unknown here, " +
24
+ "not healthy. If it persists, email info@bridgegpt.ai.";
25
25
  export const DATABASE_MIGRATION_UNREADABLE_REMEDIATION = "retry; the migration state could not be read, which is not the same as confirmed-behind. " +
26
- `If it persists, check the applied revision with \`alembic current\` (${BRING_UP_RUNBOOK} §3d).`;
26
+ `If it persists, check the applied revision with \`alembic current\` (see ${BRING_UP_RUNBOOK}).`;
27
27
  export const DATABASE_MIGRATION_BEHIND_REMEDIATION = "confirm the applied revision with `alembic current` (not `alembic heads`, which reads the " +
28
- "migration scripts), apply this checkout's migrations with `alembic -c alembic.ini upgrade head`, " +
29
- `then retry (${BRING_UP_RUNBOOK} §3d).`;
28
+ "migration scripts), apply this checkout's migrations with `alembic upgrade head`, " +
29
+ `then retry (see ${BRING_UP_RUNBOOK}).`;
30
30
  export const WORKER_HEARTBEAT_UNREADABLE_REMEDIATION = "retry once the Bridge API database is reachable; the reconciler heartbeat could not be read, " +
31
31
  "so worker presence is unknown, not confirmed absent.";
32
32
  export const WORKER_NOT_PRESENT_REMEDIATION = "start a worker (`python worker.py`, or bring up a local plane) — a server started with " +
33
33
  "DISABLE_SCHEDULER=true runs none. Create and approve only against a server that has a " +
34
- `worker (${BRING_UP_RUNBOOK} §3d).`;
34
+ `worker (see ${BRING_UP_RUNBOOK}).`;
35
35
  export const SECOND_RECONCILER_REMEDIATION = "find and stop the extra reconciler: check `ps aux | grep worker.py` for a reparented " +
36
- `survivor of an earlier plane (${BRING_UP_RUNBOOK} §6), and note that a dev server started ` +
36
+ `survivor of an earlier plane (see ${BRING_UP_RUNBOOK}), and note that a dev server started ` +
37
37
  "without DISABLE_SCHEDULER=true runs a reconciler too. A reconciler stopped in the last 120 " +
38
38
  "seconds still counts — heartbeat rows are not deleted on shutdown — so wait and retry. " +
39
39
  "On a hosted deployment, check that exactly one worker process is scaled (for example one " +
@@ -19,13 +19,18 @@ import { probeCommandDrift, } from "./command-drift.js";
19
19
  /** Bounded timeout for one Git subprocess. */
20
20
  const GIT_TIMEOUT_MS = 5_000;
21
21
  const BLOB_ID = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
22
- export function createGitRunner(cwd) {
22
+ /**
23
+ * `timeoutMs` bounds each Git subprocess. Production keeps the 5 s default;
24
+ * tests that run real Git on a shared, loaded CI machine pass a longer bound so
25
+ * a slow process start is not mistaken for "Git could not be inspected".
26
+ */
27
+ export function createGitRunner(cwd, timeoutMs = GIT_TIMEOUT_MS) {
23
28
  return (args, input) => {
24
29
  const result = spawnSync("git", args, {
25
30
  cwd,
26
31
  input,
27
32
  encoding: "utf-8",
28
- timeout: GIT_TIMEOUT_MS,
33
+ timeout: timeoutMs,
29
34
  stdio: [input === undefined ? "ignore" : "pipe", "pipe", "ignore"],
30
35
  });
31
36
  if (result.error)
@@ -1,3 +1,4 @@
1
+ import { monotonicNow, elapsedMs } from "./precheck-timings.js";
1
2
  /**
2
3
  * Combined, strictly read-only epic-implementer doctor report (BAPI-395, BAPI-418).
3
4
  *
@@ -14,10 +15,13 @@ import { doctorConductorLedger } from "./store.js";
14
15
  import { detectClaudeLogin, formatClaudeLoginAdvisory } from "../claude-login.js";
15
16
  import { inspectConductorGitHooks } from "./git-hooks.js";
16
17
  import { MERGE_WORKFLOW_IDENTIFIER } from "./merge-execution-contract.js";
18
+ import { LOCAL_MERGE_CREDENTIAL_ALIAS_ENV_KEY, LOCAL_MERGE_CREDENTIAL_ENV_KEYS, resolveLocalMergeCredentialDetailed, } from "./merge-credential.js";
19
+ import { resolveMergeCredentialAtAction } from "./stored-merge-credential.js";
17
20
  import { resolveMcpShimInvocationForRuntime, resolvePackageRootFromModuleUrl, } from "../mcp-server-invocation.js";
18
21
  import { projectCommandDriftRow } from "./command-drift.js";
19
22
  import { MCP_PACKAGE_NAME } from "../mcp-identity.js";
20
23
  import { resolveProfiles } from "../mcp-profile.js";
24
+ import { isValidWorkerDatabaseName } from "../executor/worker-database-target.js";
21
25
  import { createReadinessCheck, createReadinessCheckSafely, } from "../readiness-check.js";
22
26
  /**
23
27
  * Remediation for a conductor context whose resolved MCP groups omit `epic_implementer`.
@@ -53,7 +57,7 @@ export const GH_CLI_REMEDIATION = "install the GitHub CLI (`gh`) and put it on P
53
57
  * and changes nothing. `merge-pull-request.ts` says exactly that about the same
54
58
  * text; this is the last place it was still live.
55
59
  */
56
- export const GH_AUTH_REMEDIATION = "set BAPI_LOCAL_MERGE_TOKEN (or BAPI_MACHINE_MERGE_TOKEN for machine-user mode) in the " +
60
+ export const GH_AUTH_REMEDIATION = "set GITHUB_MERGE_TOKEN (or BAPI_MACHINE_MERGE_TOKEN for machine-user mode) in the " +
57
61
  "environment this host launches the conductor with; local merge has no ambient-login " +
58
62
  "fallback and fails closed with a named reason when neither is configured.";
59
63
  /** Detail used when the credential check was not reached because `gh` is absent. */
@@ -80,6 +84,347 @@ export const DENY_ENFORCEMENT_SKIP_REMEDIATION = "run `epic-implementer doctor`
80
84
  "preflight; `epic-implementer readiness` never spawns that probe itself.";
81
85
  /** Explicit display value for an unset `BRIDGE_MCP_PROFILE`. */
82
86
  export const MCP_PROFILE_UNSET = "(unset)";
87
+ /** BAPI-1461: the printed setup command, used in stored-token remedies. */
88
+ const PRINTED_SETUP_COMMAND = `npx -y ${MCP_PACKAGE_NAME} install conductor`;
89
+ /** BAPI-1461: the fix for a stored token GitHub rejected. */
90
+ export const STORED_MERGE_TOKEN_REJECTED_REMEDIATION = `replace the stored merge token: run \`${PRINTED_SETUP_COMMAND}\` and accept the offer to ` +
91
+ `replace it, or remove it with \`${PRINTED_SETUP_COMMAND} --remove-merge-token\`.`;
92
+ /** BAPI-1461: the advice when the stored token could not be checked. */
93
+ export const STORED_MERGE_TOKEN_UNVERIFIED_REMEDIATION = "the stored merge token could not be checked right now (GitHub or the credential store did " +
94
+ "not answer). This is not a rejection; run doctor again later.";
95
+ /**
96
+ * BAPI-1461: collect the stored-entry finding. It runs only when no LOCAL
97
+ * credential is set in the environment (an env value always wins, and an
98
+ * invalid one is never rescued), resolves through the shared resolver, and —
99
+ * for a stored token — runs the bounded capability probe. Never throws and
100
+ * never returns the token.
101
+ */
102
+ export async function collectStoredMergeCredentialEvidence(env, context) {
103
+ if (resolveLocalMergeCredentialDetailed(env, "local").status !== "missing")
104
+ return { status: "absent" };
105
+ let resolution;
106
+ try {
107
+ resolution = await resolveMergeCredentialAtAction(env, "local", context);
108
+ }
109
+ catch {
110
+ return { status: "unverified" };
111
+ }
112
+ if (resolution.status === "store-unavailable")
113
+ return { status: "unverified" };
114
+ if (resolution.status === "invalid")
115
+ return { status: "rejected", reason: "invalid" };
116
+ if (resolution.status !== "resolved" || resolution.source !== "store")
117
+ return { status: "absent" };
118
+ if (context.probe === undefined)
119
+ return { status: "configured" };
120
+ const repository = context.providerRepository ?? context.localRemote ?? null;
121
+ if (repository === null)
122
+ return { status: "configured" };
123
+ let verdict;
124
+ try {
125
+ verdict = await context.probe({ repository, credential: resolution.credential });
126
+ }
127
+ catch {
128
+ return { status: "unverified" };
129
+ }
130
+ switch (verdict) {
131
+ case "passed":
132
+ return { status: "configured" };
133
+ case "credential_invalid":
134
+ return { status: "rejected", reason: "invalid" };
135
+ case "no_access":
136
+ return { status: "rejected", reason: "unpermitted" };
137
+ default:
138
+ // An unavailable or inconclusive probe is uncertainty — never a revocation.
139
+ return { status: "unverified" };
140
+ }
141
+ }
142
+ /**
143
+ * BAPI-1452: the note printed when the deprecated local alias supplies the
144
+ * credential. Names the canonical key; never mentions the machine credential,
145
+ * which has no alias and is not deprecated.
146
+ */
147
+ export const LOCAL_MERGE_ALIAS_DEPRECATION_NOTE = `the local merge credential is being read from the deprecated ${LOCAL_MERGE_CREDENTIAL_ALIAS_ENV_KEY}; ` +
148
+ `it still works, but rename it to ${LOCAL_MERGE_CREDENTIAL_ENV_KEYS.local}.`;
149
+ // ---------------------------------------------------------------------------
150
+ // Worker-database advisory section (BAPI-1479)
151
+ // ---------------------------------------------------------------------------
152
+ /**
153
+ * Runbook section every worker-database row points to. Mirrors
154
+ * `WORKER_DATABASE_RUNBOOK_SECTION` in `executor/worker-database.ts`, which is
155
+ * not imported at runtime (see the import note above); a test pins the two
156
+ * values together.
157
+ */
158
+ export const WORKER_DATABASE_DOCTOR_RUNBOOK_SECTION = "docs/claude/runbooks/local-db-safety.md#worker-databases";
159
+ /** Who acts on every worker-database row. */
160
+ export const WORKER_DATABASE_DOCTOR_OWNER = "host operator";
161
+ /** Hard ceiling on one worker-database inspection, so it can never hang doctor. */
162
+ export const WORKER_DATABASE_DOCTOR_TIMEOUT_MS = 20_000;
163
+ /** Maximum validated names listed per inventory group; the rest are counted. */
164
+ export const WORKER_DATABASE_DOCTOR_NAME_LIMIT = 20;
165
+ const ROW_STATES = new Set(["healthy", "unsafe", "unknown"]);
166
+ const RETAIN_REASONS = new Set([
167
+ "owner_alive",
168
+ "owner_unknown",
169
+ "foreign_host",
170
+ "no_comment",
171
+ "malformed_comment",
172
+ "ownership_changed",
173
+ "drop_failed",
174
+ ]);
175
+ const UNAVAILABLE_CATEGORIES = new Set([
176
+ "client_missing",
177
+ "postgres_unavailable",
178
+ "role_missing",
179
+ "role_misconfigured",
180
+ "bridgeapi_reachable",
181
+ "boundary_unknown",
182
+ "alembic_missing",
183
+ "create_failed",
184
+ "migration_failed",
185
+ "timeout",
186
+ "cancelled",
187
+ ]);
188
+ function safeState(value) {
189
+ return typeof value === "string" && ROW_STATES.has(value) ? value : "unknown";
190
+ }
191
+ function safeCategory(value) {
192
+ return typeof value === "string" && UNAVAILABLE_CATEGORIES.has(value)
193
+ ? value
194
+ : undefined;
195
+ }
196
+ /** Fixed prose for a category that made a check unavailable or unsafe. */
197
+ function describeUnavailableCategory(category) {
198
+ switch (category) {
199
+ case "client_missing":
200
+ return "the psql client was not found";
201
+ case "postgres_unavailable":
202
+ return "local PostgreSQL could not be reached";
203
+ case "timeout":
204
+ return "the check timed out";
205
+ case "cancelled":
206
+ return "the check was cancelled";
207
+ default:
208
+ return "the check could not be completed";
209
+ }
210
+ }
211
+ function makeRow(id, label, state, detail) {
212
+ return {
213
+ id,
214
+ label,
215
+ state,
216
+ owner: WORKER_DATABASE_DOCTOR_OWNER,
217
+ detail,
218
+ ...(state === "healthy" ? {} : { runbook: WORKER_DATABASE_DOCTOR_RUNBOOK_SECTION }),
219
+ };
220
+ }
221
+ function roleRow(role) {
222
+ const r = (role ?? {});
223
+ let state = safeState(r.state);
224
+ const category = safeCategory(r.category);
225
+ let detail;
226
+ if (state === "healthy") {
227
+ detail = "bridge_epic_worker exists with the expected attributes and no elevating memberships";
228
+ }
229
+ else if (state === "unsafe") {
230
+ detail =
231
+ category === "role_missing"
232
+ ? "bridge_epic_worker does not exist"
233
+ : "bridge_epic_worker attributes or memberships differ from the expected least-privilege set";
234
+ }
235
+ else if (category === "role_missing") {
236
+ // A definitive "missing" answer is actionable, not unknown.
237
+ state = "unsafe";
238
+ detail = "bridge_epic_worker does not exist";
239
+ }
240
+ else {
241
+ detail = `unknown — ${describeUnavailableCategory(category)}`;
242
+ }
243
+ return makeRow("worker-db-role", "worker role", state, detail);
244
+ }
245
+ function boundaryRow(boundary) {
246
+ const b = (boundary ?? {});
247
+ const state = safeState(b.state);
248
+ const category = safeCategory(b.category);
249
+ const detail = state === "healthy"
250
+ ? "bridge_epic_worker is refused on bridgeapi"
251
+ : state === "unsafe"
252
+ ? "UNSAFE — bridge_epic_worker can connect to bridgeapi"
253
+ : `unknown — ${category === "boundary_unknown" ? "the bridgeapi refusal could not be confirmed" : describeUnavailableCategory(category)}`;
254
+ return makeRow("worker-db-boundary", "bridgeapi boundary", state, detail);
255
+ }
256
+ function alembicRow(alembic) {
257
+ const state = safeState(alembic?.state);
258
+ const detail = state === "healthy"
259
+ ? "the operator checkout's .venv Alembic is present"
260
+ : state === "unsafe"
261
+ ? "the operator checkout's .venv Alembic is missing"
262
+ : "unknown — the operator checkout's .venv Alembic could not be checked";
263
+ return makeRow("worker-db-alembic", "operator-checkout Alembic", state, detail);
264
+ }
265
+ function safeNameList(value, redacted) {
266
+ if (!Array.isArray(value))
267
+ return [];
268
+ const out = [];
269
+ for (const entry of value) {
270
+ if (isValidWorkerDatabaseName(entry))
271
+ out.push(entry);
272
+ else
273
+ redacted.count += 1;
274
+ }
275
+ return out;
276
+ }
277
+ function sanitizeInventory(inventory) {
278
+ const inv = inventory;
279
+ if (!inv || inv.state !== "known" || typeof inv.value !== "object" || inv.value === null) {
280
+ return { state: "unknown" };
281
+ }
282
+ const value = inv.value;
283
+ if (!Array.isArray(value.active) ||
284
+ !Array.isArray(value.leftovers) ||
285
+ !Array.isArray(value.unverifiable) ||
286
+ typeof value.harnessCount !== "number" ||
287
+ !Number.isInteger(value.harnessCount) ||
288
+ value.harnessCount < 0) {
289
+ return { state: "unknown" };
290
+ }
291
+ const redacted = { count: 0 };
292
+ const active = safeNameList(value.active, redacted);
293
+ const leftovers = safeNameList(value.leftovers, redacted);
294
+ const unverifiable = [];
295
+ for (const entry of value.unverifiable) {
296
+ const e = (entry ?? {});
297
+ if (!isValidWorkerDatabaseName(e.name)) {
298
+ redacted.count += 1;
299
+ continue;
300
+ }
301
+ const reason = typeof e.reason === "string" && RETAIN_REASONS.has(e.reason)
302
+ ? e.reason
303
+ : "unrecognized";
304
+ unverifiable.push({ name: e.name, reason });
305
+ }
306
+ return {
307
+ state: "known",
308
+ active,
309
+ leftovers,
310
+ unverifiable,
311
+ harness_count: value.harnessCount,
312
+ redacted_count: redacted.count,
313
+ };
314
+ }
315
+ function inventoryRows(inventory) {
316
+ if (inventory.state === "unknown") {
317
+ const detail = "unknown — the database inventory could not be read";
318
+ return [
319
+ makeRow("worker-db-leftovers", "worker databases", "unknown", detail),
320
+ makeRow("worker-db-unverifiable", "unverifiable worker databases", "unknown", detail),
321
+ makeRow("worker-db-harness", "conductor_harness databases", "unknown", detail),
322
+ ];
323
+ }
324
+ const leftoverCount = inventory.leftovers.length;
325
+ // A redacted name is unverifiable by definition — it could not be validated.
326
+ const unverifiableCount = inventory.unverifiable.length + inventory.redacted_count;
327
+ return [
328
+ makeRow("worker-db-leftovers", "worker databases", leftoverCount === 0 ? "healthy" : "unsafe", `${inventory.active.length} active (owned by a live executor), ${leftoverCount} left over ` +
329
+ "(dead executor on this host; the next executor start sweeps them)"),
330
+ makeRow("worker-db-unverifiable", "unverifiable worker databases", unverifiableCount === 0 ? "healthy" : "unsafe", `${unverifiableCount} with unreadable, malformed, foreign-host, or unknown ownership ` +
331
+ "(left in place; review manually)"),
332
+ makeRow("worker-db-harness", "conductor_harness databases", inventory.harness_count === 0 ? "healthy" : "unsafe", `${inventory.harness_count} present (owned by the Python harness reaper; the executor never cleans them)`),
333
+ ];
334
+ }
335
+ /** Project a (possibly hostile or malformed) inspection into the sanitized advisory section. */
336
+ export function buildWorkerDatabaseDoctorSection(inspection) {
337
+ const insp = (inspection ?? {});
338
+ const inventory = inspection ? sanitizeInventory(insp.inventory) : { state: "unknown" };
339
+ return {
340
+ advisory: true,
341
+ owner: WORKER_DATABASE_DOCTOR_OWNER,
342
+ runbook: WORKER_DATABASE_DOCTOR_RUNBOOK_SECTION,
343
+ rows: [
344
+ roleRow(insp.role),
345
+ boundaryRow(insp.boundary),
346
+ alembicRow(insp.alembic),
347
+ ...inventoryRows(inventory),
348
+ ].map((row) => ({ ...row, duration_ms: inspection?.timings?.[row.id] ?? elapsedMs(monotonicNow()) })),
349
+ inventory,
350
+ };
351
+ }
352
+ /**
353
+ * Run the worker-database inspector with a hard ceiling. A throw, a rejection,
354
+ * or a timeout yields an all-unknown section — never healthy, never a crash.
355
+ *
356
+ * BAPI-1496: exported so a local `drive-epic` launch can collect the same
357
+ * advisory section the doctor shows. `onFailure` receives only the closed
358
+ * `timeout`/`error` classification — never the thrown value — so a caller can
359
+ * say that the inspection failed without echoing exception text.
360
+ */
361
+ export async function collectWorkerDatabaseDoctorSection(inspect, timeoutMs = WORKER_DATABASE_DOCTOR_TIMEOUT_MS, onFailure) {
362
+ const started = monotonicNow();
363
+ const failedSection = () => {
364
+ const section = buildWorkerDatabaseDoctorSection(null);
365
+ return { ...section, rows: section.rows.map((row) => ({ ...row, duration_ms: elapsedMs(started) })) };
366
+ };
367
+ let timer;
368
+ try {
369
+ const timeout = new Promise((resolve) => {
370
+ timer = setTimeout(() => resolve(null), timeoutMs);
371
+ timer.unref?.();
372
+ });
373
+ const inspection = await Promise.race([Promise.resolve().then(inspect), timeout]);
374
+ if (inspection === null)
375
+ onFailure?.("timeout");
376
+ return inspection === null ? failedSection() : buildWorkerDatabaseDoctorSection(inspection);
377
+ }
378
+ catch {
379
+ onFailure?.("error");
380
+ return failedSection();
381
+ }
382
+ finally {
383
+ if (timer)
384
+ clearTimeout(timer);
385
+ }
386
+ }
387
+ const WORKER_DB_STATE_TAG = {
388
+ healthy: "[OK]",
389
+ unsafe: "[WARNING]",
390
+ unknown: "[UNKNOWN]",
391
+ };
392
+ function formatNameGroup(lines, heading, names) {
393
+ if (names.length === 0)
394
+ return;
395
+ lines.push(` ${heading}:`);
396
+ for (const name of names.slice(0, WORKER_DATABASE_DOCTOR_NAME_LIMIT))
397
+ lines.push(` - ${name}`);
398
+ if (names.length > WORKER_DATABASE_DOCTOR_NAME_LIMIT) {
399
+ lines.push(` … and ${names.length - WORKER_DATABASE_DOCTOR_NAME_LIMIT} more`);
400
+ }
401
+ }
402
+ /** Render the advisory worker-database section. Names are re-validated at render time. */
403
+ export function formatWorkerDatabaseDoctorSection(section) {
404
+ const lines = [];
405
+ lines.push("Worker databases (advisory, read-only)");
406
+ lines.push("──────────────────────────────────────");
407
+ for (const row of section.rows) {
408
+ const state = safeState(row.state);
409
+ lines.push(`${row.label.padEnd(30)} ${WORKER_DB_STATE_TAG[state]} ${state} — ${row.detail}`);
410
+ if (state !== "healthy") {
411
+ lines.push(` → ${WORKER_DATABASE_DOCTOR_OWNER}: see ${WORKER_DATABASE_DOCTOR_RUNBOOK_SECTION}`);
412
+ }
413
+ }
414
+ const inv = section.inventory;
415
+ if (inv.state === "known") {
416
+ formatNameGroup(lines, "active", inv.active.filter(isValidWorkerDatabaseName));
417
+ formatNameGroup(lines, "left over", inv.leftovers.filter(isValidWorkerDatabaseName));
418
+ formatNameGroup(lines, "unverifiable", inv.unverifiable
419
+ .filter((e) => isValidWorkerDatabaseName(e.name))
420
+ .map((e) => `${e.name} (${RETAIN_REASONS.has(e.reason) ? e.reason : "unrecognized"})`));
421
+ if (inv.redacted_count > 0) {
422
+ lines.push(` ${inv.redacted_count} name(s) failed validation and are not shown`);
423
+ }
424
+ }
425
+ lines.push("These rows are advisory: they never change this command's exit status.");
426
+ return lines;
427
+ }
83
428
  /**
84
429
  * The CLI-only verbs that call the Bridge API from a shell-spawned process and
85
430
  * therefore resolve credentials themselves (CLAUDE.md "Shell-Spawned Credential
@@ -103,6 +448,8 @@ export const CREDENTIALED_RECOVERY_COMMANDS = [
103
448
  // BAPI-1300: parked-child continuation and its read-only receipt lookup.
104
449
  "continue-child",
105
450
  "continuation-receipt",
451
+ // BAPI-1469: the read-only bounded wait on a run's state.
452
+ "wait-run",
106
453
  ];
107
454
  /** Remediation for recovery/repair verbs that cannot resolve Bridge credentials. */
108
455
  export const REPAIR_CREDENTIAL_REMEDIATION = "export BAPI_API_KEY in the shell that runs `conductor`, or store a credential for this " +
@@ -439,7 +786,13 @@ export function inspectMcpProfile(env) {
439
786
  * `gh auth status` (no writes, no merge) and reports whether the host could merge
440
787
  * a PR locally if `policy_json.local_merge.enabled` were set. Never throws.
441
788
  */
442
- export function inspectLocalMerge(runCommand, env = process.env) {
789
+ export function inspectLocalMerge(runCommand, env = process.env,
790
+ /**
791
+ * BAPI-1461: the stored-entry finding, collected beforehand by
792
+ * {@link collectStoredMergeCredentialEvidence}. Absent ⇒ env-only, exactly as
793
+ * before. Never consulted for machine-user mode.
794
+ */
795
+ stored) {
443
796
  const run = runCommand ??
444
797
  ((cmd, args) => {
445
798
  try {
@@ -481,16 +834,62 @@ export function inspectLocalMerge(runCommand, env = process.env) {
481
834
  // read-only from the environment — no subprocess, no network, and no credential
482
835
  // VALUE anywhere in the result. Either mode's key satisfies it: which one a run
483
836
  // uses is the server-resolved typed mode, which a local doctor cannot know.
484
- const merge_credential_configured = ["BAPI_LOCAL_MERGE_TOKEN", "BAPI_MACHINE_MERGE_TOKEN"].some((key) => typeof env[key] === "string" && env[key].trim().length > 0);
837
+ //
838
+ // BAPI-1452: presence is now decided by the SAME resolver the merge uses, so
839
+ // the canonical-then-alias precedence and the "an invalid canonical value is
840
+ // not rescued by the alias" rule cannot drift between doctor and the merge.
841
+ const localResolution = resolveLocalMergeCredentialDetailed(env, "local");
842
+ const machineResolution = resolveLocalMergeCredentialDetailed(env, "machine_token");
843
+ // BAPI-1461: a stored token counts only when the environment set no local
844
+ // value at all, and only when GitHub did not reject it.
845
+ const storedConfigured = localResolution.status === "missing" && stored?.status === "configured";
846
+ const storedRejected = localResolution.status === "missing" && stored?.status === "rejected";
847
+ const storedUnverified = localResolution.status === "missing" && stored?.status === "unverified";
848
+ const merge_credential_configured = localResolution.status === "resolved" || storedConfigured || machineResolution.status === "resolved";
849
+ const localInvalid = localResolution.status === "invalid";
850
+ const local_credential_source = localResolution.status === "resolved"
851
+ ? localResolution.via_alias
852
+ ? "alias"
853
+ : "env"
854
+ : storedConfigured
855
+ ? "store"
856
+ : undefined;
857
+ const notes = [];
858
+ if (localResolution.status === "resolved" && localResolution.via_alias) {
859
+ notes.push(LOCAL_MERGE_ALIAS_DEPRECATION_NOTE);
860
+ }
485
861
  const warnings = [];
486
862
  if (!gh_available) {
487
863
  warnings.push("`gh` is not installed or not on PATH. Local merge (policy_json.local_merge.enabled) " +
488
864
  "cannot run; install the GitHub CLI to enable conductor-driven merges.");
489
865
  }
866
+ else if (!merge_credential_configured && storedRejected) {
867
+ warnings.push("the merge token stored for this repository was rejected by GitHub (expired, revoked, or " +
868
+ `without write access), so it is not configured. Fix: ${STORED_MERGE_TOKEN_REJECTED_REMEDIATION}`);
869
+ }
870
+ else if (!merge_credential_configured && storedUnverified) {
871
+ warnings.push(`no merge credential could be confirmed: ${STORED_MERGE_TOKEN_UNVERIFIED_REMEDIATION}`);
872
+ }
490
873
  else if (!merge_credential_configured) {
491
- warnings.push("`gh` is installed but no merge credential is configured. Set BAPI_LOCAL_MERGE_TOKEN " +
492
- "(or BAPI_MACHINE_MERGE_TOKEN for machine-user mode); local merge has no ambient-login " +
493
- "fallback and fails closed with a named reason.");
874
+ warnings.push(localInvalid
875
+ ? "`gh` is installed but the configured GITHUB_MERGE_TOKEN is not a usable token value " +
876
+ "(it contains whitespace or control characters), and BAPI_LOCAL_MERGE_TOKEN is not " +
877
+ "used in its place. Fix GITHUB_MERGE_TOKEN (or set BAPI_MACHINE_MERGE_TOKEN for " +
878
+ "machine-user mode)."
879
+ : "`gh` is installed but no merge credential is configured. Set GITHUB_MERGE_TOKEN " +
880
+ "(or BAPI_MACHINE_MERGE_TOKEN for machine-user mode); local merge has no ambient-login " +
881
+ "fallback and fails closed with a named reason.");
882
+ }
883
+ else if (storedRejected) {
884
+ // BAPI-1461: a machine credential must not conceal a rejected local one.
885
+ warnings.push("the merge token stored for this repository was rejected by GitHub, so a local-mode merge " +
886
+ `would refuse. Fix: ${STORED_MERGE_TOKEN_REJECTED_REMEDIATION}`);
887
+ }
888
+ else if (localInvalid) {
889
+ // A machine credential satisfies the check, but the local one is still
890
+ // broken — worth saying, because local mode would refuse.
891
+ warnings.push("the configured GITHUB_MERGE_TOKEN is not a usable token value, so a local-mode merge " +
892
+ "would refuse; BAPI_LOCAL_MERGE_TOKEN is not used in its place.");
494
893
  }
495
894
  // Capability gap only — local merge is opt-in, so an unconfigured host is not a
496
895
  // hard failure unless the operator enabled it. Reported as degraded for visibility.
@@ -537,18 +936,52 @@ export function inspectLocalMerge(runCommand, env = process.env) {
537
936
  id: "merge-credential",
538
937
  label: "Configured merge credential",
539
938
  status: "pass",
540
- detail: "BAPI_LOCAL_MERGE_TOKEN or BAPI_MACHINE_MERGE_TOKEN is set",
939
+ detail: localResolution.status === "resolved"
940
+ ? localResolution.via_alias
941
+ ? "the local credential is set through the deprecated BAPI_LOCAL_MERGE_TOKEN"
942
+ : "GITHUB_MERGE_TOKEN is set"
943
+ : storedConfigured
944
+ ? "a merge token is stored for this repository"
945
+ : "BAPI_MACHINE_MERGE_TOKEN is set",
541
946
  }
542
- : {
543
- id: "merge-credential",
544
- label: "Configured merge credential",
545
- status: "warn",
546
- detail: "`gh` is installed but neither BAPI_LOCAL_MERGE_TOKEN nor " +
547
- "BAPI_MACHINE_MERGE_TOKEN is set, so a local merge would fail closed",
548
- remediation: GH_AUTH_REMEDIATION,
549
- },
947
+ : storedRejected
948
+ ? {
949
+ id: "merge-credential",
950
+ label: "Configured merge credential",
951
+ status: "warn",
952
+ detail: "the merge token stored for this repository was rejected by GitHub",
953
+ remediation: STORED_MERGE_TOKEN_REJECTED_REMEDIATION,
954
+ }
955
+ : storedUnverified
956
+ ? {
957
+ id: "merge-credential",
958
+ label: "Configured merge credential",
959
+ status: "warn",
960
+ detail: "the stored merge token could not be checked right now",
961
+ remediation: STORED_MERGE_TOKEN_UNVERIFIED_REMEDIATION,
962
+ }
963
+ : {
964
+ id: "merge-credential",
965
+ label: "Configured merge credential",
966
+ status: "warn",
967
+ detail: localInvalid
968
+ ? "`gh` is installed but GITHUB_MERGE_TOKEN is not a usable token value and " +
969
+ "BAPI_MACHINE_MERGE_TOKEN is not set, so a local merge would fail closed"
970
+ : "`gh` is installed but neither GITHUB_MERGE_TOKEN nor " +
971
+ "BAPI_MACHINE_MERGE_TOKEN is set, so a local merge would fail closed",
972
+ remediation: GH_AUTH_REMEDIATION,
973
+ },
550
974
  ];
551
- return { gh_available, merge_credential_configured, degraded, warnings, outcomes };
975
+ return {
976
+ gh_available,
977
+ merge_credential_configured,
978
+ degraded,
979
+ warnings,
980
+ outcomes,
981
+ notes,
982
+ ...(local_credential_source !== undefined ? { local_credential_source } : {}),
983
+ ...(stored !== undefined ? { stored_credential: stored } : {}),
984
+ };
552
985
  }
553
986
  /** Remediation when this host has no `gh` identity to observe with. */
554
987
  export const GH_ACTIONS_MERGE_AUTH_REMEDIATION = "run `gh auth login` so this host has a GitHub identity; without one it cannot " +
@@ -698,17 +1131,25 @@ export async function buildConductorDoctorReport(deps = {}) {
698
1131
  const command_drift = deps.inspectCommandDrift
699
1132
  ? await inspectCommandDriftSafe(deps.inspectCommandDrift)
700
1133
  : undefined;
1134
+ const worker_database = deps.inspectWorkerDatabase
1135
+ ? await collectWorkerDatabaseDoctorSection(deps.inspectWorkerDatabase, deps.workerDatabaseTimeoutMs ?? WORKER_DATABASE_DOCTOR_TIMEOUT_MS)
1136
+ : undefined;
701
1137
  return {
702
1138
  ledger,
703
1139
  git_hooks: inspectHooks(deps.hooksDeps),
704
1140
  mcp_profile,
705
- local_merge: inspectLocalMerge(deps.runCommand),
1141
+ // BAPI-1461: the SAME env the rest of the report reads, plus the stored-entry
1142
+ // finding when a store context was supplied.
1143
+ local_merge: inspectLocalMerge(deps.runCommand, deps.env ?? process.env, deps.storedMergeCredential
1144
+ ? await collectStoredMergeCredentialEvidence(deps.env ?? process.env, deps.storedMergeCredential)
1145
+ : undefined),
706
1146
  github_actions_merge: inspectGitHubActionsMergeSafe(deps),
707
1147
  native_ledger,
708
1148
  deny_enforcement,
709
1149
  claude_login,
710
1150
  repair_credentials: await inspectRepairVerbCredentials(deps.env ?? process.env, deps.resolveRepairAccess),
711
1151
  ...(command_drift ? { command_drift } : {}),
1152
+ ...(worker_database ? { worker_database } : {}),
712
1153
  };
713
1154
  }
714
1155
  /** Run the drift inspector, containing any throw as an unassessable `warn`. */
@@ -865,7 +1306,9 @@ export function formatConductorDoctorReport(report) {
865
1306
  : "[WARNING] no merge credential configured"
866
1307
  : "[WARNING] not installed";
867
1308
  lines.push(`gh available: ${local_merge.gh_available} ${ghTag}`);
868
- lines.push(`merge credential set: ${local_merge.merge_credential_configured}`);
1309
+ lines.push(`merge credential set: ${local_merge.merge_credential_configured}` +
1310
+ // BAPI-1461: say where a stored token came from (never its value).
1311
+ (local_merge.local_credential_source === "store" ? " (stored for this repository)" : ""));
869
1312
  lines.push(`degraded: ${local_merge.degraded}`);
870
1313
  // BAPI-1135 — the two observations render INDEPENDENTLY, each leading with its
871
1314
  // own decisive word, because they have two different fixes. Collapsing them
@@ -897,6 +1340,11 @@ export function formatConductorDoctorReport(report) {
897
1340
  for (const w of local_merge.warnings)
898
1341
  lines.push(` - ${w}`);
899
1342
  }
1343
+ if (local_merge.notes && local_merge.notes.length > 0) {
1344
+ lines.push("local merge notes:");
1345
+ for (const n of local_merge.notes)
1346
+ lines.push(` - ${n}`);
1347
+ }
900
1348
  if (report.repair_credentials) {
901
1349
  const repair = report.repair_credentials;
902
1350
  lines.push("");
@@ -965,6 +1413,12 @@ export function formatConductorDoctorReport(report) {
965
1413
  if (row.remediation)
966
1414
  lines.push(` → ${row.remediation}`);
967
1415
  }
1416
+ // BAPI-1479 — advisory worker-database rows, after every existing section so
1417
+ // the output of a report without them is byte-identical.
1418
+ if (report.worker_database) {
1419
+ lines.push("");
1420
+ lines.push(...formatWorkerDatabaseDoctorSection(report.worker_database));
1421
+ }
968
1422
  return lines.join("\n");
969
1423
  }
970
1424
  // ---------------------------------------------------------------------------