@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,6 +1,16 @@
1
1
  /**
2
2
  * `install-bridge conductor` — the nested conductor bootstrap phase (BAPI-679).
3
3
  *
4
+ * BAPI-1461 — CONVERGING SETUP. With the production setup seams (always
5
+ * supplied by `install-bridge.ts`), this command is a loop, not a script: it
6
+ * reads the Claude login marker, confirms the base URL, checks `gh auth
7
+ * status`, collects every readiness finding read-only, fixes only the missing
8
+ * items in order (each write surface behind its own consent), checks again —
9
+ * running the deny-enforcement probe once, there — and prints one verdict
10
+ * beside the legacy completion line. The fixed eight-phase sequence below
11
+ * remains only for a caller that supplies no setup seams. See
12
+ * `install-bridge-conductor-setup.ts` for the item model and fix planner.
13
+ *
4
14
  * Standing up Epic Conductor v2 on a fresh repository previously meant a manual
5
15
  * sequence of API calls and hand-written config, with five server-side
6
16
  * prerequisites that were invisible until an epic was already running and
@@ -47,7 +57,7 @@
47
57
  * MCP entries (`.mcp.json`, `.vscode/mcp.json`, `.cursor/mcp.json` only,
48
58
  * never Codex or Copilot), then print the restart advisory, because
49
59
  * `ACTIVE_GROUPS` is frozen at MCP server startup.
50
- * local observability — install the managed conductor Git hooks, then report
60
+ * local observability — install the managed Git hooks, then report
51
61
  * native ledger loadability. The ledger probe is READ-ONLY, so it needs no
52
62
  * consent and runs whether hook consent was accepted or declined.
53
63
  *
@@ -111,6 +121,14 @@ import { emptyConductorGateFlags, hasExplicitGateInput, parseLocalCommandFlag, p
111
121
  import { bootstrapConductorSupervisorDefaults, classifySupervisorBootstrapFailure, fetchConductorReadiness, previewConductorSupervisorBootstrap, } from "./conductor/bridge-api-client.js";
112
122
  import { CONDUCTOR_OPERATOR_RUNBOOK_POINTER, EXECUTOR_PROVISIONING_GUIDANCE, conductorInstallDoctorExitCode, conductorInstallDoctorHasFatal, formatConductorInstallDoctorReport, } from "./conductor/install-doctor.js";
113
123
  import { describeNativeLedgerAvailability, } from "./conductor/doctor.js";
124
+ import { resolveGithubMergeRepositoryIdentity, } from "./credential-store.js";
125
+ import { isUsableMergeCredentialValue, resolveLocalMergeCredentialDetailed, } from "./conductor/merge-credential.js";
126
+ import { readStoredTestCommand, writeStoredTestCommand, } from "./testing-config-client.js";
127
+ import { describeToolchainResolution, resolveRepositoryToolchains, } from "./repository-toolchains.js";
128
+ import { detectTestCommand } from "./test-command-detection.js";
129
+ import { TestCommandValidationError, validateTestCommand, } from "./test-command-validation.js";
130
+ import { EPIC_IMPLEMENTER_CI_CHECK_NAME } from "./epic-ci-workflow.js";
131
+ import { assessSetupIndex, catalogLabel, compareIndexedToMerge, isTestCommandFix, planSetupFixes, projectSetupItems, readSetupPullRequest, renderSetupAssessment, setupVerdictLine, unmetBlockingItems, } from "./install-bridge-conductor-setup.js";
114
132
  import { CONDUCTOR_BIN_UNRESOLVED_ERROR, MANAGED_HOOK_NAMES, } from "./conductor/git-hooks.js";
115
133
  import os from "node:os";
116
134
  import path from "node:path";
@@ -119,6 +137,7 @@ import { bindEpicLaunchCredential, readStoredBinding, } from "./credential-store
119
137
  import { EPIC_LAUNCH_EXECUTION_MODES, EPIC_LAUNCH_PROFILE_NAME_PATTERN, EPIC_LAUNCH_PROFILE_VERSION, createNodeEpicLaunchStoreDeps, readEpicLaunchProfile, renderEpicLaunchCommand, resolveEpicLaunchTarget, writeEpicLaunchProfile, } from "./epic-launch-profile.js";
120
138
  import { DEFAULT_BAPI_BASE_URL } from "./executor/credentials.js";
121
139
  import { MCP_PACKAGE_NAME } from "./mcp-identity.js";
140
+ import { LOCAL_MERGE_CREDENTIAL_ENV_KEYS } from "./conductor/merge-credential.js";
122
141
  import { CLAUDE_REVIEW_WORKFLOW_RELPATH, renderClaudeReviewWorkflow, } from "./claude-review-workflow.js";
123
142
  import { formatExecutorInstallPreflight, } from "./executor/install-preflight.js";
124
143
  import { buildExecutorServiceStartPlan, formatExecutorServiceStartFailure, } from "./executor/service-lifecycle.js";
@@ -149,24 +168,63 @@ export function getInstallBridgeConductorUsage() {
149
168
  return [
150
169
  "Usage: install conductor [options]",
151
170
  "",
152
- "Bootstrap the Epic Implementer for this repository: run the unified read-only",
153
- "doctor, write the safe project-default supervisor posture, optionally scaffold",
154
- "the claude-review workflow, report the capability matrix, and re-run the doctor.",
171
+ "Set up this repository for the Epic Implementer. It checks everything first",
172
+ "(read-only), fixes only what is missing, checks again, and ends with one",
173
+ "verdict: \"Ready for your first epic\" or \"Not ready: N steps left\" with the fix",
174
+ "for each step. The last line is still complete or complete-with-manual-steps.",
175
+ "It exits 0 when ready and 1 otherwise (0 for --dry-run and for a declined URL",
176
+ "confirmation). `install-bridge conductor` is the same command.",
177
+ "",
178
+ "It first reads your Claude sign-in (~/.claude.json only) and, after the URL",
179
+ "confirmation, runs `gh auth status`. A ready repository gets no questions and no",
180
+ "writes. Otherwise it asks only what a missing item needs, each with a default of no:",
181
+ " - which repository, only when it cannot tell;",
182
+ " - saving the test command, only when none is stored (or replacing it, when you",
183
+ " pass --test-command);",
184
+ " - opening the setup pull request with the CI workflow;",
185
+ " - storing the repository gate and safe defaults, when they would change;",
186
+ " - storing a GitHub merge token on this computer (read with no echo).",
187
+ "The URL confirmation is asked on every run and is not one of these. Without an",
188
+ "interactive terminal every question is a decline: no token is stored and no",
189
+ "pull request is opened. When setup reports that its setup pull request is",
190
+ "waiting, merge it and run setup again: the re-run queues one repository index",
191
+ "if needed and reports it pending until it finishes.",
192
+ "",
193
+ "Merge token: setup can store a GitHub token for this repository in your user",
194
+ "credential store (~/.config/bridge/credentials.json). GITHUB_MERGE_TOKEN, then",
195
+ "BAPI_LOCAL_MERGE_TOKEN, take precedence over it. It is never sent to Bridge.",
196
+ "When GitHub rejects it, setup offers to replace it. Removing it deletes the",
197
+ "local copy only; it does not revoke the token at GitHub, and a running executor",
198
+ "keeps the token it started with until it restarts.",
199
+ "",
200
+ "Test command: setup prints the stored command (and what CI installs for it) on",
201
+ "every run. To save or replace it, pass --test-command \"<command>\": the flag is",
202
+ "your consent for that one write, so there is no command question. The command is",
203
+ "checked first (one line, no GitHub Actions expression, at most 500 characters),",
204
+ "saved once, and read back; setup reports success only when the stored value",
205
+ "matches. The same value again is \"unchanged\" and writes nothing. The flag does",
206
+ "NOT replace the base-URL confirmation (still asked, so it needs a terminal) and",
207
+ "does NOT consent to the workflow pull request, which asks for itself. With",
208
+ "--dry-run nothing is saved. Do not put a credential in a command: setup prints",
209
+ "it and the workflow file contains it.",
155
210
  "",
156
211
  "Options:",
212
+ " --test-command <command> Save or replace the repository's test command.",
213
+ " Not combinable with --remove-merge-token or",
214
+ " --clear-gate; may be given once.",
215
+ " --remove-merge-token Remove the merge token stored on this computer for",
216
+ " this repository (its own consent), then exit.",
157
217
  " --repo <name> Repository name (default: BAPI_REPO_NAME / .bridge/config)",
158
- " --required-check <name> A provider check for the gate (repeatable). Explicit",
159
- " owner input: stored as a confirmed provider gate and",
160
- " projected into the done gate, as before.",
218
+ " --required-check <name> A provider check for the gate (repeatable). Stored as a",
219
+ " confirmed provider gate and projected into the done gate.",
161
220
  " --required-checks a,b Comma-separated form of --required-check",
162
221
  "",
163
- "Repository gate (BAPI-1391) — what must pass before a child merges. A CONFIRMED",
164
- "gate is required: provider checks, local commands, both (mixed), or none.",
165
- "Without gate flags, a confirmed gate already stored (including an older",
166
- "--required-check setup) is used unchanged; otherwise discovery reads this",
167
- "working tree and the provider's real check history and PROPOSES a gate, which",
168
- "is stored only after you confirm or edit it at a prompt. Discovery saves",
169
- "nothing. Explicit gate flags are owner input and are stored as confirmed.",
222
+ "Repository gate — what must pass before a child merges. A CONFIRMED gate is",
223
+ "required: provider checks, local commands, both (mixed), or none. Without gate",
224
+ "flags, a confirmed gate already stored is used unchanged; otherwise discovery",
225
+ "reads this working tree and the provider's real check history and PROPOSES a",
226
+ "gate, which is stored only after you confirm or edit it at a prompt. Discovery",
227
+ "saves nothing. Explicit gate flags are stored as confirmed.",
170
228
  " --provider-check <name> An exact provider-reported check name (repeatable).",
171
229
  " Admission refuses one that has never reported.",
172
230
  " --local-command <cmd> A local command the executor runs before each merge",
@@ -184,35 +242,20 @@ export function getInstallBridgeConductorUsage() {
184
242
  " --clear-gate Clear the confirmed gate (its own consent), then exit.",
185
243
  " --qualify-gate Qualify a confirmed local or mixed gate: queue the",
186
244
  " qualification job and drain it with a short-lived",
187
- " repository-wide executor limited to that job type.",
188
- " Alone, it does only that; with gate flags it runs",
189
- " after they are stored, without the offer prompt.",
190
- " Every gate write first checks that the server advertises gate_profile.v1;",
191
- " against an older server it prints \"Bridge API update required\" and exits 1.",
245
+ " executor limited to that job type. Alone, it does only",
246
+ " that; with gate flags it runs after they are stored,",
247
+ " without the offer prompt.",
192
248
  "",
193
249
  ` --review-policy <source> One of: ${CONDUCTOR_REVIEW_POLICY_SOURCES.join(", ")}`,
194
- " Omitted, install assumes repository_policy: the",
195
- " prospective default for a new feature-branch run at",
196
- " first approval when neither the run nor the",
197
- " repository sets a policy. It scaffolds no Claude",
198
- " review workflow and stores no default at all.",
199
- " AI review is an explicit opt-in: pass",
200
- " --review-policy verdict_protocol to scaffold the",
201
- " workflow. Supplying any value EXPLICITLY also",
202
- " persists it as the supervisor project default,",
203
- " stamped into a new run that carries no review",
204
- " policy of its own.",
250
+ " Omitted, install assumes repository_policy and",
251
+ " scaffolds no Claude review workflow. AI review is an",
252
+ " explicit opt-in: pass --review-policy verdict_protocol",
253
+ " to scaffold the workflow. Supplying any value also",
254
+ " persists it as the project default, stamped into a new",
255
+ " run that carries no review policy of its own.",
205
256
  " --epic-key <KEY> Epic key for the setup-epic verification phase",
206
257
  " --plan-file <path> Plan sidecar for the setup-epic verification phase",
207
- " --executor-id <id> Stable executor id. Supplying it OPTS IN to the",
208
- " consented executor-provisioning phase below; the",
209
- " phase is skipped entirely without it.",
210
- " --epic-run-id <id> Claim scope for the generated unit (repeatable).",
211
- " --repo-wide Claim-scope opt-out: claim from every authorized",
212
- " repo, unscoped by run. EXACTLY ONE of --epic-run-id",
213
- " or --repo-wide is required with --executor-id — the",
214
- " executor refuses to start without one, so a unit",
215
- " generated without it would fail on every boot.",
258
+ " AI PR review only (--review-policy verdict_protocol):",
216
259
  " --allowed-bot <slug> claude-review workflow: allowed bot login",
217
260
  " --secret-name <NAME> claude-review workflow: OAuth token secret NAME",
218
261
  " --branches a,b claude-review workflow: PR branch triggers",
@@ -222,85 +265,50 @@ export function getInstallBridgeConductorUsage() {
222
265
  " install keeps the stored gate and only adds missing",
223
266
  " checks. Any requirement a replacement would remove",
224
267
  " is previewed and needs its own exact approval.",
225
- " --launch-profile <name> (BAPI-1260) Opt in to the reusable epic launch: after",
226
- " every mandatory prerequisite is verified, persist a",
227
- " host-local profile and print the ONE drive-epic",
228
- " command that selects it (runs in a fresh shell).",
229
- " Optional for production — drive-epic targets it with",
230
- " no profile. Needed for local or durable-host targets.",
231
- " --base-url <url> Explicit Bridge API target for --launch-profile.",
232
- " Required there (or BAPI_BASE_URL): guided setup",
233
- " approves one named server and has no default.",
234
- " --execution-mode <mode> local | durable (default: durable with",
235
- " --executor-id, otherwise local).",
236
- " --policy-file <path> Run policy the profile references. An unattended",
237
- " run escalates to a notify.webhook_url reachable",
238
- " from the API server or, with none declared, to the",
239
- " account's email (notify.local_sink is not enough).",
268
+ " --epic-branch-ci-decision <include|decline>",
269
+ " (GitHub only) Record whether child merges into an epic",
270
+ " branch wait for CI on that PR. Without it you are",
271
+ " asked; a non-interactive run records nothing.",
240
272
  " --dry-run Diagnose and preview only. Performs NO writes:",
241
273
  " no POST, no file write, no host MCP config write,",
242
274
  " no Git hook write, no install-state or capability",
243
- " write, no service-unit write, no launchctl/systemctl",
244
- " or other lifecycle command, and no write- or",
245
- " start-consent prompt.",
246
- " Still asks the base-URL confirmation below first —",
247
- " its doctor readiness GET carries the repo API key.",
248
- " --epic-branch-ci-decision <include|decline>",
249
- " (BAPI-1405, GitHub only) Record whether child merges",
250
- " into an epic branch wait for CI on that PR. Without",
251
- " it you are asked; a non-interactive run records",
252
- " nothing. Never consent to change an approval rule.",
275
+ " write, no service-unit write, and no write- or",
276
+ " start-consent prompt. Still asks the base-URL",
277
+ " confirmation first — its readiness read carries the",
278
+ " repo API key.",
253
279
  " -h, --help Show this help",
254
280
  "",
281
+ "Owner options (durable hosts and launch profiles; see `drive-epic --help-advanced`):",
282
+ " --executor-id <id> Stable executor id. Opts in to the consented",
283
+ " executor-provisioning phase.",
284
+ " --epic-run-id <id> Claim scope for the generated unit (repeatable).",
285
+ " --repo-wide Claim from every run in the repository. EXACTLY ONE of",
286
+ " --epic-run-id or --repo-wide is required with",
287
+ " --executor-id.",
288
+ " --launch-profile <name> Save a host-local launch profile and print the one",
289
+ " drive-epic command that selects it.",
290
+ " --base-url <url> Explicit Bridge API target for --launch-profile.",
291
+ " --execution-mode <mode> local | durable (default: durable with",
292
+ " --executor-id, otherwise local).",
293
+ " --policy-file <path> Run policy the profile references.",
294
+ "",
255
295
  "The resolved BAPI_BASE_URL is displayed and confirmed BEFORE any network call",
256
- "(including the read-only doctor GET — BAPI_BASE_URL silently defaults to",
257
- "production when unset). The bootstrap POST then asks its own, separate write",
258
- "consent. Without a TTY there is no consent, so the command aborts.",
296
+ "(BAPI_BASE_URL silently defaults to production when unset). The bootstrap POST",
297
+ "then asks its own, separate write consent. Without a TTY there is no consent,",
298
+ "so the command aborts.",
259
299
  "",
260
300
  "Tool visibility (its own consent): adds the `epic_implementer` token to the",
261
301
  "BRIDGE_MCP_PROFILE of the Bridge entry in host MCP configurations that",
262
- "ALREADY have one. Automatic merging covers .mcp.json, .vscode/mcp.json, and",
263
- ".cursor/mcp.json only — never Codex or Copilot, which are neither inspected",
264
- "nor changed. No file is ever created: when no supported config carries a",
265
- "a Bridge entry, the run says so and points at the base `install` command.",
266
- "The MCP server captures its active groups at startup, so a merge activates on",
267
- "the next launch — restart your MCP client to see the Epic Implementer tools.",
268
- "",
269
- "Local observability (a SEPARATE consent): installs or updates this",
270
- "repository's managed conductor Git hooks (post-commit,",
271
- "reference-transaction) and reports each hook's action. It then probes native",
272
- "ledger loadability, which is READ-ONLY and therefore runs with or without",
273
- "hook consent; a degraded ledger reports the module, NODE_MODULE_VERSION, and",
274
- "failure kind, and never triggers an install, rebuild, or migration.",
302
+ "ALREADY have one (.mcp.json, .vscode/mcp.json, and .cursor/mcp.json only). No",
303
+ "file is ever created: when no supported config carries a Bridge entry, the run",
304
+ "says so and points at the base `install` command. Restart your MCP client to",
305
+ "see the Epic Implementer tools.",
275
306
  "",
276
- "Durable-host mode: this command is the supported bring-up for a persistent,",
277
- "laptop-independent executor. It composes planning, separately consented unit",
278
- "writing, separately consented start, read-only local inspection, and bounded",
279
- "server-observed readiness. `executor install-service` still generates a unit and",
280
- "nothing else, and remains available for operators who manage lifecycle themselves.",
281
- "",
282
- "Host ownership (operator-operated or Bridge-operated) is an operational selection,",
283
- "not server policy: both run identical generation and lifecycle logic, and",
284
- "BAPI_BASE_URL is the only ownership/location input. Bridge-operated mode allocates",
285
- "no host — it configures one already assigned. A repository with no assigned durable",
286
- "host is NOT ready; escalate that to Bridge operations.",
287
- "",
288
- "With --executor-id, this command does the whole leg. A preflight checks the platform,",
289
- "`wt` / `git` / `claude` on PATH, and an explicit base URL, then reports whether",
290
- "this host has a `claude login` marker — that line is ADVISORY and never blocks,",
291
- "and no API key, token, or other credential is requested, stored, or checked.",
292
- "",
293
- "Two independent consents follow. The first writes the service unit; the second,",
294
- `asked separately, starts it (${"`launchctl bootstrap`"} on darwin,`,
295
- "`systemctl --user daemon-reload && systemctl --user enable --now` on linux) with",
296
- "exactly one attempt and no retry loop. Declining either one, or a start that",
297
- "fails, prints the exact start command and finishes at complete-with-manual-steps.",
298
- "",
299
- "After a successful start the command polls the server for roughly 90 seconds for",
300
- "the executor to be observed. Only that live server observation can report",
301
- "executor_ready: a written unit and a successful local start never can, so an",
302
- "observation timeout finishes at complete-with-manual-steps and says exactly what",
303
- "was and was not achieved.",
307
+ "Local observability (a SEPARATE consent): installs or updates this repository's",
308
+ "managed Git hooks (post-commit, reference-transaction) and reports each hook's",
309
+ "action. It then probes native ledger loadability, which is READ-ONLY; a degraded",
310
+ "ledger reports the module, NODE_MODULE_VERSION, and failure kind, and never",
311
+ "triggers an install, rebuild, or migration.",
304
312
  "",
305
313
  `See ${CONDUCTOR_OPERATOR_RUNBOOK_POINTER}.`,
306
314
  ].join("\n");
@@ -343,6 +351,9 @@ export function parseInstallBridgeConductorArgs(argv) {
343
351
  let executionMode;
344
352
  let policyFile;
345
353
  let epicBranchCiDecision;
354
+ let removeMergeToken = false;
355
+ let testCommand;
356
+ let testCommandSeen = false;
346
357
  const takeValue = (arg, inline, next) => {
347
358
  if (inline !== undefined) {
348
359
  if (inline.trim().length === 0)
@@ -380,6 +391,42 @@ export function parseInstallBridgeConductorArgs(argv) {
380
391
  return { status: "error", message: "--repo-wide takes no value" };
381
392
  repoWide = true;
382
393
  break;
394
+ case "--remove-merge-token":
395
+ if (inline !== undefined) {
396
+ return { status: "error", message: "--remove-merge-token takes no value" };
397
+ }
398
+ removeMergeToken = true;
399
+ break;
400
+ case "--test-command": {
401
+ if (testCommandSeen)
402
+ return { status: "error", message: "--test-command may be given once" };
403
+ testCommandSeen = true;
404
+ // The raw value is validated BEFORE any trimming: `takeValue` trims, which
405
+ // would turn a command ending in a newline into a valid one-line command.
406
+ let rawCommand;
407
+ if (inline !== undefined) {
408
+ rawCommand = inline;
409
+ }
410
+ else {
411
+ const next = argv[i + 1];
412
+ if (next === undefined || next.startsWith("-")) {
413
+ return { status: "error", message: "--test-command requires a value" };
414
+ }
415
+ rawCommand = next;
416
+ i++;
417
+ }
418
+ try {
419
+ testCommand = validateTestCommand(rawCommand);
420
+ }
421
+ catch (err) {
422
+ // The message is fixed text and never echoes the command.
423
+ if (err instanceof TestCommandValidationError) {
424
+ return { status: "error", message: `Invalid --test-command: ${err.message}` };
425
+ }
426
+ throw err;
427
+ }
428
+ break;
429
+ }
383
430
  case "--gate-none":
384
431
  case "--confirm-gate":
385
432
  case "--clear-gate":
@@ -570,6 +617,45 @@ export function parseInstallBridgeConductorArgs(argv) {
570
617
  "--executor-id.",
571
618
  };
572
619
  }
620
+ // BAPI-1536 — `--clear-gate` is a standalone action that stops before setup, so a
621
+ // command request beside it would be silently dropped. Refuse the pair.
622
+ if (testCommand !== undefined && gate.clearGate) {
623
+ return {
624
+ status: "error",
625
+ message: "--test-command cannot be combined with --clear-gate: clearing the gate is a standalone action.",
626
+ };
627
+ }
628
+ // BAPI-1461 — token removal is its own action: only --repo and --dry-run may
629
+ // accompany it, so it can never be mistaken for, or followed by, setup writes.
630
+ if (removeMergeToken) {
631
+ const conflicting = requiredChecks.length > 0 ||
632
+ hasExplicitGateInput(gate) ||
633
+ gate.clearGate ||
634
+ gate.qualifyGate ||
635
+ executorId !== undefined ||
636
+ epicRunIds.length > 0 ||
637
+ repoWide ||
638
+ launchProfile !== undefined ||
639
+ baseUrl !== undefined ||
640
+ executionMode !== undefined ||
641
+ policyFile !== undefined ||
642
+ epicKey !== undefined ||
643
+ planFile !== undefined ||
644
+ epicBranchCiDecision !== undefined ||
645
+ reviewPolicyExplicit ||
646
+ replaceDoneGate ||
647
+ skipWorkflow ||
648
+ allowedBot !== undefined ||
649
+ secretName !== undefined ||
650
+ testCommand !== undefined ||
651
+ branches !== undefined;
652
+ if (conflicting) {
653
+ return {
654
+ status: "error",
655
+ message: "--remove-merge-token is a standalone action: combine it only with --repo or --dry-run.",
656
+ };
657
+ }
658
+ }
573
659
  // BAPI-1260 — the launch-profile inputs only mean something together.
574
660
  if (launchProfile === undefined && (baseUrl !== undefined || executionMode !== undefined)) {
575
661
  return {
@@ -610,6 +696,8 @@ export function parseInstallBridgeConductorArgs(argv) {
610
696
  : {}),
611
697
  ...(policyFile ? { policyFile } : {}),
612
698
  ...(epicBranchCiDecision ? { epicBranchCiDecision } : {}),
699
+ ...(removeMergeToken ? { removeMergeToken: true } : {}),
700
+ ...(testCommand !== undefined ? { testCommand } : {}),
613
701
  },
614
702
  };
615
703
  }
@@ -706,15 +794,13 @@ const CONSENT_YES = new Set(["y", "yes"]);
706
794
  /** Fixed, value-free operator text for each bootstrap failure (BAPI-1288). */
707
795
  const BOOTSTRAP_FAILURE_TEXT = Object.freeze({
708
796
  "unsupported-protocol": "the Bridge API server does not support the gate-change preview protocol " +
709
- "(it predates BAPI-1288) or answered a response this installer cannot verify. " +
710
- "Upgrade the server before re-running; this installer never falls back to the " +
711
- "older bootstrap that replaced configured gates.",
797
+ "or answered a response this installer cannot verify. Email info@bridgegpt.ai; this " +
798
+ "installer never falls back to the older bootstrap that replaced configured gates.",
712
799
  "approval-required": "the server requires an approved preview for this change. Re-run to preview it again.",
713
800
  "stale-preview": "the project defaults changed since the preview, or the approval expired. " +
714
801
  "Re-run to preview the current state again.",
715
802
  "unknown-stored-state": "a stored project-default row cannot be read with certainty, so no change to it " +
716
- "can be evaluated. See the account-settings operator runbook " +
717
- "(unknown_stored_state) before re-running.",
803
+ "can be evaluated. Email info@bridgegpt.ai (unknown_stored_state) before re-running.",
718
804
  "non-relaxable": "the change would turn auto-merge on or drop the human merge-approval requirement, " +
719
805
  "which no gate-change approval can authorize.",
720
806
  "invalid-proposal": "the server rejected the proposed configuration as unreadable.",
@@ -793,6 +879,15 @@ async function confirm(deps, promptText) {
793
879
  const answer = await deps.promptLine(promptText);
794
880
  return CONSENT_YES.has((answer ?? "").trim().toLowerCase());
795
881
  }
882
+ /**
883
+ * BAPI-1452 — the merge-credential next step. Value-free configuration guidance
884
+ * only: it names the configuration keys and never reads, writes, migrates, or
885
+ * asks for a credential value. `GITHUB_MERGE_TOKEN` is the local merge
886
+ * credential; the machine-user credential is a distinct key, not an alias.
887
+ */
888
+ export const MERGE_CREDENTIAL_INSTALL_GUIDANCE = `set ${LOCAL_MERGE_CREDENTIAL_ENV_KEYS.local} (the local merge credential) in the environment the ` +
889
+ `executor is launched from, or ${LOCAL_MERGE_CREDENTIAL_ENV_KEYS.machine_token} for machine-user ` +
890
+ "mode; Bridge never stores either.";
796
891
  function renderCapabilityMatrix(deps, readiness) {
797
892
  const apiReady = readiness !== null;
798
893
  // BAPI-1391 — a CONFIRMED local-only or `none` gate has no CI checks by
@@ -829,6 +924,7 @@ function renderCapabilityMatrix(deps, readiness) {
829
924
  : ")") : ""));
830
925
  }
831
926
  deps.log(` executor provisioning: ${EXECUTOR_PROVISIONING_GUIDANCE}`);
927
+ deps.log(` merge credential: ${MERGE_CREDENTIAL_INSTALL_GUIDANCE}`);
832
928
  deps.log(` runbook: ${CONDUCTOR_OPERATOR_RUNBOOK_POINTER}`);
833
929
  return { apiReady, configurationReady, executorReady };
834
930
  }
@@ -1065,7 +1161,7 @@ export function formatConductorRestartAdvisory(mergedProfile) {
1065
1161
  /** Remediation printed when no supported host config carries a Bridge entry. */
1066
1162
  export const CONDUCTOR_PROFILE_EMPTY_MERGE_REMEDIATION = `run \`${PRINTED_INSTALL_COMMAND}\` to create and register the host MCP entry, ` +
1067
1163
  "then re-run `install conductor`.";
1068
- /** Remediation printed whenever the managed conductor hooks were not installed. */
1164
+ /** Remediation printed whenever the managed git hooks were not installed. */
1069
1165
  export const CONDUCTOR_HOOKS_MANUAL_REMEDIATION = "re-run `install conductor` and accept the local-observability consent, or run " +
1070
1166
  "`epic-implementer install-git-hooks` directly.";
1071
1167
  /**
@@ -1091,7 +1187,7 @@ async function runConductorToolVisibilityPhase(deps, local) {
1091
1187
  return {
1092
1188
  manualActions: [
1093
1189
  "tool visibility: re-run `install conductor` and accept the profile consent to " +
1094
- "make the conductor MCP tools visible.",
1190
+ "make the Epic Implementer MCP tools visible.",
1095
1191
  ],
1096
1192
  };
1097
1193
  }
@@ -1143,7 +1239,7 @@ async function runConductorToolVisibilityPhase(deps, local) {
1143
1239
  /**
1144
1240
  * Phase: local observability.
1145
1241
  *
1146
- * Installs the managed conductor Git hooks behind its OWN consent — never
1242
+ * Installs the managed Git hooks behind its OWN consent — never
1147
1243
  * inferred from the base-URL, bootstrap, workflow, profile-token, or executor
1148
1244
  * consents — and then always reports native ledger loadability, which is
1149
1245
  * read-only and therefore needs no consent at all.
@@ -1151,7 +1247,7 @@ async function runConductorToolVisibilityPhase(deps, local) {
1151
1247
  async function runConductorLocalObservabilityPhase(deps, local) {
1152
1248
  const manualActions = [];
1153
1249
  let fatal = false;
1154
- const consented = await confirm(deps, "Install or update this repository's managed conductor Git hooks " +
1250
+ const consented = await confirm(deps, "Install or update this repository's managed Git hooks " +
1155
1251
  "(post-commit, reference-transaction)? [y/N]: ");
1156
1252
  if (!consented) {
1157
1253
  deps.log(" declined — no Git hook and no install state were written.");
@@ -1166,7 +1262,7 @@ async function runConductorLocalObservabilityPhase(deps, local) {
1166
1262
  // Generic by design: the caught value can carry a hooks-directory path.
1167
1263
  // The phase is marked fatal but does NOT return here — the read-only
1168
1264
  // ledger report below still owes the operator its answer.
1169
- deps.errorLog(" the conductor Git hooks could not be installed.");
1265
+ deps.errorLog(" the Epic Implementer Git hooks could not be installed.");
1170
1266
  manualActions.push(`local observability: ${CONDUCTOR_HOOKS_MANUAL_REMEDIATION}`);
1171
1267
  fatal = true;
1172
1268
  }
@@ -1207,7 +1303,7 @@ async function runConductorLocalObservabilityPhase(deps, local) {
1207
1303
  if (!result.is_worktree) {
1208
1304
  deps.log(" not a git worktree, so no managed hook was installed (degraded optional capability).");
1209
1305
  manualActions.push("local observability: run `install conductor` from a git worktree to install the " +
1210
- "managed conductor hooks.");
1306
+ "managed git hooks.");
1211
1307
  }
1212
1308
  else {
1213
1309
  for (const hook of result.installed) {
@@ -1290,7 +1386,7 @@ async function runConductorLocalObservabilityPhase(deps, local) {
1290
1386
  deps.log(` ledger degraded — ${availability.module} did not load ` +
1291
1387
  `(NODE_MODULE_VERSION ${availability.nodeModulesAbi}, failure: ${availability.failureKind}).`);
1292
1388
  manualActions.push(`local observability: reinstall ${availability.module} for this Node runtime to ` +
1293
- "restore the local conductor event ledger.");
1389
+ "restore the local Epic Implementer event ledger.");
1294
1390
  }
1295
1391
  }
1296
1392
  return { manualActions, fatal };
@@ -1399,6 +1495,15 @@ function assessNotification(policy, attended, targetBaseUrl, readiness) {
1399
1495
  "delivers a verification to it at approval, and a failure there holds activation.",
1400
1496
  };
1401
1497
  }
1498
+ /** BAPI-1461 — whether a stored profile already records exactly this launch. */
1499
+ function launchProfileMatches(prior, next) {
1500
+ return (prior.baseUrl === next.baseUrl &&
1501
+ prior.repoName === next.repoName &&
1502
+ prior.executionMode === next.executionMode &&
1503
+ JSON.stringify(prior.runtime) === JSON.stringify(next.runtime) &&
1504
+ JSON.stringify(prior.policyRef ?? null) === JSON.stringify(next.policyRef ?? null) &&
1505
+ prior.credentialRef?.target === `bapi:${next.repoName}`);
1506
+ }
1402
1507
  /**
1403
1508
  * Verify every mandatory launch prerequisite at the selected target, then —
1404
1509
  * and only then — persist the profile and print the one command that selects
@@ -1422,7 +1527,7 @@ async function runLaunchProfilePhase(deps, options, inputs) {
1422
1527
  deps.log(` mode: ${mode}`);
1423
1528
  // (1) Access at THIS target — only a server answer proves the key works there.
1424
1529
  if (inputs.readiness === null) {
1425
- gaps.push("the selected target's conductor readiness could not be read with this repository's credential.");
1530
+ gaps.push("the selected target's Epic Implementer readiness could not be read with this repository's credential.");
1426
1531
  }
1427
1532
  // (2) The policy reference and what it implies.
1428
1533
  let policy = null;
@@ -1456,7 +1561,7 @@ async function runLaunchProfilePhase(deps, options, inputs) {
1456
1561
  gaps.push(consent === false
1457
1562
  ? "unattended consent is off for this repository; turn on 'Allow unattended Epic " +
1458
1563
  "Implementer runs' on the repository's Setup page in the Bridge admin panel " +
1459
- "(if it is already on, contact Bridge support) — this command never writes it."
1564
+ "(if it is already on, email info@bridgegpt.ai) — this command never writes it."
1460
1565
  : "unattended consent could not be verified at the selected target (older server or unreadable report).");
1461
1566
  }
1462
1567
  // (4) Notification, from the server's network perspective.
@@ -1535,29 +1640,41 @@ async function runLaunchProfilePhase(deps, options, inputs) {
1535
1640
  `--base-url ${inputs.baseUrl} --required-check <name> ...`);
1536
1641
  return { complete: false };
1537
1642
  }
1538
- const write = await confirm(deps, `Write epic launch profile '${name}' (references only, no secrets)? [y/N]: `);
1539
- if (!write) {
1540
- deps.log(" declined — no profile was written.");
1541
- return { complete: false };
1643
+ const policyRef = policyPath !== null ? { kind: "file", path: policyPath } : null;
1644
+ let profile;
1645
+ // BAPI-1461: an approved profile that already says exactly this is not
1646
+ // rewritten — no write consent is asked and nothing is written.
1647
+ if (existing.ok && launchProfileMatches(existing.profile, {
1648
+ baseUrl: inputs.baseUrl, repoName, executionMode: mode, runtime: inputs.runtime.runtime, policyRef,
1649
+ })) {
1650
+ deps.log(` profile '${name}' already matches — nothing written.`);
1651
+ profile = existing.profile;
1542
1652
  }
1543
- const profile = {
1544
- version: EPIC_LAUNCH_PROFILE_VERSION,
1545
- name,
1546
- baseUrl: inputs.baseUrl,
1547
- repoName,
1548
- executionMode: mode,
1549
- host: lp.hostname(),
1550
- runtime: inputs.runtime.runtime,
1551
- policyRef: policyPath !== null ? { kind: "file", path: policyPath } : null,
1552
- credentialRef: { store: "bridge-credentials", target: `bapi:${repoName}` },
1553
- approvedAt: lp.nowIso(),
1554
- };
1555
- const written = await lp.writeProfile(profile);
1556
- if (!written.ok) {
1557
- deps.errorLog(` profile write failed: ${written.message}`);
1558
- return { complete: false };
1653
+ else {
1654
+ const write = await confirm(deps, `Write epic launch profile '${name}' (references only, no secrets)? [y/N]: `);
1655
+ if (!write) {
1656
+ deps.log(" declined — no profile was written.");
1657
+ return { complete: false };
1658
+ }
1659
+ profile = {
1660
+ version: EPIC_LAUNCH_PROFILE_VERSION,
1661
+ name,
1662
+ baseUrl: inputs.baseUrl,
1663
+ repoName,
1664
+ executionMode: mode,
1665
+ host: lp.hostname(),
1666
+ runtime: inputs.runtime.runtime,
1667
+ policyRef,
1668
+ credentialRef: { store: "bridge-credentials", target: `bapi:${repoName}` },
1669
+ approvedAt: lp.nowIso(),
1670
+ };
1671
+ const written = await lp.writeProfile(profile);
1672
+ if (!written.ok) {
1673
+ deps.errorLog(` profile write failed: ${written.message}`);
1674
+ return { complete: false };
1675
+ }
1676
+ deps.log(` ${written.action} ${written.path}`);
1559
1677
  }
1560
- deps.log(` ${written.action} ${written.path}`);
1561
1678
  deps.log("");
1562
1679
  deps.log("Launch command (fresh shell; no exports needed):");
1563
1680
  deps.log(` ${renderEpicLaunchCommand(profile, {
@@ -1569,23 +1686,24 @@ async function runLaunchProfilePhase(deps, options, inputs) {
1569
1686
  .replace("'<path>'", "<path>")}`);
1570
1687
  return { complete: true };
1571
1688
  }
1572
- export async function runInstallBridgeConductorCli(argv, deps) {
1573
- const parsed = parseInstallBridgeConductorArgs(argv);
1574
- if (parsed.status === "help") {
1575
- deps.log(parsed.usage);
1576
- return 0;
1577
- }
1578
- if (parsed.status === "error") {
1579
- deps.errorLog(`Error: ${parsed.message}`);
1580
- deps.errorLog("");
1581
- deps.errorLog(getInstallBridgeConductorUsage());
1582
- return 1;
1583
- }
1584
- const options = parsed.options;
1585
- // ---- Base URL: normalized ONCE, confirmed BEFORE any network call ------
1586
- // BAPI-1260: an epic launch profile has NO production default. Its target is
1587
- // --base-url or BAPI_BASE_URL (they must agree), decided here before any
1588
- // request; the hosted default below applies to the legacy flow only.
1689
+ // ---------------------------------------------------------------------------
1690
+ // Shared steps (used by both runners)
1691
+ // ---------------------------------------------------------------------------
1692
+ /**
1693
+ * Resolve the base URL ONCE and confirm it BEFORE any network call.
1694
+ *
1695
+ * BAPI-1260: an epic launch profile has NO production default. Its target is
1696
+ * --base-url or BAPI_BASE_URL (they must agree), decided here before any
1697
+ * request; the hosted default applies to the ordinary flow only.
1698
+ *
1699
+ * This consent gates the FIRST network request of any kind — including the
1700
+ * read-only doctor readiness GET (which carries this repository's API key) and
1701
+ * the dry-run flow. The resolver silently defaults to production when
1702
+ * BAPI_BASE_URL is unset, so the operator must see and confirm the target before
1703
+ * the key is sent anywhere. No TTY means no consent means abort. The answer is
1704
+ * never persisted: every run asks again.
1705
+ */
1706
+ async function resolveAndConfirmBaseUrl(options, deps, promptText) {
1589
1707
  let baseUrl;
1590
1708
  if (options.launchProfile !== undefined) {
1591
1709
  const target = resolveEpicLaunchTarget({
@@ -1596,7 +1714,7 @@ export async function runInstallBridgeConductorCli(argv, deps) {
1596
1714
  if (!target.ok) {
1597
1715
  deps.errorLog(target.message);
1598
1716
  deps.errorLog("Nothing was sent anywhere and nothing was written.");
1599
- return 1;
1717
+ return { ok: false, code: 1 };
1600
1718
  }
1601
1719
  baseUrl = target.baseUrl;
1602
1720
  }
@@ -1604,65 +1722,53 @@ export async function runInstallBridgeConductorCli(argv, deps) {
1604
1722
  const baseUrlResult = deps.resolveBaseUrl(deps.env);
1605
1723
  if (!baseUrlResult.ok) {
1606
1724
  deps.errorLog(baseUrlResult.error);
1607
- return 1;
1725
+ return { ok: false, code: 1 };
1608
1726
  }
1609
1727
  baseUrl = baseUrlResult.value;
1610
1728
  }
1611
- // ---- Consent #1: the resolved base URL ---------------------------------
1612
- // This consent gates the FIRST network request of any kind — including the
1613
- // read-only doctor readiness GET (which carries this repository's API key)
1614
- // and the dry-run flow. The resolver silently defaults to production when
1615
- // BAPI_BASE_URL is unset, so the operator must see and confirm the target
1616
- // before the key is sent anywhere. No TTY means no consent means abort.
1617
1729
  deps.log(`Bridge API base URL: ${baseUrl}`);
1618
1730
  if (options.launchProfile !== undefined) {
1619
1731
  deps.log(` explicit target for epic launch profile '${options.launchProfile}'` +
1620
1732
  (baseUrl === DEFAULT_BAPI_BASE_URL ? " — this is the PRODUCTION Bridge API, selected deliberately." : "."));
1621
1733
  }
1622
- const baseUrlOk = await confirm(deps, "Bootstrap against this URL? [y/N]: ");
1734
+ const baseUrlOk = await confirm(deps, promptText);
1623
1735
  if (!baseUrlOk) {
1624
1736
  deps.log("Aborted — no network call (readiness GET or bootstrap POST) was attempted.");
1625
- return 0;
1737
+ return { ok: false, code: 0 };
1626
1738
  }
1627
- const accessResult = await deps.resolveAccess(options.repo, baseUrl);
1628
- const access = accessResult.ok ? accessResult.access : null;
1629
- const accessError = accessResult.ok ? undefined : accessResult.error;
1630
- // ---- BAPI-1391: the two standalone gate actions -----------------------
1631
- // `--clear-gate`, and `--qualify-gate` without gate flags, act on the stored
1632
- // gate and stop: they never bootstrap, scaffold, or provision anything else.
1633
- const gateIo = {
1739
+ return { ok: true, baseUrl };
1740
+ }
1741
+ function gateIoFor(deps) {
1742
+ return {
1634
1743
  log: deps.log,
1635
1744
  errorLog: deps.errorLog,
1636
1745
  promptLine: deps.promptLine,
1637
1746
  fetchJson: deps.fetchJson,
1638
1747
  postJson: deps.postJson,
1639
1748
  };
1640
- const qualifyOnly = options.gate.qualifyGate && !hasExplicitGateInput(options.gate);
1641
- if (options.gate.clearGate || qualifyOnly) {
1642
- if (!access) {
1643
- deps.errorLog(`Bridge API access could not be resolved: ${accessError ?? "unknown"}`);
1644
- deps.errorLog("Nothing was written.");
1645
- return 1;
1646
- }
1647
- return options.gate.clearGate
1648
- ? runClearConductorGate(gateIo, access, { dryRun: options.dryRun })
1649
- : runQualifyConductorGate(gateIo, access, deps.gate, { dryRun: options.dryRun, baseUrl });
1650
- }
1651
- // ---- Phase 1: unified doctor, BEFORE every write -----------------------
1652
- deps.log("Phase 1/8 — running the unified epic-implementer doctor (read-only)…");
1653
- const firstReport = await deps.runDoctor({
1654
- access,
1655
- accessError,
1656
- reviewPolicySource: options.reviewPolicy,
1657
- });
1658
- deps.log(formatConductorInstallDoctorReport(firstReport));
1659
- if (conductorInstallDoctorHasFatal(firstReport)) {
1660
- deps.errorLog("");
1661
- deps.errorLog("Fatal prerequisite(s) above. Aborting before any write — no bootstrap, workflow, " +
1662
- "install-state, or verification step was attempted.");
1749
+ }
1750
+ /**
1751
+ * BAPI-1391: the two standalone gate actions. `--clear-gate`, and
1752
+ * `--qualify-gate` without gate flags, act on the stored gate and stop: they
1753
+ * never bootstrap, scaffold, or provision anything else. Returns null when
1754
+ * neither was requested.
1755
+ */
1756
+ async function runStandaloneGateAction(options, deps, gateIo, access, accessError, baseUrl) {
1757
+ // BAPI-1536: a command request means setup has work to do, so `--qualify-gate`
1758
+ // is no longer standalone and its accompanying command is never discarded.
1759
+ const qualifyOnly = options.gate.qualifyGate && !hasExplicitGateInput(options.gate) && options.testCommand === undefined;
1760
+ if (!options.gate.clearGate && !qualifyOnly)
1761
+ return null;
1762
+ if (!access) {
1763
+ deps.errorLog(`Bridge API access could not be resolved: ${accessError ?? "unknown"}`);
1764
+ deps.errorLog("Nothing was written.");
1663
1765
  return 1;
1664
1766
  }
1665
- // ---- Review policy: per-run, and a repository default when explicit ----
1767
+ return options.gate.clearGate
1768
+ ? runClearConductorGate(gateIo, access, { dryRun: options.dryRun })
1769
+ : runQualifyConductorGate(gateIo, access, deps.gate, { dryRun: options.dryRun, baseUrl });
1770
+ }
1771
+ function renderReviewPolicy(deps, options) {
1666
1772
  deps.log("");
1667
1773
  deps.log(`Review policy: ${options.reviewPolicy}`);
1668
1774
  deps.log(options.reviewPolicyExplicit
@@ -1674,15 +1780,15 @@ export async function runInstallBridgeConductorCli(argv, deps) {
1674
1780
  "Claude review workflow is scaffolded. A new feature-branch run receives " +
1675
1781
  "repository_policy at first approval when nothing else sets one — pass " +
1676
1782
  "--review-policy verdict_protocol to opt in to AI review.");
1677
- // ---- Executor preflight: AFTER the URL consent, BEFORE any mutation ----
1678
- // Placed here so an unsupported host or a missing `wt`/`git`/`claude` refuses
1679
- // before the bootstrap POST, the workflow write, or a single filesystem
1680
- // effect — provisioning a service that cannot run is worse than refusing —
1681
- // and before the dry-run return, so `--dry-run` reports the same refusal.
1783
+ }
1784
+ /**
1785
+ * The executor preflight (BAPI-779): AFTER the URL consent, BEFORE any
1786
+ * mutation, and before the dry-run return, so `--dry-run` reports the same
1787
+ * refusal. Runs only with --executor-id.
1788
+ */
1789
+ async function runExecutorPreflightPhase(options, deps, baseUrl, access) {
1682
1790
  const executor = deps.executorProvisioning;
1683
- const local = deps.localProvisioning;
1684
1791
  const executorRequested = Boolean(executor && options.executorId);
1685
- let executorPlans = null;
1686
1792
  if (executor && executorRequested) {
1687
1793
  deps.log("");
1688
1794
  deps.log("Executor provisioning — preflight (read-only)…");
@@ -1696,12 +1802,12 @@ export async function runInstallBridgeConductorCli(argv, deps) {
1696
1802
  // credential complaint: the only auth-related output above is the
1697
1803
  // advisory login line.
1698
1804
  deps.errorLog("");
1699
- deps.errorLog("Executor provisioning refused — this host cannot run a conductor executor.");
1805
+ deps.errorLog("Executor provisioning refused — this host cannot run an Epic Implementer executor.");
1700
1806
  for (const remediation of preflight.remediations)
1701
1807
  deps.errorLog(` → ${remediation}`);
1702
1808
  deps.log("");
1703
1809
  deps.log("complete-with-manual-steps");
1704
- return 1;
1810
+ return { kind: "refused" };
1705
1811
  }
1706
1812
  // The unit serves the repository this run resolved access for. When access
1707
1813
  // could not be resolved the doctor above has already produced a fatal
@@ -1713,15 +1819,84 @@ export async function runInstallBridgeConductorCli(argv, deps) {
1713
1819
  deps.errorLog(`Executor provisioning refused — ${planned.error}`);
1714
1820
  deps.log("");
1715
1821
  deps.log("complete-with-manual-steps");
1716
- return 1;
1822
+ return { kind: "refused" };
1717
1823
  }
1718
- executorPlans = planned.plans;
1824
+ return { kind: "ok", plans: planned.plans };
1719
1825
  }
1720
- else if (executor) {
1826
+ if (executor) {
1721
1827
  deps.log("");
1722
1828
  deps.log(" executor provisioning skipped — pass --executor-id <id> to write and start a " +
1723
1829
  "service unit for this host.");
1724
1830
  }
1831
+ return { kind: "ok", plans: null };
1832
+ }
1833
+ export async function runInstallBridgeConductorCli(argv, deps) {
1834
+ const parsed = parseInstallBridgeConductorArgs(argv);
1835
+ if (parsed.status === "help") {
1836
+ deps.log(parsed.usage);
1837
+ return 0;
1838
+ }
1839
+ if (parsed.status === "error") {
1840
+ deps.errorLog(`Error: ${parsed.message}`);
1841
+ deps.errorLog("");
1842
+ deps.errorLog(getInstallBridgeConductorUsage());
1843
+ return 1;
1844
+ }
1845
+ const options = parsed.options;
1846
+ // BAPI-1461: production supplies the setup seams, which select the converging
1847
+ // check → fix → check → verdict runner. A caller without them keeps the
1848
+ // original phase sequence below, unchanged.
1849
+ if (deps.setup !== undefined) {
1850
+ return runConvergingSetup(options, deps, deps.setup);
1851
+ }
1852
+ if (options.removeMergeToken === true) {
1853
+ deps.errorLog("Error: --remove-merge-token is unavailable here: this caller supplied no credential-store seams.");
1854
+ return 1;
1855
+ }
1856
+ if (options.testCommand !== undefined) {
1857
+ // Accepting the flag and running an implementation that ignores it would
1858
+ // report success for a command that was never saved.
1859
+ deps.errorLog("Error: --test-command is unavailable here: this caller supplied no test-command seams.");
1860
+ return 1;
1861
+ }
1862
+ const confirmed = await resolveAndConfirmBaseUrl(options, deps, "Bootstrap against this URL? [y/N]: ");
1863
+ if (!confirmed.ok)
1864
+ return confirmed.code;
1865
+ const baseUrl = confirmed.baseUrl;
1866
+ const accessResult = await deps.resolveAccess(options.repo, baseUrl);
1867
+ const access = accessResult.ok ? accessResult.access : null;
1868
+ const accessError = accessResult.ok ? undefined : accessResult.error;
1869
+ const gateIo = gateIoFor(deps);
1870
+ const standalone = await runStandaloneGateAction(options, deps, gateIo, access, accessError, baseUrl);
1871
+ if (standalone !== null)
1872
+ return standalone;
1873
+ // ---- Phase 1: unified doctor, BEFORE every write -----------------------
1874
+ deps.log("Phase 1/8 — running the unified epic-implementer doctor (read-only)…");
1875
+ const firstReport = await deps.runDoctor({
1876
+ access,
1877
+ accessError,
1878
+ reviewPolicySource: options.reviewPolicy,
1879
+ });
1880
+ deps.log(formatConductorInstallDoctorReport(firstReport));
1881
+ if (conductorInstallDoctorHasFatal(firstReport)) {
1882
+ deps.errorLog("");
1883
+ deps.errorLog("Fatal prerequisite(s) above. Aborting before any write — no bootstrap, workflow, " +
1884
+ "install-state, or verification step was attempted.");
1885
+ return 1;
1886
+ }
1887
+ // ---- Review policy: per-run, and a repository default when explicit ----
1888
+ renderReviewPolicy(deps, options);
1889
+ // ---- Executor preflight: AFTER the URL consent, BEFORE any mutation ----
1890
+ // Placed here so an unsupported host or a missing `wt`/`git`/`claude` refuses
1891
+ // before the bootstrap POST, the workflow write, or a single filesystem
1892
+ // effect — provisioning a service that cannot run is worse than refusing —
1893
+ // and before the dry-run return, so `--dry-run` reports the same refusal.
1894
+ const executor = deps.executorProvisioning;
1895
+ const local = deps.localProvisioning;
1896
+ const preflight = await runExecutorPreflightPhase(options, deps, baseUrl, access);
1897
+ if (preflight.kind === "refused")
1898
+ return 1;
1899
+ const executorPlans = preflight.plans;
1725
1900
  // ---- BAPI-1391: the repository gate, decided BEFORE any write ----------
1726
1901
  // Capability probe first (a read, after the base-URL consent), then the stored
1727
1902
  // gate, explicit gate flags, or a discovery proposal the owner confirms. Under
@@ -1793,12 +1968,12 @@ export async function runInstallBridgeConductorCli(argv, deps) {
1793
1968
  // hook installer, the capability recorder, or the phase's ledger probe —
1794
1969
  // this branch returns before every one of them.
1795
1970
  deps.log(local
1796
- ? " Tool visibility: would ask its OWN consent before adding the `conductor` " +
1971
+ ? " Tool visibility: would ask its OWN consent before adding the `epic_implementer` " +
1797
1972
  "profile to existing .mcp.json / .vscode/mcp.json / .cursor/mcp.json entries."
1798
1973
  : " Tool visibility: skipped (this caller supplied no local-provisioning seams)");
1799
1974
  deps.log(local
1800
1975
  ? " Local observability: would ask a SEPARATE consent before installing the " +
1801
- "managed conductor Git hooks; the ledger probe is read-only."
1976
+ "managed Git hooks; the ledger probe is read-only."
1802
1977
  : " Local observability: skipped (this caller supplied no local-provisioning seams)");
1803
1978
  if (executorPlans) {
1804
1979
  deps.log(` Would write executor unit: ${executorPlans.install.unitPath}`);
@@ -1963,62 +2138,64 @@ export async function runInstallBridgeConductorCli(argv, deps) {
1963
2138
  });
1964
2139
  if (epicBranchCi.manualAction !== null)
1965
2140
  manualActions.push(epicBranchCi.manualAction);
1966
- // ---- Phase 3: optional workflow scaffold -------------------------------
1967
- deps.log("");
1968
- deps.log("Phase 3/8 — claude-review workflow…");
1969
- if (options.skipWorkflow || options.reviewPolicy !== "verdict_protocol") {
1970
- deps.log(` skipped — the '${options.reviewPolicy}' review policy does not consume the ` +
1971
- "sticky verdict this workflow emits.");
1972
- }
1973
- else if (!options.allowedBot || !options.secretName || !options.branches) {
1974
- deps.log(" skipped — --allowed-bot, --secret-name, and --branches are required to render " +
1975
- "the workflow template.");
1976
- }
1977
- else {
1978
- const wantWorkflow = await confirm(deps, `Write ${CLAUDE_REVIEW_WORKFLOW_RELPATH}? [y/N]: `);
1979
- if (!wantWorkflow) {
1980
- deps.log(" declined — no file was written.");
2141
+ if (options.reviewPolicy === "verdict_protocol") {
2142
+ // ---- Phase 3: optional workflow scaffold -------------------------------
2143
+ deps.log("");
2144
+ deps.log("Phase 3/8 — claude-review workflow…");
2145
+ if (options.skipWorkflow) {
2146
+ deps.log(` skipped — the '${options.reviewPolicy}' review policy does not consume the ` +
2147
+ "sticky verdict this workflow emits.");
2148
+ }
2149
+ else if (!options.allowedBot || !options.secretName || !options.branches) {
2150
+ deps.log(" skipped — --allowed-bot, --secret-name, and --branches are required to render " +
2151
+ "the workflow template.");
1981
2152
  }
1982
2153
  else {
1983
- let content;
1984
- try {
1985
- content = renderClaudeReviewWorkflow({
1986
- allowedBot: options.allowedBot,
1987
- secretName: options.secretName,
1988
- branches: options.branches,
1989
- });
1990
- }
1991
- catch (err) {
1992
- deps.errorLog(` workflow parameters rejected: ${err instanceof Error ? err.message : "invalid"}`);
1993
- return 1;
2154
+ const wantWorkflow = await confirm(deps, `Write ${CLAUDE_REVIEW_WORKFLOW_RELPATH}? [y/N]: `);
2155
+ if (!wantWorkflow) {
2156
+ deps.log(" declined — no file was written.");
1994
2157
  }
1995
- let result = await deps.writeWorkflow(deps.cwd, content, {});
1996
- if (result.ok && result.outcome === "skipped") {
1997
- // A DIFFERENT file already exists. Overwriting review automation needs
1998
- // its own decision — never inferred from the earlier consents.
1999
- const overwrite = await confirm(deps, `${CLAUDE_REVIEW_WORKFLOW_RELPATH} exists and differs. Overwrite? [y/N]: `);
2000
- if (!overwrite) {
2001
- deps.log(" existing workflow left untouched.");
2158
+ else {
2159
+ let content;
2160
+ try {
2161
+ content = renderClaudeReviewWorkflow({
2162
+ allowedBot: options.allowedBot,
2163
+ secretName: options.secretName,
2164
+ branches: options.branches,
2165
+ });
2002
2166
  }
2003
- else {
2004
- result = await deps.writeWorkflow(deps.cwd, content, { overwriteConsent: true });
2167
+ catch (err) {
2168
+ deps.errorLog(` workflow parameters rejected: ${err instanceof Error ? err.message : "invalid"}`);
2169
+ return 1;
2005
2170
  }
2006
- }
2007
- if (!result.ok) {
2008
- deps.errorLog(` workflow write failed: ${result.error}`);
2009
- return 1;
2010
- }
2011
- if (result.outcome === "written") {
2012
- deps.log(` wrote ${CLAUDE_REVIEW_WORKFLOW_RELPATH}`);
2013
- const recorded = await deps.recordArtifact(deps.cwd, CLAUDE_REVIEW_WORKFLOW_RELPATH);
2014
- if (!recorded.ok) {
2015
- // Advisory: install-state is a diagnostic aid, not a correctness
2016
- // dependency, so a failure here warns rather than failing the run.
2017
- deps.errorLog(` note: install-state not updated (${recorded.error ?? "unknown"})`);
2171
+ let result = await deps.writeWorkflow(deps.cwd, content, {});
2172
+ if (result.ok && result.outcome === "skipped") {
2173
+ // A DIFFERENT file already exists. Overwriting review automation needs
2174
+ // its own decision — never inferred from the earlier consents.
2175
+ const overwrite = await confirm(deps, `${CLAUDE_REVIEW_WORKFLOW_RELPATH} exists and differs. Overwrite? [y/N]: `);
2176
+ if (!overwrite) {
2177
+ deps.log(" existing workflow left untouched.");
2178
+ }
2179
+ else {
2180
+ result = await deps.writeWorkflow(deps.cwd, content, { overwriteConsent: true });
2181
+ }
2182
+ }
2183
+ if (!result.ok) {
2184
+ deps.errorLog(` workflow write failed: ${result.error}`);
2185
+ return 1;
2186
+ }
2187
+ if (result.outcome === "written") {
2188
+ deps.log(` wrote ${CLAUDE_REVIEW_WORKFLOW_RELPATH}`);
2189
+ const recorded = await deps.recordArtifact(deps.cwd, CLAUDE_REVIEW_WORKFLOW_RELPATH);
2190
+ if (!recorded.ok) {
2191
+ // Advisory: install-state is a diagnostic aid, not a correctness
2192
+ // dependency, so a failure here warns rather than failing the run.
2193
+ deps.errorLog(` note: install-state not updated (${recorded.error ?? "unknown"})`);
2194
+ }
2195
+ }
2196
+ else if (result.outcome === "unchanged") {
2197
+ deps.log(` ${CLAUDE_REVIEW_WORKFLOW_RELPATH} already matches — nothing written.`);
2018
2198
  }
2019
- }
2020
- else if (result.outcome === "unchanged") {
2021
- deps.log(` ${CLAUDE_REVIEW_WORKFLOW_RELPATH} already matches — nothing written.`);
2022
2199
  }
2023
2200
  }
2024
2201
  }
@@ -2027,7 +2204,7 @@ export async function runInstallBridgeConductorCli(argv, deps) {
2027
2204
  // executor provisioning, and the capability report, so a run that stops at a
2028
2205
  // later phase has still closed the local gap it consented to close.
2029
2206
  deps.log("");
2030
- deps.log("Phase 4/8 — conductor tool visibility…");
2207
+ deps.log("Phase 4/8 — Epic Implementer tool visibility…");
2031
2208
  if (local) {
2032
2209
  const outcome = await runConductorToolVisibilityPhase(deps, local);
2033
2210
  manualActions.push(...outcome.manualActions);
@@ -2040,7 +2217,7 @@ export async function runInstallBridgeConductorCli(argv, deps) {
2040
2217
  "`epic_implementer` profile to your host MCP configuration.");
2041
2218
  }
2042
2219
  deps.log("");
2043
- deps.log("Phase 5/8 — conductor local observability…");
2220
+ deps.log("Phase 5/8 — local observability…");
2044
2221
  let observabilityFatal = false;
2045
2222
  if (local) {
2046
2223
  const outcome = await runConductorLocalObservabilityPhase(deps, local);
@@ -2050,7 +2227,7 @@ export async function runInstallBridgeConductorCli(argv, deps) {
2050
2227
  else {
2051
2228
  deps.log(" skipped — this caller supplied no local-provisioning seams.");
2052
2229
  manualActions.push("local observability: run the packaged `install conductor` command, or " +
2053
- "`epic-implementer install-git-hooks`, to install the managed conductor Git hooks.");
2230
+ "`epic-implementer install-git-hooks`, to install the managed Git hooks.");
2054
2231
  }
2055
2232
  // The fail-loud hook-binary refusal (a package that ships no hook binary)
2056
2233
  // exits 1 — but only AFTER the phase's read-only ledger report has been
@@ -2166,3 +2343,1103 @@ export async function runInstallBridgeConductorCli(argv, deps) {
2166
2343
  deps.log(allReady ? "complete" : "complete-with-manual-steps");
2167
2344
  return conductorInstallDoctorExitCode(finalReport);
2168
2345
  }
2346
+ // ---------------------------------------------------------------------------
2347
+ // The converging setup runner (BAPI-1461)
2348
+ // ---------------------------------------------------------------------------
2349
+ /**
2350
+ * Ask for consent to one write surface. A missing prompt seam (no terminal) is
2351
+ * a decline, never a default yes, and says so in one line naming the step.
2352
+ */
2353
+ async function askConsent(deps, promptText, step) {
2354
+ if (!deps.promptLine) {
2355
+ deps.log(` skipped ${step}: there is no interactive terminal, so this counts as declined.`);
2356
+ return false;
2357
+ }
2358
+ return confirm(deps, promptText);
2359
+ }
2360
+ /**
2361
+ * Collect every independent read-only finding. A failed read becomes an
2362
+ * `unknown` finding, never an aborted collection, and nothing here writes.
2363
+ */
2364
+ async function collectSetupEvidence(deps, setup, access, readiness, inputs) {
2365
+ // Repository identity: the server's name first, the local remote second, and a
2366
+ // disagreement reads nothing.
2367
+ const identityResult = resolveGithubMergeRepositoryIdentity({
2368
+ providerRepository: readiness?.provider_repository ?? null,
2369
+ localRemote: inputs.localRemote,
2370
+ });
2371
+ const identity = identityResult.ok ? identityResult.identity : null;
2372
+ const repository = identity !== null ? `${identity.owner}/${identity.repo}` : null;
2373
+ // The stored test command, read back from the server.
2374
+ let storedCommand = null;
2375
+ let testCommand = { state: "unknown" };
2376
+ try {
2377
+ const read = await readStoredTestCommand(setup.testingConfig(access));
2378
+ if (read.ok) {
2379
+ storedCommand = read.testCommand;
2380
+ testCommand = read.testCommand === null ? { state: "missing" } : { state: "stored" };
2381
+ }
2382
+ }
2383
+ catch {
2384
+ testCommand = { state: "unknown" };
2385
+ }
2386
+ // The toolchains, read once from the working tree. Kept apart from the
2387
+ // non-sensitive readiness evidence below: they are an input to the workflow
2388
+ // assessment and to operator-only output, never a readiness row.
2389
+ const toolchains = await resolveRepositoryToolchains((relPath) => setup.readRepositoryFile(relPath));
2390
+ // The managed workflow, through the installer's own read-only preflight.
2391
+ let workflow = { state: "unknown" };
2392
+ if (storedCommand === null) {
2393
+ workflow = testCommand.state === "missing" ? { state: "needs_command" } : { state: "unknown" };
2394
+ }
2395
+ else if (inputs.commandBlocked === true) {
2396
+ // A failed command verification blocks every later workflow step, including
2397
+ // this closing read: the workflow would be judged against a command nobody
2398
+ // confirmed.
2399
+ workflow = { state: "blocked", remedy: COMMAND_UNVERIFIED_WORKFLOW_REMEDY };
2400
+ }
2401
+ else if (inputs.githubSignIn === "signed_in") {
2402
+ workflow = await assessWorkflow(setup, storedCommand, toolchains, inputs.commandChanged === true);
2403
+ }
2404
+ // The setup pull request and, once it merged, the index.
2405
+ let setupPullRequest = { state: "unknown" };
2406
+ let index = { state: "not_applicable" };
2407
+ if (repository !== null && inputs.githubSignIn === "signed_in") {
2408
+ setupPullRequest = await readSetupPullRequest(setup.runGh, repository);
2409
+ index = await assessSetupIndex(setupPullRequest, () => setup.fetchParseStatus(access), (mergeSha, indexedSha) => compareIndexedToMerge(setup.runGh, repository, mergeSha, indexedSha));
2410
+ }
2411
+ if (workflow.state === "installed" && setupPullRequest.state === "unknown") {
2412
+ index = { state: "not_applicable" };
2413
+ }
2414
+ const mergeCredential = await assessMergeCredential(deps, setup, readiness, identity);
2415
+ return {
2416
+ evidence: {
2417
+ readiness,
2418
+ claudeLoggedIn: inputs.claudeLoggedIn,
2419
+ githubSignIn: inputs.githubSignIn,
2420
+ repositoryIdentity: identityResult.ok ? "resolved" : identityResult.reason,
2421
+ testCommand,
2422
+ workflow,
2423
+ setupPullRequest,
2424
+ index,
2425
+ mergeCredential,
2426
+ gateChangeDeclined: inputs.gateChangeDeclined,
2427
+ advisories: inputs.advisories,
2428
+ },
2429
+ identity,
2430
+ repository,
2431
+ storedCommand,
2432
+ toolchains,
2433
+ };
2434
+ }
2435
+ /** The remedy shown for the workflow once a command write could not be verified. */
2436
+ const COMMAND_UNVERIFIED_WORKFLOW_REMEDY = "the test command could not be verified, so the CI workflow is not built from it; fix that first, then re-run setup";
2437
+ /** The remedy when the repository's dependency files could not be inspected. Names files, never content. */
2438
+ function toolchainInspectionRemedy(resolution) {
2439
+ const files = resolution.failures.map((f) => f.file).join(", ");
2440
+ return (`Bridge could not inspect ${files} to choose what CI installs, and it will not guess. ` +
2441
+ "Fix the file or its permissions, then re-run setup");
2442
+ }
2443
+ /**
2444
+ * Classify the managed workflow with the installer's read-only dry run.
2445
+ *
2446
+ * `commandChanged` marks a command written during this run: the workflow must
2447
+ * then change too, so a local precondition that stops the preflight (a dirty
2448
+ * worktree) is a known outstanding change and must not be hidden by an older
2449
+ * server-ready workflow fact.
2450
+ */
2451
+ async function assessWorkflow(setup, testCommand, toolchains, commandChanged = false) {
2452
+ if (toolchains.status === "unknown") {
2453
+ return { state: "blocked", remedy: toolchainInspectionRemedy(toolchains) };
2454
+ }
2455
+ let result;
2456
+ try {
2457
+ result = await setup.installCiWorkflow(testCommand, toolchains.toolchains, { dryRun: true, quiet: true });
2458
+ }
2459
+ catch {
2460
+ return { state: "unknown" };
2461
+ }
2462
+ switch (result.outcome) {
2463
+ case "identical":
2464
+ return { state: "installed" };
2465
+ case "existing-pr":
2466
+ return { state: "pr_open", url: result.prUrl };
2467
+ case "dry-run":
2468
+ return { state: "needs_pr" };
2469
+ case "installed-pr-opened":
2470
+ case "upgrade-pr-opened":
2471
+ // A dry run never opens one; treat an impossible answer as unknown.
2472
+ return { state: "unknown" };
2473
+ case "failed":
2474
+ if (result.reason === "worktree_not_clean" || result.reason === "not_repository_root") {
2475
+ return commandChanged
2476
+ ? { state: "blocked", remedy: result.remediation }
2477
+ : { state: "precondition", remedy: result.remediation };
2478
+ }
2479
+ return result.prUrl !== undefined &&
2480
+ (result.reason === "existing_pr_differs" || result.reason === "historical_managed_pr_open")
2481
+ ? { state: "blocked", remedy: `${result.remediation} (${result.prUrl})` }
2482
+ : { state: "blocked", remedy: result.remediation };
2483
+ }
2484
+ }
2485
+ /**
2486
+ * The merge credential, as setup's own check sees it. The order is fixed:
2487
+ * `GITHUB_MERGE_TOKEN`, `BAPI_LOCAL_MERGE_TOKEN`, then the stored entry. An
2488
+ * invalid env value is never rescued. Machine-user mode reads only its own key.
2489
+ * A stored token counts only after the bounded probe confirms GitHub accepts
2490
+ * it; an unavailable probe is uncertainty, never a rejection.
2491
+ */
2492
+ async function assessMergeCredential(deps, setup, readiness, identity) {
2493
+ const mode = readiness?.resolved_merge_execution_mode;
2494
+ if (mode === "github_actions")
2495
+ return { state: "not_applicable" };
2496
+ if (mode === "machine_token") {
2497
+ const machine = resolveLocalMergeCredentialDetailed(deps.env, "machine_token");
2498
+ if (machine.status === "resolved")
2499
+ return { state: "configured", source: "machine" };
2500
+ if (machine.status === "invalid")
2501
+ return { state: "env_invalid", sourceKey: machine.source_key };
2502
+ return { state: "machine_missing" };
2503
+ }
2504
+ const env = resolveLocalMergeCredentialDetailed(deps.env, "local");
2505
+ if (env.status === "resolved")
2506
+ return { state: "configured", source: env.via_alias ? "alias" : "env" };
2507
+ if (env.status === "invalid")
2508
+ return { state: "env_invalid", sourceKey: env.source_key };
2509
+ if (identity === null)
2510
+ return { state: "missing" };
2511
+ let stored;
2512
+ try {
2513
+ stored = await setup.readMergeToken(identity);
2514
+ }
2515
+ catch {
2516
+ return { state: "unknown" };
2517
+ }
2518
+ if (stored.status === "unavailable")
2519
+ return { state: "unknown" };
2520
+ if (stored.status === "absent")
2521
+ return { state: "missing" };
2522
+ if (!isUsableMergeCredentialValue(stored.token))
2523
+ return { state: "stored_rejected" };
2524
+ let verdict;
2525
+ try {
2526
+ verdict = await setup.probeMergeToken({
2527
+ repository: `${identity.owner}/${identity.repo}`,
2528
+ credential: { kind: "local", token: stored.token },
2529
+ });
2530
+ }
2531
+ catch {
2532
+ return { state: "unknown" };
2533
+ }
2534
+ if (verdict === "passed")
2535
+ return { state: "configured", source: "store" };
2536
+ if (verdict === "credential_invalid" || verdict === "no_access")
2537
+ return { state: "stored_rejected" };
2538
+ return { state: "unknown" };
2539
+ }
2540
+ /**
2541
+ * The doctor's store context for this run's repository. The store is read
2542
+ * through setup's own seam, so the doctor and setup's check can never read two
2543
+ * different stores, and the doctor probes a stored token the same bounded way.
2544
+ */
2545
+ function storedMergeContextFor(setup, providerRepository, localRemote) {
2546
+ return {
2547
+ allowStoredEntry: true,
2548
+ providerRepository,
2549
+ localRemote,
2550
+ readStored: (identity) => setup.readMergeToken(identity),
2551
+ probe: (args) => setup.probeMergeToken(args),
2552
+ };
2553
+ }
2554
+ /** Whether the gate or the supervisor defaults would change (no POST needed). */
2555
+ function gateOrDefaultsNeedWrite(gatePlan, readiness) {
2556
+ if (gatePlan === null)
2557
+ return false;
2558
+ if (gatePlan.write !== null)
2559
+ return true;
2560
+ if (readiness === null)
2561
+ return false;
2562
+ return !readiness.supervisor.setup_present || !readiness.supervisor.config_present;
2563
+ }
2564
+ /** Whether a bootstrap preview shows anything the apply would change. */
2565
+ function bootstrapPreviewChangesSomething(preview) {
2566
+ return (preview.approval_required ||
2567
+ preview.changed_field_names.length > 0 ||
2568
+ preview.setup_outcome !== "preserved" ||
2569
+ preview.config_outcome !== "preserved");
2570
+ }
2571
+ function bootstrapRequestFor(options, checks) {
2572
+ return {
2573
+ required_checks: checks,
2574
+ ...(options.reviewPolicyExplicit ? { review_policy: { source: options.reviewPolicy } } : {}),
2575
+ merge_approval_required: "true",
2576
+ ...(options.replaceDoneGate ? { replace_done_gate: true } : {}),
2577
+ };
2578
+ }
2579
+ /**
2580
+ * Fix: store the repository gate and the safe supervisor defaults, under ONE
2581
+ * consent for this surface (plus the separate exact approval a weakening change
2582
+ * needs). Never inferred from the setup-PR or any other consent.
2583
+ */
2584
+ async function fixGateAndDefaults(deps, options, access, gatePlan) {
2585
+ const gateIo = gateIoFor(deps);
2586
+ deps.log("");
2587
+ deps.log("Repository gate and safe defaults");
2588
+ const ok = await askConsent(deps, "Store the repository gate and the safe supervisor defaults now? [y/N]: ", "storing the repository gate and the safe supervisor defaults");
2589
+ if (!ok) {
2590
+ deps.log(" declined — nothing was written.");
2591
+ return false;
2592
+ }
2593
+ const checks = gatePlan.desired.providerChecks;
2594
+ const request = bootstrapRequestFor(options, checks);
2595
+ const gateFirst = gatePlan.write !== null && (checks.length === 0 || gatePlan.current.source === "stored");
2596
+ if (gateFirst && (await storeConductorGate(gateIo, access, gatePlan)) === null)
2597
+ return false;
2598
+ let preview;
2599
+ try {
2600
+ preview = await previewConductorSupervisorBootstrap(access, request, deps.postJson);
2601
+ }
2602
+ catch (err) {
2603
+ reportBootstrapFailure(deps, "preview", classifySupervisorBootstrapFailure(err));
2604
+ return false;
2605
+ }
2606
+ if (bootstrapPreviewChangesSomething(preview)) {
2607
+ renderBootstrapPreview(deps, preview);
2608
+ let applyRequest = request;
2609
+ if (preview.approval_required) {
2610
+ const exact = await askConsent(deps, "Approve EXACTLY the gate changes listed above? [y/N]: ", "approving the listed gate changes");
2611
+ if (!exact || !preview.approval_token) {
2612
+ deps.log(" not approved — every configured requirement is unchanged.");
2613
+ return false;
2614
+ }
2615
+ applyRequest = { ...request, approval: { approve: true, approval_token: preview.approval_token } };
2616
+ }
2617
+ let response;
2618
+ try {
2619
+ response = await bootstrapConductorSupervisorDefaults(access, applyRequest, deps.postJson);
2620
+ }
2621
+ catch (err) {
2622
+ reportBootstrapFailure(deps, "apply", classifySupervisorBootstrapFailure(err));
2623
+ return false;
2624
+ }
2625
+ if (response.setup_outcome === null || response.config_outcome === null) {
2626
+ reportBootstrapFailure(deps, "apply", "unsupported-protocol");
2627
+ return false;
2628
+ }
2629
+ renderBootstrapOutcome(deps, response);
2630
+ }
2631
+ else {
2632
+ deps.log(" the safe supervisor defaults are already in place — nothing to write.");
2633
+ }
2634
+ if (!gateFirst && gatePlan.write !== null && (await storeConductorGate(gateIo, access, gatePlan)) === null) {
2635
+ return false;
2636
+ }
2637
+ return true;
2638
+ }
2639
+ /**
2640
+ * Write failures that are a definite refusal: the server answered and said no.
2641
+ * Every other failure is UNCERTAIN (the write may have landed), so it is read
2642
+ * back and never retried.
2643
+ */
2644
+ const DEFINITE_WRITE_REFUSALS = new Set([
2645
+ "unauthenticated",
2646
+ "forbidden",
2647
+ "not_found",
2648
+ "invalid_command",
2649
+ ]);
2650
+ /**
2651
+ * Validate `requested`, attempt ONE write, then read the stored value back.
2652
+ *
2653
+ * - Invalid input is never sent.
2654
+ * - A definite refusal (unauthenticated, forbidden, not found, invalid) stops
2655
+ * there: nothing changed, so there is nothing to verify.
2656
+ * - An accepted write and an uncertain one are both read back. The write is
2657
+ * never retried.
2658
+ * - Success needs BOTH an accepted write and a read-back equal to the validated
2659
+ * requested value.
2660
+ */
2661
+ export async function saveAndReadBackTestCommand(config, requested) {
2662
+ let command;
2663
+ try {
2664
+ command = validateTestCommand(requested);
2665
+ }
2666
+ catch (err) {
2667
+ return { kind: "invalid_input", reason: err instanceof TestCommandValidationError ? err.reason : "invalid" };
2668
+ }
2669
+ let written;
2670
+ try {
2671
+ written = await writeStoredTestCommand(config, command);
2672
+ }
2673
+ catch {
2674
+ written = { ok: false, reason: "transport_failure", status: 0 };
2675
+ }
2676
+ if (!written.ok && DEFINITE_WRITE_REFUSALS.has(written.reason)) {
2677
+ return { kind: "write_failed", reason: written.reason, stored: undefined };
2678
+ }
2679
+ let readBack;
2680
+ try {
2681
+ readBack = await readStoredTestCommand(config);
2682
+ }
2683
+ catch {
2684
+ readBack = { ok: false, reason: "transport_failure", status: 0 };
2685
+ }
2686
+ if (!written.ok) {
2687
+ return { kind: "write_failed", reason: written.reason, stored: readBack.ok ? readBack.testCommand : undefined };
2688
+ }
2689
+ if (!readBack.ok)
2690
+ return { kind: "unreadable_verification" };
2691
+ if (readBack.testCommand !== command)
2692
+ return { kind: "read_back_mismatch", stored: readBack.testCommand };
2693
+ return { kind: "confirmed", testCommand: readBack.testCommand };
2694
+ }
2695
+ const COMMAND_NOT_ATTEMPTED = { confirmed: null, failure: null, serverValue: undefined };
2696
+ /** The blocking operation result for a failed command write. Fixed text, no command. */
2697
+ function testCommandOperationFailure(remedy) {
2698
+ return {
2699
+ id: "test-command-save",
2700
+ label: "Test command",
2701
+ state: "needs_action",
2702
+ blocking: true,
2703
+ remedy,
2704
+ };
2705
+ }
2706
+ /**
2707
+ * Report a non-confirmed outcome in fixed, sanitized words and build its blocking
2708
+ * operation result. Never prints the requested command, an upstream error body,
2709
+ * or exception text.
2710
+ */
2711
+ function reportTestCommandSaveFailure(deps, outcome, verb) {
2712
+ const head = `Test command not ${verb}`;
2713
+ switch (outcome.kind) {
2714
+ case "invalid_input":
2715
+ deps.log(` ${head} — that command cannot be stored (${outcome.reason}).`);
2716
+ return {
2717
+ confirmed: null,
2718
+ failure: testCommandOperationFailure("give a valid one-line command with --test-command, then re-run setup"),
2719
+ serverValue: undefined,
2720
+ };
2721
+ case "write_failed":
2722
+ deps.log(` ${head} — the save did not complete (${outcome.reason}).`);
2723
+ return {
2724
+ confirmed: null,
2725
+ failure: testCommandOperationFailure(outcome.reason === "forbidden" || outcome.reason === "unauthenticated"
2726
+ ? "this key cannot change the stored test command; use an administrator key, then re-run setup"
2727
+ : "the save did not complete; check the connection and re-run setup"),
2728
+ serverValue: outcome.stored,
2729
+ };
2730
+ case "unreadable_verification":
2731
+ deps.log(` ${head} — save may have succeeded; verification failed.`);
2732
+ return {
2733
+ confirmed: null,
2734
+ failure: testCommandOperationFailure("the save may have succeeded but could not be verified; re-run setup to read the stored command"),
2735
+ serverValue: undefined,
2736
+ };
2737
+ case "read_back_mismatch":
2738
+ deps.log(` ${head}. The stored value is not the one requested.`);
2739
+ return {
2740
+ confirmed: null,
2741
+ failure: testCommandOperationFailure("the stored value differs from the requested one; check the stored command and re-run setup"),
2742
+ serverValue: outcome.stored,
2743
+ };
2744
+ }
2745
+ }
2746
+ /** Run one save/replace and turn it into a fix result, logging the outcome. */
2747
+ async function persistTestCommand(deps, config, command, verb) {
2748
+ const outcome = await saveAndReadBackTestCommand(config, command);
2749
+ if (outcome.kind !== "confirmed")
2750
+ return reportTestCommandSaveFailure(deps, outcome, verb);
2751
+ deps.log(` ${verb} — the stored test command is now in place.`);
2752
+ return { confirmed: outcome.testCommand, failure: null, serverValue: outcome.testCommand };
2753
+ }
2754
+ /**
2755
+ * The single accept-or-replace question for a detected proposal. Enter skips,
2756
+ * `y` or `yes` accepts the proposal, and anything else is a typed replacement.
2757
+ * No terminal means no prompt: the proposal and the unresolved step are shown
2758
+ * and nothing is saved.
2759
+ */
2760
+ async function askAcceptOrReplace(deps, proposed) {
2761
+ if (!deps.promptLine) {
2762
+ deps.log(" skipped saving the test command: there is no interactive terminal, so this counts as declined.");
2763
+ return null;
2764
+ }
2765
+ const answer = (await deps.promptLine(`Save \`${proposed}\` as the test command? Press y to save it, type a different command to save that ` +
2766
+ "instead, or press Enter to skip [y/N]: ")).trim();
2767
+ if (answer.length === 0)
2768
+ return null;
2769
+ if (/^y(es)?$/i.test(answer))
2770
+ return proposed;
2771
+ return answer;
2772
+ }
2773
+ /**
2774
+ * Fix: save the repository's test command through the setup route, after one
2775
+ * contextual agreement. The command is never run here. Only the value read back
2776
+ * from the server is used afterwards.
2777
+ */
2778
+ async function fixTestCommand(deps, setup, access) {
2779
+ const config = setup.testingConfig(access);
2780
+ deps.log("");
2781
+ deps.log("Test command");
2782
+ let detection;
2783
+ try {
2784
+ detection = await detectTestCommand({ skipStoredRead: true }, { config, readFile: (relPath) => setup.readRepositoryFile(relPath) });
2785
+ }
2786
+ catch {
2787
+ detection = { status: "failed", reason: "repository_read_failed" };
2788
+ }
2789
+ let command = null;
2790
+ if (detection.status === "detected") {
2791
+ deps.log(` Proposed: \`${detection.selected}\` (found in ${detection.provenance}). It is not run now.`);
2792
+ command = await askAcceptOrReplace(deps, detection.selected);
2793
+ }
2794
+ else {
2795
+ if (detection.status === "failed") {
2796
+ // An uninspectable repository is reported as such, never as "nothing found".
2797
+ deps.log(` The repository files could not be inspected (${detection.reason}` +
2798
+ `${detection.file !== undefined ? `: ${detection.file}` : ""}), so no command was proposed.`);
2799
+ }
2800
+ else {
2801
+ deps.log(" No test command could be found in this repository.");
2802
+ }
2803
+ if (!deps.promptLine) {
2804
+ deps.log(" skipped saving a test command: there is no interactive terminal, so this counts as declined.");
2805
+ }
2806
+ else {
2807
+ const typed = (await deps.promptLine("Test command that runs your tests (press Enter to skip; a command you type is saved): ")).trim();
2808
+ if (typed.length > 0)
2809
+ command = typed;
2810
+ }
2811
+ }
2812
+ if (command === null) {
2813
+ deps.log(" not saved — the test command stays a step left.");
2814
+ return COMMAND_NOT_ATTEMPTED;
2815
+ }
2816
+ try {
2817
+ command = validateTestCommand(command);
2818
+ }
2819
+ catch (err) {
2820
+ // A typed answer is validated once; the reason is shown and there is no retry loop.
2821
+ const reason = err instanceof TestCommandValidationError ? err.reason : "invalid";
2822
+ deps.log(` not saved — that command cannot be stored (${reason}).`);
2823
+ return COMMAND_NOT_ATTEMPTED;
2824
+ }
2825
+ return persistTestCommand(deps, config, command, "saved");
2826
+ }
2827
+ /**
2828
+ * Fix: save or replace the test command the operator passed with
2829
+ * `--test-command`. The validated flag IS the consent for this one write, so the
2830
+ * command write never goes through {@link askConsent}. The same validation,
2831
+ * single write, and server read-back apply.
2832
+ */
2833
+ async function fixExplicitTestCommand(deps, setup, access, command, hadStoredCommand) {
2834
+ deps.log("");
2835
+ deps.log("Test command");
2836
+ deps.log(" saving the command you passed with --test-command; that flag is the consent for this write.");
2837
+ return persistTestCommand(deps, setup.testingConfig(access), command, hadStoredCommand ? "replaced" : "saved");
2838
+ }
2839
+ /** The one operator-only line for a readable stored command, then what CI installs for it. */
2840
+ function logStoredCommandAndToolchains(deps, storedCommand, toolchains) {
2841
+ deps.log("");
2842
+ if (storedCommand !== null) {
2843
+ deps.log(`Test command: \`${storedCommand}\` (stored). Change it with --test-command "...".`);
2844
+ }
2845
+ deps.log("What CI installs for it:");
2846
+ for (const line of describeToolchainResolution(toolchains))
2847
+ deps.log(` ${line}`);
2848
+ }
2849
+ /** Fix: open the one setup pull request through the artifact-set installer. */
2850
+ async function fixSetupPullRequest(deps, setup, testCommand, toolchains, repository) {
2851
+ deps.log("");
2852
+ deps.log("CI workflow");
2853
+ if (toolchains.status === "unknown") {
2854
+ // Uninspectable dependency files are a blocking inspection failure, never "no lockfile".
2855
+ const remedy = toolchainInspectionRemedy(toolchains);
2856
+ deps.log(` skipped — ${remedy}.`);
2857
+ return { workflow: { state: "blocked", remedy }, pr: null };
2858
+ }
2859
+ let result;
2860
+ try {
2861
+ // The setup pull request has its OWN consent, separate from the command write.
2862
+ result = await setup.installCiWorkflow(testCommand, toolchains.toolchains, { dryRun: false }, (promptText) => askConsent(deps, promptText, "opening the setup pull request"));
2863
+ }
2864
+ catch {
2865
+ deps.log(" the setup pull request could not be prepared; re-run setup.");
2866
+ return { workflow: { state: "unknown" }, pr: null };
2867
+ }
2868
+ switch (result.outcome) {
2869
+ case "installed-pr-opened":
2870
+ case "upgrade-pr-opened":
2871
+ deps.log(` opened the setup PR: ${result.prUrl}`);
2872
+ return { workflow: { state: "pr_open", url: result.prUrl }, pr: null };
2873
+ case "existing-pr":
2874
+ deps.log(` the setup PR is already open: ${result.prUrl}`);
2875
+ return { workflow: { state: "pr_open", url: result.prUrl }, pr: null };
2876
+ case "identical":
2877
+ deps.log(" the CI workflow is already in place — nothing to change.");
2878
+ return { workflow: { state: "installed" }, pr: null };
2879
+ case "dry-run":
2880
+ return { workflow: { state: "needs_pr" }, pr: null };
2881
+ case "failed": {
2882
+ if (result.reason === "consent_declined") {
2883
+ deps.log(" declined — no branch was pushed and no pull request was opened.");
2884
+ return { workflow: { state: "needs_pr" }, pr: null };
2885
+ }
2886
+ deps.log(` the setup pull request was not opened (${result.reason}): ${result.remediation}`);
2887
+ if (result.prUrl !== undefined)
2888
+ deps.log(` pull request: ${result.prUrl}`);
2889
+ if (result.compareUrl !== undefined)
2890
+ deps.log(` open it by hand: ${result.compareUrl}`);
2891
+ // An uncertain creation is re-read, never repeated.
2892
+ const pr = repository !== null ? await readSetupPullRequest(setup.runGh, repository) : null;
2893
+ if (pr?.state === "open")
2894
+ return { workflow: { state: "pr_open", url: pr.url }, pr };
2895
+ return { workflow: { state: "blocked", remedy: result.remediation }, pr };
2896
+ }
2897
+ }
2898
+ }
2899
+ /**
2900
+ * Fix: store (or replace) the GitHub merge token for this repository, after its
2901
+ * own consent, read with no echo. Never printed, logged, committed, or sent.
2902
+ */
2903
+ async function fixMergeToken(deps, setup, identity, replacing) {
2904
+ const repository = `${identity.owner}/${identity.repo}`;
2905
+ deps.log("");
2906
+ deps.log("GitHub merge token");
2907
+ if (replacing) {
2908
+ deps.log(` GitHub rejected the merge token stored for ${repository} (expired, revoked, or without write access).`);
2909
+ }
2910
+ else {
2911
+ deps.log(` Merges need a GitHub token with write access to ${repository}. Setup can keep it in your ` +
2912
+ "user credential store on this computer, for this repository only. It is never sent to Bridge.");
2913
+ }
2914
+ const ok = await askConsent(deps, replacing
2915
+ ? `Replace the stored merge token for ${repository}? [y/N]: `
2916
+ : `Store a GitHub merge token for ${repository} on this computer? [y/N]: `, replacing ? "replacing the stored merge token" : "storing a merge token");
2917
+ if (!ok) {
2918
+ deps.log(replacing
2919
+ ? " declined — the stored token was left as it is."
2920
+ : " declined — nothing was stored. You can set GITHUB_MERGE_TOKEN instead.");
2921
+ return false;
2922
+ }
2923
+ if (!setup.promptSecret) {
2924
+ deps.log(" skipped reading the token: there is no interactive terminal. Nothing was stored.");
2925
+ return false;
2926
+ }
2927
+ let token = "";
2928
+ try {
2929
+ token = (await setup.promptSecret("GitHub merge token (input is hidden): ")).trim();
2930
+ }
2931
+ catch {
2932
+ token = "";
2933
+ }
2934
+ if (token.length === 0) {
2935
+ deps.log(" no token was entered; nothing was stored.");
2936
+ return false;
2937
+ }
2938
+ if (!isUsableMergeCredentialValue(token)) {
2939
+ deps.log(" that value cannot be a GitHub token (it has spaces or control characters); nothing was stored.");
2940
+ return false;
2941
+ }
2942
+ const result = await setup.storeMergeToken(identity, token);
2943
+ let stored = result.ok;
2944
+ if (!result.ok && result.kind === "post-rename-uncertain") {
2945
+ // Uncertain publication: read the entry back before deciding.
2946
+ const reread = await setup.readMergeToken(identity);
2947
+ stored = reread.status === "present" && reread.token === token;
2948
+ }
2949
+ token = "";
2950
+ if (!stored) {
2951
+ deps.log(` the token could not be stored (${result.ok ? "unconfirmed" : result.kind}); nothing changed.`);
2952
+ return false;
2953
+ }
2954
+ deps.log(` stored the merge token for ${repository} on this computer.`);
2955
+ if (replacing) {
2956
+ deps.log(" A run already in progress keeps the token its executor started with until that executor restarts.");
2957
+ }
2958
+ return true;
2959
+ }
2960
+ /**
2961
+ * Fix: queue ONE repository parse when the merged setup PR is not yet indexed.
2962
+ * Re-reads the parse status first and never queues while one is queued or
2963
+ * running. Concurrent runs rely on the server's coalescing.
2964
+ */
2965
+ async function fixReindex(deps, setup, access) {
2966
+ deps.log("");
2967
+ deps.log("Repository indexing");
2968
+ let status;
2969
+ try {
2970
+ status = await setup.fetchParseStatus(access);
2971
+ }
2972
+ catch {
2973
+ deps.log(" the indexing status could not be read; nothing was queued. Re-run setup later.");
2974
+ return { state: "unknown" };
2975
+ }
2976
+ if (status.status === "queued" || status.status === "in_progress") {
2977
+ deps.log(" indexing is already running; nothing new was queued.");
2978
+ return { state: "in_progress" };
2979
+ }
2980
+ try {
2981
+ await setup.triggerParse(access);
2982
+ }
2983
+ catch {
2984
+ deps.log(" indexing could not be queued right now; re-run setup later.");
2985
+ return { state: "behind" };
2986
+ }
2987
+ deps.log(" queued one repository index so it reaches the merged setup PR. It is pending until it finishes.");
2988
+ return { state: "queued_by_setup" };
2989
+ }
2990
+ /**
2991
+ * `--remove-merge-token`: remove this repository's stored merge token under the
2992
+ * store lock, behind its own consent, then stop. The repository comes from the
2993
+ * local github.com remote, so no network call is needed. Read-only on --dry-run.
2994
+ */
2995
+ async function runRemoveMergeToken(options, deps, setup) {
2996
+ const remote = await setup.readLocalGithubRemote();
2997
+ const identity = resolveGithubMergeRepositoryIdentity({ localRemote: remote });
2998
+ if (!identity.ok) {
2999
+ deps.errorLog("Could not tell which repository's token to remove: run this from a checkout whose `origin` " +
3000
+ "remote is the github.com repository. Nothing was removed.");
3001
+ return 1;
3002
+ }
3003
+ const repository = `${identity.identity.owner}/${identity.identity.repo}`;
3004
+ deps.log(`Stored GitHub merge token for ${repository}`);
3005
+ if (options.dryRun) {
3006
+ deps.log(" Dry run — would ask, then remove the token stored on this computer. Nothing was removed.");
3007
+ return 0;
3008
+ }
3009
+ const ok = await askConsent(deps, `Remove the merge token stored for ${repository} on this computer? [y/N]: `, "removing the stored merge token");
3010
+ if (!ok) {
3011
+ deps.log(" declined — nothing was removed.");
3012
+ return 0;
3013
+ }
3014
+ const result = await setup.removeMergeToken(identity.identity);
3015
+ if (!result.ok) {
3016
+ deps.errorLog(` the token could not be removed (${result.kind}); nothing changed.`);
3017
+ return 1;
3018
+ }
3019
+ deps.log(result.action === "removed"
3020
+ ? ` removed the merge token stored for ${repository}.`
3021
+ : ` no merge token was stored for ${repository}; nothing to remove.`);
3022
+ deps.log(" This deletes the local copy only; it does not revoke the token at GitHub. GITHUB_MERGE_TOKEN or " +
3023
+ "BAPI_LOCAL_MERGE_TOKEN in your environment, and a token already handed to a running executor, " +
3024
+ "still work. To cut access now, revoke the token at GitHub and stop the executor.");
3025
+ return 0;
3026
+ }
3027
+ /** Advisory, never blocking: local extras the default flow no longer asks about. */
3028
+ function localAdvisories(report) {
3029
+ const out = [];
3030
+ const section = (id) => report.sections.find((s) => s.id === id);
3031
+ const profile = section("epic-implementer-profile-token");
3032
+ if (profile !== undefined && profile.status !== "ok") {
3033
+ out.push("to see the Epic Implementer tools in your editor, add `epic_implementer` to BRIDGE_MCP_PROFILE " +
3034
+ "in your MCP configuration, then restart the editor");
3035
+ }
3036
+ const hooks = section("conductor-hook-targets");
3037
+ if (hooks !== undefined && hooks.status !== "ok") {
3038
+ out.push("for local event history, run `epic-implementer install-git-hooks`");
3039
+ }
3040
+ return out;
3041
+ }
3042
+ /**
3043
+ * The converging setup: check everything read-only, fix only what is missing
3044
+ * (each fix behind its own consent), check again, and print one verdict.
3045
+ *
3046
+ * The four pinned properties hold: base-URL consent comes before any network
3047
+ * call (every run, never persisted); --dry-run writes nothing; each write
3048
+ * surface asks for itself; and executor readiness is only ever the server's
3049
+ * observation.
3050
+ */
3051
+ async function runConvergingSetup(options, deps, setup) {
3052
+ if (options.removeMergeToken === true)
3053
+ return runRemoveMergeToken(options, deps, setup);
3054
+ // ---- First operational check: the Claude login marker (a file read only) --
3055
+ let claudeLoggedIn = null;
3056
+ try {
3057
+ claudeLoggedIn = (await setup.detectClaudeLogin()).detected;
3058
+ }
3059
+ catch {
3060
+ claudeLoggedIn = false;
3061
+ }
3062
+ // ---- Base URL, confirmed before any network call -----------------------
3063
+ const confirmed = await resolveAndConfirmBaseUrl(options, deps, "Set up against this URL? [y/N]: ");
3064
+ if (!confirmed.ok)
3065
+ return confirmed.code;
3066
+ const baseUrl = confirmed.baseUrl;
3067
+ // ---- GitHub sign-in, right after the URL consent -----------------------
3068
+ let githubSignIn = "unavailable";
3069
+ try {
3070
+ githubSignIn = await setup.checkGithubSignIn();
3071
+ }
3072
+ catch {
3073
+ githubSignIn = "unavailable";
3074
+ }
3075
+ let localRemote = null;
3076
+ try {
3077
+ localRemote = await setup.readLocalGithubRemote();
3078
+ }
3079
+ catch {
3080
+ localRemote = null;
3081
+ }
3082
+ // ---- Repository: ask only when it is genuinely ambiguous ----------------
3083
+ let accessResult = await deps.resolveAccess(options.repo, baseUrl);
3084
+ if (!accessResult.ok && options.repo === undefined && deps.promptLine) {
3085
+ const suggestion = localRemote?.split("/")[1] ?? null;
3086
+ deps.log("");
3087
+ deps.log("Which repository is this? Bridge could not tell from the environment or .bridge/config.");
3088
+ const answer = (await deps.promptLine(suggestion !== null
3089
+ ? `Bridge repository name [${suggestion}]: `
3090
+ : "Bridge repository name (press Enter to skip): ")).trim();
3091
+ const chosen = answer.length > 0 ? answer : suggestion;
3092
+ if (chosen !== null)
3093
+ accessResult = await deps.resolveAccess(chosen, baseUrl);
3094
+ }
3095
+ const access = accessResult.ok ? accessResult.access : null;
3096
+ const accessError = accessResult.ok ? undefined : accessResult.error;
3097
+ const gateIo = gateIoFor(deps);
3098
+ const standalone = await runStandaloneGateAction(options, deps, gateIo, access, accessError, baseUrl);
3099
+ if (standalone !== null)
3100
+ return standalone;
3101
+ // ---- Check 1: the read-only doctor (no deny probe yet) ------------------
3102
+ deps.log("");
3103
+ deps.log("Checking your setup (read-only)…");
3104
+ const storedContext = storedMergeContextFor(setup, null, localRemote);
3105
+ const firstReport = await deps.runDoctor({
3106
+ access,
3107
+ accessError,
3108
+ reviewPolicySource: options.reviewPolicy,
3109
+ skipDenyProbe: true,
3110
+ storedMergeCredential: storedContext,
3111
+ });
3112
+ if (conductorInstallDoctorHasFatal(firstReport) || !access) {
3113
+ deps.log(formatConductorInstallDoctorReport(firstReport));
3114
+ deps.errorLog("");
3115
+ deps.errorLog("Setup cannot continue until the problem above is fixed. Nothing was written.");
3116
+ deps.log("");
3117
+ deps.log("Not ready: 1 step left");
3118
+ deps.log("complete-with-manual-steps");
3119
+ return 1;
3120
+ }
3121
+ const preflight = await runExecutorPreflightPhase(options, deps, baseUrl, access);
3122
+ if (preflight.kind === "refused")
3123
+ return 1;
3124
+ const executorPlans = preflight.plans;
3125
+ // ---- The gate: explicit flags win; otherwise the CI check is added ------
3126
+ const gatePhase = await resolveConductorGate(gateIo, access, options.gate, deps.gate, {
3127
+ dryRun: options.dryRun,
3128
+ ...(hasExplicitGateInput(options.gate) ? {} : { ensureProviderCheck: EPIC_IMPLEMENTER_CI_CHECK_NAME }),
3129
+ });
3130
+ if (gatePhase.kind === "exit")
3131
+ return gatePhase.code;
3132
+ const gatePlan = gatePhase.kind === "plan" ? gatePhase.plan : null;
3133
+ const gateChangeDeclined = gatePhase.kind === "plan" && gatePhase.ensureDeclined === true;
3134
+ const advisories = localAdvisories(firstReport);
3135
+ const collectInputs = { claudeLoggedIn, githubSignIn, localRemote, gateChangeDeclined, advisories };
3136
+ const first = await collectSetupEvidence(deps, setup, access, firstReport.readiness, collectInputs);
3137
+ const state = {
3138
+ evidence: first.evidence,
3139
+ identity: first.identity,
3140
+ repository: first.repository,
3141
+ storedCommand: first.storedCommand,
3142
+ toolchains: first.toolchains,
3143
+ commandChanged: false,
3144
+ commandBlocked: false,
3145
+ failedOperations: [],
3146
+ };
3147
+ const firstItems = projectSetupItems(state.evidence);
3148
+ for (const line of renderSetupAssessment(firstItems, "What setup found"))
3149
+ deps.log(line);
3150
+ // An explicit --test-command asks for a write unless the stored value already
3151
+ // equals it. A stored value that could not be read is eligible for the write.
3152
+ // Only this non-sensitive boolean reaches the planner; the text never does.
3153
+ const explicitCommand = options.testCommand;
3154
+ const commandAlreadyStored = explicitCommand !== undefined &&
3155
+ state.evidence.testCommand.state === "stored" &&
3156
+ state.storedCommand === explicitCommand;
3157
+ const replaceTestCommandRequested = explicitCommand !== undefined && !commandAlreadyStored;
3158
+ const planContext = {
3159
+ gateOrDefaultsNeedWrite: gateOrDefaultsNeedWrite(gatePlan, firstReport.readiness),
3160
+ dryRun: options.dryRun,
3161
+ };
3162
+ let fixes = planSetupFixes(state.evidence, { ...planContext, replaceTestCommandRequested });
3163
+ if (commandAlreadyStored) {
3164
+ deps.log("");
3165
+ deps.log("Test command unchanged — it already matches --test-command, so nothing was written.");
3166
+ }
3167
+ // ---- Dry run: preview only, before every write and write prompt ---------
3168
+ if (options.dryRun) {
3169
+ logStoredCommandAndToolchains(deps, state.storedCommand, state.toolchains);
3170
+ deps.log("");
3171
+ deps.log("Dry run — nothing was written and nothing was asked.");
3172
+ if (fixes.length === 0)
3173
+ deps.log(" No fix is needed.");
3174
+ for (const fix of fixes)
3175
+ deps.log(` Would offer: ${DRY_RUN_FIX_TEXT[fix]}`);
3176
+ if (executorPlans) {
3177
+ deps.log(` Would write executor unit: ${executorPlans.install.unitPath}`);
3178
+ deps.log(` Would start it with: ${executorPlans.start.manualCommand}`);
3179
+ }
3180
+ deps.log("");
3181
+ deps.log(setupVerdictLine(firstItems));
3182
+ deps.log("complete-with-manual-steps (dry run)");
3183
+ return 0;
3184
+ }
3185
+ // ---- Fix only what is missing, once, in order ---------------------------
3186
+ if (fixes.length > 0) {
3187
+ deps.log("");
3188
+ deps.log("Fixing what is missing…");
3189
+ }
3190
+ // Each fix runs at most once per invocation: re-planning after a command write
3191
+ // can add the workflow fix, but never repeats a write, a declined prompt, or
3192
+ // an independent setup operation.
3193
+ const attempted = new Set();
3194
+ while (fixes.length > 0) {
3195
+ const fix = fixes.shift();
3196
+ if (attempted.has(fix))
3197
+ continue;
3198
+ attempted.add(fix);
3199
+ if (isTestCommandFix(fix)) {
3200
+ const result = fix === "replace_test_command" && explicitCommand !== undefined
3201
+ ? await fixExplicitTestCommand(deps, setup, access, explicitCommand, state.evidence.testCommand.state === "stored")
3202
+ : await fixTestCommand(deps, setup, access);
3203
+ if (result.failure !== null) {
3204
+ // A write that was not confirmed: report it as a blocking operation, keep
3205
+ // only the server's returned value, and block every later workflow step.
3206
+ state.failedOperations.push(result.failure);
3207
+ state.commandBlocked = true;
3208
+ if (result.serverValue !== undefined) {
3209
+ state.storedCommand = result.serverValue;
3210
+ state.evidence = {
3211
+ ...state.evidence,
3212
+ testCommand: { state: result.serverValue === null ? "missing" : "stored" },
3213
+ };
3214
+ }
3215
+ state.evidence = { ...state.evidence, workflow: { state: "blocked", remedy: COMMAND_UNVERIFIED_WORKFLOW_REMEDY } };
3216
+ }
3217
+ else if (result.confirmed !== null) {
3218
+ state.storedCommand = result.confirmed;
3219
+ state.commandChanged = true;
3220
+ state.evidence = { ...state.evidence, testCommand: { state: "stored" } };
3221
+ // Reassess the workflow against the CONFIRMED value and the same
3222
+ // toolchain snapshot, then derive what is left from the updated evidence.
3223
+ const reassessed = state.evidence.githubSignIn === "signed_in"
3224
+ ? await assessWorkflow(setup, result.confirmed, state.toolchains, true)
3225
+ : { state: "unknown" };
3226
+ state.evidence = { ...state.evidence, workflow: reassessed };
3227
+ fixes = planSetupFixes(state.evidence, { ...planContext, replaceTestCommandRequested: false }).filter((kind) => !attempted.has(kind) && !isTestCommandFix(kind));
3228
+ }
3229
+ }
3230
+ else if (fix === "setup_pr") {
3231
+ if (state.commandBlocked) {
3232
+ deps.log("");
3233
+ deps.log("CI workflow");
3234
+ deps.log(" skipped — the test command could not be verified, so the workflow is not built from it.");
3235
+ continue;
3236
+ }
3237
+ if (state.storedCommand === null) {
3238
+ deps.log("");
3239
+ deps.log("CI workflow");
3240
+ deps.log(" skipped — it is built from the stored test command, which is not saved yet.");
3241
+ continue;
3242
+ }
3243
+ const opened = await fixSetupPullRequest(deps, setup, state.storedCommand, state.toolchains, state.repository);
3244
+ state.evidence = { ...state.evidence, workflow: opened.workflow };
3245
+ }
3246
+ else if (fix === "gate_and_defaults" && gatePlan !== null) {
3247
+ await fixGateAndDefaults(deps, options, access, gatePlan);
3248
+ }
3249
+ else if (fix === "merge_token" && state.identity !== null) {
3250
+ await fixMergeToken(deps, setup, state.identity, state.evidence.mergeCredential.state === "stored_rejected");
3251
+ }
3252
+ else if (fix === "reindex") {
3253
+ state.evidence = { ...state.evidence, index: await fixReindex(deps, setup, access) };
3254
+ }
3255
+ }
3256
+ // ---- Explicit operations, each behind its own consent (unchanged) -------
3257
+ if (options.gate.qualifyGate && gatePlan !== null && gatePlan.desired.localCommands.length > 0) {
3258
+ await runConductorGateQualification(gateIo, access, deps.gate, {
3259
+ revision: gatePlan.current.revision,
3260
+ baseUrl,
3261
+ });
3262
+ }
3263
+ if (options.epicBranchCiDecision !== undefined) {
3264
+ const epicBranchCi = await runEpicBranchCiInspection(gateIo, access, deps.gate, {
3265
+ decisionFlag: options.epicBranchCiDecision,
3266
+ dryRun: false,
3267
+ });
3268
+ if (epicBranchCi.manualAction !== null)
3269
+ state.evidence.advisories.push(epicBranchCi.manualAction);
3270
+ }
3271
+ if (options.reviewPolicy === "verdict_protocol" && !options.skipWorkflow) {
3272
+ await runClaudeReviewWorkflowOperation(deps, options, state);
3273
+ }
3274
+ if (options.epicKey && options.planFile) {
3275
+ deps.log("");
3276
+ deps.log("Verifying the plan with `setup-epic --dry-run`…");
3277
+ const verification = await deps.runSetupEpicDryRun([
3278
+ "--dry-run",
3279
+ "--epic-key",
3280
+ options.epicKey,
3281
+ "--plan-file",
3282
+ options.planFile,
3283
+ "--review-policy",
3284
+ options.reviewPolicy,
3285
+ ...(options.repo ? ["--repo", options.repo] : []),
3286
+ ]);
3287
+ if (verification.exitCode !== 0) {
3288
+ state.failedOperations.push({
3289
+ id: "setup-epic-verification",
3290
+ label: "Plan verification",
3291
+ state: "needs_action",
3292
+ blocking: true,
3293
+ remedy: "fix the plan problems `setup-epic --dry-run` reported, then re-run setup",
3294
+ });
3295
+ }
3296
+ else {
3297
+ deps.log(" passed.");
3298
+ }
3299
+ }
3300
+ let observedReadiness = null;
3301
+ if (deps.executorProvisioning && executorPlans) {
3302
+ deps.log("");
3303
+ deps.log("Executor service");
3304
+ observedReadiness = await runExecutorProvisioningPhase(deps, deps.executorProvisioning, executorPlans, access);
3305
+ }
3306
+ // ---- Check 2: the closing assessment (deny probe runs once, here) -------
3307
+ deps.log("");
3308
+ deps.log("Checking again…");
3309
+ const finalReport = await deps.runDoctor({
3310
+ access,
3311
+ reviewPolicySource: options.reviewPolicy,
3312
+ storedMergeCredential: storedMergeContextFor(setup, firstReport.readiness?.provider_repository ?? null, localRemote),
3313
+ });
3314
+ const finalReadiness = observedReadiness ?? finalReport.readiness;
3315
+ const closing = await collectSetupEvidence(deps, setup, access, finalReadiness, {
3316
+ ...collectInputs,
3317
+ advisories: state.evidence.advisories,
3318
+ commandChanged: state.commandChanged,
3319
+ commandBlocked: state.commandBlocked,
3320
+ });
3321
+ // A parse this run queued is pending, whatever the first read-back says.
3322
+ if (state.evidence.index.state === "queued_by_setup" && closing.evidence.index.state !== "reached") {
3323
+ closing.evidence.index = { state: "queued_by_setup" };
3324
+ }
3325
+ const items = [...projectSetupItems(closing.evidence), ...state.failedOperations];
3326
+ if (deniesEnforcementUnknown(finalReport)) {
3327
+ items.push({
3328
+ id: "conductor.deny-enforcement",
3329
+ label: catalogLabel("conductor.deny-enforcement"),
3330
+ state: "unknown",
3331
+ blocking: false,
3332
+ remedy: "the worker safety check could not run; run `epic-implementer doctor` to see why",
3333
+ });
3334
+ }
3335
+ // ---- BAPI-1260: the reusable launch profile (explicit) ------------------
3336
+ if (options.launchProfile !== undefined) {
3337
+ const launch = await runLaunchProfilePhase(deps, options, {
3338
+ access,
3339
+ baseUrl,
3340
+ readiness: finalReadiness,
3341
+ actorObserved: observedReadiness !== null || finalReadiness?.executor.ready === true,
3342
+ runtime: resolveLaunchRuntime(deps.executorProvisioning, options.executionMode ?? "local"),
3343
+ });
3344
+ if (!launch.complete) {
3345
+ items.push({
3346
+ id: "launch-profile",
3347
+ label: `Launch profile '${options.launchProfile}'`,
3348
+ state: "needs_action",
3349
+ blocking: true,
3350
+ remedy: "finish the launch-profile steps listed above, then re-run setup with --launch-profile",
3351
+ });
3352
+ }
3353
+ }
3354
+ // The latest authoritative command (after any replacement) and what CI installs
3355
+ // for it. Operator-only: written through deps.log and nowhere else.
3356
+ logStoredCommandAndToolchains(deps, closing.evidence.testCommand.state === "stored" ? closing.storedCommand : null, closing.toolchains);
3357
+ for (const line of renderSetupAssessment(items, "Where things stand"))
3358
+ deps.log(line);
3359
+ for (const advisory of closing.evidence.advisories)
3360
+ deps.log(` - ${advisory}`);
3361
+ deps.log("");
3362
+ const ready = unmetBlockingItems(items).length === 0;
3363
+ deps.log(setupVerdictLine(items));
3364
+ deps.log(ready ? "complete" : "complete-with-manual-steps");
3365
+ return ready ? conductorInstallDoctorExitCode(finalReport) : 1;
3366
+ }
3367
+ /** The deny probe could not answer: an advisory, never readiness. */
3368
+ function deniesEnforcementUnknown(report) {
3369
+ const deny = report.legacyConductor?.deny_enforcement;
3370
+ return deny !== undefined && deny !== null && deny.enforced !== true;
3371
+ }
3372
+ /** Short previews of each fix for --dry-run. */
3373
+ const DRY_RUN_FIX_TEXT = Object.freeze({
3374
+ save_test_command: "save the repository's test command (one question, then PUT /setup/testing-config)",
3375
+ replace_test_command: "save the command you passed with --test-command (that flag is the consent; one write, then a read-back), " +
3376
+ "then re-check the CI workflow against the stored value and offer the setup pull request",
3377
+ setup_pr: "open the setup pull request with the CI workflow (its own consent)",
3378
+ gate_and_defaults: "store the repository gate and the safe supervisor defaults (its own consent)",
3379
+ merge_token: "store a GitHub merge token on this computer (its own consent, read with no echo)",
3380
+ reindex: "queue one repository index so it reaches the merged setup PR",
3381
+ });
3382
+ /**
3383
+ * The claude-review workflow, only for an explicit `--review-policy
3384
+ * verdict_protocol`: its own write consent and a separate overwrite consent.
3385
+ */
3386
+ async function runClaudeReviewWorkflowOperation(deps, options, state) {
3387
+ deps.log("");
3388
+ deps.log("Claude review workflow");
3389
+ if (!options.allowedBot || !options.secretName || !options.branches) {
3390
+ deps.log(" skipped — --allowed-bot, --secret-name, and --branches are required to write it.");
3391
+ return;
3392
+ }
3393
+ const want = await askConsent(deps, `Write ${CLAUDE_REVIEW_WORKFLOW_RELPATH}? [y/N]: `, "writing the review workflow");
3394
+ if (!want) {
3395
+ deps.log(" declined — no file was written.");
3396
+ return;
3397
+ }
3398
+ let content;
3399
+ try {
3400
+ content = renderClaudeReviewWorkflow({
3401
+ allowedBot: options.allowedBot,
3402
+ secretName: options.secretName,
3403
+ branches: options.branches,
3404
+ });
3405
+ }
3406
+ catch (err) {
3407
+ deps.errorLog(` workflow parameters rejected: ${err instanceof Error ? err.message : "invalid"}`);
3408
+ state.failedOperations.push({
3409
+ id: "claude-review-workflow",
3410
+ label: "Claude review workflow",
3411
+ state: "needs_action",
3412
+ blocking: true,
3413
+ remedy: "fix --allowed-bot, --secret-name, or --branches, then re-run setup",
3414
+ });
3415
+ return;
3416
+ }
3417
+ let result = await deps.writeWorkflow(deps.cwd, content, {});
3418
+ if (result.ok && result.outcome === "skipped") {
3419
+ const overwrite = await askConsent(deps, `${CLAUDE_REVIEW_WORKFLOW_RELPATH} exists and differs. Overwrite? [y/N]: `, "overwriting the review workflow");
3420
+ if (overwrite)
3421
+ result = await deps.writeWorkflow(deps.cwd, content, { overwriteConsent: true });
3422
+ else
3423
+ deps.log(" existing workflow left untouched.");
3424
+ }
3425
+ if (!result.ok) {
3426
+ deps.errorLog(` workflow write failed: ${result.error}`);
3427
+ state.failedOperations.push({
3428
+ id: "claude-review-workflow",
3429
+ label: "Claude review workflow",
3430
+ state: "needs_action",
3431
+ blocking: true,
3432
+ remedy: "re-run setup to write the review workflow",
3433
+ });
3434
+ return;
3435
+ }
3436
+ if (result.outcome === "written") {
3437
+ deps.log(` wrote ${CLAUDE_REVIEW_WORKFLOW_RELPATH}`);
3438
+ const recorded = await deps.recordArtifact(deps.cwd, CLAUDE_REVIEW_WORKFLOW_RELPATH);
3439
+ if (!recorded.ok)
3440
+ deps.errorLog(` note: install-state not updated (${recorded.error ?? "unknown"})`);
3441
+ }
3442
+ else if (result.outcome === "unchanged") {
3443
+ deps.log(` ${CLAUDE_REVIEW_WORKFLOW_RELPATH} already matches — nothing written.`);
3444
+ }
3445
+ }