@bridge_gpt/mcp-server 0.2.71 → 0.2.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +22 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +7 -7
  5. package/build/bridge-permissions.js +31 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/ci-system-detection.js +50 -0
  9. package/build/ci-trigger-adapters.js +631 -0
  10. package/build/ci-trigger-install.js +106 -0
  11. package/build/claude-review-workflow.js +1 -1
  12. package/build/cli-help.js +6 -0
  13. package/build/codex-auto-recovery.js +126 -0
  14. package/build/codex-launcher-pin.js +33 -2
  15. package/build/codex-skill-adapter.js +5 -1
  16. package/build/command-host.js +33 -0
  17. package/build/commands.generated.js +7 -6
  18. package/build/conductor/bridge-api-client.js +1352 -50
  19. package/build/conductor/bring-up-facts.js +18 -5
  20. package/build/conductor/command-drift-production.js +42 -17
  21. package/build/conductor/command-drift.js +47 -0
  22. package/build/conductor/declare-blocked.js +554 -0
  23. package/build/conductor/doctor.js +187 -28
  24. package/build/conductor/driver-commands.js +141 -0
  25. package/build/conductor/driver-guard.js +277 -0
  26. package/build/conductor/driver-lapse.js +321 -0
  27. package/build/conductor/driver-register.js +176 -0
  28. package/build/conductor/driver-release.js +174 -0
  29. package/build/conductor/driver-session-state.js +315 -0
  30. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  31. package/build/conductor/epic-implementer-cli.js +213 -13
  32. package/build/conductor/epic-server-database.js +162 -0
  33. package/build/conductor/epic-server-guidance.js +278 -0
  34. package/build/conductor/epic-server-journal.js +239 -0
  35. package/build/conductor/epic-server-processes.js +324 -0
  36. package/build/conductor/epic-server-recipe.js +397 -0
  37. package/build/conductor/epic-server-runtime.js +1207 -0
  38. package/build/conductor/epic-server-sfcc.js +107 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +594 -0
  41. package/build/conductor/gate-discovery.js +281 -10
  42. package/build/conductor/gate-settings-review.js +525 -5
  43. package/build/conductor/git-hooks-uninstall.js +112 -0
  44. package/build/conductor/git-hooks.js +81 -15
  45. package/build/conductor/guided-repair.js +10 -1
  46. package/build/conductor/install-doctor.js +2 -4
  47. package/build/conductor/launch-need-probes.js +6 -53
  48. package/build/conductor/launch-plan.js +318 -121
  49. package/build/conductor/local-merge.js +12 -1
  50. package/build/conductor/merge-execution-contract.js +1 -1
  51. package/build/conductor/merged-child-check.js +2 -1
  52. package/build/conductor/prerequisite-inputs.js +1213 -0
  53. package/build/conductor/readiness-assessment.js +93 -0
  54. package/build/conductor/readiness-cli.js +30 -9
  55. package/build/conductor/readiness-prerequisites.js +77 -5
  56. package/build/conductor/readiness-sections.js +146 -126
  57. package/build/conductor/readiness.js +21 -3
  58. package/build/conductor/recovery-cli.js +236 -15
  59. package/build/conductor/recovery-operations.js +34 -4
  60. package/build/conductor/repair-contract.js +33 -0
  61. package/build/conductor/tools.js +36 -4
  62. package/build/conductor/wait-run-attention.js +115 -0
  63. package/build/conductor/wait-run-cli.js +300 -21
  64. package/build/conductor/worker-database-doctor-inspector.js +34 -2
  65. package/build/conductor/worker-setup-tally.js +27 -0
  66. package/build/credential-store.js +96 -21
  67. package/build/dependency-install-declarations.js +212 -0
  68. package/build/docs.generated.js +4 -4
  69. package/build/doctor.js +91 -8
  70. package/build/drive-epic-help.js +23 -4
  71. package/build/drive-epic.js +1841 -340
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +140 -0
  74. package/build/epic-capability-statement.js +107 -0
  75. package/build/epic-ci-workflow-drift.js +30 -15
  76. package/build/epic-ci-workflow-install.js +110 -42
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow.js +38 -12
  79. package/build/epic-implementer-bin.js +2184 -52
  80. package/build/epic-launch-context.js +607 -0
  81. package/build/epic-launch-profile.js +1 -1
  82. package/build/epic-server-record.js +273 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/cli.js +2 -0
  87. package/build/executor/completion-contract.js +24 -1
  88. package/build/executor/credentials.js +1 -1
  89. package/build/executor/delivery-observations.js +113 -0
  90. package/build/executor/delivery-outcome.js +30 -0
  91. package/build/executor/dependency-refresh-runner.js +132 -0
  92. package/build/executor/dependency-refresh.js +530 -0
  93. package/build/executor/deps.js +4 -0
  94. package/build/executor/env.js +119 -17
  95. package/build/executor/epic-server-context.js +141 -0
  96. package/build/executor/gate-qualification-job.js +127 -26
  97. package/build/executor/harness-coverage.js +19 -0
  98. package/build/executor/http-client.js +87 -6
  99. package/build/executor/index.js +2 -1
  100. package/build/executor/install-preflight.js +1 -1
  101. package/build/executor/job-runner.js +659 -87
  102. package/build/executor/likely-tests.js +94 -97
  103. package/build/executor/observation.js +8 -0
  104. package/build/executor/pre-pr-checks.js +363 -0
  105. package/build/executor/prompt-spec.js +127 -5
  106. package/build/executor/reconcile-overlap-job.js +5 -3
  107. package/build/executor/required-verification.js +28 -0
  108. package/build/executor/required-work-diagnostics.js +32 -0
  109. package/build/executor/required-work-ledger.js +955 -39
  110. package/build/executor/results.js +100 -0
  111. package/build/executor/service-discovery.js +42 -0
  112. package/build/executor/service-lifecycle.js +109 -2
  113. package/build/executor/service-uninstall.js +205 -0
  114. package/build/executor/service-unit.js +5 -3
  115. package/build/executor/terminal-mutation.js +8 -0
  116. package/build/executor/test-clock.js +3 -0
  117. package/build/executor/verification-hints.js +179 -0
  118. package/build/executor/worker-command.js +126 -5
  119. package/build/executor/worker-database-config.js +281 -0
  120. package/build/executor/worker-database-target.js +16 -12
  121. package/build/executor/worker-database.js +575 -116
  122. package/build/executor/worker-finalization.js +71 -10
  123. package/build/executor/worker-guard-hook.js +10 -2
  124. package/build/executor/worker-resources.js +25 -3
  125. package/build/executor/worker-verification-guidance.js +55 -5
  126. package/build/executor/worktree-inspection.js +42 -0
  127. package/build/executor/worktree.js +20 -1
  128. package/build/executor-launch.js +54 -2
  129. package/build/generated-assets-catalog.js +2 -2
  130. package/build/github-sign-in.js +1 -1
  131. package/build/index.js +1111 -381
  132. package/build/init.js +29 -14
  133. package/build/install-bridge-conductor-answers.js +465 -0
  134. package/build/install-bridge-conductor-apply.js +259 -0
  135. package/build/install-bridge-conductor-assessment.js +895 -0
  136. package/build/install-bridge-conductor-compact.js +161 -0
  137. package/build/install-bridge-conductor-contracts.js +63 -0
  138. package/build/install-bridge-conductor-gate.js +1383 -188
  139. package/build/install-bridge-conductor-setup.js +637 -92
  140. package/build/install-bridge-conductor.js +3163 -740
  141. package/build/install-bridge.js +601 -128
  142. package/build/install-maintenance.js +127 -0
  143. package/build/install-reexec.js +1 -1
  144. package/build/launcher-config-inspection.js +162 -1
  145. package/build/local-cleanup.js +59 -0
  146. package/build/mcp-grant-candidates.js +767 -0
  147. package/build/mcp-grant-doctor.js +63 -0
  148. package/build/mcp-grant.js +288 -0
  149. package/build/mcp-host-targets.js +8 -0
  150. package/build/mcp-identity.js +23 -0
  151. package/build/mcp-install-state.js +68 -2
  152. package/build/mcp-invoke.js +126 -13
  153. package/build/mcp-presets.js +107 -0
  154. package/build/mcp-provisioning.js +134 -2
  155. package/build/mcp-registration-doctor.js +31 -2
  156. package/build/mcp-server-invocation.js +6 -1
  157. package/build/merge-workflow-install.js +236 -111
  158. package/build/package-script-semantics.js +10 -0
  159. package/build/pipeline-utils.js +1 -1
  160. package/build/pipelines.generated.js +6 -6
  161. package/build/plan-discovery.js +97 -4
  162. package/build/plan-execution-ledger.js +248 -9
  163. package/build/plan-generation-io.js +262 -0
  164. package/build/plan-generation.js +424 -0
  165. package/build/plane/build-freshness.js +6 -1
  166. package/build/plane/cli.js +75 -9
  167. package/build/plane/plane-freshness.js +23 -7
  168. package/build/plane/preflight.js +50 -10
  169. package/build/plane/shutdown.js +19 -0
  170. package/build/plane/terminal-run-cleanup.js +23 -5
  171. package/build/plane/terminal-run-status.js +4 -0
  172. package/build/printed-remedy-commands.js +229 -15
  173. package/build/readiness-check.js +1 -1
  174. package/build/readiness-prerequisites.generated.js +311 -4
  175. package/build/readme.generated.js +1 -1
  176. package/build/repository-state-paths.js +38 -0
  177. package/build/repository-toolchains.js +50 -8
  178. package/build/run-unit-tests-launcher.js +8 -1
  179. package/build/setup-change-policy.js +32 -0
  180. package/build/setup-epic.js +1192 -198
  181. package/build/setup-progress.js +44 -0
  182. package/build/setup-question.js +180 -0
  183. package/build/start-tickets.js +4 -0
  184. package/build/test-command-detection.js +32 -88
  185. package/build/test-support/notes-fs.js +40 -0
  186. package/build/third-party-mcp-targets.js +30 -0
  187. package/build/ticket-delivery-enrollment.js +30 -8
  188. package/build/ticket-delivery-run-scope.js +128 -0
  189. package/build/upgrade-cli.js +85 -2
  190. package/build/v2-readiness-requirements.js +28 -1
  191. package/build/version.generated.js +3 -3
  192. package/build/worker-guard-hook-bin.js +2 -2
  193. package/build/worktrees.js +105 -0
  194. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  195. package/docs/EPIC-IMPLEMENTER.md +5 -0
  196. package/docs/epic-implementer/getting-started.md +42 -15
  197. package/docs/epic-implementer/self-hosting.md +14 -1
  198. package/package.json +2 -2
@@ -1,5 +1,18 @@
1
+ import { writeJsonDocument, flushProcessStdout } from './conductor/json-output.js';
2
+ import { INSTALL_ASSESSMENT_SCHEMA_VERSION, } from './install-bridge-conductor-contracts.js';
3
+ import { buildInstallAssessment, buildInstallChoices, epicBranchCiStateText, indexDisplayStatus, } from './install-bridge-conductor-assessment.js';
4
+ import { GITHUB_ACTIONS_TRIGGER_ADAPTER, recognizeAppliedEdit, selectTriggerEdit, sha256Hex, } from './ci-trigger-adapters.js';
5
+ import { detectCiSystems } from './ci-system-detection.js';
6
+ import { describeDeclinedCiChange, describeProposedCiChange } from './epic-branch-ci-summary.js';
7
+ import { buildCompactApply, buildCompactAssessment, buildCompactProposal } from './install-bridge-conductor-compact.js';
8
+ import { decisionFor, normalizeInstallAnswers, parseAnswersText, readAnswersSource, } from './install-bridge-conductor-answers.js';
9
+ import { applyInstallProposal, } from './install-bridge-conductor-apply.js';
10
+ import { previewConductorSetupPolicy, applyConductorSetupPolicy, fetchConductorSetupPolicy, fetchConductorGateProfile, fetchConductorRepositoryLearning, ConductorSetupPolicyError, SETUP_POLICY_PROTOCOL } from "./conductor/bridge-api-client.js";
11
+ import { askPlainConsent, askPlainSetupQuestion, askSetupQuestion, createPlainInputSession, setupConsentQuestion, } from "./setup-question.js";
12
+ import { readBridgeConfig } from "./bridge-config.js";
13
+ import { withSetupProgress } from "./setup-progress.js";
1
14
  /**
2
- * `install-bridge conductor` — the nested conductor bootstrap phase (BAPI-679).
15
+ * `install epic-implementer` — the nested conductor bootstrap phase (BAPI-679).
3
16
  *
4
17
  * BAPI-1461 — CONVERGING SETUP. With the production setup seams (always
5
18
  * supplied by `install-bridge.ts`), this command is a loop, not a script: it
@@ -20,26 +33,13 @@
20
33
  *
21
34
  * Four properties are load-bearing and are pinned by tests:
22
35
  *
23
- * 1. **Base-URL consent before ANY network call.** `resolveInstallBridgeBaseUrl`
24
- * silently defaults to production when `BAPI_BASE_URL` is unset, and even the
25
- * read-only doctor's readiness GET carries this repository's API key — so the
26
- * resolved URL is displayed and explicitly confirmed BEFORE the first request
27
- * of any kind, including under `--dry-run`. Non-interactive (no TTY) means no
28
- * consent, which means abort. Only after that does the unified doctor run,
29
- * still BEFORE any write, and a fatal finding aborts. Repairable gaps
30
- * (missing supervisor rows — exactly what bootstrap fixes) are `degraded`
31
- * and do not block.
32
- * 2. **`--dry-run` writes nothing, anywhere.** It returns before every POST,
33
- * filesystem write, install-state write, and write-consent prompt. (It still
34
- * asks the base-URL confirmation above, because its doctor GET is a network
35
- * call that reveals the key to the resolved host.)
36
- * 3. **One consent per write surface.** Confirming the resolved base URL is NOT
37
- * consent to write; consent to overwrite a workflow file is not consent to
38
- * edit host MCP configuration; and neither is consent to install Git hooks.
39
- * The rule is per-SURFACE, not a fixed count — BAPI-775 added two more write
40
- * surfaces (host MCP configs, managed Git hooks) and each asks for itself, so
41
- * counting consents was never the invariant. A missing prompt seam (no TTY)
42
- * is a decline everywhere, never a default-yes.
36
+ * 1. **Destination before requests.** Parent installation settles credential
37
+ * identity and endpoint approval before authenticated requests. The nested
38
+ * command displays the resolved destination before access resolution.
39
+ * 2. **`--dry-run` writes nothing, anywhere.** Read-only diagnostics remain
40
+ * available without redundant URL confirmation or write-consent questions.
41
+ * 3. **One consent per consequential effect.** Destination selection does not
42
+ * authorize policy, credential, service, workflow, or hook changes.
43
43
  * 4. **The executor leg is never claimed as provisioned by local success.**
44
44
  * AMENDED BY BAPI-779 (R-1): this command can now write the service unit
45
45
  * *and* start it. What did not change — and must not — is where readiness
@@ -67,7 +67,7 @@
67
67
  * DURABLE-HOST MODE (BAPI-1137). The executor phase below is the supported
68
68
  * bring-up for a *durable host*: an execution home that is not an interactive
69
69
  * shell session, so a sleeping or closed operator laptop no longer stalls a run.
70
- * The client command spelling is unchanged — it is still `install conductor` —
70
+ * The client command spelling is unchanged — it is still `install epic-implementer` —
71
71
  * and so is every primitive it drives; what this slice does is name the
72
72
  * composition and make its boundaries explicit. Durable-host mode IS that
73
73
  * composition, and nothing more:
@@ -115,26 +115,45 @@
115
115
  *
116
116
  * The command does NOT persist a repository-level review policy: that is
117
117
  * BAPI-694's. The policy selected here is per-run and is reported as such.
118
+ *
119
+ * BAPI-1603 — LEARNED FIRST, A CI PLAN WITH NO QUESTIONS. The converging setup
120
+ * reads whether the repository has been learned before any ordinary write and
121
+ * stops (`repository_not_learned`) only when the server confirms it has not; an
122
+ * unknown reading warns and continues. It then decides the CI plan from facts
123
+ * (explicit gate flags, then a stored confirmed gate, then discovery): checks the
124
+ * repository's CI has reported become WATCHED gate members, and the test command
125
+ * is learned and proven by the server's own trial, never asked for and never
126
+ * written by this client. Bridge's own workflow is a single default-No offer on a
127
+ * proven local plan, its check is added to the gate only after the setup pull
128
+ * request is open, and every input to that pull request comes from the remote
129
+ * default branch, not the person's folder. The one stop this adds is the learned
130
+ * stop; everything else it adds only warns.
118
131
  */
119
132
  import { PRINTED_INSTALL_COMMAND, PRINTED_QUALIFY_GATE_COMMAND } from "./printed-remedy-commands.js";
120
- import { emptyConductorGateFlags, hasExplicitGateInput, parseLocalCommandFlag, parseEpicBranchCiDecisionFlag, parseMigrationGuardFlag, resolveConductorGate, runEpicBranchCiInspection, runClearConductorGate, runConductorGateQualification, runQualifyConductorGate, storeConductorGate, validateConductorGateFlags, } from "./install-bridge-conductor-gate.js";
121
- import { bootstrapConductorSupervisorDefaults, classifySupervisorBootstrapFailure, fetchConductorReadiness, previewConductorSupervisorBootstrap, } from "./conductor/bridge-api-client.js";
133
+ import { collectEpicBranchCi, confirmRequestFor, planDeclarationSelections, describeGateRestoration, desiredFromStored, emptyConductorGateFlags, hasExplicitGateInput, parseLocalCommandFlag, parseEpicBranchCiDecisionFlag, parseMigrationGuardFlag, planManagedProviderGate, reportLearnedCommandTrial, describePolicyChanges, resolveConductorGate, runEpicBranchCiInspection, runGateConsequenceSummary, runClearConductorGate, runConductorGateQualification, runLearnedTestCommandTrial, runQualifyConductorGate, validateConductorGateFlags, } from "./install-bridge-conductor-gate.js";
134
+ import { classifyEpicPullRequestTrigger, readDefaultBranchRequiredChecksViaGh, readPullRequestBranchFilters, } from "./conductor/epic-branch-ci-inspection.js";
135
+ import { describeGateConsequence } from "./conductor/readiness-sections.js";
136
+ import { fetchConductorReadiness, } from "./conductor/bridge-api-client.js";
122
137
  import { CONDUCTOR_OPERATOR_RUNBOOK_POINTER, EXECUTOR_PROVISIONING_GUIDANCE, conductorInstallDoctorExitCode, conductorInstallDoctorHasFatal, formatConductorInstallDoctorReport, } from "./conductor/install-doctor.js";
123
138
  import { describeNativeLedgerAvailability, } from "./conductor/doctor.js";
124
139
  import { resolveGithubMergeRepositoryIdentity, } from "./credential-store.js";
125
140
  import { isUsableMergeCredentialValue, resolveLocalMergeCredentialDetailed, } from "./conductor/merge-credential.js";
126
- import { readStoredTestCommand, writeStoredTestCommand, } from "./testing-config-client.js";
141
+ import { readStoredTestCommand } from "./testing-config-client.js";
127
142
  import { describeToolchainResolution, resolveRepositoryToolchains, } from "./repository-toolchains.js";
128
143
  import { detectTestCommand } from "./test-command-detection.js";
129
144
  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";
145
+ import { EPIC_CI_WORKFLOW_PATH, EPIC_IMPLEMENTER_CI_CHECK_NAME, renderEpicImplementerCiWorkflow } from "./epic-ci-workflow.js";
146
+ import { normalizeStorefrontOrigin, isValidCredentialReference, isValidSfccSandboxId, sameEpicServerRecord, } from "./epic-server-record.js";
147
+ import { CANDIDATE_EXCLUSION_TEXT, CANDIDATE_ORIGIN_LABEL, describeInventoryExclusions, GRANT_SELECTION_PROMPT, parseGrantSelection, } from "./mcp-grant-candidates.js";
148
+ import { buildEpicCapabilityStatement } from "./epic-capability-statement.js";
149
+ import { MCP_GRANT_MAX_SERVERS } from "./mcp-grant.js";
150
+ import { advisoryFindingLines, assessIndexFreshness, assessSetupIndex, catalogLabel, NPM_SETUP_LAUNCHER, closedSetupPullRequestNotice, compareIndexedToMerge, planSetupFixes, projectSetupItems, readSetupPullRequest, renderSetupAssessment, setupItemRemedy, setupVerdictLine, unmetBlockingItems, } from "./install-bridge-conductor-setup.js";
132
151
  import { CONDUCTOR_BIN_UNRESOLVED_ERROR, MANAGED_HOOK_NAMES, } from "./conductor/git-hooks.js";
133
152
  import os from "node:os";
134
153
  import path from "node:path";
135
154
  import { readFile as readFileAsync, stat as statAsync } from "node:fs/promises";
136
155
  import { bindEpicLaunchCredential, readStoredBinding, } from "./credential-store.js";
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";
156
+ import { EPIC_LAUNCH_EXECUTION_MODES, EPIC_LAUNCH_PROFILE_NAME_PATTERN, EPIC_LAUNCH_PROFILE_VERSION, createNodeEpicLaunchStoreDeps, readEpicLaunchProfile, renderEpicLaunchCommand, resolveEpicLaunchTarget, shellQuote, writeEpicLaunchProfile, } from "./epic-launch-profile.js";
138
157
  import { DEFAULT_BAPI_BASE_URL } from "./executor/credentials.js";
139
158
  import { MCP_PACKAGE_NAME } from "./mcp-identity.js";
140
159
  import { LOCAL_MERGE_CREDENTIAL_ENV_KEYS } from "./conductor/merge-credential.js";
@@ -163,32 +182,55 @@ export const CONDUCTOR_REVIEW_POLICY_SOURCES = [
163
182
  * at first approval. AI review is an explicit `--review-policy verdict_protocol`.
164
183
  */
165
184
  export const DEFAULT_CONDUCTOR_REVIEW_POLICY = "repository_policy";
166
- /** Usage text for `install-bridge conductor`. */
185
+ /** Usage text for `install epic-implementer`. */
167
186
  export function getInstallBridgeConductorUsage() {
168
187
  return [
169
- "Usage: install conductor [options]",
188
+ "Usage: install epic-implementer [options]",
170
189
  "",
171
190
  "Set up this repository for the Epic Implementer. It checks everything first",
172
191
  "(read-only), fixes only what is missing, checks again, and ends with one",
173
192
  "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.",
193
+ "for each step. Interactive output ends with an advisory readiness verdict.",
194
+ " --json Emit one JSON document (schema version 2) on stdout: every setup item with its",
195
+ " fix, and every open choice with its options, consequences, recommended option,",
196
+ " and answer_key. With --dry-run it is read-only. Progress goes to stderr.",
197
+ " --compact Emit the smaller view of the --json document. It requires --json.",
198
+ " --answers <file> Apply the choices in a JSON answers file keyed by answer_key, with no",
199
+ " prompts. It must carry the top-level proposal_digest proposal mode returned, and",
200
+ " state every consequential choice; anything unstated or changed is refused before",
201
+ " any write. The merge token is accepted only as a reference, never a value.",
202
+ " --answers - --dry-run --json Read draft answers on stdin and return the normalized",
203
+ " proposal and its proposal_digest. Writes nothing.",
204
+ " --assessment-epic-run-id <id> Observe this run's readiness (default: repository preview).",
205
+ "It exits 0 when ready and 1 for unresolved requested capabilities (0 for --dry-run).",
177
206
  "",
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;",
207
+ "It displays the destination and reads your Claude sign-in (~/.claude.json only)",
208
+ "and `gh auth status`. A ready repository gets no questions and no",
209
+ "writes. Otherwise it asks only what a missing item needs. Each question marks a",
210
+ "recommended option: press Enter to take it, or type ? for details. Consequential",
211
+ "questions (a pull request, a stored token, a merge-rule change) still need an",
212
+ "explicit yes. Setup applies these without asking:",
213
+ " - the project this folder is bound to (it asks which repository only when no",
214
+ " project is bound and it cannot tell);",
215
+ " - safe CI settings and the previewed policy, each printed with a receipt;",
216
+ " - the epic-branch CI choice, when a workflow is shown to run on epic-branch PRs",
217
+ " (otherwise it prints how to record the choice);",
218
+ " - the default indexing branch, when the repository's own default is shown.",
219
+ "It asks about:",
220
+ " - which indexing branch to use, only when an existing different branch makes",
221
+ " the choice unclear;",
222
+ " - adding Bridge's own GitHub workflow, once, only for a repository with no CI of",
223
+ " its own and a test command Bridge has proven (then the setup pull request has",
224
+ " its own consent);",
186
225
  " - 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.",
226
+ "Setup never asks for a test command. The destination is displayed without a",
227
+ "redundant URL question. Without an interactive terminal every question is a",
228
+ "decline: no token is stored and no pull request is opened. When setup reports",
229
+ "that its setup pull request is waiting, merge it and run setup again. Recovery diagnoses the demonstrated",
230
+ "target, offers keep/correct/defer when needed, and tracks one durable initial",
231
+ "request. Failed or ineffective work needs an explicit retry; pending work is",
232
+ "observed without cancellation. Unsupported backends require an upgrade;",
233
+ "noninteractive runs cannot authorize branch corrections or retries.",
192
234
  "",
193
235
  "Merge token: setup can store a GitHub token for this repository in your user",
194
236
  "credential store (~/.config/bridge/credentials.json). GITHUB_MERGE_TOKEN, then",
@@ -197,21 +239,51 @@ export function getInstallBridgeConductorUsage() {
197
239
  "local copy only; it does not revoke the token at GitHub, and a running executor",
198
240
  "keeps the token it started with until it restarts.",
199
241
  "",
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",
242
+ "Learned first: setup stops before any write if Bridge has not learned this",
243
+ "repository yet (`repository_not_learned`, exit 1). Run /learn-repository in",
244
+ "Claude Code, wait for it to finish, then run setup again; Bridge needs your",
245
+ "project's standards to write useful code. If setup cannot tell whether the",
246
+ "repository was learned, it warns once and continues. With --dry-run it reports the",
247
+ "stop and keeps previewing the rest.",
248
+ "",
249
+ "Test command: Bridge's server learns the command from your repository, and setup",
250
+ "proves it by running it once on this computer, in a clean checkout of your default",
251
+ "branch. The server stores it as the gate's local command only if it passes, so a",
252
+ "command that fails or cannot run is never stored. Nobody is asked for it. To use",
253
+ "your own, pass --test-command \"<command>\": the flag offers it for the same proof",
254
+ "(one line, no GitHub Actions expression, at most 500 characters) and it is stored",
255
+ "only if it passes. The flag does NOT authorize credential endpoint transfer and",
207
256
  "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.",
257
+ "--dry-run nothing is requested or run. Do not put a credential in a command: setup",
258
+ "prints it and the workflow file contains it.",
259
+ "",
260
+ "Existing CI is watched, not required: checks your CI has already reported are",
261
+ "stored as watched members of the gate. A red watched check stops a merge; a",
262
+ "missing one only warns. A gate you already confirmed is kept as it is.",
263
+ "",
264
+ "Bridge's workflow is optional: for a repository with no CI of its own and a proven",
265
+ "test command, setup offers it once (default no). It runs only for pull requests",
266
+ "into epic/** branches, and its check is added to the gate only after the setup",
267
+ "pull request is open. The pull request is built from a clean copy of your default",
268
+ "branch, so uncommitted or unpushed changes in your folder never block it or enter it.",
269
+ "",
270
+ "What setup stops on: the one stop this adds is a repository that has not been",
271
+ "learned. It no longer asks for a test command and no longer refuses a folder with",
272
+ "uncommitted changes. Stops added: one. Push targets, the default-branch push",
273
+ "refusal, merge-credential checks, and the human-gated integration pull request",
274
+ "are unchanged.",
210
275
  "",
211
276
  "Options:",
212
- " --test-command <command> Save or replace the repository's test command.",
277
+ " --test-command <command> Offer your own test command for Bridge to prove once;",
278
+ " it replaces the stored local command only if it passes.",
213
279
  " Not combinable with --remove-merge-token or",
214
280
  " --clear-gate; may be given once.",
281
+ " --verbose Print the full assessment, routine advisories, and",
282
+ " command detail. Without it setup prints blocking",
283
+ " problems, a one-line verdict, and one next step.",
284
+ " --review-ci-settings Review each discovered CI setting one by one. Without",
285
+ " it, safe settings are applied and a committed literal",
286
+ " that needs your typed yes is skipped, by name only.",
215
287
  " --remove-merge-token Remove the merge token stored on this computer for",
216
288
  " this repository (its own consent), then exit.",
217
289
  " --repo <name> Repository name (default: BAPI_REPO_NAME / .bridge/config)",
@@ -220,11 +292,12 @@ export function getInstallBridgeConductorUsage() {
220
292
  " --required-checks a,b Comma-separated form of --required-check",
221
293
  "",
222
294
  "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.",
295
+ "required: provider checks, local commands, both (mixed), watched checks, or none.",
296
+ "Explicit gate flags are the complete requested gate. Otherwise a confirmed gate",
297
+ "already stored is used unchanged; otherwise setup decides from facts, with no",
298
+ "question: checks your CI has really reported become watched members, and the",
299
+ "server adds a proven local command. Nothing is stored until you authorize the",
300
+ "combined policy change that setup previews.",
228
301
  " --provider-check <name> An exact provider-reported check name (repeatable).",
229
302
  " Admission refuses one that has never reported.",
230
303
  " --local-command <cmd> A local command the executor runs before each merge",
@@ -237,8 +310,6 @@ export function getInstallBridgeConductorUsage() {
237
310
  " child merge. Exclusive with the member flags.",
238
311
  " --customized-command <n> A packaged command this repository customizes, stored",
239
312
  " in the confirmed gate (repeatable), e.g. implement-ticket.",
240
- " --confirm-gate Confirm explicit gate flags even when they REMOVE",
241
- " members from the stored gate (otherwise you are asked).",
242
313
  " --clear-gate Clear the confirmed gate (its own consent), then exit.",
243
314
  " --qualify-gate Qualify a confirmed local or mixed gate: queue the",
244
315
  " qualification job and drain it with a short-lived",
@@ -247,10 +318,12 @@ export function getInstallBridgeConductorUsage() {
247
318
  " without the offer prompt.",
248
319
  "",
249
320
  ` --review-policy <source> One of: ${CONDUCTOR_REVIEW_POLICY_SOURCES.join(", ")}`,
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",
321
+ " Omitted, setup keeps a project default that is already",
322
+ " stored. With none stored it stores verdict_protocol when",
323
+ " .github/workflows/claude-review.yml exists on your default",
324
+ " branch, and repository_policy when it does not or cannot",
325
+ " be read. It scaffolds no Claude review workflow unless you",
326
+ " pass --review-policy verdict_protocol. Supplying any value",
254
327
  " persists it as the project default, stamped into a new",
255
328
  " run that carries no review policy of its own.",
256
329
  " --epic-key <KEY> Epic key for the setup-epic verification phase",
@@ -260,6 +333,9 @@ export function getInstallBridgeConductorUsage() {
260
333
  " --secret-name <NAME> claude-review workflow: OAuth token secret NAME",
261
334
  " --branches a,b claude-review workflow: PR branch triggers",
262
335
  " --skip-workflow Never offer the claude-review workflow",
336
+ " --epic-server Ask again which epic server Epic Implementer runs use",
337
+ " (none, local, or sfcc_shared_active), behind its own",
338
+ " consent. Without it, an unchanged choice asks nothing.",
263
339
  " --replace-done-gate Replace an EXISTING done gate with the CI-only gate",
264
340
  " built from --required-check. Without it, a repeat",
265
341
  " install keeps the stored gate and only adds missing",
@@ -273,8 +349,8 @@ export function getInstallBridgeConductorUsage() {
273
349
  " no POST, no file write, no host MCP config write,",
274
350
  " no Git hook write, no install-state or capability",
275
351
  " 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",
352
+ " start-consent prompt. Still displays the resolved",
353
+ " base URL first — its readiness read carries the",
278
354
  " repo API key.",
279
355
  " -h, --help Show this help",
280
356
  "",
@@ -292,10 +368,10 @@ export function getInstallBridgeConductorUsage() {
292
368
  " --executor-id, otherwise local).",
293
369
  " --policy-file <path> Run policy the profile references.",
294
370
  "",
295
- "The resolved BAPI_BASE_URL is displayed and confirmed BEFORE any network call",
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.",
371
+ "The resolved BAPI_BASE_URL is displayed BEFORE any network call",
372
+ "(BAPI_BASE_URL silently defaults to production when unset). In a terminal,",
373
+ "setup then applies the previewed bootstrap policy. Without a TTY it shows",
374
+ "the preview and writes no policy.",
299
375
  "",
300
376
  "Tool visibility (its own consent): adds the `epic_implementer` token to the",
301
377
  "BRIDGE_MCP_PROFILE of the Bridge entry in host MCP configurations that",
@@ -332,14 +408,18 @@ export function parseInstallBridgeConductorArgs(argv) {
332
408
  }
333
409
  let repo;
334
410
  let dryRun = false;
411
+ let json = false;
412
+ let compact = false;
335
413
  let skipWorkflow = false;
336
414
  let replaceDoneGate = false;
415
+ let epicServerChange = false;
337
416
  let reviewPolicy = DEFAULT_CONDUCTOR_REVIEW_POLICY;
338
417
  let reviewPolicyExplicit = false;
339
418
  let epicKey;
340
419
  let planFile;
341
420
  let executorId;
342
421
  const epicRunIds = [];
422
+ let assessmentEpicRunId;
343
423
  let repoWide = false;
344
424
  let allowedBot;
345
425
  let secretName;
@@ -354,6 +434,9 @@ export function parseInstallBridgeConductorArgs(argv) {
354
434
  let removeMergeToken = false;
355
435
  let testCommand;
356
436
  let testCommandSeen = false;
437
+ let answers;
438
+ let verbose = false;
439
+ let reviewCiSettings = false;
357
440
  const takeValue = (arg, inline, next) => {
358
441
  if (inline !== undefined) {
359
442
  if (inline.trim().length === 0)
@@ -371,6 +454,29 @@ export function parseInstallBridgeConductorArgs(argv) {
371
454
  const flag = eq === -1 ? raw : raw.slice(0, eq);
372
455
  const inline = eq === -1 ? undefined : raw.slice(eq + 1);
373
456
  switch (flag) {
457
+ case "--json":
458
+ if (inline !== undefined)
459
+ return { status: "error", message: "--json takes no value" };
460
+ json = true;
461
+ break;
462
+ case "--compact":
463
+ if (inline !== undefined)
464
+ return { status: "error", message: "--compact takes no value" };
465
+ compact = true;
466
+ break;
467
+ case "--answers": {
468
+ // `-` is the stdin source, so it is taken as a value here (unlike other flags).
469
+ const next = argv[i + 1];
470
+ const value = inline !== undefined ? inline.trim() : next === "-" ? "-" : next !== undefined && !next.startsWith("-") ? next.trim() : "";
471
+ if (value.length === 0)
472
+ return { status: "error", message: "--answers requires a file path, or - for stdin" };
473
+ if (answers !== undefined)
474
+ return { status: "error", message: "--answers may be given once" };
475
+ answers = value;
476
+ if (inline === undefined)
477
+ i++;
478
+ break;
479
+ }
374
480
  case "--dry-run":
375
481
  if (inline !== undefined)
376
482
  return { status: "error", message: "--dry-run takes no value" };
@@ -381,11 +487,27 @@ export function parseInstallBridgeConductorArgs(argv) {
381
487
  return { status: "error", message: "--skip-workflow takes no value" };
382
488
  skipWorkflow = true;
383
489
  break;
490
+ case "--verbose":
491
+ if (inline !== undefined)
492
+ return { status: "error", message: "--verbose takes no value" };
493
+ verbose = true;
494
+ break;
495
+ case "--review-ci-settings":
496
+ if (inline !== undefined) {
497
+ return { status: "error", message: "--review-ci-settings takes no value" };
498
+ }
499
+ reviewCiSettings = true;
500
+ break;
384
501
  case "--replace-done-gate":
385
502
  if (inline !== undefined)
386
503
  return { status: "error", message: "--replace-done-gate takes no value" };
387
504
  replaceDoneGate = true;
388
505
  break;
506
+ case "--epic-server":
507
+ if (inline !== undefined)
508
+ return { status: "error", message: "--epic-server takes no value" };
509
+ epicServerChange = true;
510
+ break;
389
511
  case "--repo-wide":
390
512
  if (inline !== undefined)
391
513
  return { status: "error", message: "--repo-wide takes no value" };
@@ -435,6 +557,7 @@ export function parseInstallBridgeConductorArgs(argv) {
435
557
  return { status: "error", message: `${flag} takes no value` };
436
558
  if (flag === "--gate-none")
437
559
  gate.gateNone = true;
560
+ // No effect today; this name is reserved for a later step where an agent relays the user's consent.
438
561
  else if (flag === "--confirm-gate")
439
562
  gate.confirmGate = true;
440
563
  else if (flag === "--clear-gate")
@@ -450,6 +573,7 @@ export function parseInstallBridgeConductorArgs(argv) {
450
573
  case "--plan-file":
451
574
  case "--executor-id":
452
575
  case "--epic-run-id":
576
+ case "--assessment-epic-run-id":
453
577
  case "--allowed-bot":
454
578
  case "--secret-name":
455
579
  case "--branches":
@@ -509,6 +633,12 @@ export function parseInstallBridgeConductorArgs(argv) {
509
633
  executorId = value;
510
634
  else if (flag === "--epic-run-id")
511
635
  epicRunIds.push(value);
636
+ else if (flag === "--assessment-epic-run-id") {
637
+ if (assessmentEpicRunId !== undefined || !isValidExecutorEpicRunId(value)) {
638
+ return { status: "error", message: "--assessment-epic-run-id requires one valid run ID and may be given once." };
639
+ }
640
+ assessmentEpicRunId = value;
641
+ }
512
642
  else if (flag === "--allowed-bot")
513
643
  allowedBot = value;
514
644
  else if (flag === "--secret-name")
@@ -625,6 +755,9 @@ export function parseInstallBridgeConductorArgs(argv) {
625
755
  message: "--test-command cannot be combined with --clear-gate: clearing the gate is a standalone action.",
626
756
  };
627
757
  }
758
+ // BAPI-1653 — checked on the completed argument set, so flag order never matters.
759
+ if (compact && !json)
760
+ return { status: "error", message: "--compact requires --json" };
628
761
  // BAPI-1461 — token removal is its own action: only --repo and --dry-run may
629
762
  // accompany it, so it can never be mistaken for, or followed by, setup writes.
630
763
  if (removeMergeToken) {
@@ -648,6 +781,8 @@ export function parseInstallBridgeConductorArgs(argv) {
648
781
  allowedBot !== undefined ||
649
782
  secretName !== undefined ||
650
783
  testCommand !== undefined ||
784
+ reviewCiSettings ||
785
+ answers !== undefined ||
651
786
  branches !== undefined;
652
787
  if (conflicting) {
653
788
  return {
@@ -675,6 +810,8 @@ export function parseInstallBridgeConductorArgs(argv) {
675
810
  options: {
676
811
  repo,
677
812
  dryRun,
813
+ json,
814
+ ...(compact ? { compact: true } : {}),
678
815
  requiredChecks: normalizedChecks,
679
816
  gate,
680
817
  reviewPolicy,
@@ -686,8 +823,10 @@ export function parseInstallBridgeConductorArgs(argv) {
686
823
  branches,
687
824
  skipWorkflow,
688
825
  ...(replaceDoneGate ? { replaceDoneGate: true } : {}),
826
+ ...(epicServerChange ? { epicServerChange: true } : {}),
689
827
  executorId,
690
828
  ...(epicRunIds.length > 0 ? { epicRunIds } : {}),
829
+ ...(assessmentEpicRunId !== undefined ? { assessmentEpicRunId } : {}),
691
830
  ...(repoWide ? { repoWide: true } : {}),
692
831
  ...(launchProfile ? { launchProfile } : {}),
693
832
  ...(baseUrl ? { baseUrl } : {}),
@@ -698,6 +837,9 @@ export function parseInstallBridgeConductorArgs(argv) {
698
837
  ...(epicBranchCiDecision ? { epicBranchCiDecision } : {}),
699
838
  ...(removeMergeToken ? { removeMergeToken: true } : {}),
700
839
  ...(testCommand !== undefined ? { testCommand } : {}),
840
+ ...(verbose ? { verbose: true } : {}),
841
+ ...(reviewCiSettings ? { reviewCiSettings: true } : {}),
842
+ ...(answers !== undefined ? { answers } : {}),
701
843
  },
702
844
  };
703
845
  }
@@ -716,7 +858,7 @@ export function createDefaultLaunchProfileDeps(env) {
716
858
  readFile: store.readFile,
717
859
  stat: (p) => statAsync(p),
718
860
  }),
719
- bindCredential: (repoName, baseUrl) => bindEpicLaunchCredential(repoName, baseUrl, store),
861
+ bindCredential: (repoName, baseUrl, observedKey) => bindEpicLaunchCredential(repoName, baseUrl, store, { observedKey: observedKey ?? null }),
720
862
  readPolicyFile: (absolutePath) => readFileAsync(absolutePath, "utf-8"),
721
863
  };
722
864
  }
@@ -873,11 +1015,8 @@ function renderBootstrapOutcome(deps, response) {
873
1015
  }
874
1016
  }
875
1017
  async function confirm(deps, promptText) {
876
- // A missing prompt seam means no TTY. Silence is NOT consent.
877
- if (!deps.promptLine)
878
- return false;
879
- const answer = await deps.promptLine(promptText);
880
- return CONSENT_YES.has((answer ?? "").trim().toLowerCase());
1018
+ const decision = await askSetupQuestion(setupConsentQuestion(promptText), { read: deps.promptLine, write: deps.log });
1019
+ return decision.status === "accept";
881
1020
  }
882
1021
  /**
883
1022
  * BAPI-1452 — the merge-credential next step. Value-free configuration guidance
@@ -1160,16 +1299,16 @@ export function formatConductorRestartAdvisory(mergedProfile) {
1160
1299
  }
1161
1300
  /** Remediation printed when no supported host config carries a Bridge entry. */
1162
1301
  export const CONDUCTOR_PROFILE_EMPTY_MERGE_REMEDIATION = `run \`${PRINTED_INSTALL_COMMAND}\` to create and register the host MCP entry, ` +
1163
- "then re-run `install conductor`.";
1302
+ "then re-run `install epic-implementer`.";
1164
1303
  /** Remediation printed whenever the managed git hooks were not installed. */
1165
- export const CONDUCTOR_HOOKS_MANUAL_REMEDIATION = "re-run `install conductor` and accept the local-observability consent, or run " +
1304
+ export const CONDUCTOR_HOOKS_MANUAL_REMEDIATION = "re-run `install epic-implementer` and accept the local-observability consent, or run " +
1166
1305
  "`epic-implementer install-git-hooks` directly.";
1167
1306
  /**
1168
1307
  * Remediation for a non-fatal hook refusal (BAPI-1290): the hooks need a
1169
1308
  * persistent install to embed, and the repair is to create one and reinstall.
1170
1309
  */
1171
1310
  export const CONDUCTOR_HOOKS_DURABLE_REMEDIATION = `install the CLI persistently (\`npm i -g ${MCP_PACKAGE_NAME}\`), then run ` +
1172
- "`epic-implementer install-git-hooks` (or re-run `install conductor` and accept the " +
1311
+ "`epic-implementer install-git-hooks` (or re-run `install epic-implementer` and accept the " +
1173
1312
  "local-observability consent).";
1174
1313
  /**
1175
1314
  * Phase: tool visibility.
@@ -1186,7 +1325,7 @@ async function runConductorToolVisibilityPhase(deps, local) {
1186
1325
  deps.log(" declined — no host MCP configuration and no install state were written.");
1187
1326
  return {
1188
1327
  manualActions: [
1189
- "tool visibility: re-run `install conductor` and accept the profile consent to " +
1328
+ "tool visibility: re-run `install epic-implementer` and accept the profile consent to " +
1190
1329
  "make the Epic Implementer MCP tools visible.",
1191
1330
  ],
1192
1331
  };
@@ -1282,7 +1421,7 @@ async function runConductorLocalObservabilityPhase(deps, local) {
1282
1421
  "(engine admission is unaffected).");
1283
1422
  // Only BAPI-772's broken-package case stays fatal: the executing artifact
1284
1423
  // ships no hook binary at all. Every other refusal — an npx-cache runtime
1285
- // (the documented `npx … install conductor` path), an unqualified or
1424
+ // (the documented `npx … install epic-implementer` path), an unqualified or
1286
1425
  // unloadable runtime, an unsafe existing hook — is a manual action, and
1287
1426
  // the installer continues to setup-epic verification and executor
1288
1427
  // provisioning. Optional hooks must never stop the phases that do gate
@@ -1302,7 +1441,7 @@ async function runConductorLocalObservabilityPhase(deps, local) {
1302
1441
  else if (result !== null && result.ok) {
1303
1442
  if (!result.is_worktree) {
1304
1443
  deps.log(" not a git worktree, so no managed hook was installed (degraded optional capability).");
1305
- manualActions.push("local observability: run `install conductor` from a git worktree to install the " +
1444
+ manualActions.push("local observability: run `install epic-implementer` from a git worktree to install the " +
1306
1445
  "managed git hooks.");
1307
1446
  }
1308
1447
  else {
@@ -1495,6 +1634,57 @@ function assessNotification(policy, attended, targetBaseUrl, readiness) {
1495
1634
  "delivers a verification to it at approval, and a failure there holds activation.",
1496
1635
  };
1497
1636
  }
1637
+ /**
1638
+ * BAPI-1635 — the selected launch profile's escalation evidence, for setup's
1639
+ * effective escalation item.
1640
+ *
1641
+ * The profile is chosen the way `drive-epic` chooses it: `--launch-profile` first,
1642
+ * then `BAPI_EPIC_LAUNCH_PROFILE`. It is read through the one validated reader and
1643
+ * its policy is judged by {@link assessNotification}; no second policy parser exists.
1644
+ * Account email is deliberately not counted here (readiness is passed as null): a
1645
+ * live-email route is the server row's own fact and is kept independently.
1646
+ *
1647
+ * Only bounded state leaves this function: the profile name and the policy file's
1648
+ * path. A missing profile (not yet saved) and an attended policy are "no evidence";
1649
+ * a profile or policy that cannot be read is `unreadable`, never a confirmed absence.
1650
+ * Policy contents, a webhook value, an email address, and raw reader errors are
1651
+ * never returned.
1652
+ */
1653
+ async function collectNotificationEvidence(deps, options, baseUrl) {
1654
+ const fromEnv = deps.env.BAPI_EPIC_LAUNCH_PROFILE?.trim();
1655
+ const name = options.launchProfile ?? (fromEnv !== undefined && fromEnv !== "" ? fromEnv : undefined);
1656
+ if (name === undefined)
1657
+ return undefined;
1658
+ const lp = deps.launchProfiles ?? createDefaultLaunchProfileDeps(deps.env);
1659
+ let read;
1660
+ try {
1661
+ read = await lp.readProfile(name);
1662
+ }
1663
+ catch {
1664
+ return { state: "unreadable", profile: name };
1665
+ }
1666
+ if (!read.ok)
1667
+ return read.kind === "profile-missing" ? undefined : { state: "unreadable", profile: name };
1668
+ const policyPath = read.profile.policyRef?.path;
1669
+ if (policyPath === undefined)
1670
+ return { state: "absent", profile: name };
1671
+ let policy;
1672
+ try {
1673
+ const parsed = JSON.parse(await lp.readPolicyFile(policyPath));
1674
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
1675
+ return { state: "unreadable", profile: name };
1676
+ policy = parsed;
1677
+ }
1678
+ catch {
1679
+ return { state: "unreadable", profile: name };
1680
+ }
1681
+ const assessed = assessNotification(policy, policy.posture === "attended", baseUrl, null);
1682
+ if (assessed.status === "not-applicable")
1683
+ return undefined;
1684
+ return assessed.status === "ok"
1685
+ ? { state: "declared", profile: name, policyFile: policyPath }
1686
+ : { state: "absent", profile: name, policyFile: policyPath };
1687
+ }
1498
1688
  /** BAPI-1461 — whether a stored profile already records exactly this launch. */
1499
1689
  function launchProfileMatches(prior, next) {
1500
1690
  return (prior.baseUrl === next.baseUrl &&
@@ -1623,7 +1813,7 @@ async function runLaunchProfilePhase(deps, options, inputs) {
1623
1813
  gaps.push("the credential binding was not approved, so a launch could not use the stored key.");
1624
1814
  }
1625
1815
  else {
1626
- const result = await lp.bindCredential(repoName, inputs.baseUrl);
1816
+ const result = await lp.bindCredential(repoName, inputs.baseUrl, inputs.access.apiKey);
1627
1817
  if (!result.ok)
1628
1818
  gaps.push(`the credential binding could not be written: ${result.error}`);
1629
1819
  else
@@ -1636,7 +1826,7 @@ async function runLaunchProfilePhase(deps, options, inputs) {
1636
1826
  deps.log(` incomplete — profile '${name}' was NOT written:`);
1637
1827
  for (const gap of gaps)
1638
1828
  deps.log(` → ${gap}`);
1639
- deps.log(` re-run: npx -y ${MCP_PACKAGE_NAME} install conductor --launch-profile ${name} ` +
1829
+ deps.log(` re-run: npx -y ${MCP_PACKAGE_NAME} install epic-implementer --launch-profile ${name} ` +
1640
1830
  `--base-url ${inputs.baseUrl} --required-check <name> ...`);
1641
1831
  return { complete: false };
1642
1832
  }
@@ -1731,11 +1921,6 @@ async function resolveAndConfirmBaseUrl(options, deps, promptText) {
1731
1921
  deps.log(` explicit target for epic launch profile '${options.launchProfile}'` +
1732
1922
  (baseUrl === DEFAULT_BAPI_BASE_URL ? " — this is the PRODUCTION Bridge API, selected deliberately." : "."));
1733
1923
  }
1734
- const baseUrlOk = await confirm(deps, promptText);
1735
- if (!baseUrlOk) {
1736
- deps.log("Aborted — no network call (readiness GET or bootstrap POST) was attempted.");
1737
- return { ok: false, code: 0 };
1738
- }
1739
1924
  return { ok: true, baseUrl };
1740
1925
  }
1741
1926
  function gateIoFor(deps) {
@@ -1768,8 +1953,34 @@ async function runStandaloneGateAction(options, deps, gateIo, access, accessErro
1768
1953
  ? runClearConductorGate(gateIo, access, { dryRun: options.dryRun })
1769
1954
  : runQualifyConductorGate(gateIo, access, deps.gate, { dryRun: options.dryRun, baseUrl });
1770
1955
  }
1771
- function renderReviewPolicy(deps, options) {
1956
+ /**
1957
+ * Explain the review policy. With a decision (the converging setup) it says whether
1958
+ * the source is explicit, preserved, or inferred from the remote default branch;
1959
+ * without one (a caller with no setup seams) it keeps the original install text.
1960
+ */
1961
+ function renderReviewPolicy(deps, options, decision) {
1772
1962
  deps.log("");
1963
+ if (decision !== undefined) {
1964
+ if (decision.kind === "preserve") {
1965
+ deps.log(decision.basis === "stored"
1966
+ ? `Review policy: kept as the project default already stored (${terminalSafeText(decision.stored ?? "unrecognized")}). ` +
1967
+ "Pass --review-policy to change it."
1968
+ : "Review policy: Bridge could not read the stored review settings, so it leaves them as they are this time.");
1969
+ return;
1970
+ }
1971
+ deps.log(`Review policy: ${decision.source}`);
1972
+ deps.log(decision.basis === "explicit"
1973
+ ? " Explicitly selected with --review-policy, so it is ALSO persisted as the supervisor project " +
1974
+ "default and stamped into a new run that sets no review policy of its own. An explicit per-run " +
1975
+ "policy always wins, and changing this later never alters an already-approved run."
1976
+ : decision.basis === "workflow_present"
1977
+ ? ` Inferred: ${CLAUDE_REVIEW_WORKFLOW_RELPATH} exists on your default branch. It is stored as the ` +
1978
+ "project default, and a stored default is never overwritten by a later run. Pass --review-policy to choose another."
1979
+ : ` Inferred: no ${CLAUDE_REVIEW_WORKFLOW_RELPATH} was found on your default branch, so no Claude review ` +
1980
+ "workflow is needed. It is stored as the project default, and a stored default is never overwritten by a " +
1981
+ "later run. Pass --review-policy verdict_protocol to opt in to AI review.");
1982
+ return;
1983
+ }
1773
1984
  deps.log(`Review policy: ${options.reviewPolicy}`);
1774
1985
  deps.log(options.reviewPolicyExplicit
1775
1986
  ? " Explicitly selected, so it is ALSO persisted as the supervisor project " +
@@ -1781,6 +1992,10 @@ function renderReviewPolicy(deps, options) {
1781
1992
  "repository_policy at first approval when nothing else sets one — pass " +
1782
1993
  "--review-policy verdict_protocol to opt in to AI review.");
1783
1994
  }
1995
+ /** A stored value printed on one line: control characters and over-long text never reach the terminal. */
1996
+ function terminalSafeText(value) {
1997
+ return value.replace(/[\u0000-\u001F\u007F]/g, "?").slice(0, 80);
1998
+ }
1784
1999
  /**
1785
2000
  * The executor preflight (BAPI-779): AFTER the URL consent, BEFORE any
1786
2001
  * mutation, and before the dry-run return, so `--dry-run` reports the same
@@ -1831,6 +2046,123 @@ async function runExecutorPreflightPhase(options, deps, baseUrl, access) {
1831
2046
  return { kind: "ok", plans: null };
1832
2047
  }
1833
2048
  export async function runInstallBridgeConductorCli(argv, deps) {
2049
+ const parsed = parseInstallBridgeConductorArgs(argv);
2050
+ const machine = argv.includes('--json');
2051
+ const human = !machine && deps.isTTY === true;
2052
+ let verdict;
2053
+ // BAPI-1604: the compact summary's single next step, held so it prints after the verdict.
2054
+ let nextStep;
2055
+ let outcome = 'complete-with-manual-steps';
2056
+ let assessment;
2057
+ // BAPI-1603: a named stop outcome, kept apart from the numeric exit code so the
2058
+ // result can say WHICH refusal happened without changing the return convention.
2059
+ let namedOutcome;
2060
+ let parts = {};
2061
+ const inner = { ...deps,
2062
+ get promptLine() { return deps.promptLine; },
2063
+ assessmentSink: (value) => { assessment = value; deps.assessmentSink?.(value); },
2064
+ installDocumentSink: (value) => { parts = { ...parts, ...value }; deps.installDocumentSink?.(value); },
2065
+ log: (line) => {
2066
+ if (/^complete(?:-with-manual-steps)?(?: \(dry run\))?$/.test(line)) {
2067
+ outcome = line === 'complete' ? 'complete' : 'complete-with-manual-steps';
2068
+ if (!machine && !human)
2069
+ deps.log(line);
2070
+ return;
2071
+ }
2072
+ if (/^(Ready(?: for your first epic)?|Not ready|Readiness not confirmed)(?:$|:| —)/.test(line)) {
2073
+ verdict = line;
2074
+ if (!machine && !human)
2075
+ deps.log(line);
2076
+ return;
2077
+ }
2078
+ if (human && /^Next step: /.test(line)) {
2079
+ nextStep = line;
2080
+ return;
2081
+ }
2082
+ if (machine)
2083
+ deps.errorLog(line);
2084
+ else
2085
+ deps.log(line);
2086
+ },
2087
+ errorLog: (line) => {
2088
+ // BAPI-1650: a fixed two-token set. The approval stop outranks the learned stop and,
2089
+ // once captured, is never replaced; no other line becomes an outcome.
2090
+ if (line === CREDENTIAL_ENDPOINT_UNAPPROVED_OUTCOME)
2091
+ namedOutcome = line;
2092
+ else if (line === REPOSITORY_NOT_LEARNED_OUTCOME && namedOutcome !== CREDENTIAL_ENDPOINT_UNAPPROVED_OUTCOME)
2093
+ namedOutcome = line;
2094
+ deps.errorLog(line);
2095
+ },
2096
+ };
2097
+ let exitCode;
2098
+ try {
2099
+ exitCode = await runInstallBridgeConductorCore(argv, inner);
2100
+ }
2101
+ catch {
2102
+ exitCode = 1;
2103
+ outcome = 'complete-with-manual-steps';
2104
+ deps.errorLog('Setup stopped unexpectedly. Completed independent work is retained; rerun setup to inspect it.');
2105
+ }
2106
+ if (machine) {
2107
+ // BAPI-1638: schema version 2 keeps every version 1 field, with the same meaning.
2108
+ let text;
2109
+ try {
2110
+ const document = {
2111
+ ...buildInstallAssessment({
2112
+ legacy: {
2113
+ outcome,
2114
+ exitCode,
2115
+ dryRun: parsed.status === 'ok' && parsed.options.dryRun,
2116
+ ...(namedOutcome ? { namedOutcome } : {}),
2117
+ ...(assessment ? { assessment, advisoryVerdict: verdict ?? 'Readiness not confirmed' } : {}),
2118
+ },
2119
+ items: parts.items ?? [],
2120
+ decisions: parts.decisions ?? null,
2121
+ ...(parts.choices !== undefined ? { choices: parts.choices } : {}),
2122
+ }),
2123
+ ...(parts.proposal !== undefined ? { proposal: parts.proposal } : {}),
2124
+ ...(parts.digest !== undefined ? { proposal_digest: parts.digest } : {}),
2125
+ ...(parts.refusal !== undefined ? { refusal: parts.refusal } : {}),
2126
+ ...(parts.apply !== undefined ? { apply: parts.apply } : {}),
2127
+ };
2128
+ // BAPI-1653: the compact view is chosen here, at the JSON-output boundary, from the
2129
+ // invocation mode. A refused apply still gets the apply view.
2130
+ if (parsed.status === 'ok' && parsed.options.compact === true) {
2131
+ const options = parsed.options;
2132
+ const view = options.answers === undefined
2133
+ ? buildCompactAssessment(document)
2134
+ : options.dryRun
2135
+ ? buildCompactProposal(document)
2136
+ : buildCompactApply(document);
2137
+ text = JSON.stringify(view);
2138
+ }
2139
+ else {
2140
+ text = JSON.stringify(document);
2141
+ }
2142
+ }
2143
+ catch {
2144
+ exitCode = 1;
2145
+ text = JSON.stringify({ schemaVersion: INSTALL_ASSESSMENT_SCHEMA_VERSION, outcome: 'complete-with-manual-steps', exitCode,
2146
+ dryRun: parsed.status === 'ok' && parsed.options.dryRun, items: [], choices: [],
2147
+ repository_facts: { ci_workflows: null, package_manager: null, mcp_configs: null } });
2148
+ deps.errorLog('The setup result could not be rendered as JSON; rerun setup.');
2149
+ }
2150
+ await writeJsonDocument(text, { log: deps.log, flush: deps.isTTY === undefined ? async () => true : flushProcessStdout });
2151
+ }
2152
+ else if (human && parsed.status === 'ok') {
2153
+ const closingVerdict = verdict ?? 'Readiness not confirmed — setup did not establish all required evidence; advisory only.';
2154
+ if (deps.holdClosingResult !== undefined) {
2155
+ deps.holdClosingResult({ verdict: closingVerdict, ...(nextStep !== undefined ? { nextStep } : {}) });
2156
+ }
2157
+ else {
2158
+ deps.log(closingVerdict);
2159
+ if (nextStep !== undefined)
2160
+ deps.log(nextStep);
2161
+ }
2162
+ }
2163
+ return exitCode;
2164
+ }
2165
+ async function runInstallBridgeConductorCore(argv, deps) {
1834
2166
  const parsed = parseInstallBridgeConductorArgs(argv);
1835
2167
  if (parsed.status === "help") {
1836
2168
  deps.log(parsed.usage);
@@ -1863,9 +2195,14 @@ export async function runInstallBridgeConductorCli(argv, deps) {
1863
2195
  if (!confirmed.ok)
1864
2196
  return confirmed.code;
1865
2197
  const baseUrl = confirmed.baseUrl;
2198
+ if (!options.dryRun && !(await assessEpicInstallerPrerequisites(deps, Boolean(options.executorId))).available)
2199
+ return 1;
1866
2200
  const accessResult = await deps.resolveAccess(options.repo, baseUrl);
1867
2201
  const access = accessResult.ok ? accessResult.access : null;
1868
2202
  const accessError = accessResult.ok ? undefined : accessResult.error;
2203
+ const earlyPreflight = await runExecutorPreflightPhase(options, deps, baseUrl, access);
2204
+ if (earlyPreflight.kind === "refused")
2205
+ return 1;
1869
2206
  const gateIo = gateIoFor(deps);
1870
2207
  const standalone = await runStandaloneGateAction(options, deps, gateIo, access, accessError, baseUrl);
1871
2208
  if (standalone !== null)
@@ -1876,6 +2213,8 @@ export async function runInstallBridgeConductorCli(argv, deps) {
1876
2213
  access,
1877
2214
  accessError,
1878
2215
  reviewPolicySource: options.reviewPolicy,
2216
+ assessmentVersion: 1,
2217
+ epicRunId: options.assessmentEpicRunId,
1879
2218
  });
1880
2219
  deps.log(formatConductorInstallDoctorReport(firstReport));
1881
2220
  if (conductorInstallDoctorHasFatal(firstReport)) {
@@ -1893,10 +2232,7 @@ export async function runInstallBridgeConductorCli(argv, deps) {
1893
2232
  // and before the dry-run return, so `--dry-run` reports the same refusal.
1894
2233
  const executor = deps.executorProvisioning;
1895
2234
  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;
2235
+ const executorPlans = earlyPreflight.plans;
1900
2236
  // ---- BAPI-1391: the repository gate, decided BEFORE any write ----------
1901
2237
  // Capability probe first (a read, after the base-URL consent), then the stored
1902
2238
  // gate, explicit gate flags, or a discovery proposal the owner confirms. Under
@@ -1906,7 +2242,7 @@ export async function runInstallBridgeConductorCli(argv, deps) {
1906
2242
  return 1;
1907
2243
  }
1908
2244
  const gatePhase = await resolveConductorGate(gateIo, access, options.gate, deps.gate, {
1909
- dryRun: options.dryRun,
2245
+ dryRun: options.dryRun, planningOnly: true,
1910
2246
  });
1911
2247
  if (gatePhase.kind === "exit")
1912
2248
  return gatePhase.code;
@@ -1919,6 +2255,8 @@ export async function runInstallBridgeConductorCli(argv, deps) {
1919
2255
  if (options.dryRun) {
1920
2256
  deps.log("");
1921
2257
  deps.log("Dry run — no writes will be performed.");
2258
+ if (gatePlan !== null)
2259
+ await fixGateAndDefaults(deps, options, access, gatePlan, legacyReviewDefault(options));
1922
2260
  if (gatePlan === null) {
1923
2261
  deps.log(" Repository gate: none confirmed — a real run asks you to confirm one before any write.");
1924
2262
  }
@@ -1944,7 +2282,7 @@ export async function runInstallBridgeConductorCli(argv, deps) {
1944
2282
  deps.log(" - done_gate_config.required_checks " +
1945
2283
  `(${bootstrapChecks.length} check(s))`);
1946
2284
  if (options.reviewPolicyExplicit)
1947
- deps.log(" - review_policy");
2285
+ deps.log(" - defaults.review_policy");
1948
2286
  if (options.replaceDoneGate)
1949
2287
  deps.log(" - replace_done_gate");
1950
2288
  deps.log(" - auto_merge_enabled");
@@ -2006,104 +2344,12 @@ export async function runInstallBridgeConductorCli(argv, deps) {
2006
2344
  // replacing bootstrap when the server cannot preview.
2007
2345
  deps.log("");
2008
2346
  deps.log("Phase 2/8 — bootstrapping supervisor project defaults…");
2009
- const bootstrapRequest = {
2010
- required_checks: bootstrapChecks,
2011
- // BAPI-694 — the narrow ReviewPolicy object, sent ONLY on an explicit
2012
- // selection. `review_source` is deliberately NOT sent: on an existing
2013
- // repository an omitted field keeps its stored value, and a new repository
2014
- // receives the server's `verdict_protocol` default either way.
2015
- ...(options.reviewPolicyExplicit
2016
- ? { review_policy: { source: options.reviewPolicy } }
2017
- : {}),
2018
- merge_approval_required: "true",
2019
- ...(options.replaceDoneGate ? { replace_done_gate: true } : {}),
2020
- };
2021
- // BAPI-1391 — the gate is stored FIRST, under its own combined consent, in
2022
- // two cases:
2023
- // * a gate with no provider checks (local-only or `none`): the server
2024
- // accepts an empty CI list only for a stored gate of that kind;
2025
- // * any change to an already STORED gate: the bootstrap apply would
2026
- // otherwise run BAPI-1390's profile sync first, which merges the additive
2027
- // CI list into the stored profile under a new revision — so a later PUT
2028
- // would be refused as stale while the gate had silently been widened.
2029
- // Stored first, the CI checks already equal the gate, the bootstrap adds
2030
- // nothing, and the sync has nothing to change.
2031
- // A legacy or unconfirmed repository keeps the original order (preview,
2032
- // consent, apply) and is stored after the apply; the sync never touches it.
2033
- const gateFirst = gatePlan.write !== null &&
2034
- (bootstrapChecks.length === 0 || gatePlan.current.source === "stored");
2035
- let storedGate = gatePlan.write === null ? gatePlan.current : null;
2036
- if (gateFirst) {
2037
- deps.log("");
2038
- const gateOk = await confirm(deps, "Store this repository gate and write the safe project-default supervisor posture now? [y/N]: ");
2039
- if (!gateOk) {
2040
- deps.log("Aborted — no server write was attempted.");
2041
- return 0;
2042
- }
2043
- storedGate = await storeConductorGate(gateIo, access, gatePlan);
2044
- if (storedGate === null)
2045
- return 1;
2046
- }
2047
- let preview;
2048
- try {
2049
- preview = await previewConductorSupervisorBootstrap(access, bootstrapRequest, deps.postJson);
2050
- }
2051
- catch (err) {
2052
- reportBootstrapFailure(deps, "preview", classifySupervisorBootstrapFailure(err));
2053
- return 1;
2054
- }
2055
- renderBootstrapPreview(deps, preview);
2056
- // ---- Consent #2: the bootstrap write itself ----------------------------
2057
- // Deliberately separate from the base-URL consent above (which was given
2058
- // before any network call). Confirming WHERE to write is not consent TO write.
2059
- // A gate stored first above was stored under its own combined consent.
2060
- if (!gateFirst) {
2061
- deps.log("");
2062
- const bootstrapOk = await confirm(deps, "Write the safe project-default supervisor posture now? [y/N]: ");
2063
- if (!bootstrapOk) {
2064
- deps.log("Aborted — no server write was attempted.");
2065
- return 0;
2066
- }
2067
- }
2068
- // ---- Consent #3: the EXACT gate change, only when the preview needs it ---
2069
- // Never inferred from consent #2: agreeing to install is not agreeing to
2070
- // remove a configured requirement. A missing prompt seam is a refusal.
2071
- let applyRequest = bootstrapRequest;
2072
- if (preview.approval_required) {
2073
- deps.log("");
2074
- const gateChangeOk = await confirm(deps, "Approve EXACTLY the gate changes listed above? [y/N]: ");
2075
- if (!gateChangeOk || !preview.approval_token) {
2076
- deps.errorLog("Gate change not approved — no server write was attempted, and every configured " +
2077
- "requirement is unchanged.");
2078
- return 1;
2079
- }
2080
- applyRequest = {
2081
- ...bootstrapRequest,
2082
- approval: { approve: true, approval_token: preview.approval_token },
2083
- };
2084
- }
2085
- let bootstrapResponse;
2086
- try {
2087
- bootstrapResponse = await bootstrapConductorSupervisorDefaults(access, applyRequest, deps.postJson);
2088
- }
2089
- catch (err) {
2090
- reportBootstrapFailure(deps, "apply", classifySupervisorBootstrapFailure(err));
2091
- return 1;
2092
- }
2093
- if (bootstrapResponse.setup_outcome === null || bootstrapResponse.config_outcome === null) {
2094
- reportBootstrapFailure(deps, "apply", "unsupported-protocol");
2347
+ const combined = await fixGateAndDefaults(deps, options, access, gatePlan, legacyReviewDefault(options));
2348
+ if (combined.status === "deferred" || combined.status === "unknown")
2095
2349
  return 1;
2096
- }
2097
- renderBootstrapOutcome(deps, bootstrapResponse);
2098
- // ---- BAPI-1391: store the confirmed gate, then offer its qualification --
2099
- // Stored after the apply so the bootstrap's additive CI write cannot widen
2100
- // the gate's exact provider checks: the gate PUT rewrites that projection to
2101
- // exactly the confirmed checks, under the server's revision compare-and-swap.
2102
- if (storedGate === null) {
2103
- storedGate = await storeConductorGate(gateIo, access, gatePlan);
2104
- if (storedGate === null)
2105
- return 1;
2106
- }
2350
+ const storedGate = combined.current
2351
+ ? { revision: combined.current.state.revision, qualification_state: combined.current.policy.qualification }
2352
+ : gatePlan.current;
2107
2353
  const manualActions = [];
2108
2354
  if (gatePlan.desired.localCommands.length > 0) {
2109
2355
  const qualified = storedGate.qualification_state === "qualified";
@@ -2138,6 +2384,8 @@ export async function runInstallBridgeConductorCli(argv, deps) {
2138
2384
  });
2139
2385
  if (epicBranchCi.manualAction !== null)
2140
2386
  manualActions.push(epicBranchCi.manualAction);
2387
+ // BAPI-1637: say what the STORED gate means for merges, from readiness's own facts.
2388
+ await runGateConsequenceSummary(gateIo, access, deps.gate);
2141
2389
  if (options.reviewPolicy === "verdict_protocol") {
2142
2390
  // ---- Phase 3: optional workflow scaffold -------------------------------
2143
2391
  deps.log("");
@@ -2213,7 +2461,7 @@ export async function runInstallBridgeConductorCli(argv, deps) {
2213
2461
  }
2214
2462
  else {
2215
2463
  deps.log(" skipped — this caller supplied no local-provisioning seams.");
2216
- manualActions.push("tool visibility: run the packaged `install conductor` command to add the " +
2464
+ manualActions.push("tool visibility: run the packaged `install epic-implementer` command to add the " +
2217
2465
  "`epic_implementer` profile to your host MCP configuration.");
2218
2466
  }
2219
2467
  deps.log("");
@@ -2226,7 +2474,7 @@ export async function runInstallBridgeConductorCli(argv, deps) {
2226
2474
  }
2227
2475
  else {
2228
2476
  deps.log(" skipped — this caller supplied no local-provisioning seams.");
2229
- manualActions.push("local observability: run the packaged `install conductor` command, or " +
2477
+ manualActions.push("local observability: run the packaged `install epic-implementer` command, or " +
2230
2478
  "`epic-implementer install-git-hooks`, to install the managed Git hooks.");
2231
2479
  }
2232
2480
  // The fail-loud hook-binary refusal (a package that ships no hook binary)
@@ -2290,7 +2538,7 @@ export async function runInstallBridgeConductorCli(argv, deps) {
2290
2538
  let postReadiness = observedReadiness;
2291
2539
  if (postReadiness === null) {
2292
2540
  try {
2293
- postReadiness = await fetchConductorReadiness(access, deps.fetchJson);
2541
+ postReadiness = await fetchConductorReadiness(access, deps.fetchJson, { assessmentVersion: 1, epicRunId: options.assessmentEpicRunId });
2294
2542
  }
2295
2543
  catch {
2296
2544
  // Degraded, not fatal: the write already succeeded, and the matrix simply
@@ -2304,6 +2552,8 @@ export async function runInstallBridgeConductorCli(argv, deps) {
2304
2552
  const finalReport = await deps.runDoctor({
2305
2553
  access,
2306
2554
  reviewPolicySource: options.reviewPolicy,
2555
+ assessmentVersion: 1,
2556
+ epicRunId: options.assessmentEpicRunId,
2307
2557
  });
2308
2558
  deps.log(formatConductorInstallDoctorReport(finalReport));
2309
2559
  // Manual actions (BAPI-775): every declined, unavailable, empty, or incomplete
@@ -2350,12 +2600,34 @@ export async function runInstallBridgeConductorCli(argv, deps) {
2350
2600
  * Ask for consent to one write surface. A missing prompt seam (no terminal) is
2351
2601
  * a decline, never a default yes, and says so in one line naming the step.
2352
2602
  */
2353
- async function askConsent(deps, promptText, step) {
2603
+ async function askConsent(deps, promptText, step, recordingHint = "rerun setup in an interactive terminal; no flag records this consent.",
2604
+ /** BAPI-1638 — a decision the shared apply already holds. Only an explicit one skips the question. */
2605
+ decision) {
2606
+ if (decision !== undefined)
2607
+ return decision;
2354
2608
  if (!deps.promptLine) {
2355
2609
  deps.log(` skipped ${step}: there is no interactive terminal, so this counts as declined.`);
2356
2610
  return false;
2357
2611
  }
2358
- return confirm(deps, promptText);
2612
+ // The safe answer to a consequential write is No, so Enter declines.
2613
+ return askPlainConsent(promptText, recordingHint, plainTerminalFor(deps), "no");
2614
+ }
2615
+ /** The terminal a converted EI question reads from; availability is explicit, never inferred from the reader. */
2616
+ function plainTerminalFor(deps) {
2617
+ return { read: deps.promptLine, write: deps.log, isTTY: deps.isTTY };
2618
+ }
2619
+ function snapshotToolchainReader(setup, snapshot) {
2620
+ let pending = null;
2621
+ return () => {
2622
+ if (pending === null) {
2623
+ const read = setup.readSnapshotFile;
2624
+ pending =
2625
+ snapshot === null || read === undefined
2626
+ ? Promise.resolve(null)
2627
+ : resolveRepositoryToolchains((relPath) => read(snapshot, relPath));
2628
+ }
2629
+ return pending;
2630
+ };
2359
2631
  }
2360
2632
  /**
2361
2633
  * Collect every independent read-only finding. A failed read becomes an
@@ -2370,7 +2642,8 @@ async function collectSetupEvidence(deps, setup, access, readiness, inputs) {
2370
2642
  });
2371
2643
  const identity = identityResult.ok ? identityResult.identity : null;
2372
2644
  const repository = identity !== null ? `${identity.owner}/${identity.repo}` : null;
2373
- // The stored test command, read back from the server.
2645
+ // The stored test command, read back from the server. Evidence only: nothing
2646
+ // here asks for one, and a missing command is not a setup item.
2374
2647
  let storedCommand = null;
2375
2648
  let testCommand = { state: "unknown" };
2376
2649
  try {
@@ -2383,35 +2656,71 @@ async function collectSetupEvidence(deps, setup, access, readiness, inputs) {
2383
2656
  catch {
2384
2657
  testCommand = { state: "unknown" };
2385
2658
  }
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.
2659
+ // The managed workflow, through the installer's own read-only preflight. It can
2660
+ // only be compared with a command that is stored, and it is built from the
2661
+ // remote default branch, never from the person's checkout.
2662
+ const workflowWanted = inputs.ciPlan === "managed" || inputs.gateRequiresManagedCheck;
2391
2663
  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);
2664
+ let toolchains = null;
2665
+ if (storedCommand !== null && inputs.githubSignIn === "signed_in") {
2666
+ toolchains = await inputs.readToolchains();
2667
+ workflow = await assessWorkflow(setup, storedCommand, toolchains, inputs.snapshot, workflowWanted);
2403
2668
  }
2404
2669
  // The setup pull request and, once it merged, the index.
2405
2670
  let setupPullRequest = { state: "unknown" };
2406
2671
  let index = { state: "not_applicable" };
2672
+ let recovery;
2407
2673
  if (repository !== null && inputs.githubSignIn === "signed_in") {
2408
2674
  setupPullRequest = await readSetupPullRequest(setup.runGh, repository);
2409
2675
  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" };
2676
+ if (setupPullRequest.state === "merged" && setup.fetchRecoveryEvidence) {
2677
+ const prefix = `https://github.com/${repository}/pull/`;
2678
+ const numberText = setupPullRequest.url.startsWith(prefix) ? setupPullRequest.url.slice(prefix.length) : "";
2679
+ const prNumber = /^[1-9][0-9]*$/.test(numberText) ? Number(numberText) : NaN;
2680
+ recovery = Number.isSafeInteger(prNumber) ? await setup.fetchRecoveryEvidence(access, prNumber) : { supported: false, reason: "evidence_unavailable" };
2681
+ if (recovery.supported) {
2682
+ const r = recovery.evidence;
2683
+ if (r.canonical.verified && ["equal", "contains_target"].includes(r.canonical_relation))
2684
+ index = { state: "reached" };
2685
+ else if (r.reason)
2686
+ index = { state: "unknown" };
2687
+ else if (r.request && ["queued", "in_progress"].includes(r.request.status ?? ""))
2688
+ index = { state: "recovery_pending", requestId: r.request.id, runId: r.request.parse_run_id };
2689
+ else if (r.canonical_relation === "behind" || r.canonical_relation === "diverged")
2690
+ index = { state: r.canonical_relation };
2691
+ }
2692
+ }
2413
2693
  }
2414
2694
  const mergeCredential = await assessMergeCredential(deps, setup, readiness, identity);
2695
+ // BAPI-1635: default-branch index lag, committed-asset drift, and the launcher form.
2696
+ // Each is a read-only fact; a failed read leaves the fact out, never aborts the collection.
2697
+ let freshness;
2698
+ if (repository !== null && inputs.githubSignIn === "signed_in" && inputs.snapshot !== null) {
2699
+ try {
2700
+ freshness = await assessIndexFreshness(inputs.snapshot.defaultBranchSha, () => setup.fetchParseStatus(access), (targetSha, indexedSha) => compareIndexedToMerge(setup.runGh, repository, targetSha, indexedSha));
2701
+ }
2702
+ catch {
2703
+ freshness = undefined;
2704
+ }
2705
+ }
2706
+ let drift;
2707
+ if (setup.inspectCommandDrift !== undefined) {
2708
+ try {
2709
+ drift = await setup.inspectCommandDrift();
2710
+ }
2711
+ catch {
2712
+ drift = undefined;
2713
+ }
2714
+ }
2715
+ let launcher = null;
2716
+ if (setup.detectLauncher !== undefined) {
2717
+ try {
2718
+ launcher = await setup.detectLauncher(access.repoName);
2719
+ }
2720
+ catch {
2721
+ launcher = null;
2722
+ }
2723
+ }
2415
2724
  return {
2416
2725
  evidence: {
2417
2726
  readiness,
@@ -2419,11 +2728,18 @@ async function collectSetupEvidence(deps, setup, access, readiness, inputs) {
2419
2728
  githubSignIn: inputs.githubSignIn,
2420
2729
  repositoryIdentity: identityResult.ok ? "resolved" : identityResult.reason,
2421
2730
  testCommand,
2731
+ ...(inputs.ciPlan !== undefined ? { ciPlan: inputs.ciPlan } : {}),
2732
+ ...(inputs.gateRequiresManagedCheck ? { gateRequiresManagedCheck: true } : {}),
2733
+ ...(inputs.plannedGateWrite === true ? { plannedGateWrite: true } : {}),
2422
2734
  workflow,
2423
2735
  setupPullRequest,
2424
2736
  index,
2737
+ ...(recovery ? { recovery } : {}),
2425
2738
  mergeCredential,
2426
- gateChangeDeclined: inputs.gateChangeDeclined,
2739
+ ...(freshness !== undefined ? { freshness } : {}),
2740
+ ...(drift !== undefined ? { drift } : {}),
2741
+ ...(launcher !== null ? { launcher } : {}),
2742
+ ...(inputs.path !== undefined ? { path: inputs.path } : {}),
2427
2743
  advisories: inputs.advisories,
2428
2744
  },
2429
2745
  identity,
@@ -2432,8 +2748,6 @@ async function collectSetupEvidence(deps, setup, access, readiness, inputs) {
2432
2748
  toolchains,
2433
2749
  };
2434
2750
  }
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
2751
  /** The remedy when the repository's dependency files could not be inspected. Names files, never content. */
2438
2752
  function toolchainInspectionRemedy(resolution) {
2439
2753
  const files = resolution.failures.map((f) => f.file).join(", ");
@@ -2441,20 +2755,25 @@ function toolchainInspectionRemedy(resolution) {
2441
2755
  "Fix the file or its permissions, then re-run setup");
2442
2756
  }
2443
2757
  /**
2444
- * Classify the managed workflow with the installer's read-only dry run.
2758
+ * Classify the managed workflow with the installer's read-only dry run, against
2759
+ * the remote default branch snapshot (never the person's checkout).
2445
2760
  *
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.
2761
+ * `workflowWanted` says whether the workflow matters to this run: the plan is
2762
+ * `managed`, or the gate already requires its check. A repository that does not
2763
+ * want it is not blocked because its dependency files could not be read, since no
2764
+ * workflow is going to be generated from them.
2450
2765
  */
2451
- async function assessWorkflow(setup, testCommand, toolchains, commandChanged = false) {
2766
+ async function assessWorkflow(setup, testCommand, toolchains, snapshot, workflowWanted) {
2767
+ // No snapshot (or no way to read it) is uncertainty, never a reason to guess
2768
+ // the toolchains from the person's folder.
2769
+ if (toolchains === null || snapshot === null)
2770
+ return { state: "unknown" };
2452
2771
  if (toolchains.status === "unknown") {
2453
- return { state: "blocked", remedy: toolchainInspectionRemedy(toolchains) };
2772
+ return workflowWanted ? { state: "blocked", remedy: toolchainInspectionRemedy(toolchains) } : { state: "unknown" };
2454
2773
  }
2455
2774
  let result;
2456
2775
  try {
2457
- result = await setup.installCiWorkflow(testCommand, toolchains.toolchains, { dryRun: true, quiet: true });
2776
+ result = await setup.installCiWorkflow(testCommand, toolchains.toolchains, { dryRun: true, quiet: true, snapshot });
2458
2777
  }
2459
2778
  catch {
2460
2779
  return { state: "unknown" };
@@ -2465,17 +2784,13 @@ async function assessWorkflow(setup, testCommand, toolchains, commandChanged = f
2465
2784
  case "existing-pr":
2466
2785
  return { state: "pr_open", url: result.prUrl };
2467
2786
  case "dry-run":
2468
- return { state: "needs_pr" };
2787
+ // An installed Bridge workflow that differs is an upgrade; nothing installed is just absent.
2788
+ return result.upgrade ? { state: "needs_pr" } : { state: "absent" };
2469
2789
  case "installed-pr-opened":
2470
2790
  case "upgrade-pr-opened":
2471
2791
  // A dry run never opens one; treat an impossible answer as unknown.
2472
2792
  return { state: "unknown" };
2473
2793
  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
2794
  return result.prUrl !== undefined &&
2480
2795
  (result.reason === "existing_pr_differs" || result.reason === "historical_managed_pr_open")
2481
2796
  ? { state: "blocked", remedy: `${result.remediation} (${result.prUrl})` }
@@ -2552,336 +2867,337 @@ function storedMergeContextFor(setup, providerRepository, localRemote) {
2552
2867
  };
2553
2868
  }
2554
2869
  /** Whether the gate or the supervisor defaults would change (no POST needed). */
2555
- function gateOrDefaultsNeedWrite(gatePlan, readiness) {
2870
+ function gateOrDefaultsNeedWrite(gatePlan, readiness, reviewDefault) {
2556
2871
  if (gatePlan === null)
2557
2872
  return false;
2558
2873
  if (gatePlan.write !== null)
2559
2874
  return true;
2875
+ // A review default that is missing, or that an explicit flag changes, is a write
2876
+ // of its own: supervisor row presence alone says nothing about it.
2877
+ if (reviewDefault.kind === "send" && reviewDefault.stored !== reviewDefault.source)
2878
+ return true;
2560
2879
  if (readiness === null)
2561
2880
  return false;
2562
2881
  return !readiness.supervisor.setup_present || !readiness.supervisor.config_present;
2563
2882
  }
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;
2883
+ /** The review source a stored project default names, or `null` when none is stored. */
2884
+ function storedReviewSource(policy) {
2885
+ const stored = policy.policy.setup.review_policy;
2886
+ if (stored === null || stored === undefined)
2887
+ return null;
2888
+ if (typeof stored === "object" && typeof stored.source === "string") {
2889
+ return stored.source;
2592
2890
  }
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)
2891
+ // A stored value this client cannot interpret is still a stored choice.
2892
+ return "unrecognized";
2893
+ }
2894
+ /** Whether `.github/workflows/claude-review.yml` exists on the remote default branch snapshot. */
2895
+ async function remoteReviewWorkflowExists(setup, snapshot) {
2896
+ if (snapshot === null || setup.readSnapshotFile === undefined)
2597
2897
  return false;
2598
- let preview;
2599
2898
  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.");
2899
+ await setup.readSnapshotFile(snapshot, CLAUDE_REVIEW_WORKFLOW_RELPATH);
2900
+ return true;
2633
2901
  }
2634
- if (!gateFirst && gatePlan.write !== null && (await storeConductorGate(gateIo, access, gatePlan)) === null) {
2902
+ catch {
2903
+ // Absent and unreadable both fall back to repository_policy, which needs no workflow.
2635
2904
  return false;
2636
2905
  }
2637
- return true;
2638
2906
  }
2639
2907
  /**
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.
2908
+ * Decide the review default: explicit `--review-policy` first; otherwise none when
2909
+ * a project default is already stored (or cannot be read); otherwise
2910
+ * `verdict_protocol` when the claude-review workflow exists on the remote default
2911
+ * branch and `repository_policy` when it is absent or cannot be read. The remote
2912
+ * snapshot decides, never the person's checkout. Reads only.
2643
2913
  */
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;
2914
+ async function resolveReviewDefault(deps, options, setup, access, snapshot) {
2915
+ let stored;
2680
2916
  try {
2681
- readBack = await readStoredTestCommand(config);
2917
+ stored = storedReviewSource(await fetchConductorSetupPolicy(access, deps.fetchJson));
2682
2918
  }
2683
2919
  catch {
2684
- readBack = { ok: false, reason: "transport_failure", status: 0 };
2920
+ stored = undefined;
2685
2921
  }
2686
- if (!written.ok) {
2687
- return { kind: "write_failed", reason: written.reason, stored: readBack.ok ? readBack.testCommand : undefined };
2922
+ if (options.reviewPolicyExplicit) {
2923
+ return { kind: "send", source: options.reviewPolicy, basis: "explicit", stored: stored ?? null };
2688
2924
  }
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) {
2925
+ if (stored === undefined)
2926
+ return { kind: "preserve", basis: "unreadable", stored: null };
2927
+ if (stored !== null)
2928
+ return { kind: "preserve", basis: "stored", stored };
2929
+ const exists = await remoteReviewWorkflowExists(setup, snapshot);
2698
2930
  return {
2699
- id: "test-command-save",
2700
- label: "Test command",
2701
- state: "needs_action",
2702
- blocking: true,
2703
- remedy,
2931
+ kind: "send",
2932
+ source: exists ? "verdict_protocol" : "repository_policy",
2933
+ basis: exists ? "workflow_present" : "workflow_absent",
2934
+ stored: null,
2704
2935
  };
2705
2936
  }
2706
2937
  /**
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.
2938
+ * The review default for a caller that supplies no setup seams: only an explicit
2939
+ * `--review-policy` is sent, exactly as before BAPI-1603.
2710
2940
  */
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
- }
2941
+ function legacyReviewDefault(options) {
2942
+ return options.reviewPolicyExplicit
2943
+ ? { kind: "send", source: options.reviewPolicy, basis: "explicit", stored: null }
2944
+ : { kind: "preserve", basis: "stored", stored: null };
2945
+ }
2946
+ /** The review source the readiness doctor should assume: the one this run sends or keeps. */
2947
+ function effectiveReviewPolicy(options, reviewDefault) {
2948
+ if (reviewDefault.kind === "send")
2949
+ return reviewDefault.source;
2950
+ const stored = CONDUCTOR_REVIEW_POLICY_SOURCES.find((source) => source === reviewDefault.stored);
2951
+ return stored ?? options.reviewPolicy;
2745
2952
  }
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 };
2953
+ function bootstrapRequestFor(options, plan, reviewDefault) {
2954
+ const { action, confirm, expected_revision, ...gate } = plan.write ?? confirmRequestFor(plan.desired, plan.current.revision, plan.current.profile);
2955
+ return { protocol: SETUP_POLICY_PROTOCOL, ...(plan.write !== null ? { gate } : {}),
2956
+ defaults: { ...(reviewDefault.kind === "send" ? { review_policy: { source: reviewDefault.source } } : {}),
2957
+ merge_approval_required: "true" }, replace_done_gate: options.replaceDoneGate === true };
2958
+ }
2959
+ function policyMatches(expected, actual) {
2960
+ const canonical = (value) => {
2961
+ if (Array.isArray(value))
2962
+ return `[${value.map(canonical).join(",")}]`;
2963
+ if (value && typeof value === "object")
2964
+ return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
2965
+ return JSON.stringify(value);
2966
+ };
2967
+ return canonical(expected) === canonical(actual);
2753
2968
  }
2754
2969
  /**
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.
2970
+ * BAPI-1604 — a policy effect as text, with worker-variable VALUES removed. A gate
2971
+ * projection can carry `worker_env` entries, and an automatic receipt must never
2972
+ * print a value that setup did not ask the owner to read.
2759
2973
  */
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;
2974
+ function policyEffectText(value) {
2975
+ return JSON.stringify(value, (key, inner) => key === "worker_env" && Array.isArray(inner)
2976
+ ? inner.map((entry) => (entry !== null && typeof entry === "object" && "name" in entry ? { name: entry.name } : entry))
2977
+ : inner);
2772
2978
  }
2979
+ /** BAPI-1658 — the line shown for an effect whose shared description comes back empty, by category. */
2980
+ const PLANNED_CHANGE_FALLBACKS = {
2981
+ gate: "Gate settings changed",
2982
+ setup: "Review settings changed",
2983
+ config: "Merge settings changed",
2984
+ sources: "Settings sources changed",
2985
+ qualification: "Gate qualification changed",
2986
+ };
2773
2987
  /**
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.
2988
+ * BAPI-1658 — the complete, ordered list of changes the automatic path is about to apply.
2989
+ *
2990
+ * One call per server effect, in the server's order, appending every returned line
2991
+ * with no merging or de-duplication, so its length is the count the owner sees. An
2992
+ * effect that describes to nothing still gets one fixed fallback line (never its
2993
+ * token or contents). Presentation only: it describes effects the server already
2994
+ * established, performs no I/O, and must not influence request construction,
2995
+ * consent, persistence, or the proposal digest.
2777
2996
  */
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);
2997
+ function describePlannedPolicyChanges(effects, ciFacts) {
2998
+ const planned = [];
2999
+ for (const effect of effects) {
3000
+ const described = describePolicyChanges([effect], ciFacts, { brief: true });
3001
+ if (described.length > 0)
3002
+ planned.push(...described);
3003
+ else
3004
+ planned.push(PLANNED_CHANGE_FALLBACKS[effect.category] ?? "Setup policy changed");
2793
3005
  }
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.`);
3006
+ return planned;
3007
+ }
3008
+ async function fixGateAndDefaults(deps, options, access, gatePlan, reviewDefault,
3009
+ /** BAPI-1604 — the converging setup applies the previewed policy without a question; the phase-based sequence still asks. */
3010
+ applyWithoutQuestion = false,
3011
+ /**
3012
+ * BAPI-1638 — the approved `gate` answer. `approve` applies the previewed policy with no
3013
+ * terminal; `decline` writes nothing. Absent keeps the terminal rule below unchanged.
3014
+ */
3015
+ decision) {
3016
+ if (decision === "decline" && !options.dryRun) {
3017
+ deps.log("Declined: the combined policy was not approved, so the gate and defaults are unchanged.");
3018
+ return { status: "deferred", declined: true };
3019
+ }
3020
+ const request = bootstrapRequestFor(options, gatePlan, reviewDefault);
3021
+ // In the converging setup the previewed policy is applied without a question, but only in an
3022
+ // available terminal. Without one the preview is shown and nothing is written, as before.
3023
+ const automatic = applyWithoutQuestion && (decision === "approve" || (deps.isTTY === true && deps.promptLine !== undefined));
3024
+ for (let attempt = 0; attempt < 2; attempt++) {
3025
+ let preview;
3026
+ try {
3027
+ preview = await previewConductorSetupPolicy(access, request, deps.postJson);
3028
+ }
3029
+ catch {
3030
+ deps.log("Deferred: combined setup policy is unavailable or unsupported. Rerun with a compatible server; ask a bootstrap administrator if this persists.");
3031
+ return { status: "deferred" };
3032
+ }
3033
+ // One plain line per changed setting. The before → after JSON is a diagnostic, shown only under --verbose.
3034
+ const logEffects = (effects) => {
3035
+ for (const line of describePolicyChanges(effects))
3036
+ deps.log(line);
3037
+ if (options.verbose)
3038
+ for (const effect of effects)
3039
+ deps.log(`${effect.category}: ${policyEffectText(effect.before)} → ${policyEffectText(effect.after)}`);
3040
+ };
3041
+ const printEffects = () => {
3042
+ deps.log(`Proposed required checks: ${gatePlan.desired.providerChecks.join(", ") || "none"}`);
3043
+ if ((gatePlan.desired.watchedChecks ?? []).length > 0) {
3044
+ deps.log(`Proposed watched checks: ${(gatePlan.desired.watchedChecks ?? []).join(", ")}`);
3045
+ }
3046
+ logEffects(preview.effects);
3047
+ };
3048
+ if (options.dryRun) {
3049
+ printEffects();
3050
+ deps.log("Dry run: combined preview only; no policy was applied.");
3051
+ return { status: "deferred" };
3052
+ }
3053
+ if (!preview.approval_required) {
3054
+ printEffects();
3055
+ deps.log("No change: combined policy already matches.");
3056
+ return { status: "unchanged" };
3057
+ }
3058
+ if (!applyWithoutQuestion) {
3059
+ printEffects();
3060
+ const decision = await askSetupQuestion({
3061
+ purpose: "Authorize exactly the combined repository policy changes shown above.",
3062
+ prompt: "Apply these consequential policy changes? [y/N]: ",
3063
+ evidence: ["The server computed these effects from one locked policy snapshot.",
3064
+ "Existing epic overrides keep precedence. Failed or unknown CI evidence does not relax admission."],
3065
+ options: [{ id: "yes", label: "Apply this exact policy" }, { id: "no", label: "Keep policy unchanged" }],
3066
+ consequences: ["Required checks can prevent merges. Local commands require qualification; changed commands can invalidate it.",
3067
+ "Gate and supervisor defaults commit together, preserving omitted settings."],
3068
+ deferred: "Coupled policy remains unchanged; independent setup work can continue.",
3069
+ recovery: "Rerun setup for a fresh preview; contact the bootstrap administrator if unavailable.",
3070
+ }, { read: deps.promptLine, write: deps.log });
3071
+ if (decision.status !== "accept") {
3072
+ deps.log("Deferred: combined policy was not approved.");
3073
+ return { status: "deferred" };
3074
+ }
3075
+ }
3076
+ else if (!automatic) {
3077
+ printEffects();
3078
+ deps.log("Deferred: combined policy was not approved.");
3079
+ return { status: "deferred" };
2799
3080
  }
2800
3081
  else {
2801
- deps.log(" No test command could be found in this repository.");
3082
+ // BAPI-1658: list what is about to be applied. Built per attempt from this attempt's own preview;
3083
+ // every visible count comes from this list, never from the number of effect categories.
3084
+ const planned = describePlannedPolicyChanges(preview.effects);
3085
+ if (planned.length > 0) {
3086
+ deps.log(planned.length === 1 ? "Setup will apply this change:" : `Setup will apply these ${planned.length} changes:`);
3087
+ for (const line of planned)
3088
+ deps.log(` ${line}`);
3089
+ }
3090
+ deps.log(`Applying ${planned.length} previewed policy change${planned.length === 1 ? "" : "s"}…`);
3091
+ }
3092
+ let current;
3093
+ let appliedState;
3094
+ let uncertain = false;
3095
+ try {
3096
+ appliedState = (await applyConductorSetupPolicy(access, request, preview, true, deps.postJson)).state;
3097
+ }
3098
+ catch (error) {
3099
+ uncertain = true;
3100
+ if (error instanceof ConductorSetupPolicyError && error.reason === "stale" && attempt === 0 && (applyWithoutQuestion || deps.promptLine)) {
3101
+ deps.log(applyWithoutQuestion
3102
+ ? "The policy changed since the preview. Setup is refreshing the effects once."
3103
+ : "Policy changed: refreshing the preview once. The new effects require a new answer.");
3104
+ continue;
3105
+ }
3106
+ if (error instanceof ConductorSetupPolicyError && ["refused", "stale", "unsupported"].includes(error.reason)) {
3107
+ deps.log("Deferred: policy was refused or changed. Rerun for a fresh preview.");
3108
+ return { status: "deferred" };
3109
+ }
3110
+ }
3111
+ try {
3112
+ current = await fetchConductorSetupPolicy(access, deps.fetchJson);
3113
+ }
3114
+ catch {
3115
+ deps.log("Unknown—verify before retrying: policy apply could not be confirmed. Ask the bootstrap administrator.");
3116
+ return { status: "unknown" };
3117
+ }
3118
+ if (uncertain
3119
+ || (appliedState !== undefined && !policyMatches(appliedState, current.state))
3120
+ || !policyMatches(preview.after, current.policy) || current.state.generation <= preview.state.generation
3121
+ || current.state.revision < preview.state.revision) {
3122
+ deps.log("Unknown—verify before retrying: coherent read-back does not confirm the intended complete policy.");
3123
+ return { status: "unknown" };
2802
3124
  }
2803
- if (!deps.promptLine) {
2804
- deps.log(" skipped saving a test command: there is no interactive terminal, so this counts as declined.");
3125
+ if (applyWithoutQuestion) {
3126
+ deps.log("Policy applied (confirmed by reading it back).");
3127
+ // Describe what the read-back shows, not what was proposed.
3128
+ logEffects(preview.effects.map((effect) => ({ category: effect.category, before: effect.before, after: current.policy[effect.category] })));
2805
3129
  }
2806
3130
  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;
3131
+ deps.log("Completed: coherent server state matches the intended policy.");
2810
3132
  }
3133
+ // Report removals only now that the read-back confirmed the policy was applied.
3134
+ const priorProfile = gatePlan.current.profile;
3135
+ if (gatePlan.removals.length > 0 && gatePlan.current.confirmed && priorProfile !== null) {
3136
+ deps.log(`Removed from the repository gate: ${gatePlan.removals.join("; ")}.`);
3137
+ deps.log("Those checks no longer gate child merges in your Epic Implementer runs.");
3138
+ for (const line of describeGateRestoration(desiredFromStored(priorProfile)))
3139
+ deps.log(line);
3140
+ }
3141
+ return { status: "completed", current };
2811
3142
  }
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");
3143
+ return { status: "deferred" };
2838
3144
  }
2839
3145
  /** The one operator-only line for a readable stored command, then what CI installs for it. */
2840
3146
  function logStoredCommandAndToolchains(deps, storedCommand, toolchains) {
3147
+ if (storedCommand === null)
3148
+ return;
2841
3149
  deps.log("");
2842
- if (storedCommand !== null) {
2843
- deps.log(`Test command: \`${storedCommand}\` (stored). Change it with --test-command "...".`);
3150
+ deps.log(`Test command: \`${storedCommand}\` (stored). Change it with --test-command "<your command>".`);
3151
+ if (toolchains !== null) {
3152
+ deps.log("What CI installs for it:");
3153
+ for (const line of describeToolchainResolution(toolchains))
3154
+ deps.log(` ${line}`);
2844
3155
  }
2845
- deps.log("What CI installs for it:");
2846
- for (const line of describeToolchainResolution(toolchains))
2847
- deps.log(` ${line}`);
2848
3156
  }
2849
3157
  /** Fix: open the one setup pull request through the artifact-set installer. */
2850
- async function fixSetupPullRequest(deps, setup, testCommand, toolchains, repository) {
3158
+ async function fixSetupPullRequest(deps, setup, testCommand, toolchains, snapshot, repository,
3159
+ /** BAPI-1638 — the approved `setup_pr` answer, which stands in for the installer's own question. */
3160
+ consent) {
2851
3161
  deps.log("");
2852
3162
  deps.log("CI workflow");
3163
+ if (toolchains === null || snapshot === null) {
3164
+ // No snapshot of the default branch is uncertainty, never a reason to read the
3165
+ // person's folder instead. Only workflow generation is skipped.
3166
+ deps.log(" skipped — Bridge could not read your default branch to choose what CI installs, and it will not guess.");
3167
+ return { workflow: { state: "unknown" }, pr: null, result: null };
3168
+ }
2853
3169
  if (toolchains.status === "unknown") {
2854
3170
  // Uninspectable dependency files are a blocking inspection failure, never "no lockfile".
2855
3171
  const remedy = toolchainInspectionRemedy(toolchains);
2856
3172
  deps.log(` skipped — ${remedy}.`);
2857
- return { workflow: { state: "blocked", remedy }, pr: null };
3173
+ return { workflow: { state: "blocked", remedy }, pr: null, result: null };
2858
3174
  }
2859
3175
  let result;
2860
3176
  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"));
3177
+ // The setup pull request has its OWN consent: it pushes a branch and opens a PR.
3178
+ result = await setup.installCiWorkflow(testCommand, toolchains.toolchains, { dryRun: false, snapshot }, (promptText) => askConsent(deps, promptText, "opening the setup pull request", undefined, consent));
2863
3179
  }
2864
3180
  catch {
2865
3181
  deps.log(" the setup pull request could not be prepared; re-run setup.");
2866
- return { workflow: { state: "unknown" }, pr: null };
3182
+ return { workflow: { state: "unknown" }, pr: null, result: null };
2867
3183
  }
2868
3184
  switch (result.outcome) {
2869
3185
  case "installed-pr-opened":
2870
3186
  case "upgrade-pr-opened":
2871
3187
  deps.log(` opened the setup PR: ${result.prUrl}`);
2872
- return { workflow: { state: "pr_open", url: result.prUrl }, pr: null };
3188
+ return { workflow: { state: "pr_open", url: result.prUrl }, pr: null, result };
2873
3189
  case "existing-pr":
2874
3190
  deps.log(` the setup PR is already open: ${result.prUrl}`);
2875
- return { workflow: { state: "pr_open", url: result.prUrl }, pr: null };
3191
+ return { workflow: { state: "pr_open", url: result.prUrl }, pr: null, result };
2876
3192
  case "identical":
2877
3193
  deps.log(" the CI workflow is already in place — nothing to change.");
2878
- return { workflow: { state: "installed" }, pr: null };
3194
+ return { workflow: { state: "installed" }, pr: null, result };
2879
3195
  case "dry-run":
2880
- return { workflow: { state: "needs_pr" }, pr: null };
3196
+ return { workflow: result.upgrade ? { state: "needs_pr" } : { state: "absent" }, pr: null, result };
2881
3197
  case "failed": {
2882
3198
  if (result.reason === "consent_declined") {
2883
3199
  deps.log(" declined — no branch was pushed and no pull request was opened.");
2884
- return { workflow: { state: "needs_pr" }, pr: null };
3200
+ return { workflow: { state: "absent" }, pr: null, result };
2885
3201
  }
2886
3202
  deps.log(` the setup pull request was not opened (${result.reason}): ${result.remediation}`);
2887
3203
  if (result.prUrl !== undefined)
@@ -2891,8 +3207,8 @@ async function fixSetupPullRequest(deps, setup, testCommand, toolchains, reposit
2891
3207
  // An uncertain creation is re-read, never repeated.
2892
3208
  const pr = repository !== null ? await readSetupPullRequest(setup.runGh, repository) : null;
2893
3209
  if (pr?.state === "open")
2894
- return { workflow: { state: "pr_open", url: pr.url }, pr };
2895
- return { workflow: { state: "blocked", remedy: result.remediation }, pr };
3210
+ return { workflow: { state: "pr_open", url: pr.url }, pr, result };
3211
+ return { workflow: { state: "blocked", remedy: result.remediation }, pr, result };
2896
3212
  }
2897
3213
  }
2898
3214
  }
@@ -2900,7 +3216,11 @@ async function fixSetupPullRequest(deps, setup, testCommand, toolchains, reposit
2900
3216
  * Fix: store (or replace) the GitHub merge token for this repository, after its
2901
3217
  * own consent, read with no echo. Never printed, logged, committed, or sent.
2902
3218
  */
2903
- async function fixMergeToken(deps, setup, identity, replacing) {
3219
+ /** BAPI-1638 — the non-secret name of this repository's merge-token entry, as answers reference it. */
3220
+ export function mergeTokenStoreTarget(identity) {
3221
+ return `merge_token:${identity.owner}/${identity.repo}`;
3222
+ }
3223
+ async function fixMergeToken(deps, setup, identity, replacing, answer) {
2904
3224
  const repository = `${identity.owner}/${identity.repo}`;
2905
3225
  deps.log("");
2906
3226
  deps.log("GitHub merge token");
@@ -2913,31 +3233,66 @@ async function fixMergeToken(deps, setup, identity, replacing) {
2913
3233
  }
2914
3234
  const ok = await askConsent(deps, replacing
2915
3235
  ? `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");
3236
+ : `Store a GitHub merge token for ${repository} on this computer? [y/N]: `, replacing ? "replacing the stored merge token" : "storing a merge token", undefined, answer === undefined ? undefined : answer.decision === "reference");
2917
3237
  if (!ok) {
2918
3238
  deps.log(replacing
2919
3239
  ? " declined — the stored token was left as it is."
2920
3240
  : " 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;
3241
+ return { status: "declined" };
2926
3242
  }
2927
3243
  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;
3244
+ if (answer?.decision === "reference") {
3245
+ // The token is resolved from its approved reference here, at apply time, and never echoed.
3246
+ const reference = answer.reference;
3247
+ if (reference.kind === "env") {
3248
+ token = (deps.env[reference.name] ?? "").trim();
3249
+ if (token.length === 0) {
3250
+ deps.log(` the environment variable ${reference.name} is not set; nothing was stored.`);
3251
+ return { status: "failed", reason: `the environment variable ${reference.name} is not set` };
3252
+ }
3253
+ }
3254
+ else {
3255
+ if (reference.target !== mergeTokenStoreTarget(identity)) {
3256
+ deps.log(` setup reads only this repository's own credential-store entry (${mergeTokenStoreTarget(identity)}); nothing was stored.`);
3257
+ return { status: "failed", reason: `the reference must name ${mergeTokenStoreTarget(identity)}` };
3258
+ }
3259
+ let stored;
3260
+ try {
3261
+ stored = await setup.readMergeToken(identity);
3262
+ }
3263
+ catch {
3264
+ return { status: "failed", reason: "the credential store could not be read" };
3265
+ }
3266
+ if (stored.status !== "present") {
3267
+ deps.log(" the referenced credential-store entry holds no token for this repository; nothing was stored.");
3268
+ return { status: "failed", reason: "the referenced credential-store entry holds no token for this repository" };
3269
+ }
3270
+ // The repository's own store entry is the only credential-store target setup reads.
3271
+ if (isUsableMergeCredentialValue(stored.token))
3272
+ return replacing ? { status: "failed", reason: "the stored token is the one GitHub rejected" } : { status: "unchanged" };
3273
+ return { status: "failed", reason: "the referenced credential-store entry is not a usable token" };
3274
+ }
2937
3275
  }
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;
3276
+ else {
3277
+ if (!setup.promptSecret) {
3278
+ deps.log(" skipped reading the token: there is no interactive terminal. Nothing was stored.");
3279
+ return { status: "declined" };
3280
+ }
3281
+ try {
3282
+ token = (await setup.promptSecret("GitHub merge token (input is hidden): ")).trim();
3283
+ }
3284
+ catch {
3285
+ token = "";
3286
+ }
3287
+ if (token.length === 0) {
3288
+ deps.log(" no token was entered; nothing was stored.");
3289
+ return { status: "declined" };
3290
+ }
3291
+ }
3292
+ if (!isUsableMergeCredentialValue(token)) {
3293
+ token = "";
3294
+ deps.log(" that value cannot be a GitHub token (it has spaces or control characters); nothing was stored.");
3295
+ return { status: "failed", reason: "the referenced value cannot be a GitHub token" };
2941
3296
  }
2942
3297
  const result = await setup.storeMergeToken(identity, token);
2943
3298
  let stored = result.ok;
@@ -2949,43 +3304,157 @@ async function fixMergeToken(deps, setup, identity, replacing) {
2949
3304
  token = "";
2950
3305
  if (!stored) {
2951
3306
  deps.log(` the token could not be stored (${result.ok ? "unconfirmed" : result.kind}); nothing changed.`);
2952
- return false;
3307
+ return { status: "failed", reason: `the token could not be stored (${result.ok ? "unconfirmed" : result.kind})` };
2953
3308
  }
2954
3309
  deps.log(` stored the merge token for ${repository} on this computer.`);
2955
3310
  if (replacing) {
2956
3311
  deps.log(" A run already in progress keeps the token its executor started with until that executor restarts.");
2957
3312
  }
2958
- return true;
3313
+ return { status: "written" };
2959
3314
  }
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) {
3315
+ /** The refusal remedy when fresh recovery evidence asks a question the answers did not state. */
3316
+ const REINDEX_REFUSED_REMEDY = "Refused: the recovery evidence now asks a question the answers did not state, so nothing was queued. " +
3317
+ "Run --answers - --dry-run --json for a fresh proposal, then rerun with its answers.";
3318
+ export async function fixReindex(deps, setup, access, initial, answers) {
2966
3319
  deps.log("");
2967
3320
  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" };
3321
+ const unresolved = (remedy, choice) => {
3322
+ deps.log(` ${remedy}`);
3323
+ return { state: "recovery_unresolved", remedy, ...(choice ? { choice } : {}) };
3324
+ };
3325
+ if (!initial?.supported || !setup.fetchRecoveryEvidence || !setup.correctBranch || !setup.admitRecovery)
3326
+ return unresolved("Upgrade the Bridge backend/client for target-aware recovery; nothing was queued.");
3327
+ // Terminal availability is explicit: a reader alone is not an interactive terminal.
3328
+ if (answers === undefined && (!deps.promptLine || deps.isTTY !== true))
3329
+ return unresolved("Branch recovery is deferred: there is no interactive terminal. Re-run setup interactively to review the exact effect; nothing was queued. No flag records this choice.", "deferred");
3330
+ let current = initial.evidence;
3331
+ const knownUnverified = (e) => !e.canonical.verified
3332
+ && ["absent", "unverified"].includes(e.canonical_observation ?? "unknown");
3333
+ // A definite stale refusal gets at most one new evidence review. No prior
3334
+ // consent survives that transition, and uncertain writes are never retried.
3335
+ for (let review = 0; review < 2; review++) {
3336
+ let corrected = false;
3337
+ if ((!current.canonical.verified && !knownUnverified(current)) || current.reason || !current.required_commit_sha || !current.destination_branch)
3338
+ return unresolved("Recovery evidence is unknown; ask your Bridge administrator to inspect the target and canonical index. Nothing was queued.");
3339
+ if (current.canonical.verified && ["equal", "contains_target"].includes(current.canonical_relation))
3340
+ return { state: "reached" };
3341
+ if (current.configured_relation === "unknown")
3342
+ return unresolved("Configured branch ancestry is unknown; inspect it before retrying. Nothing was queued.");
3343
+ deps.log(` setup target ${current.destination_branch}@${current.required_commit_sha}; stored branch ${JSON.stringify(current.configured_branch)}; resolved ${current.resolved_branch}@${current.resolved_head_sha}; provider default ${current.provider_default}; canonical ${current.canonical_relation}`);
3344
+ if (!["equal", "contains_target"].includes(current.configured_relation) || current.canonical_relation === "diverged") {
3345
+ // The demonstrated default branch with nothing else configured is not a choice: take it,
3346
+ // say so, and continue through the same correction and verification path.
3347
+ const unambiguous = current.destination_branch === current.provider_default
3348
+ && (current.configured_branch === null || current.configured_branch === "" || current.configured_branch === current.destination_branch);
3349
+ if (!unambiguous && answers !== undefined && answers.branch === undefined)
3350
+ return unresolved(REINDEX_REFUSED_REMEDY, "refused");
3351
+ const decision = unambiguous
3352
+ ? { status: "selected", id: "correct" }
3353
+ : answers?.branch !== undefined
3354
+ ? { status: "selected", id: answers.branch }
3355
+ : await askPlainSetupQuestion({
3356
+ question: `Which branch should Bridge index? Your stored branch is ${JSON.stringify(current.configured_branch)} and the setup used ${current.destination_branch}.`,
3357
+ options: [
3358
+ { id: "correct", label: `Use the default branch (${current.destination_branch})` },
3359
+ { id: "keep", label: `Keep the current branch (${JSON.stringify(current.configured_branch)})` },
3360
+ ],
3361
+ recommended: "correct",
3362
+ recordingFlag: "no flag records this choice; rerun setup in an interactive terminal.",
3363
+ evidence: [`Stored branch: ${JSON.stringify(current.configured_branch)}. Proposed destination: ${current.destination_branch}.`,
3364
+ `Required setup revision: ${current.required_commit_sha}; configured head: ${current.resolved_head_sha}; canonical content: ${current.canonical_relation}.`],
3365
+ consequences: [
3366
+ `Using the default changes the shared branch from ${JSON.stringify(current.configured_branch)} to ${current.destination_branch}, then queues one tracked first parse once the change reads back and the fresh evidence agrees.`,
3367
+ "Parsing picks the configured branch again when it runs, so what it reads can differ from this preview.",
3368
+ "The shared branch affects future deliveries. Existing pull request bases and delivery policy do not change; work already in flight may still use the earlier branch.",
3369
+ "Keeping your branch preserves it. Setup can index it only if fresh evidence shows it contains the setup revision; otherwise merge the setup changes there first.",
3370
+ ],
3371
+ recovery: "Check the branch with the repository maintainer, then re-run setup interactively.",
3372
+ }, plainTerminalFor(deps));
3373
+ if (unambiguous)
3374
+ deps.log(` The repository's default branch is ${current.destination_branch}, so setup uses it for indexing.`);
3375
+ if (decision.status !== "selected")
3376
+ return unresolved("Branch choice deferred; no correction or parse was submitted. Re-run setup interactively when ready.", "deferred");
3377
+ if (decision.id === "keep" && !["equal", "contains_target"].includes(current.configured_relation))
3378
+ return unresolved(`Kept ${JSON.stringify(current.configured_branch)}. Integrate setup revision ${current.required_commit_sha} into that branch, then re-run setup; nothing was queued.`, "kept");
3379
+ if (decision.id === "correct") {
3380
+ const outcome = await setup.correctBranch(access, current.configured_branch, current.destination_branch);
3381
+ if (outcome === "conflict") {
3382
+ if (review === 1)
3383
+ return unresolved("Configuration changed again; the reviewed effect was discarded. Re-run setup for a fresh decision.");
3384
+ const refreshed = await setup.fetchRecoveryEvidence(access, current.setup_pr_number);
3385
+ if (!refreshed.supported)
3386
+ return unresolved("Configuration changed and fresh evidence is unavailable. Re-run setup; nothing was queued.");
3387
+ current = refreshed.evidence;
3388
+ continue;
3389
+ }
3390
+ if (outcome !== "verified")
3391
+ return unresolved(`Branch correction ${outcome}; no parse was admitted. Verify the stored branch with your Bridge administrator before retrying.`);
3392
+ corrected = true;
3393
+ }
3394
+ }
3395
+ const refreshed = await setup.fetchRecoveryEvidence(access, current.setup_pr_number);
3396
+ if (!refreshed.supported)
3397
+ return unresolved("Fresh branch evidence is unavailable; nothing was queued.");
3398
+ if (refreshed.evidence.required_commit_sha !== current.required_commit_sha
3399
+ || refreshed.evidence.configured_branch !== (corrected ? current.destination_branch : current.configured_branch)
3400
+ || (!corrected && refreshed.evidence.configuration_fingerprint !== current.configuration_fingerprint))
3401
+ return unresolved("Configuration or target changed after review; the effect was discarded. Re-run setup for a fresh decision; nothing was queued.");
3402
+ current = refreshed.evidence;
3403
+ if (current.canonical.verified && ["equal", "contains_target"].includes(current.canonical_relation))
3404
+ return { state: "reached" };
3405
+ if (current.reason || (!current.canonical.verified && !knownUnverified(current)) || !["equal", "contains_target"].includes(current.configured_relation))
3406
+ return unresolved("The reviewed branch cannot be verified to contain the setup revision; no parse was admitted.");
3407
+ let retry;
3408
+ if (current.request && ["queued", "in_progress"].includes(current.request.status ?? ""))
3409
+ return { state: "recovery_pending", requestId: current.request.id, runId: current.request.parse_run_id };
3410
+ if (current.request) {
3411
+ if (current.retry_generation === null)
3412
+ return unresolved("The retained request has no verified retry generation; inspect its history with your Bridge administrator.");
3413
+ if (answers !== undefined && answers.retry === undefined)
3414
+ return unresolved(REINDEX_REFUSED_REMEDY, "refused");
3415
+ const decision = answers?.retry !== undefined ? { status: "selected", id: answers.retry } : await askPlainSetupQuestion({
3416
+ question: "The earlier indexing attempt did not finish the job. Retry it once?",
3417
+ options: [
3418
+ { id: "retry", label: "Retry once" },
3419
+ { id: "no_retry", label: "Do not retry" },
3420
+ ],
3421
+ recommended: "retry",
3422
+ recordingFlag: "no flag records this choice; rerun setup in an interactive terminal.",
3423
+ evidence: [
3424
+ `Prior request ${current.request.id}, run ${current.request.parse_run_id ?? "retained"}, status ${current.request.status}.`,
3425
+ `Canonical content relation is ${current.canonical_relation} for ${current.required_commit_sha}; configured head ${current.resolved_head_sha} contains it. Failed attempts may leave canonical content unverified; lifecycle success never proves coverage.`,
3426
+ `Retry generation ${current.retry_generation} for branch ${JSON.stringify(current.configured_branch)} and configuration ${current.configuration_fingerprint}.`,
3427
+ ],
3428
+ consequences: ["Retrying queues one new tracked attempt that picks the configured branch when it runs. Asking again for the same retry cannot queue another.", "This retry is separate from automatic worker recovery. Healthy running work is never cancelled."],
3429
+ recovery: "Look at the earlier attempt, then re-run interactive setup.",
3430
+ }, plainTerminalFor(deps));
3431
+ if (!(decision.status === "selected" && decision.id === "retry"))
3432
+ return decision.status === "selected"
3433
+ ? unresolved("Retry declined; no request was submitted. Re-run setup after reviewing the prior attempt.", "declined")
3434
+ : unresolved("Retry deferred; no request was submitted. Re-run setup after reviewing the prior attempt.", "deferred");
3435
+ retry = current.retry_generation;
3436
+ }
3437
+ deps.log(` admitting one tracked ${retry === undefined ? "initial parse" : `retry generation ${retry}`} for ${current.resolved_branch}@${current.resolved_head_sha}; execution resolves the branch again.`);
3438
+ const admission = await setup.admitRecovery(access, current, retry);
3439
+ if (admission.reason === "configuration_changed")
3440
+ return unresolved("Configuration changed before admission; the reviewed effect was discarded. Re-run setup for a fresh review.");
3441
+ // One bounded read also recovers an uncertain response without another
3442
+ // mutation. Never mint a replacement retry identity or cancel healthy work.
3443
+ const observed = await setup.fetchRecoveryEvidence(access, current.setup_pr_number);
3444
+ if (observed.supported) {
3445
+ const e = observed.evidence;
3446
+ if (e.canonical.verified && ["equal", "contains_target"].includes(e.canonical_relation))
3447
+ return { state: "reached" };
3448
+ if (e.request && ["queued", "in_progress"].includes(e.request.status ?? "")) {
3449
+ deps.log(` pending request ${e.request.id}, run ${e.request.parse_run_id ?? "retained"}; re-run setup to inspect it. Observation never cancels parsing.`);
3450
+ return { state: "recovery_pending", requestId: e.request.id, runId: e.request.parse_run_id };
3451
+ }
3452
+ if (e.request && ["failed", "succeeded"].includes(e.request.status ?? ""))
3453
+ return unresolved(`Request ${e.request.id} ${e.request.status}; target coverage is still unresolved. Re-run setup to review an explicit retry.`);
3454
+ }
3455
+ return unresolved(`Admission ${admission.outcome}; inspection is incomplete. Re-run setup to inspect durable history before retrying; no cancellation was requested.`);
2986
3456
  }
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" };
3457
+ return unresolved("Configuration changed; re-run setup for a new review. Nothing was queued.");
2989
3458
  }
2990
3459
  /**
2991
3460
  * `--remove-merge-token`: remove this repository's stored merge token under the
@@ -3037,78 +3506,1273 @@ function localAdvisories(report) {
3037
3506
  if (hooks !== undefined && hooks.status !== "ok") {
3038
3507
  out.push("for local event history, run `epic-implementer install-git-hooks`");
3039
3508
  }
3040
- return out;
3509
+ return out;
3510
+ }
3511
+ /** Non-mutating boundary shared by explicit and converging setup actions. */
3512
+ export async function assessEpicInstallerPrerequisites(deps, executorRequested = false,
3513
+ /** BAPI-1604 — print only general asset-maintenance commentary under `--verbose`; failures and remedies always print. */
3514
+ quietGeneralCommentary = false) {
3515
+ if (!quietGeneralCommentary) {
3516
+ deps.log("Epic Implementer requires a supported github.com repository, GitHub CLI and Claude Code tooling and sign-in before dependent changes. General Bridge maintenance remains available.");
3517
+ }
3518
+ let observed = { claudeLoggedIn: null, githubSignIn: "unavailable", localRemote: null, toolsAvailable: false, platformSupported: false };
3519
+ try {
3520
+ if (deps.prerequisites)
3521
+ observed = await deps.prerequisites(executorRequested);
3522
+ }
3523
+ catch { /* unknown remains blocked */ }
3524
+ if (deps.setup) {
3525
+ try {
3526
+ observed.claudeLoggedIn = (await deps.setup.detectClaudeLogin()).detected;
3527
+ }
3528
+ catch {
3529
+ observed.claudeLoggedIn = null;
3530
+ }
3531
+ try {
3532
+ observed.githubSignIn = await deps.setup.checkGithubSignIn();
3533
+ }
3534
+ catch {
3535
+ observed.githubSignIn = "unavailable";
3536
+ }
3537
+ try {
3538
+ observed.localRemote = await deps.setup.readLocalGithubRemote();
3539
+ }
3540
+ catch {
3541
+ observed.localRemote = null;
3542
+ }
3543
+ }
3544
+ const available = observed.claudeLoggedIn === true && observed.githubSignIn === "signed_in" && observed.localRemote !== null && observed.toolsAvailable && observed.platformSupported;
3545
+ if (!available) {
3546
+ const missing = [observed.claudeLoggedIn !== true ? "Claude Code sign-in missing or unknown" : null,
3547
+ observed.githubSignIn !== "signed_in" ? `GitHub sign-in ${observed.githubSignIn}` : null,
3548
+ !observed.localRemote ? "supported github.com origin missing or unknown" : null,
3549
+ !observed.toolsAvailable ? "required tools missing or unknown" : null,
3550
+ !observed.platformSupported ? "host/platform unsupported or unknown" : null].filter(Boolean);
3551
+ deps.errorLog(`Epic Implementer setup blocked: ${missing.join("; ")}. Check the github.com origin and required tools; run gh auth login and claude auth login, then rerun install epic-implementer. Dependent changes remain unavailable${quietGeneralCommentary ? "." : "; general Bridge assets can be maintained separately."}`);
3552
+ }
3553
+ return { ...observed, available };
3554
+ }
3555
+ // ---------------------------------------------------------------------------
3556
+ // BAPI-1603: learned first
3557
+ // ---------------------------------------------------------------------------
3558
+ /**
3559
+ * The named outcome of the one stop this change adds. The first line of the
3560
+ * refusal, so it is greppable and survives into the machine-readable result.
3561
+ */
3562
+ export const REPOSITORY_NOT_LEARNED_OUTCOME = "repository_not_learned";
3563
+ /**
3564
+ * BAPI-1650: the named outcome for a saved key that needs the owner's one-time
3565
+ * approval at a non-production address. It outranks {@link REPOSITORY_NOT_LEARNED_OUTCOME}.
3566
+ */
3567
+ export const CREDENTIAL_ENDPOINT_UNAPPROVED_OUTCOME = "credential_endpoint_unapproved";
3568
+ /** The fixed id of the one blocking item that carries the owner's bind command. */
3569
+ export const CREDENTIAL_ENDPOINT_APPROVAL_ITEM_ID = "local.credential-endpoint-approval";
3570
+ /**
3571
+ * BAPI-1657: the default profile for a bind command the owner has not given one. It
3572
+ * comes from the repository segment after the last `/`, never the checkout directory.
3573
+ * Invalid characters become `-`, edge hyphens are trimmed, and the result is capped at
3574
+ * 57 characters. An empty or unusable name falls back to `local`.
3575
+ */
3576
+ export function generatedLaunchProfileName(repoName) {
3577
+ const segment = repoName.split("/").pop() ?? "";
3578
+ const normalized = segment
3579
+ .toLowerCase()
3580
+ .replace(/[^a-z0-9._-]/g, "-")
3581
+ .replace(/^-+|-+$/g, "")
3582
+ .slice(0, 57);
3583
+ return EPIC_LAUNCH_PROFILE_NAME_PATTERN.test(normalized) ? normalized : "local";
3584
+ }
3585
+ /**
3586
+ * Build the bind command through the CLI's own launcher. A nonblank `BAPI_MCP_CLI`
3587
+ * stays a command prefix (never quoted as a whole); otherwise the detected launcher,
3588
+ * then the published package. The profile follows `--launch-profile`, then
3589
+ * `BAPI_EPIC_LAUNCH_PROFILE`, then the generated default from the repository name.
3590
+ * Profile and target are quoted independently. No key value is read or printed.
3591
+ */
3592
+ async function endpointApprovalCommand(deps, options, approval) {
3593
+ const override = deps.env.BAPI_MCP_CLI?.trim();
3594
+ let base;
3595
+ if (override !== undefined && override !== "") {
3596
+ base = override.split(/\s+/).join(" ");
3597
+ }
3598
+ else {
3599
+ base = await detectedLauncherBase(deps, approval.repoName);
3600
+ }
3601
+ const profile = explicitLaunchProfile(deps, options) ?? generatedLaunchProfileName(approval.repoName);
3602
+ return `${base} install epic-implementer --launch-profile ${shellQuote(profile)} --base-url ${shellQuote(approval.target)}`;
3603
+ }
3604
+ /** The launch profile the owner supplied, from `--launch-profile` or then `BAPI_EPIC_LAUNCH_PROFILE`. */
3605
+ function explicitLaunchProfile(deps, options) {
3606
+ const fromEnv = deps.env.BAPI_EPIC_LAUNCH_PROFILE?.trim();
3607
+ return options.launchProfile ?? (fromEnv !== undefined && fromEnv !== "" ? fromEnv : undefined);
3608
+ }
3609
+ /** The one blocking item for an unapproved endpoint, with the command as one back-quoted span. */
3610
+ async function endpointApprovalItem(deps, options, approval) {
3611
+ const command = await endpointApprovalCommand(deps, options, approval);
3612
+ const generatedProfile = explicitLaunchProfile(deps, options) === undefined ? generatedLaunchProfileName(approval.repoName) : null;
3613
+ const profileNote = generatedProfile === null
3614
+ ? ""
3615
+ : ` \`${generatedProfile}\` is the name this approval is saved under on this computer; to launch an epic against this server later, pass \`--launch-profile ${generatedProfile}\`.`;
3616
+ return {
3617
+ id: CREDENTIAL_ENDPOINT_APPROVAL_ITEM_ID,
3618
+ label: "Saved Bridge key approval for this address",
3619
+ state: "needs_action",
3620
+ blocking: true,
3621
+ remedy: `Your saved Bridge key cannot safely be used at ${approval.target} until you approve that address once. ` +
3622
+ "Sending it to an address you have not approved could hand your key to the wrong server. " +
3623
+ `In your own terminal, run \`${command}\`, answer yes to the one-time approval question, ` +
3624
+ `then run /install-epic-implementer again.${profileNote}`,
3625
+ };
3626
+ }
3627
+ /** Report the approval stop: the greppable token first, then the plain reason. */
3628
+ function reportCredentialEndpointUnapproved(deps) {
3629
+ deps.errorLog(CREDENTIAL_ENDPOINT_UNAPPROVED_OUTCOME);
3630
+ deps.errorLog("Your saved Bridge key has not been approved for this address yet.");
3631
+ }
3632
+ /** Print the plain stop for a repository that has not been (fully) learned. */
3633
+ function reportRepositoryNotLearned(deps, fieldsSet) {
3634
+ deps.errorLog(REPOSITORY_NOT_LEARNED_OUTCOME);
3635
+ deps.errorLog(fieldsSet > 0
3636
+ ? "Bridge has not finished learning this repository."
3637
+ : "Bridge has not learned this repository yet.");
3638
+ deps.errorLog(`${fieldsSet > 0 ? "Finish" : "Run"} /learn-repository in Claude Code, wait for it to finish, then run this ` +
3639
+ "setup again. Bridge needs your project's standards to write useful code.");
3640
+ }
3641
+ /**
3642
+ * Read whether the repository has been learned. Returns `true` only for a
3643
+ * validated `learned: false`. An unknown reading (an older server, a 503, a bad
3644
+ * body, a failed transport) warns once and returns `false`: an unknown never
3645
+ * becomes a stop.
3646
+ */
3647
+ async function repositoryNotLearned(deps, access) {
3648
+ const learning = await fetchConductorRepositoryLearning(access, deps.fetchJson);
3649
+ if (learning.status === "unknown") {
3650
+ deps.log("Bridge could not check whether this repository has been learned, so setup continues. If you have not " +
3651
+ "run /learn-repository in Claude Code yet, run it.");
3652
+ return false;
3653
+ }
3654
+ if (learning.learned)
3655
+ return false;
3656
+ reportRepositoryNotLearned(deps, learning.learned_fields_set);
3657
+ return true;
3658
+ }
3659
+ // ---------------------------------------------------------------------------
3660
+ // BAPI-1603: the test command, proven by the server's trial
3661
+ // ---------------------------------------------------------------------------
3662
+ /** What file detection found, as optional hints for the server. Detection never stores anything. */
3663
+ async function learnedCommandHints(setup, access) {
3664
+ let detection;
3665
+ try {
3666
+ detection = await detectTestCommand({ skipStoredRead: true }, { config: setup.testingConfig(access), readFile: (relPath) => setup.readRepositoryFile(relPath) });
3667
+ }
3668
+ catch {
3669
+ return [];
3670
+ }
3671
+ if (detection.status === "failed")
3672
+ return [];
3673
+ // The command text is sent as detected. A command that belongs to a
3674
+ // subdirectory is named as one in its source, and is never rewritten into a
3675
+ // guessed root command.
3676
+ return detection.candidates.map((candidate) => ({
3677
+ command: candidate.command,
3678
+ source: candidate.workingDirectory !== undefined && candidate.workingDirectory !== "."
3679
+ ? `${candidate.provenance}; directory ${candidate.workingDirectory}`
3680
+ : candidate.provenance,
3681
+ }));
3682
+ }
3683
+ /**
3684
+ * Ask the server for the learned (or the owner's) test command and prove it.
3685
+ *
3686
+ * Runs only after the initial gate write, bound to the gate's refreshed revision:
3687
+ * the server's promotion then adds the local member to the stored profile and keeps
3688
+ * the watched checks. An automatic trial is allowed only for a newly inferred plan;
3689
+ * a `--test-command` goes through the same route as the owner's command, on any
3690
+ * gate. Nothing here writes a local member, and an uncertain outcome is reported,
3691
+ * never retried.
3692
+ */
3693
+ async function runTestCommandPhase(deps, options, setup, access, baseUrl, state, gatePlan, policyResult,
3694
+ /**
3695
+ * BAPI-1638 — the approved `test_command` answer. `learn` runs the bounded
3696
+ * discovery-and-promotion trial; `skip`/`keep` run nothing; a command is the
3697
+ * owner's own. Absent keeps the flag-and-inference rule below.
3698
+ */
3699
+ answer) {
3700
+ if (answer !== undefined && (answer.decision === "skip" || answer.decision === "keep"))
3701
+ return;
3702
+ const ownerCommand = answer?.decision === "command" ? answer.command : options.testCommand;
3703
+ const automatic = ownerCommand === undefined && gatePlan?.inferred?.trialEligible === true;
3704
+ if (ownerCommand === undefined && !automatic)
3705
+ return;
3706
+ deps.log("");
3707
+ deps.log("Test command");
3708
+ let current;
3709
+ try {
3710
+ current = await fetchConductorGateProfile(access, deps.fetchJson);
3711
+ }
3712
+ catch {
3713
+ deps.log(" skipped — the stored gate could not be read, so nothing was started.");
3714
+ return;
3715
+ }
3716
+ // A policy change the owner deferred only holds the trial back when it WAS the gate the
3717
+ // command attaches to; an unrelated deferral never stops a confirmed gate's command proof.
3718
+ if ((policyResult?.status === "deferred" || policyResult?.status === "unknown") && !current.confirmed) {
3719
+ deps.log(" skipped — the gate and defaults were not stored, so there is no stored gate to attach a proven command to.");
3720
+ return;
3721
+ }
3722
+ const candidates = automatic ? await learnedCommandHints(setup, access) : undefined;
3723
+ const io = gateIoFor(deps);
3724
+ const trialGateDeps = deps.gate !== undefined && deps.progressTimer !== undefined && deps.gate.progressTimer === undefined
3725
+ ? { ...deps.gate, progressTimer: deps.progressTimer }
3726
+ : deps.gate;
3727
+ const result = await runLearnedTestCommandTrial(io, access, trialGateDeps, {
3728
+ baseUrl,
3729
+ current,
3730
+ ...(candidates !== undefined ? { candidates } : {}),
3731
+ ...(ownerCommand !== undefined ? { ownerCommand } : {}),
3732
+ });
3733
+ reportLearnedCommandTrial(io, result);
3734
+ state.trial = result;
3735
+ if (result.status === "uncertain")
3736
+ state.commandUncertain = true;
3737
+ if (result.status === "promoted")
3738
+ state.promotedCommands = result.commands;
3739
+ }
3740
+ /**
3741
+ * Settle the inferred CI plan once the trial is known, and print its plain
3742
+ * explanation once. Only an inferred plan has one: a stored or explicit gate keeps
3743
+ * its own provenance. `none` needs both no reported checks AND no proven command,
3744
+ * and an unknown completion is never described as `none`.
3745
+ */
3746
+ function settleCiPlan(deps, state, gatePlan) {
3747
+ const inferred = gatePlan?.inferred;
3748
+ if (inferred === undefined || inferred.storedUnreadable)
3749
+ return;
3750
+ // Unknown CI history stored nothing and ran no trial: there is no plan to describe.
3751
+ if (!inferred.trialEligible && inferred.reportedChecks.length === 0)
3752
+ return;
3753
+ const promoted = state.trial?.status === "promoted";
3754
+ if (inferred.reportedChecks.length > 0) {
3755
+ state.ciPlan = "watched";
3756
+ }
3757
+ else if (promoted) {
3758
+ state.ciPlan = "local";
3759
+ }
3760
+ else if (state.commandUncertain) {
3761
+ return;
3762
+ }
3763
+ else {
3764
+ state.ciPlan = "none";
3765
+ }
3766
+ for (const reason of inferred.reasons) {
3767
+ if (state.ciPlan !== "none")
3768
+ deps.log(reason);
3769
+ }
3770
+ if (state.ciPlan === "none") {
3771
+ deps.log("");
3772
+ // BAPI-1654: "no CI" is said only when no CI files exist. No reported checks is not no CI.
3773
+ const systems = state.ciSystems ?? [];
3774
+ deps.log(systems.length > 0
3775
+ ? `Bridge found CI configuration (${[...new Set(systems.map((s) => s.name))].join(", ")}) but no checks have ` +
3776
+ "reported from it yet, and it could not prove a test command. Child pull requests will merge into the epic " +
3777
+ "branch without a test gate. You review everything in the final pull request."
3778
+ : "Bridge found no CI and could not prove a test command. Child pull requests will merge into the epic " +
3779
+ "branch without a test gate. You review everything in the final pull request.");
3780
+ }
3781
+ }
3782
+ // ---------------------------------------------------------------------------
3783
+ // BAPI-1603: Bridge's own workflow, an option on a proven local plan
3784
+ // ---------------------------------------------------------------------------
3785
+ /** The review default a managed-gate write leaves alone: it changes the gate only. */
3786
+ const MANAGED_WRITE_REVIEW_DEFAULT = { kind: "preserve", basis: "stored", stored: null };
3787
+ /**
3788
+ * The one yes/no about CI: add Bridge's GitHub workflow. Default No. Asked at most
3789
+ * once per invocation; No, Enter, and a deferred or unanswerable question all leave
3790
+ * the plan local, open no pull request, and store no permanent decline.
3791
+ */
3792
+ async function offerManagedWorkflow(deps) {
3793
+ let readFailed = false;
3794
+ const read = deps.promptLine;
3795
+ const decision = await askPlainSetupQuestion({
3796
+ question: "Also add Bridge's GitHub workflow, so your tests also run on GitHub for each epic pull request?",
3797
+ options: [
3798
+ { id: "yes", label: "Add the workflow (a setup pull request you review and merge)", aliases: ["y"] },
3799
+ { id: "no", label: "Keep the local test gate only", aliases: ["n"] },
3800
+ ],
3801
+ // Opening a pull request is consequential, so the safe answer stays No.
3802
+ recommended: "no",
3803
+ recordingFlag: "no flag records this choice; rerun setup in an interactive terminal to be asked again.",
3804
+ evidence: [
3805
+ "Bridge already runs your proven test command before each merge, so the gate works without it.",
3806
+ "The workflow runs the same command on GitHub, only for pull requests into epic branches.",
3807
+ ],
3808
+ consequences: [
3809
+ "Yes opens a setup pull request built from a clean copy of your default branch. You merge it yourself.",
3810
+ "Once the pull request is open, Bridge adds the workflow's check to the gate and checks the gate again.",
3811
+ ],
3812
+ recovery: "Run setup again to be asked once more.",
3813
+ }, {
3814
+ read: read === undefined
3815
+ ? undefined
3816
+ : async (promptText) => {
3817
+ try {
3818
+ return await read(promptText);
3819
+ }
3820
+ catch (error) {
3821
+ readFailed = true;
3822
+ throw error;
3823
+ }
3824
+ },
3825
+ write: deps.log,
3826
+ isTTY: deps.isTTY,
3827
+ });
3828
+ if (decision.status === "selected" && decision.id === "yes")
3829
+ return true;
3830
+ if (decision.status === "defer" && (read === undefined || readFailed || deps.isTTY !== true)) {
3831
+ deps.log(" The workflow was not added because nobody could answer.");
3832
+ }
3833
+ else {
3834
+ deps.log(" Kept the local test gate only. No workflow was added.");
3835
+ }
3836
+ return false;
3837
+ }
3838
+ /**
3839
+ * After the setup pull request is open: add the workflow's check to the CURRENT
3840
+ * gate (so the server-promoted local member and any watched checks are kept),
3841
+ * through the same revision-aware policy writer, then qualify the new revision
3842
+ * with the short-lived executor. Managed readiness is claimed only after a
3843
+ * validated passing qualification; a failure or an uncertain answer keeps the
3844
+ * authoritative state and says why.
3845
+ */
3846
+ async function promoteManagedGate(deps, options, access, baseUrl, state,
3847
+ /**
3848
+ * BAPI-1638 — adding the workflow's check to the gate is part of the approved
3849
+ * setup-PR effect, so an approved `setup_pr` answer applies it with no terminal.
3850
+ */
3851
+ decision) {
3852
+ deps.log("");
3853
+ deps.log("Gate");
3854
+ let fresh;
3855
+ try {
3856
+ fresh = await fetchConductorGateProfile(access, deps.fetchJson);
3857
+ }
3858
+ catch {
3859
+ deps.log(" The stored gate could not be read, so Bridge's workflow check was not added. The local test gate stays as it is.");
3860
+ return;
3861
+ }
3862
+ const plan = planManagedProviderGate(fresh, EPIC_IMPLEMENTER_CI_CHECK_NAME);
3863
+ if (plan !== null) {
3864
+ const written = await fixGateAndDefaults(deps, options, access, plan, MANAGED_WRITE_REVIEW_DEFAULT, true, decision);
3865
+ if (written.status === "deferred" || written.status === "unknown") {
3866
+ deps.log(" Bridge's workflow check was not added to the gate. The local test gate stays as it is.");
3867
+ return;
3868
+ }
3869
+ }
3870
+ state.ciPlan = "managed";
3871
+ let after;
3872
+ try {
3873
+ after = await fetchConductorGateProfile(access, deps.fetchJson);
3874
+ }
3875
+ catch {
3876
+ deps.log(" The gate could not be read after the change, so Bridge did not check it again and does not call the workflow ready.");
3877
+ return;
3878
+ }
3879
+ if (after.profile === null || after.profile.local_commands.length === 0)
3880
+ return;
3881
+ const report = await runConductorGateQualification(gateIoFor(deps), access, deps.gate, {
3882
+ revision: after.revision,
3883
+ baseUrl,
3884
+ });
3885
+ if (report === "qualified") {
3886
+ deps.log(" Bridge's workflow check is part of the gate, and the gate passed its check at the new revision.");
3887
+ }
3888
+ else {
3889
+ deps.log(" Bridge's workflow is set up, but the gate has not passed its check at the new revision, so Bridge does not call it ready.");
3890
+ }
3891
+ }
3892
+ /**
3893
+ * The optional managed workflow, in one place: assess it against the remote
3894
+ * default branch with the command the gate now holds, upgrade an installed Bridge
3895
+ * workflow that differs, or offer a first one once (a proven single-command local
3896
+ * plan with no CI of its own, never an explicit gate request, never a watched or
3897
+ * `none` plan). The check is added to the gate only after the installer opened or
3898
+ * reused the setup pull request. A command whose proof is unknown, a missing
3899
+ * snapshot, or an installer failure skips only this step.
3900
+ */
3901
+ async function runWorkflowPhase(deps, options, setup, access, baseUrl, state, readToolchains, gateRequiresManagedCheck,
3902
+ /** BAPI-1638 — the approved `setup_pr` answer. Absent keeps today's questions. */
3903
+ setupPrDecision) {
3904
+ const none = { status: "none" };
3905
+ if (state.evidence.githubSignIn !== "signed_in" || state.repository === null)
3906
+ return none;
3907
+ if (state.commandUncertain) {
3908
+ deps.log("");
3909
+ deps.log("CI workflow");
3910
+ deps.log(" skipped — it is built from the test command, and Bridge cannot tell yet whether that command was stored.");
3911
+ return { status: "unattempted", reason: "Bridge cannot tell yet whether the test command was stored" };
3912
+ }
3913
+ // The setup PR's effect is conditional: it opens only if the approved check passed.
3914
+ const trial = state.trial;
3915
+ if (setupPrDecision === "approve" && trial !== null && trial.status !== "promoted" && trial.status !== "not_needed") {
3916
+ const phase = "evidence" in trial && trial.evidence !== undefined ? trial.evidence.phase : null;
3917
+ deps.log("");
3918
+ deps.log("CI workflow");
3919
+ // BAPI-1657: the owner never sees the raw `no_command` token; the plain reason stands in for it.
3920
+ deps.log(trial.status === "no_command"
3921
+ ? ` not opened — the setup pull request opens only if the test-command check passes, and ${NO_TEST_COMMAND_REASON}.`
3922
+ : ` not opened — the setup pull request opens only if the test-command check passes, and it did not (${trial.status}${phase !== null ? `, phase ${phase}` : ""}).`);
3923
+ const reason = trial.status === "no_command" ? NO_TEST_COMMAND_REASON : `the test-command check did not pass (${trial.status})`;
3924
+ return { status: "declined", reason, phase };
3925
+ }
3926
+ let profile = null;
3927
+ try {
3928
+ profile = await fetchConductorGateProfile(access, deps.fetchJson);
3929
+ }
3930
+ catch {
3931
+ profile = null;
3932
+ }
3933
+ if (profile === null || !profile.confirmed || profile.profile === null)
3934
+ return none;
3935
+ // The command the workflow runs is the one the server proved this run, else the stored one.
3936
+ let command = state.promotedCommands?.length === 1 ? state.promotedCommands[0].command : null;
3937
+ if (command === null) {
3938
+ try {
3939
+ const read = await readStoredTestCommand(setup.testingConfig(access));
3940
+ if (read.ok)
3941
+ command = read.testCommand;
3942
+ }
3943
+ catch {
3944
+ command = null;
3945
+ }
3946
+ }
3947
+ if (command === null)
3948
+ return none;
3949
+ const toolchains = await readToolchains();
3950
+ state.toolchains = toolchains;
3951
+ // The first read already assessed the workflow against this very command when no
3952
+ // trial changed it this run; only a command that may have changed is assessed again.
3953
+ const assessed = state.trial === null && command === state.storedCommand && state.evidence.workflow.state !== "unknown"
3954
+ ? state.evidence.workflow
3955
+ : await assessWorkflow(setup, command, toolchains, state.snapshot, true);
3956
+ state.evidence = { ...state.evidence, workflow: assessed };
3957
+ const localOnly = profile.profile.kind === "local" &&
3958
+ profile.profile.provider_checks.length === 0 &&
3959
+ (profile.profile.watched_checks ?? []).length === 0;
3960
+ const oneCommand = profile.profile.local_commands.length === 1;
3961
+ const offerEligible = localOnly &&
3962
+ !hasExplicitGateInput(options.gate) &&
3963
+ (assessed.state === "absent" || assessed.state === "pr_open");
3964
+ let install = false;
3965
+ if (assessed.state === "needs_pr" || (assessed.state === "absent" && gateRequiresManagedCheck)) {
3966
+ // An installed Bridge workflow that differs is offered as an upgrade, and a gate that
3967
+ // already requires the workflow's check needs the workflow itself: the installer's own
3968
+ // consent is the only question.
3969
+ install = true;
3970
+ }
3971
+ else if (offerEligible) {
3972
+ if (!oneCommand) {
3973
+ deps.log("");
3974
+ deps.log("CI workflow");
3975
+ deps.log(" not offered — the workflow runs one command and this gate has more than one.");
3976
+ return none;
3977
+ }
3978
+ try {
3979
+ validateTestCommand(command);
3980
+ }
3981
+ catch (error) {
3982
+ if (!(error instanceof TestCommandValidationError))
3983
+ throw error;
3984
+ deps.log("");
3985
+ deps.log("CI workflow");
3986
+ deps.log(" not offered — the workflow cannot run this test command as written (one line, no GitHub Actions expression, at most 500 characters).");
3987
+ return none;
3988
+ }
3989
+ install = setupPrDecision !== undefined ? setupPrDecision === "approve" : await offerManagedWorkflow(deps);
3990
+ if (setupPrDecision === "decline")
3991
+ deps.log(" Kept the local test gate only. No workflow was added.");
3992
+ }
3993
+ if (!install)
3994
+ return setupPrDecision === "decline" ? { status: "declined" } : none;
3995
+ const outcome = await fixSetupPullRequest(deps, setup, command, toolchains, state.snapshot, state.repository, setupPrDecision === undefined ? undefined : setupPrDecision === "approve");
3996
+ state.evidence = { ...state.evidence, workflow: outcome.workflow };
3997
+ const result = outcome.result;
3998
+ const opened = result !== null &&
3999
+ (result.outcome === "installed-pr-opened" || result.outcome === "upgrade-pr-opened" || result.outcome === "existing-pr");
4000
+ // Only a first workflow adds the managed check; an upgrade of an installed one does not touch the gate.
4001
+ if (opened && offerEligible) {
4002
+ await promoteManagedGate(deps, options, access, baseUrl, state, setupPrDecision === "approve" ? "approve" : undefined);
4003
+ }
4004
+ if (result === null)
4005
+ return { status: "failed", reason: "the setup pull request could not be prepared" };
4006
+ switch (result.outcome) {
4007
+ case "installed-pr-opened":
4008
+ case "upgrade-pr-opened":
4009
+ return { status: "written", url: result.prUrl };
4010
+ case "existing-pr":
4011
+ return { status: "unchanged", url: result.prUrl };
4012
+ case "identical":
4013
+ return { status: "unchanged" };
4014
+ case "dry-run":
4015
+ return none;
4016
+ case "failed":
4017
+ return result.reason === "consent_declined" ? { status: "declined" } : { status: "failed", reason: result.reason };
4018
+ }
4019
+ }
4020
+ /**
4021
+ * Warn, never stop, when the default branch's rules require the managed workflow's
4022
+ * check. The workflow runs only for pull requests into `epic/**`, so the final
4023
+ * pull request into the default branch would wait for a check that never starts.
4024
+ * Any inspection that gives no reliable answer is silent: unknown is not "no rule".
4025
+ */
4026
+ async function warnDefaultBranchRequiresManagedCheck(setup, state) {
4027
+ if (state.repository === null || state.evidence.githubSignIn !== "signed_in")
4028
+ return;
4029
+ const runGh = setup.runGh;
4030
+ const found = await readDefaultBranchRequiredChecksViaGh(async (args) => {
4031
+ const result = await runGh(args);
4032
+ return { exitCode: result.status ?? 1, stdout: result.stdout, stderr: result.stderr };
4033
+ }, state.repository, state.snapshot?.defaultBranch);
4034
+ if (found.status !== "known" || !found.requiredChecks.includes(EPIC_IMPLEMENTER_CI_CHECK_NAME))
4035
+ return;
4036
+ state.evidence.advisories.push(`Your rules for ${found.defaultBranch} require \`${EPIC_IMPLEMENTER_CI_CHECK_NAME}\`. Bridge's workflow runs only ` +
4037
+ `for pull requests into epic branches, so the final pull request into ${found.defaultBranch} would wait for a ` +
4038
+ "check that never starts. Remove that required check from the branch protection rule or ruleset that applies to it.");
4039
+ }
4040
+ /** Whether Bridge's own workflow is in play, so its default-branch rule warning can matter. */
4041
+ function managedWorkflowInPlay(state, gateRequiresManagedCheck) {
4042
+ const workflow = state.evidence.workflow.state;
4043
+ return (state.ciPlan === "managed" ||
4044
+ gateRequiresManagedCheck ||
4045
+ workflow === "installed" ||
4046
+ workflow === "pr_open" ||
4047
+ workflow === "needs_pr");
4048
+ }
4049
+ /** What a dry run says about the CI plan: conditional outcomes, nothing requested or started. */
4050
+ function renderDryRunCiPlan(deps, options, gatePlan) {
4051
+ deps.log("");
4052
+ if (options.testCommand !== undefined) {
4053
+ deps.log(" Test command: a real run offers your --test-command to Bridge's server and proves it by running it once on " +
4054
+ "this computer. Dry run requested nothing and started nothing.");
4055
+ }
4056
+ else if (gatePlan?.inferred?.trialEligible === true) {
4057
+ deps.log(" Test command: a real run asks Bridge's server to learn it from this repository and proves it by running it " +
4058
+ "once on this computer, and nobody is asked for it. Dry run requested nothing and started nothing.");
4059
+ }
4060
+ const inferred = gatePlan?.inferred;
4061
+ if (inferred !== undefined && !inferred.storedUnreadable) {
4062
+ deps.log(inferred.reportedChecks.length > 0
4063
+ ? ` CI plan: watch the ${inferred.reportedChecks.length} check(s) your CI already reports. A local test gate ` +
4064
+ "is added only if the command passes."
4065
+ : " CI plan: no CI reported. A local test gate is stored only if the command passes; otherwise the gate has " +
4066
+ "no members.");
4067
+ deps.log(" Bridge's workflow: offered once, only for a proven local plan, and only added if you say yes and the setup " +
4068
+ "pull request opens. Dry run asked nothing and opened nothing.");
4069
+ }
4070
+ }
4071
+ /** Read the folder's project binding. Only an absent file counts as "not bound". */
4072
+ async function resolveFolderBinding(deps) {
4073
+ const read = await readBridgeConfig(deps.cwd, {
4074
+ readFile: deps.readBindingFile ?? ((filePath) => readFileAsync(filePath, "utf-8")),
4075
+ });
4076
+ if (read.ok)
4077
+ return { status: "bound", repo: read.manifest.repoName };
4078
+ return read.kind === "missing" ? { status: "absent" } : { status: "unresolved" };
4079
+ }
4080
+ // ---------------------------------------------------------------------------
4081
+ // BAPI-1638: decision evidence and the shared apply's adapters
4082
+ // ---------------------------------------------------------------------------
4083
+ // ---------------------------------------------------------------------------
4084
+ // BAPI-1654: the CI change setup can offer (read-only)
4085
+ // ---------------------------------------------------------------------------
4086
+ /** The domain-separated identity of a file that does not exist yet. Never the hash of an empty file. */
4087
+ export function absentSourceSha256(path) {
4088
+ return sha256Hex(`bapi-ci-absent-source/v1\u0000${path}`);
4089
+ }
4090
+ /**
4091
+ * Collect the CI change on offer, from the remote default-branch snapshot (the
4092
+ * same head the pull request is built from), never from the person's checkout.
4093
+ * At most one remedy: none when coverage is confirmed, else one eligible trigger
4094
+ * edit, else Bridge's managed workflow when a stored test command is known.
4095
+ * Read-only.
4096
+ */
4097
+ async function collectCiOffer(input) {
4098
+ const { setup, state, collected } = input;
4099
+ const ciSystems = state.ciSystems === undefined ? undefined : state.ciSystems === null ? null : state.ciSystems.map((c) => ({ name: c.name, path: c.path }));
4100
+ const base = { evidence: { ...(ciSystems !== undefined ? { ciSystems } : {}) }, delivery: null };
4101
+ if (collected === undefined || collected.status !== "collected")
4102
+ return base;
4103
+ const snapshot = state.snapshot;
4104
+ const read = setup.readSnapshotFile;
4105
+ const coverage = collected.coverage;
4106
+ const sources = new Map();
4107
+ const classified = [];
4108
+ const epicResults = [];
4109
+ const targetCoverages = [];
4110
+ let unread = false;
4111
+ const paths = [...new Set(coverage.workflows.map((w) => w.path))].sort();
4112
+ if (snapshot !== null && read !== undefined) {
4113
+ for (const path of paths) {
4114
+ let text;
4115
+ try {
4116
+ text = await read(snapshot, path);
4117
+ }
4118
+ catch {
4119
+ text = null;
4120
+ }
4121
+ if (typeof text !== "string") {
4122
+ unread = true;
4123
+ continue;
4124
+ }
4125
+ sources.set(path, text);
4126
+ classified.push(GITHUB_ACTIONS_TRIGGER_ADAPTER.classify(path, text));
4127
+ const body = text.startsWith("\uFEFF") ? text.slice(1) : text;
4128
+ epicResults.push({ path, ...classifyEpicPullRequestTrigger(body) });
4129
+ targetCoverages.push(classifyEpicPullRequestTrigger(body, { targetBranch: snapshot.defaultBranch }).coverage);
4130
+ }
4131
+ }
4132
+ // Snapshot-bound coverage: when every listed workflow was read at the default-branch head, its
4133
+ // bytes decide, not the person's checkout. Otherwise the inspection's own answer stands.
4134
+ const snapshotComplete = snapshot !== null && read !== undefined && !unread && paths.length > 0 && coverage.reason !== "file_limit_reached";
4135
+ const epicCoverages = epicResults.map((r) => r.coverage);
4136
+ const excludedWorkflows = (snapshotComplete ? epicResults : coverage.workflows)
4137
+ .filter((w) => w.coverage === "does_not_cover" && w.reason === "branch_filter_excludes_epic")
4138
+ .map((w) => {
4139
+ const c = classified.find((x) => x.path === w.path);
4140
+ const branches = c === undefined ? null : c.kind === "eligible" ? c.edit.branchesBefore : c.kind === "ineligible" ? c.branches : null;
4141
+ return { path: w.path, branches };
4142
+ });
4143
+ const integrationTarget = snapshot === null || read === undefined
4144
+ ? null
4145
+ : {
4146
+ branch: snapshot.defaultBranch,
4147
+ coverage: (targetCoverages.includes("covers")
4148
+ ? "covers"
4149
+ : unread || targetCoverages.includes("could_not_tell") || coverage.coverage === "could_not_tell"
4150
+ ? "could_not_tell"
4151
+ : "does_not_cover"),
4152
+ };
4153
+ const effectiveCoverage = !snapshotComplete
4154
+ ? coverage.coverage
4155
+ : epicCoverages.includes("covers") ? "covers" : epicCoverages.includes("could_not_tell") ? "could_not_tell" : "does_not_cover";
4156
+ const evidence = {
4157
+ ...base.evidence, excludedWorkflows, integrationTarget, ciOffer: null,
4158
+ ...(snapshotComplete ? { coverage: effectiveCoverage } : {}),
4159
+ };
4160
+ if (effectiveCoverage === "covers") {
4161
+ // A replay: an approved change already in place keeps its identity, so the same answers hash the same.
4162
+ for (const [path, text] of sources) {
4163
+ const applied = recognizeAppliedEdit(path, text);
4164
+ if (applied !== null) {
4165
+ evidence.ciOffer = {
4166
+ identity: { action_class: "trigger_edit", path, source_sha256: applied.sourceSha256, patch_sha256: applied.patchSha256 },
4167
+ applicable: false,
4168
+ branchesBefore: applied.branchesBefore,
4169
+ };
4170
+ return { evidence, delivery: null };
4171
+ }
4172
+ }
4173
+ const managed = await managedWorkflowIdentity(input, "installed");
4174
+ if (managed !== null)
4175
+ evidence.ciOffer = { identity: managed.identity, applicable: false };
4176
+ return { evidence, delivery: null };
4177
+ }
4178
+ if (setup.installCiTriggerEdit !== undefined) {
4179
+ const edit = selectTriggerEdit(classified, sources, state.storedCommand);
4180
+ if (edit !== null) {
4181
+ evidence.ciOffer = {
4182
+ identity: { action_class: "trigger_edit", path: edit.path, source_sha256: edit.sourceSha256, patch_sha256: edit.patchSha256 },
4183
+ applicable: true,
4184
+ branchesBefore: edit.branchesBefore,
4185
+ };
4186
+ return { evidence, delivery: { kind: "trigger_edit", edit } };
4187
+ }
4188
+ }
4189
+ // BAPI-1659: offered whether or not the setup pull request could also add the workflow. The CI
4190
+ // choice delivers it on its own; when both are approved the installer reuses the one open pull request.
4191
+ const managed = await managedWorkflowIdentity(input, "absent");
4192
+ if (managed !== null) {
4193
+ evidence.ciOffer = { identity: managed.identity, applicable: true };
4194
+ return { evidence, delivery: { kind: "managed_workflow", command: managed.command, toolchains: managed.toolchains } };
4195
+ }
4196
+ return { evidence, delivery: null };
4197
+ }
4198
+ /**
4199
+ * The managed fallback's identity: the absent-source marker and the hash of the
4200
+ * renderer's exact output for the stored command and snapshot toolchains. Only
4201
+ * when the managed workflow is in the wanted state (`absent` to offer it,
4202
+ * `installed` for a replay), on a signed-in GitHub repository with a snapshot
4203
+ * and a valid stored command. The renderer itself is unchanged.
4204
+ */
4205
+ async function managedWorkflowIdentity(input, wanted) {
4206
+ const { state } = input;
4207
+ if (state.evidence.githubSignIn !== "signed_in" || state.repository === null || state.snapshot === null)
4208
+ return null;
4209
+ if (state.evidence.workflow.state !== wanted)
4210
+ return null;
4211
+ const command = state.storedCommand;
4212
+ if (command === null)
4213
+ return null;
4214
+ try {
4215
+ validateTestCommand(command);
4216
+ }
4217
+ catch {
4218
+ return null;
4219
+ }
4220
+ let resolution;
4221
+ try {
4222
+ resolution = await input.readToolchains();
4223
+ }
4224
+ catch {
4225
+ resolution = null;
4226
+ }
4227
+ if (resolution === null || resolution.status !== "resolved")
4228
+ return null;
4229
+ let rendered;
4230
+ try {
4231
+ rendered = renderEpicImplementerCiWorkflow(command, resolution.toolchains);
4232
+ }
4233
+ catch {
4234
+ return null;
4235
+ }
4236
+ return {
4237
+ identity: {
4238
+ action_class: "managed_workflow",
4239
+ path: EPIC_CI_WORKFLOW_PATH,
4240
+ source_sha256: absentSourceSha256(EPIC_CI_WORKFLOW_PATH),
4241
+ patch_sha256: sha256Hex(rendered),
4242
+ },
4243
+ command,
4244
+ toolchains: resolution.toolchains,
4245
+ };
4246
+ }
4247
+ /** Read-only: build the decision evidence every open choice is projected from. */
4248
+ async function collectDecisionEvidence(input) {
4249
+ const { deps, options, access, gatePlan, state, fixes, grantInventory } = input;
4250
+ const identity = {
4251
+ repo_name: access.repoName,
4252
+ provider_repository: state.repository,
4253
+ destination: access.baseUrl.replace(/\/+$/, ""),
4254
+ // Which binding supplied the key, never the key: the parent env first, then the store target.
4255
+ credential_binding: (deps.env.BAPI_API_KEY ?? "").trim().length > 0 ? "env:BAPI_API_KEY" : `credential_store:bapi:${access.repoName}`,
4256
+ };
4257
+ const desired = gatePlan?.desired ?? null;
4258
+ const ciFacts = input.firstReport.readiness?.epic_branch_ci ?? null;
4259
+ // The gate's own effect names only the members the gate write sets. A command the
4260
+ // learned trial promotes (`test_command`) and the managed check the setup PR adds
4261
+ // (`setup_pr`) are their own approved effects, so a replay after both hashes the same.
4262
+ // Explicit gate flags are the owner's literal members and are always named.
4263
+ const fromFlags = gatePlan?.origin === "flags";
4264
+ const gate = gatePlan === null || desired === null ? null : {
4265
+ writeNeeded: fixes.includes("gate_and_defaults"),
4266
+ kind: fromFlags ? desired.kind : null,
4267
+ providerChecks: desired.providerChecks.filter((c) => fromFlags || c !== EPIC_IMPLEMENTER_CI_CHECK_NAME),
4268
+ watchedChecks: [...(desired.watchedChecks ?? [])],
4269
+ localCommands: fromFlags ? desired.localCommands.map((c) => c.name) : [],
4270
+ origin: gatePlan.origin,
4271
+ consequence: describeGateConsequence({ kind: desired.kind, hasWatchedChecks: (desired.watchedChecks ?? []).length > 0 }, ciFacts),
4272
+ currentKind: gatePlan.current.profile?.kind ?? null,
4273
+ };
4274
+ const stored = gatePlan?.current.profile ?? null;
4275
+ const declarations = input.declarationPlan.map((entry) => ({ key: entry.key, summary: entry.summary, value: declarationValue(entry.fields) }));
4276
+ // A settled declaration still names its stored value, so a replay hashes the same.
4277
+ for (const [key, value] of [
4278
+ ["dependency_install", stored?.dependency_install],
4279
+ ["ci_database", stored?.ci_database],
4280
+ ["must_order_paths", stored?.must_order_paths],
4281
+ ["worker_database", stored?.worker_database],
4282
+ ]) {
4283
+ const empty = value === undefined || value === null || (Array.isArray(value) && value.length === 0) || value === "unknown";
4284
+ if (!empty && !declarations.some((d) => d.key === key))
4285
+ declarations.push({ key, summary: [], value: declarationValue({ [declarationField(key)]: value }), applicable: false });
4286
+ }
4287
+ const workflowState = state.evidence.workflow.state;
4288
+ const trialEligible = gatePlan?.inferred?.trialEligible === true;
4289
+ const recovery = state.evidence.recovery?.supported ? state.evidence.recovery.evidence : undefined;
4290
+ const branchQuestion = fixes.includes("reindex") && recovery !== undefined && recovery.destination_branch
4291
+ && (!["equal", "contains_target"].includes(recovery.configured_relation) || recovery.canonical_relation === "diverged")
4292
+ && !(recovery.destination_branch === recovery.provider_default
4293
+ && (recovery.configured_branch === null || recovery.configured_branch === "" || recovery.configured_branch === recovery.destination_branch))
4294
+ ? { configured: recovery.configured_branch, destination: recovery.destination_branch }
4295
+ : undefined;
4296
+ const retryQuestion = fixes.includes("reindex") && recovery?.request && !["queued", "in_progress"].includes(recovery.request.status ?? "") && recovery.retry_generation !== null
4297
+ ? { requestId: recovery.request.id, generation: recovery.retry_generation }
4298
+ : undefined;
4299
+ const label = (origin) => CANDIDATE_ORIGIN_LABEL[origin];
4300
+ const mcpGrant = grantInventory === null ? null : {
4301
+ current: state.evidence.mcpGrant?.state === "needs_action" ? state.evidence.mcpGrant.reason : state.evidence.mcpGrant?.state ?? "unknown",
4302
+ applicable: fixes.includes("mcp_grant"),
4303
+ candidates: grantInventory.candidates.flatMap((c) => c.definitions.map((d) => ({ id: d.id, name: c.name, origins: d.origins.map(label) }))),
4304
+ excluded: grantInventory.exclusions.map((e) => ({ name: e.name, origin: label(e.origin), reason: CANDIDATE_EXCLUSION_TEXT[e.reason] })),
4305
+ invalidExisting: grantInventory.existingGrant?.state === "ok"
4306
+ ? grantInventory.existingGrant.findings.map((f) => ({ name: f.name, reason: CANDIDATE_EXCLUSION_TEXT[f.reason] }))
4307
+ : [],
4308
+ fingerprint: grantInventory.fingerprint,
4309
+ };
4310
+ const epicServerEvidence = state.evidence.epicServer;
4311
+ const collected = input.epicBranchCollected;
4312
+ const ciOffer = input.ciOffer ?? null;
4313
+ return {
4314
+ identity,
4315
+ gate,
4316
+ declarations,
4317
+ testCommand: { stored: state.storedCommand !== null, trialEligible, ownerCommandSupplied: options.testCommand !== undefined },
4318
+ setupPr: {
4319
+ applicable: setupPrOffersWorkflow(input),
4320
+ workflowState,
4321
+ commandSource: trialEligible ? "learned" : state.storedCommand !== null ? "stored" : null,
4322
+ },
4323
+ mergeToken: {
4324
+ state: state.evidence.mergeCredential.state,
4325
+ storeTarget: state.identity !== null ? mergeTokenStoreTarget(state.identity) : null,
4326
+ },
4327
+ reindex: {
4328
+ planned: fixes.includes("reindex"),
4329
+ // Display only: an unknown or unverified index is never described as current.
4330
+ indexStatus: indexDisplayStatus(input.firstItems, state.evidence.index),
4331
+ ...(branchQuestion ? { branchQuestion } : {}), ...(retryQuestion ? { retryQuestion } : {}),
4332
+ },
4333
+ mcpGrant,
4334
+ epicServer: epicServerEvidence === undefined ? null : {
4335
+ current: epicServerEvidence.state === "met" ? epicServerEvidence.mode : null,
4336
+ applicable: fixes.includes("epic_server"),
4337
+ },
4338
+ // The decision readiness reports as recorded is shown on the choice only; it never sets
4339
+ // `recommended` or `applicable`, so it cannot move a digest.
4340
+ epicBranchCi: collected === undefined || collected.status === "skipped_no_seams" ? null : {
4341
+ ...(collected.status === "collected"
4342
+ ? { coverage: collected.coverage.coverage, approvalsRequired: collected.rules?.approvalsRequired ?? "could_not_tell", ownerRepo: collected.ownerRepo, recordedDecision: ciFacts?.decision ?? null }
4343
+ : { coverage: null, approvalsRequired: null, ownerRepo: null, recordedDecision: ciFacts?.decision ?? null }),
4344
+ // BAPI-1654: the CI change on offer and the facts the honest wording reads.
4345
+ ...(ciOffer !== null ? ciOffer.evidence : {}),
4346
+ ...(setupPrOffersWorkflow(input) && workflowState !== "installed" ? { managedWorkflowViaSetupPr: true } : {}),
4347
+ },
4348
+ launchProfile: { selected: options.launchProfile ?? null, notification: state.evidence.notification?.state ?? null },
4349
+ repositoryFacts: {
4350
+ ...(await collectRepositoryFacts(deps, grantInventory, input.readToolchains)),
4351
+ ...(state.ciSystems !== undefined
4352
+ ? { ci_systems: state.ciSystems === null ? null : state.ciSystems.map((c) => ({ name: c.name, path: c.path })) }
4353
+ : {}),
4354
+ },
4355
+ };
4356
+ }
4357
+ /**
4358
+ * Whether the setup pull request opens Bridge's own workflow this run (an
4359
+ * upgrade, a required workflow, or a first offer). A first workflow is offered
4360
+ * only on a proven local plan: an inferred `none` plan with no explicit gate
4361
+ * input (a watched plan already has CI of its own and is never offered one).
4362
+ */
4363
+ function setupPrOffersWorkflow(input) {
4364
+ const { options, gatePlan, state, fixes } = input;
4365
+ const workflowState = state.evidence.workflow.state;
4366
+ const trialEligible = gatePlan?.inferred?.trialEligible === true;
4367
+ return state.evidence.githubSignIn === "signed_in" && state.repository !== null
4368
+ && (fixes.includes("setup_pr") || (trialEligible && gatePlan?.inferred?.ciPlan === "none" && !hasExplicitGateInput(options.gate)
4369
+ && (workflowState === "absent" || workflowState === "unknown")));
4370
+ }
4371
+ function declarationField(key) {
4372
+ return key === "dependency_install" ? "dependencyInstall" : key === "ci_database" ? "ciDatabase" : key === "must_order_paths" ? "mustOrderPaths" : "workerDatabase";
4373
+ }
4374
+ /** The declaration's canonical value, for the digest. Worker-database credentials are names, never values. */
4375
+ function declarationValue(fields) {
4376
+ return JSON.parse(JSON.stringify(Object.values(fields)[0] ?? null));
4377
+ }
4378
+ /** Read-only repository facts: workflow branch filters, package manager and lockfile, MCP config names and origins. */
4379
+ async function collectRepositoryFacts(deps, grantInventory, readToolchains) {
4380
+ let ciWorkflows = null;
4381
+ const fs = deps.gate?.discoveryFs;
4382
+ if (fs !== undefined) {
4383
+ try {
4384
+ const entries = (await fs.listDir(".github/workflows")) ?? [];
4385
+ ciWorkflows = [];
4386
+ for (const name of [...entries].filter((n) => /^[^/\\]+\.ya?ml$/.test(n)).sort().slice(0, 50)) {
4387
+ const path = `.github/workflows/${name}`;
4388
+ let text = null;
4389
+ try {
4390
+ text = await fs.readText(path);
4391
+ }
4392
+ catch {
4393
+ text = null;
4394
+ }
4395
+ const filters = text === null ? { kind: "could_not_tell" } : readPullRequestBranchFilters(text);
4396
+ if (filters.kind === "filters")
4397
+ ciWorkflows.push({ path, pull_request_branches: filters.branches });
4398
+ }
4399
+ }
4400
+ catch {
4401
+ ciWorkflows = null;
4402
+ }
4403
+ }
4404
+ let packageManager = null;
4405
+ try {
4406
+ const resolution = await readToolchains();
4407
+ const js = resolution?.status === "resolved" ? resolution.toolchains.javascript : null;
4408
+ const py = resolution?.status === "resolved" ? resolution.toolchains.python : null;
4409
+ if (js !== null && js !== undefined)
4410
+ packageManager = { name: js.manager, lockfile: js.dependencyFile };
4411
+ else if (py !== null && py !== undefined)
4412
+ packageManager = { name: py.manager, lockfile: py.dependencyFile };
4413
+ }
4414
+ catch {
4415
+ packageManager = null;
4416
+ }
4417
+ let mcpConfigs = null;
4418
+ if (grantInventory !== null) {
4419
+ const seen = new Set();
4420
+ mcpConfigs = [];
4421
+ const push = (name, origin) => {
4422
+ const key = `${name}\u0000${origin}`;
4423
+ if (seen.has(key))
4424
+ return;
4425
+ seen.add(key);
4426
+ mcpConfigs.push({ name, origin });
4427
+ };
4428
+ for (const c of grantInventory.candidates)
4429
+ for (const d of c.definitions)
4430
+ for (const o of d.origins)
4431
+ push(c.name, CANDIDATE_ORIGIN_LABEL[o]);
4432
+ for (const e of grantInventory.exclusions)
4433
+ push(e.name, CANDIDATE_ORIGIN_LABEL[e.origin]);
4434
+ }
4435
+ return { ci_workflows: ciWorkflows, package_manager: packageManager, mcp_configs: mcpConfigs };
4436
+ }
4437
+ /** Merge the approved declarations into the gate plan, rebuilding its PUT from the same desired gate. */
4438
+ function applyApprovedDeclarations(plan, approved) {
4439
+ if (approved.length === 0)
4440
+ return plan;
4441
+ const desired = approved.reduce((acc, entry) => ({ ...acc, ...entry.fields }), plan.desired);
4442
+ return { ...plan, desired, write: confirmRequestFor(desired, plan.current.revision, plan.current.profile) };
4443
+ }
4444
+ /** A gate and declarations that already match: every approved one reports unchanged. */
4445
+ function settledGateResults(proposal) {
4446
+ return proposal.actions
4447
+ .filter((a) => (a.key === "gate" || DECLARATION_KEYS.includes(a.key)) && a.intent === "write")
4448
+ .map((a) => ({ key: a.key, status: "unchanged", target: a.effect?.target ?? "repository_gate" }));
4449
+ }
4450
+ const DECLARATION_KEYS = ["dependency_install", "ci_database", "must_order_paths", "worker_database"];
4451
+ function gateWriteResults(result, proposal, plan) {
4452
+ const readBack = result.current !== undefined ? { revision: result.current.state.revision } : undefined;
4453
+ const status = result.status === "completed" ? "written"
4454
+ : result.status === "unchanged" ? "unchanged"
4455
+ : result.status === "unknown" ? "uncertain"
4456
+ : result.declined ? "declined" : "refused";
4457
+ const gate = {
4458
+ key: "gate",
4459
+ status,
4460
+ target: "repository_gate",
4461
+ ...(readBack !== undefined ? { read_back: readBack } : {}),
4462
+ ...(status === "refused" ? { reason: "the policy was refused or changed after the preview", fix: "Rerun setup for a fresh proposal; nothing in the gate was written." } : {}),
4463
+ ...(status === "uncertain" ? { reason: "the policy write could not be confirmed by reading it back", fix: "Read the gate with `epic-implementer doctor` before retrying; setup did not retry blindly." } : {}),
4464
+ };
4465
+ if (proposal === null)
4466
+ return [gate];
4467
+ const declarations = plan.map((entry) => {
4468
+ const decision = decisionFor(proposal, entry.key);
4469
+ const approved = decision?.kind === "option" && decision.option === "approve";
4470
+ return {
4471
+ key: entry.key,
4472
+ status: !approved ? "declined" : status === "declined" ? "unattempted" : status,
4473
+ target: `repository_gate.${entry.key}`,
4474
+ ...(approved && status === "declined" ? { reason: "the gate it is stored with was declined" } : {}),
4475
+ };
4476
+ });
4477
+ return [gate, ...declarations];
4478
+ }
4479
+ function testCommandAnswer(d) {
4480
+ if (d === undefined)
4481
+ return undefined;
4482
+ if (d.kind === "command")
4483
+ return { decision: "command", command: d.command };
4484
+ if (d.kind === "option" && (d.option === "learn" || d.option === "skip" || d.option === "keep"))
4485
+ return { decision: d.option };
4486
+ return undefined;
4487
+ }
4488
+ /** BAPI-1657: the plain owner-facing reason when the repository has no test command to try. */
4489
+ export const NO_TEST_COMMAND_REASON = "Bridge found no test command in this repository";
4490
+ /** BAPI-1657: the plain owner-facing reason when the server could not read the testing instructions. */
4491
+ export const NO_COMMAND_RETRY_REASON = "the server could not read the repository's testing instructions just now";
4492
+ /**
4493
+ * BAPI-1657: the launcher text for an owner-run command. The detected launcher wins,
4494
+ * then the published package. A detection failure falls back to the published package.
4495
+ */
4496
+ async function detectedLauncherBase(deps, repoName) {
4497
+ let detected = null;
4498
+ try {
4499
+ detected = (await deps.setup?.detectLauncher?.(repoName)) ?? null;
4500
+ }
4501
+ catch {
4502
+ detected = null;
4503
+ }
4504
+ return (detected ?? NPM_SETUP_LAUNCHER).base;
4505
+ }
4506
+ /** The learned check's own entry, carrying child 3's phase. `null` when no trial ran and none was asked for. */
4507
+ export function trialWriteResult(trial, asked, launcher) {
4508
+ const target = "repository_gate.local_commands";
4509
+ if (trial === null)
4510
+ return asked ? { key: "test_command", status: "unchanged", target, reason: "no trial was needed for the stored gate" } : null;
4511
+ const phase = "evidence" in trial && trial.evidence !== undefined ? trial.evidence.phase : null;
4512
+ switch (trial.status) {
4513
+ case "no_command":
4514
+ // BAPI-1657: the owner-facing remedy names the launcher the owner runs in their own terminal.
4515
+ if (trial.reason === "llm_unavailable") {
4516
+ return { key: "test_command", status: "failed", target, reason: NO_COMMAND_RETRY_REASON, fix: "Rerun setup to try reading the repository's testing instructions again." };
4517
+ }
4518
+ return {
4519
+ key: "test_command",
4520
+ status: "failed",
4521
+ target,
4522
+ reason: NO_TEST_COMMAND_REASON,
4523
+ fix: `Child pull requests merge into the epic branch without a test gate. In your own terminal, run \`${launcher ?? NPM_SETUP_LAUNCHER.base} install epic-implementer --test-command "<your command>"\` with your test command.`,
4524
+ };
4525
+ case "promoted":
4526
+ return { key: "test_command", status: "written", target, phase, read_back: { commands: trial.commands.map((c) => c.name) } };
4527
+ case "not_needed":
4528
+ return { key: "test_command", status: "unchanged", target };
4529
+ case "uncertain":
4530
+ return { key: "test_command", status: "uncertain", target, phase, reason: `the trial's completion is unknown (${trial.reason})`, fix: "Rerun setup to read the trial again; it is not started twice." };
4531
+ case "unqualified":
4532
+ case "stale":
4533
+ case "could_not_run":
4534
+ return { key: "test_command", status: "failed", target, phase, reason: `the check did not pass (${trial.status})`, fix: "Fix what the check reported above, then rerun setup." };
4535
+ default:
4536
+ return { key: "test_command", status: "failed", target, phase: null, reason: `the trial did not run (${trial.status})`, fix: "Rerun setup; if this persists, run `epic-implementer doctor`." };
4537
+ }
4538
+ }
4539
+ function workflowWriteResult(outcome, asked) {
4540
+ const target = "github.default_branch";
4541
+ switch (outcome.status) {
4542
+ case "none":
4543
+ return asked ? { key: "setup_pr", status: "unchanged", target, reason: "no setup pull request was needed" } : null;
4544
+ case "written":
4545
+ case "unchanged":
4546
+ return { key: "setup_pr", status: outcome.status, target, ...(outcome.url !== undefined ? { read_back: { url: outcome.url } } : {}) };
4547
+ case "declined":
4548
+ return { key: "setup_pr", status: "declined", target, ...(outcome.reason !== undefined ? { reason: outcome.reason } : {}), ...(outcome.phase !== undefined ? { phase: outcome.phase } : {}) };
4549
+ case "failed":
4550
+ case "unattempted":
4551
+ return { key: "setup_pr", status: outcome.status, target, reason: outcome.reason, fix: "Rerun setup once the cause above is fixed." };
4552
+ }
4553
+ }
4554
+ function fixOutcomeResult(key, target, outcome) {
4555
+ return outcome.status === "failed"
4556
+ ? { key, status: "failed", target, reason: outcome.reason, fix: "Fix the cause above, then rerun setup with the same answers." }
4557
+ : { key, status: outcome.status, target };
4558
+ }
4559
+ function indexProgress(index) {
4560
+ if (index.state === "reached")
4561
+ return "current";
4562
+ if (index.state === "recovery_pending")
4563
+ return index.runId === null ? "requested" : "running";
4564
+ if (index.state === "queued_by_setup")
4565
+ return "requested";
4566
+ if (index.state === "in_progress")
4567
+ return "running";
4568
+ return undefined;
4569
+ }
4570
+ function reindexWriteResult(index) {
4571
+ const target = "repository_index";
4572
+ const progress = indexProgress(index);
4573
+ if (progress !== undefined)
4574
+ return { key: "reindex", status: progress === "current" ? "unchanged" : "written", target, progress };
4575
+ if (index.state === "recovery_unresolved") {
4576
+ const status = index.choice === "refused" ? "refused" : index.choice === "kept" || index.choice === "declined" ? "declined" : "failed";
4577
+ return { key: "reindex", status, target, reason: index.remedy, ...(status !== "declined" ? { fix: index.remedy } : {}) };
4578
+ }
4579
+ return { key: "reindex", status: "uncertain", target, reason: "the index state could not be read", fix: "Rerun setup to read it again." };
4580
+ }
4581
+ /** The approved epic-server answer as a record. A local mode records whether guidance is present. */
4582
+ async function epicServerAnswer(epicDeps, d) {
4583
+ if (d.kind === "epic_server_sfcc") {
4584
+ return { decision: "record", record: { version: 1, mode: "sfcc_shared_active", sfcc: { sandbox_id: d.value.sandbox_id, credential_ref: d.value.credential_ref, storefront_origin: d.value.storefront_origin } } };
4585
+ }
4586
+ if (d.kind === "option" && d.option === "local") {
4587
+ let present = false;
4588
+ try {
4589
+ present = await epicDeps.guidancePresent();
4590
+ }
4591
+ catch {
4592
+ present = false;
4593
+ }
4594
+ return { decision: "record", record: { version: 1, mode: "local", recipe: present ? "present" : "absent" } };
4595
+ }
4596
+ if (d.kind === "option" && d.option === "none")
4597
+ return { decision: "record", record: { version: 1, mode: "none" } };
4598
+ return { decision: "keep" };
3041
4599
  }
3042
4600
  /**
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.
4601
+ * BAPI-1654 — the CI change's own result. An opened or reused pull request is
4602
+ * PROPOSED, never coverage; a merged change is `unchanged` and in place. A
4603
+ * changed source is refused untouched, and an unreadable remote state is
4604
+ * uncertain, so a retry reconciles instead of opening a second pull request.
3050
4605
  */
4606
+ function ciChangeWriteResult(actionClass, target, result) {
4607
+ const key = "epic_ci_change";
4608
+ switch (result.outcome) {
4609
+ case "installed-pr-opened":
4610
+ case "upgrade-pr-opened":
4611
+ return { key, status: "written", target, reason: describeProposedCiChange(actionClass, target, result.prUrl), read_back: { path: target, pull_request: result.prUrl, state: "proposed" } };
4612
+ case "existing-pr":
4613
+ return { key, status: "unchanged", target, reason: describeProposedCiChange(actionClass, target, result.prUrl), read_back: { path: target, pull_request: result.prUrl, state: "proposed" } };
4614
+ case "identical":
4615
+ return { key, status: "unchanged", target, reason: "the CI change is already merged", read_back: { path: target, state: "in_place" } };
4616
+ case "dry-run":
4617
+ return { key, status: "unattempted", target, reason: "a dry run opens nothing" };
4618
+ case "failed":
4619
+ if (result.reason === "consent_declined")
4620
+ return { key, status: "declined", target };
4621
+ if (result.reason === "workflow_modified_or_unrecognized" || result.reason === "default_branch_moved") {
4622
+ return { key, status: "refused", target, reason: `${target} changed since setup proposed the change, so nothing was opened`, fix: "Run setup again for a fresh proposal, then approve it." };
4623
+ }
4624
+ if (result.reason === "remote_state_unverifiable" || result.reason === "existing_pr_unverifiable" || result.reason === "managed_branch_without_pr" || result.reason === "pr_open_failed") {
4625
+ return {
4626
+ key, status: "uncertain", target,
4627
+ reason: "the CI pull request could not be confirmed",
4628
+ fix: result.compareUrl !== undefined ? `Open it from ${result.compareUrl}, or rerun setup with the same answers.` : "Rerun setup with the same answers; it reconciles before opening anything.",
4629
+ ...(result.prUrl !== undefined ? { read_back: { path: target, pull_request: result.prUrl, state: "proposed" } } : {}),
4630
+ };
4631
+ }
4632
+ if (result.reason === "existing_pr_differs") {
4633
+ return { key, status: "refused", target, reason: "an open setup pull request for this file carries a different change", fix: result.prUrl !== undefined ? `Close or merge ${result.prUrl}, then rerun setup.` : "Close it, then rerun setup." };
4634
+ }
4635
+ return { key, status: "failed", target, reason: `the CI pull request could not be opened (${result.reason.replace(/_/g, " ")})`, fix: result.remediation };
4636
+ }
4637
+ }
4638
+ function epicBranchWriteResults(step, report) {
4639
+ if (!report)
4640
+ return null;
4641
+ const results = [];
4642
+ if (step.status !== "completed")
4643
+ return [{ key: "epic_branch_ci", status: "unchanged", target: "epic_branch_ci", reason: `inspection ${step.status.replace(/_/g, " ")}` }];
4644
+ results.push(step.decision === null
4645
+ ? { key: "epic_branch_ci", status: "declined", target: "epic_branch_ci", reason: "no decision was recorded; runs behave as include" }
4646
+ : step.recorded
4647
+ ? { key: "epic_branch_ci", status: step.unchanged ? "unchanged" : "written", target: "epic_branch_ci", read_back: { decision: step.decision } }
4648
+ : { key: "epic_branch_ci", status: "failed", target: "epic_branch_ci", reason: "the decision could not be recorded", fix: step.manualAction ?? "Rerun setup." });
4649
+ const outcome = step.exemptionOutcome;
4650
+ if (outcome !== null) {
4651
+ results.push(outcome === "applied" ? { key: "approval_exemption", status: "written", target: "github.rulesets" }
4652
+ : outcome === "declined" ? { key: "approval_exemption", status: "declined", target: "github.rulesets" }
4653
+ : outcome === "not_needed" ? { key: "approval_exemption", status: "unchanged", target: "github.rulesets" }
4654
+ : outcome === "could_not_tell"
4655
+ ? { key: "approval_exemption", status: "uncertain", target: "github.rulesets", reason: "the ruleset change could not be confirmed", fix: "Check the ruleset yourself; setup will not retry it blindly." }
4656
+ : { key: "approval_exemption", status: "refused", target: "github.rulesets", reason: "the approval rule is not safe to change automatically", fix: "Follow the manual steps printed above." });
4657
+ }
4658
+ return results;
4659
+ }
3051
4660
  async function runConvergingSetup(options, deps, setup) {
3052
4661
  if (options.removeMergeToken === true)
3053
4662
  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]: ");
4663
+ // One input session per run: a pasted answer's trailing line ending cannot answer the next
4664
+ // question. It wraps only the line reader; ambient stdin and the no-echo secret reader are untouched.
4665
+ // The proxy keeps every other dependency live and re-wraps if the reader is swapped mid-run.
4666
+ const bare = deps;
4667
+ let session;
4668
+ deps = new Proxy(bare, {
4669
+ get(target, property, receiver) {
4670
+ if (property !== "promptLine")
4671
+ return Reflect.get(target, property, receiver);
4672
+ const source = target.promptLine;
4673
+ if (source === undefined)
4674
+ return undefined;
4675
+ if (session?.source !== source)
4676
+ session = { source, read: createPlainInputSession(source, { now: target.plainInputClock }) };
4677
+ return session.read;
4678
+ },
4679
+ });
4680
+ const progress = (activity, operation) => withSetupProgress(activity, operation, { errorLog: deps.errorLog, timer: deps.progressTimer });
4681
+ const confirmed = await resolveAndConfirmBaseUrl(options, deps, "");
3064
4682
  if (!confirmed.ok)
3065
4683
  return confirmed.code;
3066
4684
  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) {
4685
+ // BAPI-1638: `--answers` is read once, here, and validated in full before any write.
4686
+ // With `--dry-run` it is the read-only proposal mode; without it, the answers apply.
4687
+ let answersEnvelope = null;
4688
+ if (options.answers !== undefined) {
4689
+ const refuse = (refusal) => {
4690
+ deps.installDocumentSink?.({ refusal });
4691
+ for (const reason of refusal.reasons)
4692
+ deps.errorLog(`Refused (${reason.reason}${reason.keys.length > 0 ? `: ${reason.keys.join(", ")}` : ""}): ${reason.detail}`);
4693
+ deps.errorLog(`Nothing was written. ${refusal.fix}`);
4694
+ return 1;
4695
+ };
4696
+ if (deps.answersSource === undefined) {
4697
+ return refuse({ reasons: [{ reason: "answers_unreadable", keys: [], detail: "This caller supplied no way to read an answers file." }], fix: "Run setup from the packaged CLI." });
4698
+ }
4699
+ const read = await readAnswersSource(options.answers, deps.answersSource);
4700
+ if (!read.ok)
4701
+ return refuse(read.refusal);
4702
+ const parsedAnswers = parseAnswersText(read.text);
4703
+ if (!parsedAnswers.ok)
4704
+ return refuse(parsedAnswers.refusal);
4705
+ answersEnvelope = parsedAnswers.envelope;
4706
+ }
4707
+ const proposalMode = options.answers !== undefined && options.dryRun;
4708
+ const answersApply = options.answers !== undefined && !options.dryRun;
4709
+ // BAPI-1635: `--json` is read-only like `--dry-run`, so it continues past an unavailable tool to report it.
4710
+ // BAPI-1638: with `--answers` (and no `--dry-run`), `--json` only shapes the output of an apply.
4711
+ const readOnlyRun = options.dryRun || (options.json === true && !answersApply);
4712
+ const prerequisites = await assessEpicInstallerPrerequisites(deps, Boolean(options.executorId), options.verbose !== true);
4713
+ if (!prerequisites.available && !readOnlyRun)
4714
+ return 1;
4715
+ const { claudeLoggedIn, githubSignIn, localRemote } = prerequisites;
4716
+ // ---- Repository: the folder's own binding first; ask only when genuinely unbound ----
4717
+ const binding = options.repo === undefined ? await resolveFolderBinding(deps) : { status: "explicit" };
4718
+ let accessResult = await deps.resolveAccess(options.repo ?? (binding.status === "bound" ? binding.repo : undefined), baseUrl);
4719
+ if (!accessResult.ok && binding.status === "absent" && deps.promptLine && !readOnlyRun && options.answers === undefined) {
3085
4720
  const suggestion = localRemote?.split("/")[1] ?? null;
3086
4721
  deps.log("");
3087
- deps.log("Which repository is this? Bridge could not tell from the environment or .bridge/config.");
4722
+ deps.log("Which repository is this? This folder is not bound to a Bridge project and Bridge could not tell from the environment.");
3088
4723
  const answer = (await deps.promptLine(suggestion !== null
3089
4724
  ? `Bridge repository name [${suggestion}]: `
3090
4725
  : "Bridge repository name (press Enter to skip): ")).trim();
3091
- const chosen = answer.length > 0 ? answer : suggestion;
4726
+ const typed = answer.length > 0 && !/^(y|yes|n|no)$/i.test(answer) ? answer : null;
4727
+ // Enter accepts the suggested name when there is one; without one it stays unresolved.
4728
+ const chosen = typed ?? (answer.length === 0 ? suggestion : null);
3092
4729
  if (chosen !== null)
3093
4730
  accessResult = await deps.resolveAccess(chosen, baseUrl);
3094
4731
  }
3095
4732
  const access = accessResult.ok ? accessResult.access : null;
3096
4733
  const accessError = accessResult.ok ? undefined : accessResult.error;
3097
- const gateIo = gateIoFor(deps);
4734
+ // ---- BAPI-1650: an unapproved non-production address, reported before any refusal ----
4735
+ // Dry-run only: the metadata exists only on that path. The item is recorded now so the
4736
+ // access refusal below keeps it; a successful preview continues and carries it forward.
4737
+ let endpointApprovalItemForRun = null;
4738
+ if (options.dryRun && accessResult.endpointApproval !== undefined) {
4739
+ endpointApprovalItemForRun = await endpointApprovalItem(deps, options, accessResult.endpointApproval);
4740
+ reportCredentialEndpointUnapproved(deps);
4741
+ deps.installDocumentSink?.({ items: [endpointApprovalItemForRun] });
4742
+ }
4743
+ const earlyPreflight = await runExecutorPreflightPhase(options, deps, baseUrl, access);
4744
+ if (earlyPreflight.kind === "refused")
4745
+ return 1;
4746
+ const gateIo = {
4747
+ ...gateIoFor(deps),
4748
+ isTTY: deps.isTTY,
4749
+ reviewCiSettings: options.reviewCiSettings === true,
4750
+ };
3098
4751
  const standalone = await runStandaloneGateAction(options, deps, gateIo, access, accessError, baseUrl);
3099
4752
  if (standalone !== null)
3100
4753
  return standalone;
4754
+ // ---- Learned first: before any ordinary gate, default, command, workflow, branch, or PR write ----
4755
+ // Only a validated "not learned" stops a real run; a dry run reports it and keeps previewing.
4756
+ const notLearned = access !== null ? await repositoryNotLearned(deps, access) : false;
4757
+ if (notLearned && !readOnlyRun) {
4758
+ deps.log("");
4759
+ deps.log("Not ready: 1 step left");
4760
+ deps.log("complete-with-manual-steps");
4761
+ return 1;
4762
+ }
3101
4763
  // ---- Check 1: the read-only doctor (no deny probe yet) ------------------
3102
4764
  deps.log("");
3103
4765
  deps.log("Checking your setup (read-only)…");
3104
4766
  const storedContext = storedMergeContextFor(setup, null, localRemote);
3105
- const firstReport = await deps.runDoctor({
4767
+ const firstReport = await progress("checking readiness", () => deps.runDoctor({
3106
4768
  access,
3107
4769
  accessError,
3108
4770
  reviewPolicySource: options.reviewPolicy,
4771
+ assessmentVersion: 1,
4772
+ epicRunId: options.assessmentEpicRunId,
3109
4773
  skipDenyProbe: true,
3110
4774
  storedMergeCredential: storedContext,
3111
- });
4775
+ }));
3112
4776
  if (conductorInstallDoctorHasFatal(firstReport) || !access) {
3113
4777
  deps.log(formatConductorInstallDoctorReport(firstReport));
3114
4778
  deps.errorLog("");
@@ -3118,57 +4782,199 @@ async function runConvergingSetup(options, deps, setup) {
3118
4782
  deps.log("complete-with-manual-steps");
3119
4783
  return 1;
3120
4784
  }
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, {
4785
+ const executorPlans = earlyPreflight.plans;
4786
+ // ---- The remote default branch, captured once -----------------------------
4787
+ // Every workflow input derives from this head, never from the person's folder.
4788
+ let snapshot = null;
4789
+ if (githubSignIn === "signed_in" && setup.captureDefaultBranch !== undefined) {
4790
+ try {
4791
+ snapshot = await setup.captureDefaultBranch();
4792
+ }
4793
+ catch {
4794
+ snapshot = null;
4795
+ }
4796
+ }
4797
+ const readToolchains = snapshotToolchainReader(setup, snapshot);
4798
+ // ---- The review default: explicit flag, then what is stored, then the remote workflow ----
4799
+ const reviewDefault = await resolveReviewDefault(deps, options, setup, access, snapshot);
4800
+ renderReviewPolicy(deps, options, reviewDefault);
4801
+ // ---- The gate: explicit flags win, a stored gate is kept, otherwise facts decide ----
4802
+ // BAPI-1638: the answers path plans the gate without a terminal, so no discovered
4803
+ // declaration joins it unless its own answer approves it below.
4804
+ const planIo = options.answers !== undefined ? { ...gateIo, isTTY: false, promptLine: undefined } : gateIo;
4805
+ const gatePhase = await resolveConductorGate(planIo, access, options.gate, deps.gate, {
3127
4806
  dryRun: options.dryRun,
3128
- ...(hasExplicitGateInput(options.gate) ? {} : { ensureProviderCheck: EPIC_IMPLEMENTER_CI_CHECK_NAME }),
4807
+ planningOnly: true,
4808
+ inferCi: !hasExplicitGateInput(options.gate),
3129
4809
  });
3130
4810
  if (gatePhase.kind === "exit")
3131
4811
  return gatePhase.code;
3132
4812
  const gatePlan = gatePhase.kind === "plan" ? gatePhase.plan : null;
3133
- const gateChangeDeclined = gatePhase.kind === "plan" && gatePhase.ensureDeclined === true;
4813
+ const gateRequiresManagedCheck = gatePlan !== null && gatePlan.inferred === undefined && gatePlan.desired.providerChecks.includes(EPIC_IMPLEMENTER_CI_CHECK_NAME);
3134
4814
  const advisories = localAdvisories(firstReport);
3135
- const collectInputs = { claudeLoggedIn, githubSignIn, localRemote, gateChangeDeclined, advisories };
3136
- const first = await collectSetupEvidence(deps, setup, access, firstReport.readiness, collectInputs);
4815
+ // The evidence shares this array and later pushes material advisories onto it, so the routine set is copied now.
4816
+ const routineAdvisories = [...advisories];
4817
+ // The agent route is `--json` or `--answers`; the same decision gates the choice catalog below.
4818
+ const collectDecisions = options.json === true || options.answers !== undefined;
4819
+ const setupPath = collectDecisions ? "agent" : "terminal";
4820
+ // BAPI-1657: the gate plan is resolved above, so its planned write is known before any setup item is projected.
4821
+ const plannedGateWrite = gatePlan !== null && gatePlan.write !== null;
4822
+ const collectInputs = { claudeLoggedIn, githubSignIn, localRemote, snapshot, readToolchains, gateRequiresManagedCheck, plannedGateWrite, path: setupPath };
4823
+ const first = await progress("checking readiness", () => collectSetupEvidence(deps, setup, access, firstReport.readiness, { ...collectInputs, advisories }));
3137
4824
  const state = {
3138
4825
  evidence: first.evidence,
3139
4826
  identity: first.identity,
3140
4827
  repository: first.repository,
3141
4828
  storedCommand: first.storedCommand,
4829
+ snapshot,
3142
4830
  toolchains: first.toolchains,
3143
- commandChanged: false,
3144
- commandBlocked: false,
4831
+ ciPlan: undefined,
4832
+ commandUncertain: false,
4833
+ trial: null,
4834
+ promotedCommands: null,
3145
4835
  failedOperations: [],
3146
4836
  };
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;
4837
+ // BAPI-1654: which CI systems the repository's files configure, read-only, independent of the remote host.
4838
+ if (deps.gate?.discoveryFs !== undefined) {
4839
+ const detected = await detectCiSystems(deps.gate.discoveryFs);
4840
+ state.ciSystems = detected.complete || detected.systems.length > 0 ? detected.systems : null;
4841
+ }
4842
+ // BAPI-1545: the worker MCP grant, read-only here. Its item is advisory.
4843
+ let grantInventory = null;
4844
+ if (setup.mcpGrant !== undefined) {
4845
+ const assessed = await assessMcpGrant(setup.mcpGrant, access.repoName);
4846
+ grantInventory = assessed.inventory;
4847
+ state.evidence = { ...state.evidence, mcpGrant: assessed.evidence };
4848
+ }
4849
+ // BAPI-1546: the epic-server record, read-only here. Its item is advisory.
4850
+ if (setup.epicServer !== undefined) {
4851
+ state.evidence = { ...state.evidence, epicServer: await assessEpicServer(setup.epicServer, access.repoName) };
4852
+ }
4853
+ // BAPI-1635: the selected profile's escalation declaration, read-only.
4854
+ {
4855
+ const notification = await collectNotificationEvidence(deps, options, baseUrl);
4856
+ if (notification !== undefined)
4857
+ state.evidence = { ...state.evidence, notification };
4858
+ }
4859
+ const firstItems = [
4860
+ ...projectSetupItems(state.evidence),
4861
+ ...(endpointApprovalItemForRun !== null ? [endpointApprovalItemForRun] : []),
4862
+ ];
4863
+ deps.assessmentSink?.(firstItems.find(i => i.assessment)?.assessment);
4864
+ // The full first assessment is detail; a failure or refusal below always prints on its own.
4865
+ if (options.verbose === true || options.dryRun) {
4866
+ for (const line of renderSetupAssessment(firstItems, "What setup found", "initial"))
4867
+ deps.log(line);
4868
+ }
4869
+ // A review default the run would add or change is worth offering; only a missing gate or
4870
+ // missing supervisor rows make a deferred policy block readiness.
4871
+ const policyRequired = gateOrDefaultsNeedWrite(gatePlan, firstReport.readiness, MANAGED_WRITE_REVIEW_DEFAULT);
3158
4872
  const planContext = {
3159
- gateOrDefaultsNeedWrite: gateOrDefaultsNeedWrite(gatePlan, firstReport.readiness),
3160
- dryRun: options.dryRun,
4873
+ gateOrDefaultsNeedWrite: gateOrDefaultsNeedWrite(gatePlan, firstReport.readiness, reviewDefault),
4874
+ suppliedPolicyInput: options.reviewPolicyExplicit || options.replaceDoneGate || hasExplicitGateInput(options.gate),
4875
+ ...(options.epicServerChange === true ? { epicServerChangeRequested: true } : {}),
3161
4876
  };
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) {
4877
+ const fixes = planSetupFixes(state.evidence, planContext);
4878
+ // ---- BAPI-1638: the decision evidence behind every open choice (read-only) ----
4879
+ // Collected for `--json` and `--answers` only: an ordinary interactive run asks at
4880
+ // each decision point exactly as before and needs no catalog.
4881
+ const epicBranchCiWanted = options.epicBranchCiDecision !== undefined || deps.gate?.epicBranchCi !== undefined;
4882
+ const epicBranchCollected = collectDecisions && epicBranchCiWanted ? await collectEpicBranchCi(deps.gate) : undefined;
4883
+ const declarationPlan = collectDecisions && gatePlan !== null
4884
+ ? await planDeclarationSelections(gatePlan.current, gatePlan.desired, deps.gate)
4885
+ : [];
4886
+ // BAPI-1654: the one CI change on offer, from the default-branch snapshot (read-only).
4887
+ const ciOfferCollection = collectDecisions && epicBranchCollected !== undefined
4888
+ ? await collectCiOffer({
4889
+ setup, state, collected: epicBranchCollected, readToolchains,
4890
+ })
4891
+ : null;
4892
+ const decisionEvidence = collectDecisions
4893
+ ? await collectDecisionEvidence({
4894
+ deps, options, access, gatePlan, state, fixes, grantInventory, firstReport,
4895
+ declarationPlan, epicBranchCollected, readToolchains, firstItems, ciOffer: ciOfferCollection,
4896
+ })
4897
+ : null;
4898
+ const choices = decisionEvidence === null ? [] : buildInstallChoices(decisionEvidence);
4899
+ // ---- BAPI-1638: proposal mode — normalize the draft answers and return; nothing is written ----
4900
+ let proposal = null;
4901
+ let proposalDigest = null;
4902
+ let resolvedChoices;
4903
+ if (options.answers !== undefined && decisionEvidence !== null) {
4904
+ const normalized = normalizeInstallAnswers({
4905
+ envelope: answersEnvelope,
4906
+ choices,
4907
+ identity: decisionEvidence.identity,
4908
+ flags: {
4909
+ ...(options.testCommand !== undefined ? { testCommand: options.testCommand } : {}),
4910
+ ...(options.epicBranchCiDecision !== undefined ? { epicBranchCiDecision: options.epicBranchCiDecision } : {}),
4911
+ ...(options.launchProfile !== undefined ? { launchProfile: options.launchProfile } : {}),
4912
+ },
4913
+ mode: proposalMode ? "proposal" : "apply",
4914
+ recommendationContext: {
4915
+ setupSuppliesWorkflow: decisionEvidence.epicBranchCi?.managedWorkflowViaSetupPr === true,
4916
+ stateText: epicBranchCiStateText(decisionEvidence.epicBranchCi ?? null),
4917
+ },
4918
+ });
4919
+ if (proposalMode) {
4920
+ deps.installDocumentSink?.({
4921
+ items: firstItems,
4922
+ decisions: decisionEvidence,
4923
+ choices: normalized.choices,
4924
+ ...(normalized.proposal !== undefined ? { proposal: normalized.proposal } : {}),
4925
+ ...(normalized.digest !== undefined ? { digest: normalized.digest } : {}),
4926
+ ...(!normalized.ok ? { refusal: normalized.refusal } : {}),
4927
+ });
4928
+ deps.log("");
4929
+ deps.log("Proposal (read-only) — nothing was written and nothing was asked.");
4930
+ if (normalized.proposal !== undefined) {
4931
+ for (const action of normalized.proposal.actions) {
4932
+ if (action.intent === "write")
4933
+ deps.log(` ${action.key}: ${action.consequence}`);
4934
+ }
4935
+ }
4936
+ if (normalized.digest !== undefined)
4937
+ deps.log(` proposal_digest: ${normalized.digest}`);
4938
+ if (!normalized.ok) {
4939
+ for (const reason of normalized.refusal.reasons)
4940
+ deps.log(` Needs an answer (${reason.reason}): ${reason.keys.join(", ")}`);
4941
+ }
4942
+ deps.log("complete-with-manual-steps (dry run)");
4943
+ return normalized.ok ? 0 : 1;
4944
+ }
4945
+ if (!normalized.ok) {
4946
+ deps.installDocumentSink?.({ items: firstItems, decisions: decisionEvidence, choices: normalized.choices, refusal: normalized.refusal });
4947
+ for (const reason of normalized.refusal.reasons) {
4948
+ deps.errorLog(`Refused (${reason.reason}: ${reason.keys.join(", ")}): ${reason.detail}`);
4949
+ }
4950
+ deps.errorLog(`Nothing was written. ${normalized.refusal.fix}`);
4951
+ deps.log("");
4952
+ deps.log("Not ready: the answers were refused before any write");
4953
+ deps.log("complete-with-manual-steps");
4954
+ return 1;
4955
+ }
4956
+ proposal = normalized.proposal;
4957
+ proposalDigest = normalized.digest;
4958
+ resolvedChoices = normalized.choices;
4959
+ }
4960
+ // ---- Read-only: preview only, before every write and write prompt -------
4961
+ // BAPI-1635: `--json` is a read-only assessment like `--dry-run`. Both return here,
4962
+ // before the fix loop, the launch-profile save, credential writes, MCP grants, policy
4963
+ // changes, setup pull requests, and re-indexing.
4964
+ if (readOnlyRun && !proposalMode) {
4965
+ // BAPI-1638: `--json` reads only, so it skips the policy preview POST a plain dry run shows.
4966
+ if (options.dryRun && options.json !== true && gatePlan !== null)
4967
+ await fixGateAndDefaults(deps, options, access, gatePlan, reviewDefault, true);
4968
+ deps.installDocumentSink?.({ items: firstItems, decisions: decisionEvidence });
3169
4969
  logStoredCommandAndToolchains(deps, state.storedCommand, state.toolchains);
4970
+ renderDryRunCiPlan(deps, options, gatePlan);
4971
+ if (managedWorkflowInPlay(state, gateRequiresManagedCheck))
4972
+ await warnDefaultBranchRequiresManagedCheck(setup, state);
3170
4973
  deps.log("");
3171
- deps.log("Dry run — nothing was written and nothing was asked.");
4974
+ deps.log(options.dryRun ? "Dry run — nothing was written and nothing was asked." : "Read-only assessment — nothing was written and nothing was asked.");
4975
+ if (notLearned) {
4976
+ deps.log(" A real run would stop here: this repository has not been learned (see repository_not_learned above).");
4977
+ }
3172
4978
  if (fixes.length === 0)
3173
4979
  deps.log(" No fix is needed.");
3174
4980
  for (const fix of fixes)
@@ -3177,104 +4983,289 @@ async function runConvergingSetup(options, deps, setup) {
3177
4983
  deps.log(` Would write executor unit: ${executorPlans.install.unitPath}`);
3178
4984
  deps.log(` Would start it with: ${executorPlans.start.manualCommand}`);
3179
4985
  }
4986
+ for (const advisory of state.evidence.advisories)
4987
+ deps.log(` - ${advisory}`);
4988
+ // `--json` keeps the closing summary it always printed: what still needs attention (with the
4989
+ // closed setup PR named once), then the verdict and the one next step.
4990
+ const readOnlyUnmet = unmetBlockingItems(firstItems);
4991
+ if (!options.dryRun) {
4992
+ const readOnlyPr = state.evidence.setupPullRequest;
4993
+ const notice = readOnlyPr.state === "closed_unmerged" && state.evidence.workflow.state !== "installed"
4994
+ ? closedSetupPullRequestNotice(readOnlyPr)
4995
+ : undefined;
4996
+ const printNotice = notice !== undefined && !readOnlyUnmet.some((item) => item.remedy === notice);
4997
+ if (readOnlyUnmet.length > 0 || printNotice) {
4998
+ deps.log("");
4999
+ deps.log("What still needs attention");
5000
+ for (const item of readOnlyUnmet)
5001
+ deps.log(` - ${item.label}: ${setupItemRemedy(item)}`);
5002
+ if (printNotice)
5003
+ deps.log(` - ${notice}`);
5004
+ }
5005
+ }
5006
+ for (const line of advisoryFindingLines(firstItems))
5007
+ deps.log(line);
3180
5008
  deps.log("");
3181
5009
  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 ---------------------------
5010
+ if (!options.dryRun) {
5011
+ deps.log(`Next step: ${readOnlyUnmet.length === 0 ? "Run drive-epic to start your first epic" : setupItemRemedy(readOnlyUnmet[0])}`);
5012
+ }
5013
+ deps.log(options.dryRun ? "complete-with-manual-steps (dry run)" : "complete-with-manual-steps");
5014
+ // A dry run always exits 0. A read-only `--json` assessment keeps the exit code of a
5015
+ // normal one: 1 while a blocking step is left, otherwise the doctor's own code.
5016
+ // An unlearned repository also keeps exit 1: a real run would have stopped there with 1.
5017
+ return options.dryRun ? 0 : notLearned || unmetBlockingItems(firstItems).length > 0 ? 1 : conductorInstallDoctorExitCode(firstReport);
5018
+ }
5019
+ // ---- Fix only what is missing, once, in order: the shared apply (BAPI-1638) ----
5020
+ // Both paths reach the same apply. On the answers path each decision point reads
5021
+ // its stated answer; on the interactive path it asks its question as before.
3186
5022
  if (fixes.length > 0) {
3187
5023
  deps.log("");
3188
5024
  deps.log("Fixing what is missing…");
3189
5025
  }
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" },
5026
+ let policyResult = null;
5027
+ let epicServerChanged = false;
5028
+ const answerOf = (key) => decisionFor(proposal, key);
5029
+ const optionOf = (key) => {
5030
+ const d = answerOf(key);
5031
+ return d === undefined ? undefined : d.kind === "decline" ? "decline" : d.kind === "option" ? d.option : undefined;
5032
+ };
5033
+ // BAPI-1659: whether the setup pull request really opened this run. Only then may a declined CI
5034
+ // change say the workflow still arrives through it; an approved answer alone proves nothing.
5035
+ let setupWorkflowOpened = false;
5036
+ const operations = [
5037
+ {
5038
+ key: "gate",
5039
+ run: async () => {
5040
+ if (gatePlan === null)
5041
+ return null;
5042
+ const approvedDeclarations = proposal === null ? [] : declarationPlan.filter((e) => optionOf(e.key) === "approve");
5043
+ const gateOpen = fixes.includes("gate_and_defaults");
5044
+ if (!gateOpen && approvedDeclarations.length === 0) {
5045
+ if (proposal === null)
5046
+ return null;
5047
+ return settledGateResults(proposal);
5048
+ }
5049
+ const gateAnswer = proposal === null ? undefined : gateOpen ? (optionOf("gate") === "decline" ? "decline" : "approve") : "approve";
5050
+ const plan = applyApprovedDeclarations(gatePlan, approvedDeclarations);
5051
+ policyResult = await fixGateAndDefaults(deps, options, access, plan, reviewDefault, true, gateAnswer);
5052
+ return gateWriteResults(policyResult, proposal, declarationPlan);
5053
+ },
5054
+ },
5055
+ {
5056
+ key: "test_command",
5057
+ // The interactive path keeps each phase's own skip rule; only approved answers chain.
5058
+ ...(proposal !== null ? { dependsOn: ["gate"] } : {}),
5059
+ run: async () => {
5060
+ const answer = proposal === null ? undefined : testCommandAnswer(answerOf("test_command"));
5061
+ await runTestCommandPhase(deps, options, setup, access, baseUrl, state, gatePlan, policyResult, answer);
5062
+ settleCiPlan(deps, state, gatePlan);
5063
+ // BAPI-1657: only the no-command remedy needs the launcher text, so detection runs only for that outcome.
5064
+ const launcher = state.trial?.status === "no_command" ? await detectedLauncherBase(deps, access.repoName) : undefined;
5065
+ return trialWriteResult(state.trial, proposal !== null && answer !== undefined && answer.decision !== "skip" && answer.decision !== "keep", launcher);
5066
+ },
5067
+ },
5068
+ {
5069
+ key: "setup_pr",
5070
+ // It depends on the gate. A learned check that ran and failed is not a blocker here:
5071
+ // the workflow phase reports the PR `declined` with the check's phase.
5072
+ ...(proposal !== null ? { dependsOn: ["gate"] } : {}),
5073
+ run: async () => {
5074
+ const setupPr = proposal === null ? undefined : optionOf("setup_pr") === "approve" ? "approve" : optionOf("setup_pr") === "decline" ? "decline" : undefined;
5075
+ // BAPI-1659: the setup choice is asked only for real setup-workflow work. When none was proposed
5076
+ // (the CI change has its own pull request), this step opens nothing and never touches the gate.
5077
+ if (proposal !== null && setupPr !== undefined && decisionEvidence !== null && !decisionEvidence.setupPr.applicable
5078
+ && decisionEvidence.epicBranchCi?.ciOffer?.applicable === true) {
5079
+ return setupPr === "decline"
5080
+ ? { key: "setup_pr", status: "declined", target: "github.default_branch" }
5081
+ : { key: "setup_pr", status: "unchanged", target: "github.default_branch", reason: "no setup pull request was needed" };
5082
+ }
5083
+ const outcome = await runWorkflowPhase(deps, options, setup, access, baseUrl, state, readToolchains, gateRequiresManagedCheck, setupPr);
5084
+ if (managedWorkflowInPlay(state, gateRequiresManagedCheck))
5085
+ await warnDefaultBranchRequiresManagedCheck(setup, state);
5086
+ const written = workflowWriteResult(outcome, proposal !== null && setupPr !== undefined);
5087
+ setupWorkflowOpened = written?.status === "written";
5088
+ return written;
5089
+ },
5090
+ },
5091
+ {
5092
+ key: "test_command",
5093
+ run: async () => {
5094
+ // ---- Explicit operations, each behind its own consent (unchanged) -------
5095
+ if (options.gate.qualifyGate && gatePlan !== null && gatePlan.desired.localCommands.length > 0
5096
+ && policyResult?.status !== "deferred" && policyResult?.status !== "unknown") {
5097
+ await runConductorGateQualification(gateIo, access, deps.gate, {
5098
+ revision: policyResult?.current?.state.revision ?? gatePlan.current.revision,
5099
+ baseUrl,
5100
+ });
5101
+ }
5102
+ return null;
5103
+ },
5104
+ },
5105
+ {
5106
+ key: "merge_token",
5107
+ run: async () => {
5108
+ if (!fixes.includes("merge_token") || state.identity === null) {
5109
+ return proposal === null || answerOf("merge_token")?.kind !== "reference" ? null
5110
+ : { key: "merge_token", status: "unchanged", target: "merge_token" };
5111
+ }
5112
+ const d = answerOf("merge_token");
5113
+ const answer = proposal === null || d === undefined ? undefined
5114
+ : d.kind === "reference" ? { decision: "reference", reference: d.reference } : { decision: "decline" };
5115
+ const outcome = await fixMergeToken(deps, setup, state.identity, state.evidence.mergeCredential.state === "stored_rejected", answer);
5116
+ return fixOutcomeResult("merge_token", "merge_token", outcome);
5117
+ },
5118
+ },
5119
+ {
5120
+ key: "reindex",
5121
+ run: async () => {
5122
+ if (!fixes.includes("reindex")) {
5123
+ return proposal === null || optionOf("reindex") !== "approve" ? null
5124
+ : { key: "reindex", status: "unchanged", target: "repository_index", progress: indexProgress(state.evidence.index) ?? "current" };
5125
+ }
5126
+ if (proposal !== null && optionOf("reindex") === "skip") {
5127
+ return { key: "reindex", status: "declined", target: "repository_index" };
5128
+ }
5129
+ const answers = proposal === null ? undefined : {
5130
+ ...(optionOf("reindex_branch") === "correct" || optionOf("reindex_branch") === "keep" ? { branch: optionOf("reindex_branch") } : {}),
5131
+ ...(optionOf("reindex_retry") === "retry" || optionOf("reindex_retry") === "no_retry" ? { retry: optionOf("reindex_retry") } : {}),
5132
+ };
5133
+ state.evidence = { ...state.evidence, index: await fixReindex(deps, setup, access, state.evidence.recovery, answers) };
5134
+ return reindexWriteResult(state.evidence.index);
5135
+ },
5136
+ },
5137
+ {
5138
+ key: "worker_mcp_grant",
5139
+ run: async () => {
5140
+ if (!fixes.includes("mcp_grant") || setup.mcpGrant === undefined || grantInventory === null) {
5141
+ return proposal === null || answerOf("worker_mcp_grant")?.kind !== "selection" ? null
5142
+ : { key: "worker_mcp_grant", status: "unchanged", target: "mcp_grant" };
5143
+ }
5144
+ const d = answerOf("worker_mcp_grant");
5145
+ const answer = proposal === null || d === undefined ? undefined
5146
+ : d.kind === "selection" ? { decision: "select", ids: d.ids } : { decision: "decline" };
5147
+ const outcome = await fixMcpGrant(deps, setup.mcpGrant, access.repoName, grantInventory, answer);
5148
+ return fixOutcomeResult("worker_mcp_grant", "mcp_grant", outcome);
5149
+ },
5150
+ },
5151
+ {
5152
+ key: "epic_server",
5153
+ run: async () => {
5154
+ if (setup.epicServer === undefined)
5155
+ return null;
5156
+ const d = answerOf("epic_server");
5157
+ if (!fixes.includes("epic_server")) {
5158
+ if (proposal === null || d === undefined || (d.kind === "option" && d.option === "keep"))
5159
+ return null;
5160
+ }
5161
+ const answer = proposal === null || d === undefined ? undefined : await epicServerAnswer(setup.epicServer, d);
5162
+ const outcome = await fixEpicServer(deps, setup.epicServer, access.repoName, answer);
5163
+ epicServerChanged = outcome.status === "written";
5164
+ return fixOutcomeResult("epic_server", "epic_server_record", outcome);
5165
+ },
5166
+ },
5167
+ {
5168
+ key: "epic_branch_ci",
5169
+ run: async () => {
5170
+ // The inspection runs once on every ordinary run: an explicit flag wins, a confirmed
5171
+ // workflow on epic-branch PRs is recorded as include, and anything else is only reported.
5172
+ if (!epicBranchCiWanted)
5173
+ return null;
5174
+ const ci = optionOf("epic_branch_ci");
5175
+ const exemption = optionOf("approval_exemption");
5176
+ const epicBranchCi = await runEpicBranchCiInspection(gateIo, access, deps.gate, {
5177
+ decisionFlag: proposal !== null && (ci === "include" || ci === "decline") ? ci : options.epicBranchCiDecision ?? null,
5178
+ dryRun: false,
5179
+ inferFromCoverage: true,
5180
+ ...(epicBranchCollected !== undefined ? { collected: epicBranchCollected } : {}),
5181
+ ...(proposal !== null ? { exemptionDecision: exemption === "approve" ? "approve" : "decline" } : {}),
5182
+ // On the answers path a decision readiness already reports is not written again.
5183
+ ...(proposal !== null ? { recordedDecision: firstReport.readiness?.epic_branch_ci?.decision ?? null } : {}),
5184
+ });
5185
+ if (epicBranchCi.manualAction !== null)
5186
+ state.evidence.advisories.push(epicBranchCi.manualAction);
5187
+ // BAPI-1637: once per run, after the CI step, from readiness's own facts.
5188
+ await runGateConsequenceSummary(gateIo, access, deps.gate);
5189
+ // BAPI-1654: the plain state, in the same words the choice used.
5190
+ const stateText = epicBranchCiStateText(decisionEvidence?.epicBranchCi ?? null);
5191
+ if (proposal !== null && stateText !== null)
5192
+ deps.log(` ${stateText}`);
5193
+ return epicBranchWriteResults(epicBranchCi, proposal !== null);
5194
+ },
5195
+ },
5196
+ {
5197
+ // BAPI-1654: the approved CI change, delivered only as a pull request, independently of
5198
+ // the setup pull request's own result. Opening it changes no gate and adds no hold.
5199
+ key: "epic_ci_change",
5200
+ run: async () => {
5201
+ if (proposal === null)
5202
+ return null;
5203
+ const d = answerOf("epic_ci_change");
5204
+ if (d === undefined)
5205
+ return null;
5206
+ const offer = ciOfferCollection?.evidence.ciOffer ?? null;
5207
+ const target = offer?.identity.path ?? "github.default_branch";
5208
+ if (d.kind === "decline") {
5209
+ const text = describeDeclinedCiChange({
5210
+ coverage: decisionEvidence?.epicBranchCi?.coverage ?? null,
5211
+ integrationTarget: ciOfferCollection?.evidence.integrationTarget ?? null,
5212
+ coverageViaApprovedSetup: decisionEvidence?.epicBranchCi?.managedWorkflowViaSetupPr === true && setupWorkflowOpened,
5213
+ });
5214
+ deps.log("");
5215
+ deps.log("CI change for epic branches");
5216
+ deps.log(` ${text}`);
5217
+ return { key: "epic_ci_change", status: "declined", target, reason: text };
5218
+ }
5219
+ const delivery = ciOfferCollection?.delivery ?? null;
5220
+ if (offer === null || !offer.applicable || delivery === null) {
5221
+ return {
5222
+ key: "epic_ci_change", status: "unchanged", target,
5223
+ reason: offer === null ? "no CI change is needed now" : "the CI change is already in place",
5224
+ ...(offer !== null ? { read_back: { path: target, state: "in_place" } } : {}),
3213
5225
  };
3214
5226
  }
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
5227
  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
- }
5228
+ deps.log("CI change for epic branches");
5229
+ // The approved answer is this pull request's consent; nothing else is asked.
5230
+ const approved = async () => true;
5231
+ const snapshotOption = state.snapshot !== null ? { snapshot: state.snapshot } : {};
5232
+ let result;
5233
+ try {
5234
+ if (delivery.kind === "trigger_edit") {
5235
+ if (setup.installCiTriggerEdit === undefined) {
5236
+ return { key: "epic_ci_change", status: "unattempted", target, reason: "this caller cannot open the CI pull request", fix: "Run setup from the packaged CLI." };
5237
+ }
5238
+ result = await setup.installCiTriggerEdit(delivery.edit, { dryRun: false, ...snapshotOption }, approved);
5239
+ }
5240
+ else {
5241
+ result = await setup.installCiWorkflow(delivery.command, delivery.toolchains, { dryRun: false, createOnly: true, ...snapshotOption }, approved);
5242
+ }
5243
+ }
5244
+ catch {
5245
+ return { key: "epic_ci_change", status: "uncertain", target, reason: "the CI pull request's result is unknown", fix: "Rerun setup with the same answers; it reconciles an existing pull request before opening one." };
5246
+ }
5247
+ const written = ciChangeWriteResult(offer.identity.action_class, target, result);
5248
+ if (written.reason !== undefined)
5249
+ deps.log(` ${written.reason}`);
5250
+ return written;
5251
+ },
5252
+ },
5253
+ ];
5254
+ // The interactive path keeps its original question order: the missing-item fixes
5255
+ // (merge token, re-index, grant, epic server) come right after the gate and before
5256
+ // the learned check, the setup PR, and qualification. The answers path runs the
5257
+ // array as written so the learned check and setup PR chain on the gate.
5258
+ const ordered = proposal !== null ? operations
5259
+ : [operations[0], ...operations.slice(4, 8), ...operations.slice(1, 4), operations[8], operations[9]];
5260
+ const firstApply = await applyInstallProposal({ proposal, digest: proposalDigest, refusal: null }, { operations: ordered });
5261
+ const applied = firstApply.kind === "applied" ? firstApply.result : { complete: false, results: [] };
3271
5262
  if (options.reviewPolicy === "verdict_protocol" && !options.skipWorkflow) {
3272
5263
  await runClaudeReviewWorkflowOperation(deps, options, state);
3273
5264
  }
3274
5265
  if (options.epicKey && options.planFile) {
3275
5266
  deps.log("");
3276
5267
  deps.log("Verifying the plan with `setup-epic --dry-run`…");
3277
- const verification = await deps.runSetupEpicDryRun([
5268
+ const verification = await progress("checking the plan", () => deps.runSetupEpicDryRun([
3278
5269
  "--dry-run",
3279
5270
  "--epic-key",
3280
5271
  options.epicKey,
@@ -3283,8 +5274,9 @@ async function runConvergingSetup(options, deps, setup) {
3283
5274
  "--review-policy",
3284
5275
  options.reviewPolicy,
3285
5276
  ...(options.repo ? ["--repo", options.repo] : []),
3286
- ]);
5277
+ ]));
3287
5278
  if (verification.exitCode !== 0) {
5279
+ deps.log(" Plan verification failed: `setup-epic --dry-run` reported plan problems (shown above).");
3288
5280
  state.failedOperations.push({
3289
5281
  id: "setup-epic-verification",
3290
5282
  label: "Plan verification",
@@ -3303,24 +5295,87 @@ async function runConvergingSetup(options, deps, setup) {
3303
5295
  deps.log("Executor service");
3304
5296
  observedReadiness = await runExecutorProvisioningPhase(deps, deps.executorProvisioning, executorPlans, access);
3305
5297
  }
5298
+ // ---- BAPI-1545: the advisory capability statement, on every real run ----
5299
+ // Built from the grant and epic-server record as they are NOW (after any
5300
+ // approval above), never from an unapproved proposal. A failed write warns
5301
+ // once and never changes the verdict. A dry run returned long before this.
5302
+ // BAPI-1546: the same write follows an epic-server change, so the server sees
5303
+ // the current mode; a failure after a change is reported on that item only.
5304
+ let statementError = null;
5305
+ if (setup.mcpGrant !== undefined) {
5306
+ statementError = await publishCapabilityStatement(deps, setup.mcpGrant, access, options.verbose === true);
5307
+ }
3306
5308
  // ---- Check 2: the closing assessment (deny probe runs once, here) -------
3307
5309
  deps.log("");
3308
5310
  deps.log("Checking again…");
3309
- const finalReport = await deps.runDoctor({
5311
+ const finalReport = await progress("checking readiness", () => deps.runDoctor({
3310
5312
  access,
3311
- reviewPolicySource: options.reviewPolicy,
5313
+ reviewPolicySource: effectiveReviewPolicy(options, reviewDefault),
5314
+ assessmentVersion: 1,
5315
+ epicRunId: options.assessmentEpicRunId,
3312
5316
  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, {
5317
+ }));
5318
+ const finalReadiness = options.assessmentEpicRunId !== undefined
5319
+ ? finalReport.readiness
5320
+ : observedReadiness ?? finalReport.readiness;
5321
+ // The closing read carries this run's plan and warnings forward, reads the
5322
+ // toolchains it already has, and never repeats a trial or an offer.
5323
+ const closing = await progress("checking readiness", () => collectSetupEvidence(deps, setup, access, finalReadiness, {
3316
5324
  ...collectInputs,
5325
+ // BAPI-1657: after an apply, approval has already happened, so a gate still unknown is not
5326
+ // "stored on approval". Only a dry run's closing preview keeps that promise.
5327
+ plannedGateWrite: plannedGateWrite && options.dryRun === true,
3317
5328
  advisories: state.evidence.advisories,
3318
- commandChanged: state.commandChanged,
3319
- commandBlocked: state.commandBlocked,
5329
+ gateRequiresManagedCheck: gateRequiresManagedCheck || state.ciPlan === "managed",
5330
+ ...(state.ciPlan !== undefined ? { ciPlan: state.ciPlan } : {}),
5331
+ }));
5332
+ if (state.evidence.index.state === "recovery_unresolved" && closing.evidence.index.state !== "reached")
5333
+ closing.evidence.index = state.evidence.index;
5334
+ if (setup.mcpGrant !== undefined) {
5335
+ // A discovery that failed on the first check stays "could not be checked"
5336
+ // in the closing assessment instead of silently dropping the item.
5337
+ closing.evidence.mcpGrant =
5338
+ grantInventory !== null
5339
+ ? await closingMcpGrantState(setup.mcpGrant, access.repoName, grantInventory)
5340
+ : { state: "unknown" };
5341
+ }
5342
+ if (setup.epicServer !== undefined) {
5343
+ const closingEpicServer = await assessEpicServer(setup.epicServer, access.repoName);
5344
+ closing.evidence.epicServer =
5345
+ epicServerChanged && statementError !== null && closingEpicServer.state === "met"
5346
+ ? { ...closingEpicServer, statementError }
5347
+ : closingEpicServer;
5348
+ }
5349
+ // ---- BAPI-1260: the reusable launch profile (explicit) ------------------
5350
+ // BAPI-1635: this runs BEFORE the final items are projected, so a profile saved by
5351
+ // this invocation is read back and judged for escalation, not left as pre-save evidence.
5352
+ // BAPI-1638: the late stage of the same shared apply, which also writes the setup record.
5353
+ let launch;
5354
+ const lateApply = await applyInstallProposal({ proposal, digest: proposalDigest, refusal: null, prior: applied }, {
5355
+ operations: [{
5356
+ key: "launch_profile",
5357
+ run: async () => {
5358
+ if (options.launchProfile === undefined || (proposal !== null && optionOf("launch_profile") === "skip"))
5359
+ return null;
5360
+ launch = await runLaunchProfilePhase(deps, options, {
5361
+ access,
5362
+ baseUrl,
5363
+ readiness: finalReadiness,
5364
+ actorObserved: observedReadiness !== null || finalReadiness?.executor.ready === true,
5365
+ runtime: resolveLaunchRuntime(deps.executorProvisioning, options.executionMode ?? "local"),
5366
+ });
5367
+ return launch.complete
5368
+ ? { key: "launch_profile", status: "written", target: `launch_profile:${options.launchProfile}` }
5369
+ : { key: "launch_profile", status: "failed", target: `launch_profile:${options.launchProfile}`, reason: "the launch-profile steps listed above are not finished", fix: "Finish them, then rerun setup with --launch-profile." };
5370
+ },
5371
+ }],
5372
+ setupRecord: deps.setupRecordWriter ?? null,
3320
5373
  });
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" };
5374
+ const applyResult = lateApply.kind === "applied" ? lateApply.result : applied;
5375
+ {
5376
+ const notification = await collectNotificationEvidence(deps, options, baseUrl);
5377
+ if (notification !== undefined)
5378
+ closing.evidence.notification = notification;
3324
5379
  }
3325
5380
  const items = [...projectSetupItems(closing.evidence), ...state.failedOperations];
3326
5381
  if (deniesEnforcementUnknown(finalReport)) {
@@ -3332,35 +5387,85 @@ async function runConvergingSetup(options, deps, setup) {
3332
5387
  remedy: "the worker safety check could not run; run `epic-implementer doctor` to see why",
3333
5388
  });
3334
5389
  }
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"),
5390
+ if (launch !== undefined && !launch.complete) {
5391
+ items.push({
5392
+ id: "launch-profile",
5393
+ label: `Launch profile '${options.launchProfile}'`,
5394
+ state: "needs_action",
5395
+ blocking: true,
5396
+ remedy: "finish the launch-profile steps listed above, then re-run setup with --launch-profile",
3343
5397
  });
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
5398
  }
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}`);
5399
+ // The latest authoritative command and what CI installs for it. Operator-only:
5400
+ // written through deps.log and nowhere else. Detail, so it waits for --verbose.
5401
+ if (options.verbose === true) {
5402
+ logStoredCommandAndToolchains(deps, closing.evidence.testCommand.state === "stored" ? closing.storedCommand : null, closing.toolchains);
5403
+ }
5404
+ // Assigned inside the shared apply's adapters, so the compiler cannot follow it here.
5405
+ const finalPolicy = policyResult;
5406
+ if (finalPolicy?.status === "deferred" || finalPolicy?.status === "unknown") {
5407
+ items.push({ id: "setup-policy", label: "Combined repository policy", state: "needs_action", blocking: policyRequired || finalPolicy.status === "unknown",
5408
+ remedy: "rerun setup for a fresh preview; ask a bootstrap administrator if uncertainty persists" });
5409
+ }
5410
+ // The assessment sink and the verdict read the complete item list whatever the verbosity.
5411
+ deps.assessmentSink?.(items.find(i => i.assessment)?.assessment);
5412
+ const unmet = unmetBlockingItems(items);
5413
+ // A closed-unmerged setup PR is named once. The legacy path already carries the
5414
+ // notice as a blocking item's remedy, so only print it when no blocking item does.
5415
+ const closedPr = closing.evidence.setupPullRequest;
5416
+ const notice = closedPr.state === "closed_unmerged" && closing.evidence.workflow.state !== "installed" ? closedSetupPullRequestNotice(closedPr) : undefined;
5417
+ const printNotice = notice !== undefined && !unmetBlockingItems(items).some((item) => item.remedy === notice);
5418
+ if (options.verbose === true) {
5419
+ for (const line of renderSetupAssessment(items, "Where things stand", "final"))
5420
+ deps.log(line);
5421
+ for (const advisory of closing.evidence.advisories)
5422
+ deps.log(` - ${advisory}`);
5423
+ if (printNotice)
5424
+ deps.log(` - ${notice}`);
5425
+ }
5426
+ else {
5427
+ // Without --verbose the list is short, but nothing material is hidden: every unmet blocking
5428
+ // step and failed operation prints with its remedy, and so does every advisory that is not
5429
+ // routine editor/hook housekeeping.
5430
+ const problems = [...state.failedOperations, ...unmet].filter((item, index, all) => all.findIndex(o => o.id === item.id) === index);
5431
+ if (problems.length > 0 || printNotice) {
5432
+ deps.log("");
5433
+ deps.log("What still needs attention");
5434
+ for (const item of problems)
5435
+ deps.log(` - ${item.label}: ${setupItemRemedy(item)}`);
5436
+ if (printNotice)
5437
+ deps.log(` - ${notice}`);
5438
+ }
5439
+ for (const advisory of closing.evidence.advisories.filter(a => !routineAdvisories.includes(a)))
5440
+ deps.log(` - ${advisory}`);
5441
+ for (const line of advisoryFindingLines(items))
5442
+ deps.log(line);
5443
+ }
5444
+ // BAPI-1638: each write's own result, then the read-back-driven verdict.
5445
+ if (proposal !== null) {
5446
+ const incomplete = applyResult.results.filter((r) => r.status === "failed" || r.status === "refused" || r.status === "uncertain" || r.status === "unattempted");
5447
+ deps.log("");
5448
+ deps.log("What the answers applied");
5449
+ for (const r of applyResult.results) {
5450
+ deps.log(` - ${r.key}: ${r.status}${r.progress !== undefined ? ` (${r.progress})` : ""}${r.reason !== undefined ? ` — ${r.reason}` : ""}`);
5451
+ }
5452
+ for (const r of incomplete)
5453
+ if (r.fix !== undefined)
5454
+ deps.log(` ${r.key}: ${r.fix}`);
5455
+ }
5456
+ deps.installDocumentSink?.({
5457
+ items,
5458
+ decisions: decisionEvidence,
5459
+ ...(resolvedChoices !== undefined ? { choices: resolvedChoices } : {}),
5460
+ ...(proposal !== null ? { proposal } : {}),
5461
+ ...(proposalDigest !== null ? { digest: proposalDigest } : {}),
5462
+ ...(proposal !== null ? { apply: applyResult } : {}),
5463
+ });
3361
5464
  deps.log("");
3362
- const ready = unmetBlockingItems(items).length === 0;
5465
+ const ready = unmet.length === 0 && (proposal === null || applyResult.complete);
3363
5466
  deps.log(setupVerdictLine(items));
5467
+ // Exactly one next step: the first unmet blocking item's remedy, or the start command.
5468
+ deps.log(`Next step: ${unmet.length === 0 ? (ready ? "Run drive-epic to start your first epic" : "Rerun setup with the same answers to finish the writes listed above") : setupItemRemedy(unmet[0])}`);
3364
5469
  deps.log(ready ? "complete" : "complete-with-manual-steps");
3365
5470
  return ready ? conductorInstallDoctorExitCode(finalReport) : 1;
3366
5471
  }
@@ -3369,15 +5474,333 @@ function deniesEnforcementUnknown(report) {
3369
5474
  const deny = report.legacyConductor?.deny_enforcement;
3370
5475
  return deny !== undefined && deny !== null && deny.enforced !== true;
3371
5476
  }
5477
+ // ---------------------------------------------------------------------------
5478
+ // BAPI-1545: the worker MCP grant and the capability statement
5479
+ // ---------------------------------------------------------------------------
5480
+ /** Compare the published grant with the current inventory. Read-only; never throws. */
5481
+ async function assessMcpGrant(grantDeps, repoName) {
5482
+ let inventory;
5483
+ try {
5484
+ inventory = await grantDeps.discover(repoName);
5485
+ }
5486
+ catch {
5487
+ return { evidence: { state: "unknown" }, inventory: null };
5488
+ }
5489
+ return { evidence: await closingMcpGrantState(grantDeps, repoName, inventory), inventory };
5490
+ }
5491
+ async function closingMcpGrantState(grantDeps, repoName, inventory) {
5492
+ let grant;
5493
+ try {
5494
+ grant = await grantDeps.readGrant(repoName);
5495
+ }
5496
+ catch {
5497
+ return { state: "unknown" };
5498
+ }
5499
+ if (grant.state === "absent")
5500
+ return { state: "needs_action", reason: "no_grant" };
5501
+ if (grant.state === "unusable")
5502
+ return { state: "needs_action", reason: "unusable" };
5503
+ return grant.grant.candidate_fingerprint === inventory.fingerprint
5504
+ ? { state: "met" }
5505
+ : { state: "needs_action", reason: "changed" };
5506
+ }
5507
+ async function fixMcpGrant(deps, grantDeps, repoName, inventory, answer) {
5508
+ deps.log("");
5509
+ deps.log("Worker MCP servers");
5510
+ deps.log(` Epic Implementer workers in ${repoName} always get Bridge. You can approve extra MCP servers for them, ` +
5511
+ "once for this repository. Workers then load exactly Bridge plus what you approve here.");
5512
+ const offered = inventory.candidates;
5513
+ if (offered.length === 0) {
5514
+ deps.log(" Offered: none.");
5515
+ }
5516
+ else {
5517
+ deps.log(" Offered:");
5518
+ offered.forEach((candidate, index) => {
5519
+ if (candidate.definitions.length === 1) {
5520
+ const origins = candidate.definitions[0].origins.map((o) => CANDIDATE_ORIGIN_LABEL[o]).join(", ");
5521
+ deps.log(` ${index + 1}. ${candidate.name} (${origins})`);
5522
+ }
5523
+ else {
5524
+ deps.log(` ${index + 1}. ${candidate.name}: ${candidate.definitions.length} different definitions, you choose one`);
5525
+ }
5526
+ });
5527
+ }
5528
+ const exclusions = describeInventoryExclusions(inventory);
5529
+ if (exclusions.length > 0) {
5530
+ deps.log(" Not offered:");
5531
+ for (const line of exclusions)
5532
+ deps.log(` - ${line}`);
5533
+ }
5534
+ if (answer?.decision === "decline") {
5535
+ // Declining preserves the stored grant byte for byte; invalid entries stay listed above.
5536
+ deps.log(" declined — nothing changed. Any earlier approval stays in force.");
5537
+ return { status: "declined" };
5538
+ }
5539
+ if (answer?.decision === "select")
5540
+ return publishApprovedGrant(deps, grantDeps, repoName, inventory, answer.ids);
5541
+ if (!deps.promptLine) {
5542
+ deps.log(" skipped approving MCP servers: there is no interactive terminal, so this counts as declined. Nothing changed.");
5543
+ return { status: "declined" };
5544
+ }
5545
+ let positions = [];
5546
+ if (offered.length > 0) {
5547
+ const answer = await deps.promptLine(GRANT_SELECTION_PROMPT);
5548
+ const parsed = parseGrantSelection(answer, offered.length);
5549
+ if (parsed === null) {
5550
+ deps.log(" That answer was not a list of offered numbers. Nothing changed; re-run setup to try again.");
5551
+ return { status: "declined" };
5552
+ }
5553
+ positions = parsed;
5554
+ }
5555
+ if (positions.length > MCP_GRANT_MAX_SERVERS) {
5556
+ deps.log(` At most ${MCP_GRANT_MAX_SERVERS} servers can be approved. Nothing changed; re-run setup and pick fewer.`);
5557
+ return { status: "declined" };
5558
+ }
5559
+ const selectedIds = [];
5560
+ const selectedNames = [];
5561
+ for (const position of positions) {
5562
+ const candidate = offered[position];
5563
+ let definition = candidate.definitions[0];
5564
+ if (candidate.definitions.length > 1) {
5565
+ deps.log(` ${candidate.name} is defined differently in more than one place:`);
5566
+ candidate.definitions.forEach((def, i) => {
5567
+ deps.log(` ${String.fromCharCode(97 + i)}. ${def.origins.map((o) => CANDIDATE_ORIGIN_LABEL[o]).join(", ")}`);
5568
+ });
5569
+ const letters = candidate.definitions.map((_, i) => String.fromCharCode(97 + i));
5570
+ const choice = (await deps.promptLine(` Which definition of ${candidate.name}? [${letters.join("/")}, Enter skips it]: `))
5571
+ .trim()
5572
+ .toLowerCase();
5573
+ const index = letters.indexOf(choice);
5574
+ if (index === -1) {
5575
+ deps.log(` ${candidate.name} skipped: no definition was chosen.`);
5576
+ continue;
5577
+ }
5578
+ definition = candidate.definitions[index];
5579
+ }
5580
+ selectedIds.push(definition.id);
5581
+ selectedNames.push(candidate.name);
5582
+ }
5583
+ deps.log(` Workers in ${repoName} would get: Bridge${selectedNames.length > 0 ? ` + ${selectedNames.join(", ")}` : " only"}.`);
5584
+ const ok = await askConsent(deps, `Approve these MCP servers for every Epic Implementer worker in ${repoName}? [y/N]: `, "approving MCP servers");
5585
+ if (!ok) {
5586
+ deps.log(" declined — nothing changed. Any earlier approval stays in force.");
5587
+ return { status: "declined" };
5588
+ }
5589
+ return publishGrant(deps, grantDeps, repoName, inventory, selectedIds);
5590
+ }
5591
+ /**
5592
+ * Publish through child 2's path: a fresh rediscovery, revalidation of every
5593
+ * selected definition, staging, then `writeMcpGrant`. A refusal or failure
5594
+ * leaves the earlier grant as it is.
5595
+ */
5596
+ async function publishGrant(deps, grantDeps, repoName, inventory, selectedIds) {
5597
+ const now = grantDeps.now?.() ?? new Date();
5598
+ let published;
5599
+ try {
5600
+ published = await grantDeps.publish(repoName, inventory, selectedIds, now);
5601
+ }
5602
+ catch {
5603
+ published = { ok: false, error: "the grant could not be saved" };
5604
+ }
5605
+ if (published.ok) {
5606
+ deps.log(" approved — saved outside every worktree. New worker spawns use it.");
5607
+ return { status: "written" };
5608
+ }
5609
+ deps.log(` Warning: ${published.error}. Any earlier approval was left as it is.`);
5610
+ return { status: "failed", reason: published.error };
5611
+ }
5612
+ /**
5613
+ * BAPI-1638 — the answers path: the selection is the approved option ids.
5614
+ * A grant that already holds exactly these servers, for the same inventory, is
5615
+ * `unchanged` and is not rewritten.
5616
+ */
5617
+ async function publishApprovedGrant(deps, grantDeps, repoName, inventory, ids) {
5618
+ const names = inventory.candidates
5619
+ .filter((c) => c.definitions.some((d) => ids.includes(d.id)))
5620
+ .map((c) => c.name)
5621
+ .sort();
5622
+ try {
5623
+ const current = await grantDeps.readGrant(repoName);
5624
+ if (current.state === "ok" && current.grant.candidate_fingerprint === inventory.fingerprint) {
5625
+ const stored = current.grant.servers.map((server) => server.name).filter((name) => name !== "playwright" || names.includes(name)).sort();
5626
+ if (stored.length === names.length && stored.every((name, i) => name === names[i])) {
5627
+ deps.log(" unchanged — the stored approval already says this.");
5628
+ return { status: "unchanged" };
5629
+ }
5630
+ }
5631
+ }
5632
+ catch {
5633
+ // An unreadable grant is replaced through the same revalidated publication below.
5634
+ }
5635
+ deps.log(` Workers in ${repoName} would get: Bridge${names.length > 0 ? ` + ${names.join(", ")}` : " only"}.`);
5636
+ return publishGrant(deps, grantDeps, repoName, inventory, ids);
5637
+ }
5638
+ /**
5639
+ * Build the advisory capability statement from the grant and epic-server record
5640
+ * as they stand now, and PUT it. One warning on failure; never the verdict.
5641
+ */
5642
+ async function publishCapabilityStatement(deps, grantDeps, access, verbose) {
5643
+ try {
5644
+ const [grant, record] = await Promise.all([
5645
+ grantDeps.readGrant(access.repoName),
5646
+ grantDeps.readEpicServerRecord(access.repoName),
5647
+ ]);
5648
+ const statement = buildEpicCapabilityStatement(grant, record, grantDeps.now?.() ?? new Date());
5649
+ await grantDeps.writeStatement(access, statement);
5650
+ if (verbose)
5651
+ deps.log("Capability statement saved to Bridge (advisory; used by plan generation and workers).");
5652
+ return null;
5653
+ }
5654
+ catch {
5655
+ deps.log("Warning: the capability statement could not be saved to Bridge. Setup continues; plans and workers go without it.");
5656
+ return "the capability statement could not be saved to Bridge";
5657
+ }
5658
+ }
5659
+ // ---------------------------------------------------------------------------
5660
+ // BAPI-1546: the epic-server item
5661
+ // ---------------------------------------------------------------------------
5662
+ /** Read the record and map it to setup evidence. Read-only; never throws. */
5663
+ async function assessEpicServer(epicDeps, repoName) {
5664
+ let read;
5665
+ try {
5666
+ read = await epicDeps.readRecord(repoName);
5667
+ }
5668
+ catch {
5669
+ return { state: "unknown" };
5670
+ }
5671
+ if (read.state === "absent")
5672
+ return { state: "needs_action", reason: "no_record" };
5673
+ if (read.state === "unusable")
5674
+ return { state: "needs_action", reason: "unusable" };
5675
+ return { state: "met", mode: read.record.mode };
5676
+ }
5677
+ const EPIC_SERVER_MODE_ANSWERS = Object.freeze({
5678
+ "1": "none",
5679
+ none: "none",
5680
+ "": "none",
5681
+ "2": "local",
5682
+ local: "local",
5683
+ "3": "sfcc_shared_active",
5684
+ sfcc: "sfcc_shared_active",
5685
+ sfcc_shared_active: "sfcc_shared_active",
5686
+ });
5687
+ async function fixEpicServer(deps, epicDeps, repoName, answer) {
5688
+ deps.log("");
5689
+ deps.log("Epic server for UI checks");
5690
+ deps.log(` An Epic Implementer run in ${repoName} can get one epic server: the driver starts the epic's code with a ` +
5691
+ "throwaway test login, and workers borrow it in turns for browser tests and rendered-UI review. " +
5692
+ "SFCC repositories use one approved sandbox instead. Off by default; a missing server only hands UI checks off.");
5693
+ if (answer?.decision === "keep") {
5694
+ deps.log(" kept — nothing changed. Any earlier choice stays in force.");
5695
+ return { status: "declined" };
5696
+ }
5697
+ if (answer?.decision === "record")
5698
+ return writeApprovedEpicServer(deps, epicDeps, repoName, answer.record);
5699
+ if (!deps.promptLine) {
5700
+ deps.log(" skipped configuring the epic server: there is no interactive terminal, so this counts as declined. Nothing changed.");
5701
+ return { status: "declined" };
5702
+ }
5703
+ let hasRecord = false;
5704
+ try {
5705
+ hasRecord = (await epicDeps.readRecord(repoName)).state === "ok";
5706
+ }
5707
+ catch {
5708
+ hasRecord = false;
5709
+ }
5710
+ const decision = await askPlainSetupQuestion({
5711
+ question: `Which epic server mode should Epic Implementer runs in ${repoName} use?`,
5712
+ options: [
5713
+ { id: "none", label: "none: no epic server. Choose this if you have no running app to test against. UI checks are handed off to you." },
5714
+ { id: "local", label: "local: the driver starts this epic's code with a throwaway test login. Choose this if the app can run on this machine; workers borrow it for browser tests." },
5715
+ { id: "sfcc_shared_active", label: "sfcc_shared_active: one approved shared SFCC sandbox. Choose this for SFCC storefronts; you will name the sandbox next.", aliases: ["sfcc"] },
5716
+ {
5717
+ id: "keep",
5718
+ label: hasRecord
5719
+ ? "keep: keep the current choice and change nothing."
5720
+ : "keep: skip this and change nothing. No epic server is set up.",
5721
+ aliases: ["skip", "n", "no"],
5722
+ },
5723
+ ],
5724
+ recommended: hasRecord ? "keep" : "none",
5725
+ recordingFlag: "no flag records this choice; rerun setup in an interactive terminal.",
5726
+ evidence: ["A missing epic server only hands UI checks off; it never blocks a run.", "Selecting a mode records it. It does not install tools, create a sandbox, or grant an MCP server."],
5727
+ consequences: [hasRecord
5728
+ ? "keep is recommended because a choice is already stored and pressing Enter should not replace it."
5729
+ : "none is recommended because it needs nothing set up and is the safe default.",
5730
+ "Nothing changes if you stop here."],
5731
+ recovery: "Rerun setup to choose again. Any earlier choice stays in force until then.",
5732
+ }, plainTerminalFor(deps));
5733
+ const mode = decision.status === "selected" ? EPIC_SERVER_MODE_ANSWERS[decision.id] : undefined;
5734
+ if (mode === undefined) {
5735
+ deps.log(" No epic server mode was chosen. Nothing changed; re-run setup to try again.");
5736
+ return { status: "declined" };
5737
+ }
5738
+ const record = { version: 1, mode };
5739
+ if (mode === "local") {
5740
+ let present = false;
5741
+ try {
5742
+ present = await epicDeps.guidancePresent();
5743
+ }
5744
+ catch {
5745
+ present = false;
5746
+ }
5747
+ record.recipe = present ? "present" : "absent";
5748
+ }
5749
+ else if (mode === "sfcc_shared_active") {
5750
+ deps.log(" Only non-secret values are asked for here. The sandbox account's secret stays in the credential store.");
5751
+ const sandboxId = (await deps.promptLine(" Approved sandbox instance id: ")).trim();
5752
+ if (!isValidSfccSandboxId(sandboxId)) {
5753
+ deps.log(" That is not a usable sandbox id. Nothing changed; re-run setup to try again.");
5754
+ return { status: "declined" };
5755
+ }
5756
+ const credentialRef = (await deps.promptLine(" Credential-store reference for its sandbox-only test account: ")).trim();
5757
+ if (!isValidCredentialReference(credentialRef)) {
5758
+ deps.log(" That is not a usable credential-store reference. Nothing changed; re-run setup to try again.");
5759
+ return { status: "declined" };
5760
+ }
5761
+ const origin = normalizeStorefrontOrigin((await deps.promptLine(" Approved storefront origin (for example https://sandbox.example.com): ")).trim());
5762
+ if (origin === null) {
5763
+ deps.log(" That is not an http or https origin without a path, query, or credentials. Nothing changed.");
5764
+ return { status: "declined" };
5765
+ }
5766
+ record.sfcc = { sandbox_id: sandboxId, credential_ref: credentialRef, storefront_origin: origin };
5767
+ }
5768
+ return writeApprovedEpicServer(deps, epicDeps, repoName, record);
5769
+ }
5770
+ /** Write one approved record through `writeEpicServerRecord`, after the no-change check. */
5771
+ async function writeApprovedEpicServer(deps, epicDeps, repoName, record) {
5772
+ try {
5773
+ const current = await epicDeps.readRecord(repoName);
5774
+ if (current.state === "ok" && sameEpicServerRecord(current.record, record)) {
5775
+ deps.log(" unchanged — the stored choice already says this.");
5776
+ return { status: "unchanged" };
5777
+ }
5778
+ }
5779
+ catch {
5780
+ /* an unreadable current record is simply replaced */
5781
+ }
5782
+ let written;
5783
+ try {
5784
+ written = await epicDeps.writeRecord(repoName, record);
5785
+ }
5786
+ catch {
5787
+ written = { ok: false, error: "the epic-server record could not be written" };
5788
+ }
5789
+ if (!written.ok) {
5790
+ deps.log(` Warning: ${written.error}. Any earlier choice was left as it is.`);
5791
+ return { status: "failed", reason: written.error };
5792
+ }
5793
+ deps.log(` saved — epic server mode ${record.mode}, stored outside every worktree. The driver reads it at run start.`);
5794
+ return { status: "written" };
5795
+ }
3372
5796
  /** Short previews of each fix for --dry-run. */
3373
5797
  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
5798
  setup_pr: "open the setup pull request with the CI workflow (its own consent)",
3378
5799
  gate_and_defaults: "store the repository gate and the safe supervisor defaults (its own consent)",
3379
5800
  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",
5801
+ mcp_grant: "approve which extra MCP servers Epic Implementer workers get in this repository (one consent; the grant is stored outside every worktree)",
5802
+ epic_server: "choose the epic server for Epic Implementer runs: none, local, or sfcc_shared_active (its own consent; the record is stored outside every worktree)",
5803
+ reindex: "use the default branch for indexing when it is the only candidate, or ask which branch to use when a different branch exists; then queue one tracked first parse, or one retry you approve. Dry run writes no configuration, queue, retry, authorization record, or file",
3381
5804
  });
3382
5805
  /**
3383
5806
  * The claude-review workflow, only for an explicit `--review-policy