@bridge_gpt/mcp-server 0.2.72 → 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 (146) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +3 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-permissions.js +27 -0
  5. package/build/ci-system-detection.js +50 -0
  6. package/build/ci-trigger-adapters.js +631 -0
  7. package/build/ci-trigger-install.js +106 -0
  8. package/build/codex-launcher-pin.js +33 -2
  9. package/build/codex-skill-adapter.js +3 -1
  10. package/build/command-host.js +33 -0
  11. package/build/commands.generated.js +7 -6
  12. package/build/conductor/bridge-api-client.js +842 -35
  13. package/build/conductor/bring-up-facts.js +18 -5
  14. package/build/conductor/command-drift-production.js +42 -17
  15. package/build/conductor/command-drift.js +47 -0
  16. package/build/conductor/declare-blocked.js +554 -0
  17. package/build/conductor/doctor.js +106 -21
  18. package/build/conductor/driver-commands.js +141 -0
  19. package/build/conductor/driver-guard.js +277 -0
  20. package/build/conductor/driver-lapse.js +321 -0
  21. package/build/conductor/driver-register.js +176 -0
  22. package/build/conductor/driver-release.js +174 -0
  23. package/build/conductor/driver-session-state.js +315 -0
  24. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  25. package/build/conductor/epic-implementer-cli.js +166 -15
  26. package/build/conductor/epic-server-database.js +162 -0
  27. package/build/conductor/epic-server-guidance.js +278 -0
  28. package/build/conductor/epic-server-journal.js +239 -0
  29. package/build/conductor/epic-server-processes.js +324 -0
  30. package/build/conductor/epic-server-recipe.js +397 -0
  31. package/build/conductor/epic-server-runtime.js +1207 -0
  32. package/build/conductor/epic-server-sfcc.js +107 -0
  33. package/build/conductor/epic-server-state.js +427 -0
  34. package/build/conductor/epic-server.js +594 -0
  35. package/build/conductor/gate-discovery.js +150 -5
  36. package/build/conductor/gate-settings-review.js +224 -4
  37. package/build/conductor/launch-need-probes.js +6 -53
  38. package/build/conductor/launch-plan.js +313 -156
  39. package/build/conductor/prerequisite-inputs.js +879 -45
  40. package/build/conductor/readiness-assessment.js +16 -1
  41. package/build/conductor/readiness-cli.js +20 -9
  42. package/build/conductor/readiness-prerequisites.js +28 -9
  43. package/build/conductor/readiness-sections.js +133 -126
  44. package/build/conductor/readiness.js +1 -1
  45. package/build/conductor/recovery-cli.js +13 -2
  46. package/build/conductor/tools.js +6 -5
  47. package/build/conductor/wait-run-attention.js +2 -2
  48. package/build/conductor/wait-run-cli.js +208 -22
  49. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  50. package/build/conductor/worker-setup-tally.js +27 -0
  51. package/build/credential-store.js +71 -1
  52. package/build/dependency-install-declarations.js +55 -0
  53. package/build/docs.generated.js +2 -2
  54. package/build/doctor.js +54 -3
  55. package/build/drive-epic-help.js +21 -2
  56. package/build/drive-epic.js +1811 -351
  57. package/build/engine-paths.js +20 -0
  58. package/build/epic-branch-ci-summary.js +140 -0
  59. package/build/epic-capability-statement.js +107 -0
  60. package/build/epic-ci-workflow-drift.js +30 -15
  61. package/build/epic-ci-workflow-install.js +110 -42
  62. package/build/epic-ci-workflow-v2.js +274 -0
  63. package/build/epic-ci-workflow.js +38 -12
  64. package/build/epic-implementer-bin.js +2101 -44
  65. package/build/epic-launch-context.js +607 -0
  66. package/build/epic-server-record.js +273 -0
  67. package/build/epic-shared/bridge-client.js +11 -3
  68. package/build/escalation-reachability.js +43 -0
  69. package/build/executor/ci-fix-test-runs.js +334 -0
  70. package/build/executor/completion-contract.js +8 -1
  71. package/build/executor/env.js +59 -22
  72. package/build/executor/epic-server-context.js +141 -0
  73. package/build/executor/gate-qualification-job.js +127 -26
  74. package/build/executor/http-client.js +52 -5
  75. package/build/executor/job-runner.js +423 -69
  76. package/build/executor/observation.js +8 -0
  77. package/build/executor/pre-pr-checks.js +363 -0
  78. package/build/executor/prompt-spec.js +114 -2
  79. package/build/executor/reconcile-overlap-job.js +5 -3
  80. package/build/executor/required-work-diagnostics.js +4 -2
  81. package/build/executor/required-work-ledger.js +936 -38
  82. package/build/executor/results.js +58 -0
  83. package/build/executor/terminal-mutation.js +8 -0
  84. package/build/executor/worker-command.js +72 -3
  85. package/build/executor/worker-database-config.js +281 -0
  86. package/build/executor/worker-database-target.js +16 -12
  87. package/build/executor/worker-database.js +320 -101
  88. package/build/executor/worker-finalization.js +7 -1
  89. package/build/executor/worker-resources.js +25 -3
  90. package/build/executor/worker-verification-guidance.js +18 -3
  91. package/build/executor/worktree.js +20 -1
  92. package/build/executor-launch.js +54 -2
  93. package/build/generated-assets-catalog.js +2 -2
  94. package/build/index.js +664 -335
  95. package/build/init.js +26 -11
  96. package/build/install-bridge-conductor-answers.js +465 -0
  97. package/build/install-bridge-conductor-apply.js +259 -0
  98. package/build/install-bridge-conductor-assessment.js +895 -0
  99. package/build/install-bridge-conductor-compact.js +161 -0
  100. package/build/install-bridge-conductor-contracts.js +63 -0
  101. package/build/install-bridge-conductor-gate.js +1197 -196
  102. package/build/install-bridge-conductor-setup.js +535 -79
  103. package/build/install-bridge-conductor.js +2885 -560
  104. package/build/install-bridge.js +199 -21
  105. package/build/install-maintenance.js +26 -3
  106. package/build/launcher-config-inspection.js +162 -1
  107. package/build/mcp-grant-candidates.js +767 -0
  108. package/build/mcp-grant-doctor.js +63 -0
  109. package/build/mcp-grant.js +288 -0
  110. package/build/mcp-host-targets.js +8 -0
  111. package/build/mcp-identity.js +23 -0
  112. package/build/mcp-invoke.js +126 -13
  113. package/build/mcp-presets.js +107 -0
  114. package/build/mcp-provisioning.js +134 -2
  115. package/build/mcp-registration-doctor.js +31 -2
  116. package/build/mcp-server-invocation.js +6 -1
  117. package/build/merge-workflow-install.js +234 -109
  118. package/build/pipelines.generated.js +5 -5
  119. package/build/plan-discovery.js +97 -4
  120. package/build/plan-execution-ledger.js +100 -7
  121. package/build/plan-generation-io.js +262 -0
  122. package/build/plan-generation.js +424 -0
  123. package/build/plane/build-freshness.js +6 -1
  124. package/build/plane/cli.js +75 -9
  125. package/build/plane/plane-freshness.js +17 -0
  126. package/build/plane/preflight.js +50 -10
  127. package/build/plane/shutdown.js +19 -0
  128. package/build/plane/terminal-run-cleanup.js +18 -4
  129. package/build/printed-remedy-commands.js +206 -12
  130. package/build/readiness-check.js +77 -0
  131. package/build/readiness-prerequisites.generated.js +122 -14
  132. package/build/readme.generated.js +1 -1
  133. package/build/repository-state-paths.js +38 -0
  134. package/build/run-unit-tests-launcher.js +8 -1
  135. package/build/setup-epic.js +1190 -196
  136. package/build/setup-progress.js +44 -0
  137. package/build/setup-question.js +122 -4
  138. package/build/third-party-mcp-targets.js +30 -0
  139. package/build/ticket-delivery-enrollment.js +9 -0
  140. package/build/upgrade-cli.js +85 -2
  141. package/build/v2-readiness-requirements.js +28 -1
  142. package/build/version.generated.js +3 -3
  143. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  144. package/docs/epic-implementer/getting-started.md +3 -1
  145. package/docs/epic-implementer/self-hosting.md +14 -1
  146. package/package.json +2 -2
@@ -1,6 +1,16 @@
1
1
  import { writeJsonDocument, flushProcessStdout } from './conductor/json-output.js';
2
- import { previewConductorSetupPolicy, applyConductorSetupPolicy, fetchConductorSetupPolicy, ConductorSetupPolicyError, SETUP_POLICY_PROTOCOL } from "./conductor/bridge-api-client.js";
3
- import { askSetupQuestion, readCustomSetupCommand, setupConsentQuestion } from "./setup-question.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";
4
14
  /**
5
15
  * `install epic-implementer` — the nested conductor bootstrap phase (BAPI-679).
6
16
  *
@@ -105,26 +115,45 @@ import { askSetupQuestion, readCustomSetupCommand, setupConsentQuestion } from "
105
115
  *
106
116
  * The command does NOT persist a repository-level review policy: that is
107
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.
108
131
  */
109
132
  import { PRINTED_INSTALL_COMMAND, PRINTED_QUALIFY_GATE_COMMAND } from "./printed-remedy-commands.js";
110
- import { confirmRequestFor, emptyConductorGateFlags, hasExplicitGateInput, parseLocalCommandFlag, parseEpicBranchCiDecisionFlag, parseMigrationGuardFlag, resolveConductorGate, runEpicBranchCiInspection, runClearConductorGate, runConductorGateQualification, runQualifyConductorGate, validateConductorGateFlags, } from "./install-bridge-conductor-gate.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";
111
136
  import { fetchConductorReadiness, } from "./conductor/bridge-api-client.js";
112
137
  import { CONDUCTOR_OPERATOR_RUNBOOK_POINTER, EXECUTOR_PROVISIONING_GUIDANCE, conductorInstallDoctorExitCode, conductorInstallDoctorHasFatal, formatConductorInstallDoctorReport, } from "./conductor/install-doctor.js";
113
138
  import { describeNativeLedgerAvailability, } from "./conductor/doctor.js";
114
139
  import { resolveGithubMergeRepositoryIdentity, } from "./credential-store.js";
115
140
  import { isUsableMergeCredentialValue, resolveLocalMergeCredentialDetailed, } from "./conductor/merge-credential.js";
116
- import { readStoredTestCommand, writeStoredTestCommand, } from "./testing-config-client.js";
141
+ import { readStoredTestCommand } from "./testing-config-client.js";
117
142
  import { describeToolchainResolution, resolveRepositoryToolchains, } from "./repository-toolchains.js";
118
143
  import { detectTestCommand } from "./test-command-detection.js";
119
144
  import { TestCommandValidationError, validateTestCommand, } from "./test-command-validation.js";
120
- import { EPIC_IMPLEMENTER_CI_CHECK_NAME } from "./epic-ci-workflow.js";
121
- 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";
122
151
  import { CONDUCTOR_BIN_UNRESOLVED_ERROR, MANAGED_HOOK_NAMES, } from "./conductor/git-hooks.js";
123
152
  import os from "node:os";
124
153
  import path from "node:path";
125
154
  import { readFile as readFileAsync, stat as statAsync } from "node:fs/promises";
126
155
  import { bindEpicLaunchCredential, readStoredBinding, } from "./credential-store.js";
127
- 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";
128
157
  import { DEFAULT_BAPI_BASE_URL } from "./executor/credentials.js";
129
158
  import { MCP_PACKAGE_NAME } from "./mcp-identity.js";
130
159
  import { LOCAL_MERGE_CREDENTIAL_ENV_KEYS } from "./conductor/merge-credential.js";
@@ -162,23 +191,42 @@ export function getInstallBridgeConductorUsage() {
162
191
  "(read-only), fixes only what is missing, checks again, and ends with one",
163
192
  "verdict: \"Ready for your first epic\" or \"Not ready: N steps left\" with the fix",
164
193
  "for each step. Interactive output ends with an advisory readiness verdict.",
165
- " --json Emit one installation result; unanswered interactive choices defer.",
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.",
166
204
  " --assessment-epic-run-id <id> Observe this run's readiness (default: repository preview).",
167
205
  "It exits 0 when ready and 1 for unresolved requested capabilities (0 for --dry-run).",
168
206
  "",
169
207
  "It displays the destination and reads your Claude sign-in (~/.claude.json only)",
170
208
  "and `gh auth status`. A ready repository gets no questions and no",
171
- "writes. Otherwise it asks only what a missing item needs, each with a default of no:",
172
- " - which repository, only when it cannot tell;",
173
- " - saving the test command, only when none is stored (or replacing it, when you",
174
- " pass --test-command);",
175
- " - opening the setup pull request with the CI workflow;",
176
- " - storing the repository gate and safe defaults, when they would change;",
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);",
177
225
  " - storing a GitHub merge token on this computer (read with no echo).",
178
- "The destination is displayed without a redundant URL question. Without an",
179
- "interactive terminal every question is a decline: no token is stored and no",
180
- "pull request is opened. When setup reports that its setup pull request is",
181
- "waiting, merge it and run setup again. Recovery diagnoses the demonstrated",
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",
182
230
  "target, offers keep/correct/defer when needed, and tracks one durable initial",
183
231
  "request. Failed or ineffective work needs an explicit retry; pending work is",
184
232
  "observed without cancellation. Unsupported backends require an upgrade;",
@@ -191,21 +239,51 @@ export function getInstallBridgeConductorUsage() {
191
239
  "local copy only; it does not revoke the token at GitHub, and a running executor",
192
240
  "keeps the token it started with until it restarts.",
193
241
  "",
194
- "Test command: setup prints the stored command (and what CI installs for it) on",
195
- "every run. To save or replace it, pass --test-command \"<command>\": the flag is",
196
- "your consent for that one write, so there is no command question. The command is",
197
- "checked first (one line, no GitHub Actions expression, at most 500 characters),",
198
- "saved once, and read back; setup reports success only when the stored value",
199
- "matches. The same value again is \"unchanged\" and writes nothing. The flag does",
200
- "NOT authorize credential endpoint transfer 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",
201
256
  "does NOT consent to the workflow pull request, which asks for itself. With",
202
- "--dry-run nothing is saved. Do not put a credential in a command: setup prints",
203
- "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.",
204
275
  "",
205
276
  "Options:",
206
- " --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.",
207
279
  " Not combinable with --remove-merge-token or",
208
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.",
209
287
  " --remove-merge-token Remove the merge token stored on this computer for",
210
288
  " this repository (its own consent), then exit.",
211
289
  " --repo <name> Repository name (default: BAPI_REPO_NAME / .bridge/config)",
@@ -214,11 +292,12 @@ export function getInstallBridgeConductorUsage() {
214
292
  " --required-checks a,b Comma-separated form of --required-check",
215
293
  "",
216
294
  "Repository gate — what must pass before a child merges. A CONFIRMED gate is",
217
- "required: provider checks, local commands, both (mixed), or none. Without gate",
218
- "flags, a confirmed gate already stored is used unchanged; otherwise discovery",
219
- "reads this working tree and the provider's real check history and PROPOSES a",
220
- "gate, which is stored only after you confirm or edit it at a prompt. Discovery",
221
- "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.",
222
301
  " --provider-check <name> An exact provider-reported check name (repeatable).",
223
302
  " Admission refuses one that has never reported.",
224
303
  " --local-command <cmd> A local command the executor runs before each merge",
@@ -231,8 +310,6 @@ export function getInstallBridgeConductorUsage() {
231
310
  " child merge. Exclusive with the member flags.",
232
311
  " --customized-command <n> A packaged command this repository customizes, stored",
233
312
  " in the confirmed gate (repeatable), e.g. implement-ticket.",
234
- " --confirm-gate Confirm explicit gate flags even when they REMOVE",
235
- " members from the stored gate (otherwise you are asked).",
236
313
  " --clear-gate Clear the confirmed gate (its own consent), then exit.",
237
314
  " --qualify-gate Qualify a confirmed local or mixed gate: queue the",
238
315
  " qualification job and drain it with a short-lived",
@@ -241,10 +318,12 @@ export function getInstallBridgeConductorUsage() {
241
318
  " without the offer prompt.",
242
319
  "",
243
320
  ` --review-policy <source> One of: ${CONDUCTOR_REVIEW_POLICY_SOURCES.join(", ")}`,
244
- " Omitted, install assumes repository_policy and",
245
- " scaffolds no Claude review workflow. AI review is an",
246
- " explicit opt-in: pass --review-policy verdict_protocol",
247
- " 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",
248
327
  " persists it as the project default, stamped into a new",
249
328
  " run that carries no review policy of its own.",
250
329
  " --epic-key <KEY> Epic key for the setup-epic verification phase",
@@ -254,6 +333,9 @@ export function getInstallBridgeConductorUsage() {
254
333
  " --secret-name <NAME> claude-review workflow: OAuth token secret NAME",
255
334
  " --branches a,b claude-review workflow: PR branch triggers",
256
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.",
257
339
  " --replace-done-gate Replace an EXISTING done gate with the CI-only gate",
258
340
  " built from --required-check. Without it, a repeat",
259
341
  " install keeps the stored gate and only adds missing",
@@ -267,8 +349,8 @@ export function getInstallBridgeConductorUsage() {
267
349
  " no POST, no file write, no host MCP config write,",
268
350
  " no Git hook write, no install-state or capability",
269
351
  " write, no service-unit write, and no write- or",
270
- " start-consent prompt. Still asks the base-URL",
271
- " confirmation first — its readiness read carries the",
352
+ " start-consent prompt. Still displays the resolved",
353
+ " base URL first — its readiness read carries the",
272
354
  " repo API key.",
273
355
  " -h, --help Show this help",
274
356
  "",
@@ -286,10 +368,10 @@ export function getInstallBridgeConductorUsage() {
286
368
  " --executor-id, otherwise local).",
287
369
  " --policy-file <path> Run policy the profile references.",
288
370
  "",
289
- "The resolved BAPI_BASE_URL is displayed and confirmed BEFORE any network call",
290
- "(BAPI_BASE_URL silently defaults to production when unset). The bootstrap POST",
291
- "then asks its own, separate write consent. Without a TTY there is no consent,",
292
- "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.",
293
375
  "",
294
376
  "Tool visibility (its own consent): adds the `epic_implementer` token to the",
295
377
  "BRIDGE_MCP_PROFILE of the Bridge entry in host MCP configurations that",
@@ -327,8 +409,10 @@ export function parseInstallBridgeConductorArgs(argv) {
327
409
  let repo;
328
410
  let dryRun = false;
329
411
  let json = false;
412
+ let compact = false;
330
413
  let skipWorkflow = false;
331
414
  let replaceDoneGate = false;
415
+ let epicServerChange = false;
332
416
  let reviewPolicy = DEFAULT_CONDUCTOR_REVIEW_POLICY;
333
417
  let reviewPolicyExplicit = false;
334
418
  let epicKey;
@@ -350,6 +434,9 @@ export function parseInstallBridgeConductorArgs(argv) {
350
434
  let removeMergeToken = false;
351
435
  let testCommand;
352
436
  let testCommandSeen = false;
437
+ let answers;
438
+ let verbose = false;
439
+ let reviewCiSettings = false;
353
440
  const takeValue = (arg, inline, next) => {
354
441
  if (inline !== undefined) {
355
442
  if (inline.trim().length === 0)
@@ -372,6 +459,24 @@ export function parseInstallBridgeConductorArgs(argv) {
372
459
  return { status: "error", message: "--json takes no value" };
373
460
  json = true;
374
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
+ }
375
480
  case "--dry-run":
376
481
  if (inline !== undefined)
377
482
  return { status: "error", message: "--dry-run takes no value" };
@@ -382,11 +487,27 @@ export function parseInstallBridgeConductorArgs(argv) {
382
487
  return { status: "error", message: "--skip-workflow takes no value" };
383
488
  skipWorkflow = true;
384
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;
385
501
  case "--replace-done-gate":
386
502
  if (inline !== undefined)
387
503
  return { status: "error", message: "--replace-done-gate takes no value" };
388
504
  replaceDoneGate = true;
389
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;
390
511
  case "--repo-wide":
391
512
  if (inline !== undefined)
392
513
  return { status: "error", message: "--repo-wide takes no value" };
@@ -436,6 +557,7 @@ export function parseInstallBridgeConductorArgs(argv) {
436
557
  return { status: "error", message: `${flag} takes no value` };
437
558
  if (flag === "--gate-none")
438
559
  gate.gateNone = true;
560
+ // No effect today; this name is reserved for a later step where an agent relays the user's consent.
439
561
  else if (flag === "--confirm-gate")
440
562
  gate.confirmGate = true;
441
563
  else if (flag === "--clear-gate")
@@ -633,6 +755,9 @@ export function parseInstallBridgeConductorArgs(argv) {
633
755
  message: "--test-command cannot be combined with --clear-gate: clearing the gate is a standalone action.",
634
756
  };
635
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" };
636
761
  // BAPI-1461 — token removal is its own action: only --repo and --dry-run may
637
762
  // accompany it, so it can never be mistaken for, or followed by, setup writes.
638
763
  if (removeMergeToken) {
@@ -656,6 +781,8 @@ export function parseInstallBridgeConductorArgs(argv) {
656
781
  allowedBot !== undefined ||
657
782
  secretName !== undefined ||
658
783
  testCommand !== undefined ||
784
+ reviewCiSettings ||
785
+ answers !== undefined ||
659
786
  branches !== undefined;
660
787
  if (conflicting) {
661
788
  return {
@@ -684,6 +811,7 @@ export function parseInstallBridgeConductorArgs(argv) {
684
811
  repo,
685
812
  dryRun,
686
813
  json,
814
+ ...(compact ? { compact: true } : {}),
687
815
  requiredChecks: normalizedChecks,
688
816
  gate,
689
817
  reviewPolicy,
@@ -695,6 +823,7 @@ export function parseInstallBridgeConductorArgs(argv) {
695
823
  branches,
696
824
  skipWorkflow,
697
825
  ...(replaceDoneGate ? { replaceDoneGate: true } : {}),
826
+ ...(epicServerChange ? { epicServerChange: true } : {}),
698
827
  executorId,
699
828
  ...(epicRunIds.length > 0 ? { epicRunIds } : {}),
700
829
  ...(assessmentEpicRunId !== undefined ? { assessmentEpicRunId } : {}),
@@ -708,6 +837,9 @@ export function parseInstallBridgeConductorArgs(argv) {
708
837
  ...(epicBranchCiDecision ? { epicBranchCiDecision } : {}),
709
838
  ...(removeMergeToken ? { removeMergeToken: true } : {}),
710
839
  ...(testCommand !== undefined ? { testCommand } : {}),
840
+ ...(verbose ? { verbose: true } : {}),
841
+ ...(reviewCiSettings ? { reviewCiSettings: true } : {}),
842
+ ...(answers !== undefined ? { answers } : {}),
711
843
  },
712
844
  };
713
845
  }
@@ -1502,6 +1634,57 @@ function assessNotification(policy, attended, targetBaseUrl, readiness) {
1502
1634
  "delivers a verification to it at approval, and a failure there holds activation.",
1503
1635
  };
1504
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
+ }
1505
1688
  /** BAPI-1461 — whether a stored profile already records exactly this launch. */
1506
1689
  function launchProfileMatches(prior, next) {
1507
1690
  return (prior.baseUrl === next.baseUrl &&
@@ -1770,8 +1953,34 @@ async function runStandaloneGateAction(options, deps, gateIo, access, accessErro
1770
1953
  ? runClearConductorGate(gateIo, access, { dryRun: options.dryRun })
1771
1954
  : runQualifyConductorGate(gateIo, access, deps.gate, { dryRun: options.dryRun, baseUrl });
1772
1955
  }
1773
- 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) {
1774
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
+ }
1775
1984
  deps.log(`Review policy: ${options.reviewPolicy}`);
1776
1985
  deps.log(options.reviewPolicyExplicit
1777
1986
  ? " Explicitly selected, so it is ALSO persisted as the supervisor project " +
@@ -1783,6 +1992,10 @@ function renderReviewPolicy(deps, options) {
1783
1992
  "repository_policy at first approval when nothing else sets one — pass " +
1784
1993
  "--review-policy verdict_protocol to opt in to AI review.");
1785
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
+ }
1786
1999
  /**
1787
2000
  * The executor preflight (BAPI-779): AFTER the URL consent, BEFORE any
1788
2001
  * mutation, and before the dry-run return, so `--dry-run` reports the same
@@ -1832,17 +2045,23 @@ async function runExecutorPreflightPhase(options, deps, baseUrl, access) {
1832
2045
  }
1833
2046
  return { kind: "ok", plans: null };
1834
2047
  }
1835
- /** One output finalizer for success, deferment, dry run, and contained failures. */
1836
2048
  export async function runInstallBridgeConductorCli(argv, deps) {
1837
2049
  const parsed = parseInstallBridgeConductorArgs(argv);
1838
2050
  const machine = argv.includes('--json');
1839
2051
  const human = !machine && deps.isTTY === true;
1840
2052
  let verdict;
2053
+ // BAPI-1604: the compact summary's single next step, held so it prints after the verdict.
2054
+ let nextStep;
1841
2055
  let outcome = 'complete-with-manual-steps';
1842
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 = {};
1843
2061
  const inner = { ...deps,
1844
2062
  get promptLine() { return deps.promptLine; },
1845
2063
  assessmentSink: (value) => { assessment = value; deps.assessmentSink?.(value); },
2064
+ installDocumentSink: (value) => { parts = { ...parts, ...value }; deps.installDocumentSink?.(value); },
1846
2065
  log: (line) => {
1847
2066
  if (/^complete(?:-with-manual-steps)?(?: \(dry run\))?$/.test(line)) {
1848
2067
  outcome = line === 'complete' ? 'complete' : 'complete-with-manual-steps';
@@ -1856,12 +2075,24 @@ export async function runInstallBridgeConductorCli(argv, deps) {
1856
2075
  deps.log(line);
1857
2076
  return;
1858
2077
  }
2078
+ if (human && /^Next step: /.test(line)) {
2079
+ nextStep = line;
2080
+ return;
2081
+ }
1859
2082
  if (machine)
1860
2083
  deps.errorLog(line);
1861
2084
  else
1862
2085
  deps.log(line);
1863
2086
  },
1864
- errorLog: (line) => { deps.errorLog(line); },
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
+ },
1865
2096
  };
1866
2097
  let exitCode;
1867
2098
  try {
@@ -1872,12 +2103,63 @@ export async function runInstallBridgeConductorCli(argv, deps) {
1872
2103
  outcome = 'complete-with-manual-steps';
1873
2104
  deps.errorLog('Setup stopped unexpectedly. Completed independent work is retained; rerun setup to inspect it.');
1874
2105
  }
1875
- if (machine)
1876
- await writeJsonDocument(JSON.stringify({ schemaVersion: 1, outcome, exitCode,
1877
- dryRun: parsed.status === 'ok' && parsed.options.dryRun,
1878
- ...(assessment ? { assessment, advisoryVerdict: verdict ?? 'Readiness not confirmed' } : {}) }), { log: deps.log, flush: deps.isTTY === undefined ? async () => true : flushProcessStdout });
1879
- else if (human && parsed.status === 'ok')
1880
- deps.log(verdict ?? 'Readiness not confirmed — setup did not establish all required evidence; advisory only.');
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
+ }
1881
2163
  return exitCode;
1882
2164
  }
1883
2165
  async function runInstallBridgeConductorCore(argv, deps) {
@@ -1974,7 +2256,7 @@ async function runInstallBridgeConductorCore(argv, deps) {
1974
2256
  deps.log("");
1975
2257
  deps.log("Dry run — no writes will be performed.");
1976
2258
  if (gatePlan !== null)
1977
- await fixGateAndDefaults(deps, options, access, gatePlan);
2259
+ await fixGateAndDefaults(deps, options, access, gatePlan, legacyReviewDefault(options));
1978
2260
  if (gatePlan === null) {
1979
2261
  deps.log(" Repository gate: none confirmed — a real run asks you to confirm one before any write.");
1980
2262
  }
@@ -2000,7 +2282,7 @@ async function runInstallBridgeConductorCore(argv, deps) {
2000
2282
  deps.log(" - done_gate_config.required_checks " +
2001
2283
  `(${bootstrapChecks.length} check(s))`);
2002
2284
  if (options.reviewPolicyExplicit)
2003
- deps.log(" - review_policy");
2285
+ deps.log(" - defaults.review_policy");
2004
2286
  if (options.replaceDoneGate)
2005
2287
  deps.log(" - replace_done_gate");
2006
2288
  deps.log(" - auto_merge_enabled");
@@ -2062,7 +2344,7 @@ async function runInstallBridgeConductorCore(argv, deps) {
2062
2344
  // replacing bootstrap when the server cannot preview.
2063
2345
  deps.log("");
2064
2346
  deps.log("Phase 2/8 — bootstrapping supervisor project defaults…");
2065
- const combined = await fixGateAndDefaults(deps, options, access, gatePlan);
2347
+ const combined = await fixGateAndDefaults(deps, options, access, gatePlan, legacyReviewDefault(options));
2066
2348
  if (combined.status === "deferred" || combined.status === "unknown")
2067
2349
  return 1;
2068
2350
  const storedGate = combined.current
@@ -2102,6 +2384,8 @@ async function runInstallBridgeConductorCore(argv, deps) {
2102
2384
  });
2103
2385
  if (epicBranchCi.manualAction !== null)
2104
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);
2105
2389
  if (options.reviewPolicy === "verdict_protocol") {
2106
2390
  // ---- Phase 3: optional workflow scaffold -------------------------------
2107
2391
  deps.log("");
@@ -2316,12 +2600,34 @@ async function runInstallBridgeConductorCore(argv, deps) {
2316
2600
  * Ask for consent to one write surface. A missing prompt seam (no terminal) is
2317
2601
  * a decline, never a default yes, and says so in one line naming the step.
2318
2602
  */
2319
- 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;
2320
2608
  if (!deps.promptLine) {
2321
2609
  deps.log(` skipped ${step}: there is no interactive terminal, so this counts as declined.`);
2322
2610
  return false;
2323
2611
  }
2324
- 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
+ };
2325
2631
  }
2326
2632
  /**
2327
2633
  * Collect every independent read-only finding. A failed read becomes an
@@ -2336,7 +2642,8 @@ async function collectSetupEvidence(deps, setup, access, readiness, inputs) {
2336
2642
  });
2337
2643
  const identity = identityResult.ok ? identityResult.identity : null;
2338
2644
  const repository = identity !== null ? `${identity.owner}/${identity.repo}` : null;
2339
- // 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.
2340
2647
  let storedCommand = null;
2341
2648
  let testCommand = { state: "unknown" };
2342
2649
  try {
@@ -2349,23 +2656,15 @@ async function collectSetupEvidence(deps, setup, access, readiness, inputs) {
2349
2656
  catch {
2350
2657
  testCommand = { state: "unknown" };
2351
2658
  }
2352
- // The toolchains, read once from the working tree. Kept apart from the
2353
- // non-sensitive readiness evidence below: they are an input to the workflow
2354
- // assessment and to operator-only output, never a readiness row.
2355
- const toolchains = await resolveRepositoryToolchains((relPath) => setup.readRepositoryFile(relPath));
2356
- // 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;
2357
2663
  let workflow = { state: "unknown" };
2358
- if (storedCommand === null) {
2359
- workflow = testCommand.state === "missing" ? { state: "needs_command" } : { state: "unknown" };
2360
- }
2361
- else if (inputs.commandBlocked === true) {
2362
- // A failed command verification blocks every later workflow step, including
2363
- // this closing read: the workflow would be judged against a command nobody
2364
- // confirmed.
2365
- workflow = { state: "blocked", remedy: COMMAND_UNVERIFIED_WORKFLOW_REMEDY };
2366
- }
2367
- else if (inputs.githubSignIn === "signed_in") {
2368
- 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);
2369
2668
  }
2370
2669
  // The setup pull request and, once it merged, the index.
2371
2670
  let setupPullRequest = { state: "unknown" };
@@ -2393,6 +2692,35 @@ async function collectSetupEvidence(deps, setup, access, readiness, inputs) {
2393
2692
  }
2394
2693
  }
2395
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
+ }
2396
2724
  return {
2397
2725
  evidence: {
2398
2726
  readiness,
@@ -2400,12 +2728,18 @@ async function collectSetupEvidence(deps, setup, access, readiness, inputs) {
2400
2728
  githubSignIn: inputs.githubSignIn,
2401
2729
  repositoryIdentity: identityResult.ok ? "resolved" : identityResult.reason,
2402
2730
  testCommand,
2731
+ ...(inputs.ciPlan !== undefined ? { ciPlan: inputs.ciPlan } : {}),
2732
+ ...(inputs.gateRequiresManagedCheck ? { gateRequiresManagedCheck: true } : {}),
2733
+ ...(inputs.plannedGateWrite === true ? { plannedGateWrite: true } : {}),
2403
2734
  workflow,
2404
2735
  setupPullRequest,
2405
2736
  index,
2406
2737
  ...(recovery ? { recovery } : {}),
2407
2738
  mergeCredential,
2408
- gateChangeDeclined: inputs.gateChangeDeclined,
2739
+ ...(freshness !== undefined ? { freshness } : {}),
2740
+ ...(drift !== undefined ? { drift } : {}),
2741
+ ...(launcher !== null ? { launcher } : {}),
2742
+ ...(inputs.path !== undefined ? { path: inputs.path } : {}),
2409
2743
  advisories: inputs.advisories,
2410
2744
  },
2411
2745
  identity,
@@ -2414,8 +2748,6 @@ async function collectSetupEvidence(deps, setup, access, readiness, inputs) {
2414
2748
  toolchains,
2415
2749
  };
2416
2750
  }
2417
- /** The remedy shown for the workflow once a command write could not be verified. */
2418
- 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";
2419
2751
  /** The remedy when the repository's dependency files could not be inspected. Names files, never content. */
2420
2752
  function toolchainInspectionRemedy(resolution) {
2421
2753
  const files = resolution.failures.map((f) => f.file).join(", ");
@@ -2423,20 +2755,25 @@ function toolchainInspectionRemedy(resolution) {
2423
2755
  "Fix the file or its permissions, then re-run setup");
2424
2756
  }
2425
2757
  /**
2426
- * 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).
2427
2760
  *
2428
- * `commandChanged` marks a command written during this run: the workflow must
2429
- * then change too, so a local precondition that stops the preflight (a dirty
2430
- * worktree) is a known outstanding change and must not be hidden by an older
2431
- * 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.
2432
2765
  */
2433
- 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" };
2434
2771
  if (toolchains.status === "unknown") {
2435
- return { state: "blocked", remedy: toolchainInspectionRemedy(toolchains) };
2772
+ return workflowWanted ? { state: "blocked", remedy: toolchainInspectionRemedy(toolchains) } : { state: "unknown" };
2436
2773
  }
2437
2774
  let result;
2438
2775
  try {
2439
- result = await setup.installCiWorkflow(testCommand, toolchains.toolchains, { dryRun: true, quiet: true });
2776
+ result = await setup.installCiWorkflow(testCommand, toolchains.toolchains, { dryRun: true, quiet: true, snapshot });
2440
2777
  }
2441
2778
  catch {
2442
2779
  return { state: "unknown" };
@@ -2447,17 +2784,13 @@ async function assessWorkflow(setup, testCommand, toolchains, commandChanged = f
2447
2784
  case "existing-pr":
2448
2785
  return { state: "pr_open", url: result.prUrl };
2449
2786
  case "dry-run":
2450
- 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" };
2451
2789
  case "installed-pr-opened":
2452
2790
  case "upgrade-pr-opened":
2453
2791
  // A dry run never opens one; treat an impossible answer as unknown.
2454
2792
  return { state: "unknown" };
2455
2793
  case "failed":
2456
- if (result.reason === "worktree_not_clean" || result.reason === "not_repository_root") {
2457
- return commandChanged
2458
- ? { state: "blocked", remedy: result.remediation }
2459
- : { state: "precondition", remedy: result.remediation };
2460
- }
2461
2794
  return result.prUrl !== undefined &&
2462
2795
  (result.reason === "existing_pr_differs" || result.reason === "historical_managed_pr_open")
2463
2796
  ? { state: "blocked", remedy: `${result.remediation} (${result.prUrl})` }
@@ -2534,19 +2867,93 @@ function storedMergeContextFor(setup, providerRepository, localRemote) {
2534
2867
  };
2535
2868
  }
2536
2869
  /** Whether the gate or the supervisor defaults would change (no POST needed). */
2537
- function gateOrDefaultsNeedWrite(gatePlan, readiness) {
2870
+ function gateOrDefaultsNeedWrite(gatePlan, readiness, reviewDefault) {
2538
2871
  if (gatePlan === null)
2539
2872
  return false;
2540
2873
  if (gatePlan.write !== null)
2541
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;
2542
2879
  if (readiness === null)
2543
2880
  return false;
2544
2881
  return !readiness.supervisor.setup_present || !readiness.supervisor.config_present;
2545
2882
  }
2546
- function bootstrapRequestFor(options, plan) {
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;
2890
+ }
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)
2897
+ return false;
2898
+ try {
2899
+ await setup.readSnapshotFile(snapshot, CLAUDE_REVIEW_WORKFLOW_RELPATH);
2900
+ return true;
2901
+ }
2902
+ catch {
2903
+ // Absent and unreadable both fall back to repository_policy, which needs no workflow.
2904
+ return false;
2905
+ }
2906
+ }
2907
+ /**
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.
2913
+ */
2914
+ async function resolveReviewDefault(deps, options, setup, access, snapshot) {
2915
+ let stored;
2916
+ try {
2917
+ stored = storedReviewSource(await fetchConductorSetupPolicy(access, deps.fetchJson));
2918
+ }
2919
+ catch {
2920
+ stored = undefined;
2921
+ }
2922
+ if (options.reviewPolicyExplicit) {
2923
+ return { kind: "send", source: options.reviewPolicy, basis: "explicit", stored: stored ?? null };
2924
+ }
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);
2930
+ return {
2931
+ kind: "send",
2932
+ source: exists ? "verdict_protocol" : "repository_policy",
2933
+ basis: exists ? "workflow_present" : "workflow_absent",
2934
+ stored: null,
2935
+ };
2936
+ }
2937
+ /**
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.
2940
+ */
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;
2952
+ }
2953
+ function bootstrapRequestFor(options, plan, reviewDefault) {
2547
2954
  const { action, confirm, expected_revision, ...gate } = plan.write ?? confirmRequestFor(plan.desired, plan.current.revision, plan.current.profile);
2548
2955
  return { protocol: SETUP_POLICY_PROTOCOL, ...(plan.write !== null ? { gate } : {}),
2549
- defaults: { ...(options.reviewPolicyExplicit ? { review_policy: { source: options.reviewPolicy } } : {}),
2956
+ defaults: { ...(reviewDefault.kind === "send" ? { review_policy: { source: reviewDefault.source } } : {}),
2550
2957
  merge_approval_required: "true" }, replace_done_gate: options.replaceDoneGate === true };
2551
2958
  }
2552
2959
  function policyMatches(expected, actual) {
@@ -2559,8 +2966,61 @@ function policyMatches(expected, actual) {
2559
2966
  };
2560
2967
  return canonical(expected) === canonical(actual);
2561
2968
  }
2562
- async function fixGateAndDefaults(deps, options, access, gatePlan) {
2563
- const request = bootstrapRequestFor(options, gatePlan);
2969
+ /**
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.
2973
+ */
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);
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
+ };
2987
+ /**
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.
2996
+ */
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");
3005
+ }
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));
2564
3024
  for (let attempt = 0; attempt < 2; attempt++) {
2565
3025
  let preview;
2566
3026
  try {
@@ -2570,32 +3030,65 @@ async function fixGateAndDefaults(deps, options, access, gatePlan) {
2570
3030
  deps.log("Deferred: combined setup policy is unavailable or unsupported. Rerun with a compatible server; ask a bootstrap administrator if this persists.");
2571
3031
  return { status: "deferred" };
2572
3032
  }
2573
- deps.log(`Proposed required checks: ${gatePlan.desired.providerChecks.join(", ") || "none"}`);
2574
- for (const effect of preview.effects)
2575
- deps.log(`${effect.category}: ${JSON.stringify(effect.before)} → ${JSON.stringify(effect.after)}`);
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
+ };
2576
3048
  if (options.dryRun) {
3049
+ printEffects();
2577
3050
  deps.log("Dry run: combined preview only; no policy was applied.");
2578
3051
  return { status: "deferred" };
2579
3052
  }
2580
3053
  if (!preview.approval_required) {
3054
+ printEffects();
2581
3055
  deps.log("No change: combined policy already matches.");
2582
3056
  return { status: "unchanged" };
2583
3057
  }
2584
- const decision = await askSetupQuestion({
2585
- purpose: "Authorize exactly the combined repository policy changes shown above.",
2586
- prompt: "Apply these consequential policy changes? [y/N]: ",
2587
- evidence: ["The server computed these effects from one locked policy snapshot.",
2588
- "Existing epic overrides keep precedence. Failed or unknown CI evidence does not relax admission."],
2589
- options: [{ id: "yes", label: "Apply this exact policy" }, { id: "no", label: "Keep policy unchanged" }],
2590
- consequences: ["Required checks can prevent merges. Local commands require qualification; changed commands can invalidate it.",
2591
- "Gate and supervisor defaults commit together, preserving omitted settings."],
2592
- deferred: "Coupled policy remains unchanged; independent setup work can continue.",
2593
- recovery: "Rerun setup for a fresh preview; contact the bootstrap administrator if unavailable.",
2594
- }, { read: deps.promptLine, write: deps.log });
2595
- if (decision.status !== "accept") {
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();
2596
3078
  deps.log("Deferred: combined policy was not approved.");
2597
3079
  return { status: "deferred" };
2598
3080
  }
3081
+ else {
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
+ }
2599
3092
  let current;
2600
3093
  let appliedState;
2601
3094
  let uncertain = false;
@@ -2604,8 +3097,10 @@ async function fixGateAndDefaults(deps, options, access, gatePlan) {
2604
3097
  }
2605
3098
  catch (error) {
2606
3099
  uncertain = true;
2607
- if (error instanceof ConductorSetupPolicyError && error.reason === "stale" && attempt === 0 && deps.promptLine) {
2608
- deps.log("Policy changed: refreshing the preview once. The new effects require a new answer.");
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.");
2609
3104
  continue;
2610
3105
  }
2611
3106
  if (error instanceof ConductorSetupPolicyError && ["refused", "stale", "unsupported"].includes(error.reason)) {
@@ -2627,241 +3122,82 @@ async function fixGateAndDefaults(deps, options, access, gatePlan) {
2627
3122
  deps.log("Unknown—verify before retrying: coherent read-back does not confirm the intended complete policy.");
2628
3123
  return { status: "unknown" };
2629
3124
  }
2630
- deps.log("Completed: coherent server state matches the intended policy.");
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] })));
3129
+ }
3130
+ else {
3131
+ deps.log("Completed: coherent server state matches the intended policy.");
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
+ }
2631
3141
  return { status: "completed", current };
2632
3142
  }
2633
3143
  return { status: "deferred" };
2634
3144
  }
2635
- /**
2636
- * Write failures that are a definite refusal: the server answered and said no.
2637
- * Every other failure is UNCERTAIN (the write may have landed), so it is read
2638
- * back and never retried.
2639
- */
2640
- const DEFINITE_WRITE_REFUSALS = new Set([
2641
- "unauthenticated",
2642
- "forbidden",
2643
- "not_found",
2644
- "invalid_command",
2645
- ]);
2646
- /**
2647
- * Validate `requested`, attempt ONE write, then read the stored value back.
2648
- *
2649
- * - Invalid input is never sent.
2650
- * - A definite refusal (unauthenticated, forbidden, not found, invalid) stops
2651
- * there: nothing changed, so there is nothing to verify.
2652
- * - An accepted write and an uncertain one are both read back. The write is
2653
- * never retried.
2654
- * - Success needs BOTH an accepted write and a read-back equal to the validated
2655
- * requested value.
2656
- */
2657
- export async function saveAndReadBackTestCommand(config, requested) {
2658
- let command;
2659
- try {
2660
- command = validateTestCommand(requested);
2661
- }
2662
- catch (err) {
2663
- return { kind: "invalid_input", reason: err instanceof TestCommandValidationError ? err.reason : "invalid" };
2664
- }
2665
- let written;
2666
- try {
2667
- written = await writeStoredTestCommand(config, command);
2668
- }
2669
- catch {
2670
- written = { ok: false, reason: "transport_failure", status: 0 };
2671
- }
2672
- if (!written.ok && DEFINITE_WRITE_REFUSALS.has(written.reason)) {
2673
- return { kind: "write_failed", reason: written.reason, stored: undefined };
2674
- }
2675
- let readBack;
2676
- try {
2677
- readBack = await readStoredTestCommand(config);
2678
- }
2679
- catch {
2680
- readBack = { ok: false, reason: "transport_failure", status: 0 };
2681
- }
2682
- if (!written.ok) {
2683
- return { kind: "write_failed", reason: written.reason, stored: readBack.ok ? readBack.testCommand : undefined };
2684
- }
2685
- if (!readBack.ok)
2686
- return { kind: "unreadable_verification" };
2687
- if (readBack.testCommand !== command)
2688
- return { kind: "read_back_mismatch", stored: readBack.testCommand };
2689
- return { kind: "confirmed", testCommand: readBack.testCommand };
2690
- }
2691
- const COMMAND_NOT_ATTEMPTED = { confirmed: null, failure: null, serverValue: undefined };
2692
- /** The blocking operation result for a failed command write. Fixed text, no command. */
2693
- function testCommandOperationFailure(remedy) {
2694
- return {
2695
- id: "test-command-save",
2696
- label: "Test command",
2697
- state: "needs_action",
2698
- blocking: true,
2699
- remedy,
2700
- };
2701
- }
2702
- /**
2703
- * Report a non-confirmed outcome in fixed, sanitized words and build its blocking
2704
- * operation result. Never prints the requested command, an upstream error body,
2705
- * or exception text.
2706
- */
2707
- function reportTestCommandSaveFailure(deps, outcome, verb) {
2708
- const head = `Test command not ${verb}`;
2709
- switch (outcome.kind) {
2710
- case "invalid_input":
2711
- deps.log(` ${head} — that command cannot be stored (${outcome.reason}).`);
2712
- return {
2713
- confirmed: null,
2714
- failure: testCommandOperationFailure("give a valid one-line command with --test-command, then re-run setup"),
2715
- serverValue: undefined,
2716
- };
2717
- case "write_failed":
2718
- deps.log(` ${head} — the save did not complete (${outcome.reason}).`);
2719
- return {
2720
- confirmed: null,
2721
- failure: testCommandOperationFailure(outcome.reason === "forbidden" || outcome.reason === "unauthenticated"
2722
- ? "this key cannot change the stored test command; use an administrator key, then re-run setup"
2723
- : "the save did not complete; check the connection and re-run setup"),
2724
- serverValue: outcome.stored,
2725
- };
2726
- case "unreadable_verification":
2727
- deps.log(` ${head} — save may have succeeded; verification failed.`);
2728
- return {
2729
- confirmed: null,
2730
- failure: testCommandOperationFailure("the save may have succeeded but could not be verified; re-run setup to read the stored command"),
2731
- serverValue: undefined,
2732
- };
2733
- case "read_back_mismatch":
2734
- deps.log(` ${head}. The stored value is not the one requested.`);
2735
- return {
2736
- confirmed: null,
2737
- failure: testCommandOperationFailure("the stored value differs from the requested one; check the stored command and re-run setup"),
2738
- serverValue: outcome.stored,
2739
- };
2740
- }
2741
- }
2742
- /** Run one save/replace and turn it into a fix result, logging the outcome. */
2743
- async function persistTestCommand(deps, config, command, verb) {
2744
- const outcome = await saveAndReadBackTestCommand(config, command);
2745
- if (outcome.kind !== "confirmed")
2746
- return reportTestCommandSaveFailure(deps, outcome, verb);
2747
- deps.log(` ${verb} — the stored test command is now in place.`);
2748
- return { confirmed: outcome.testCommand, failure: null, serverValue: outcome.testCommand };
2749
- }
2750
- /** Resolve named alternatives separately from custom command input. */
2751
- async function fixTestCommand(deps, setup, access) {
2752
- const config = setup.testingConfig(access);
2753
- let detection;
2754
- try {
2755
- detection = await detectTestCommand({ skipStoredRead: true }, { config, readFile: relPath => setup.readRepositoryFile(relPath) });
2756
- }
2757
- catch {
2758
- detection = { status: "failed", reason: "repository_read_failed" };
2759
- }
2760
- let command = null;
2761
- if (detection.status === "stored")
2762
- return { confirmed: detection.selected, failure: null, serverValue: detection.selected };
2763
- if (detection.status === "detected" && detection.question === "none"
2764
- && detection.candidates[0]?.autoSaveEligible) {
2765
- const candidate = detection.candidates[0];
2766
- deps.log(`Test command: ${candidate.command}; source: ${candidate.provenance}; runner: ${candidate.runner}; directory: ${candidate.workingDirectory}.`);
2767
- deps.log("Saving this one eligible test command for future CI and verification. Saving does not execute it; execution and coverage are unverified.");
2768
- command = candidate.command;
2769
- }
2770
- else {
2771
- const candidates = detection.status === "failed" ? [] : detection.candidates;
2772
- const terminal = { read: deps.promptLine, write: deps.log };
2773
- const decision = await askSetupQuestion({
2774
- purpose: "Select the test command future CI and verification will use.",
2775
- evidence: detection.status === "failed" ? ["Repository inspection failed; test availability is unknown."]
2776
- : candidates.map((c, i) => `${i + 1}: ${c.command} (${c.provenance}); execution unverified`),
2777
- options: [...candidates.map((c, i) => ({ id: String(i + 1), label: c.command })),
2778
- { id: "custom", label: "Enter a custom command separately" }, { id: "defer", label: "Keep this step unresolved" }],
2779
- consequences: ["The chosen command will be saved once and read back. This does not execute it."],
2780
- deferred: "Workflow preparation remains blocked until a command is verified as saved.",
2781
- recovery: 'Rerun install epic-implementer --test-command "...".',
2782
- }, terminal);
2783
- if (decision.status === "selected") {
2784
- if (decision.id === "custom") {
2785
- const custom = await readCustomSetupCommand(terminal);
2786
- if (custom.status === "custom")
2787
- command = custom.value;
2788
- }
2789
- else {
2790
- command = candidates[Number(decision.id) - 1]?.command ?? null;
2791
- }
2792
- }
2793
- }
2794
- if (command === null) {
2795
- deps.log("Deferred: test command was not saved.");
2796
- return COMMAND_NOT_ATTEMPTED;
2797
- }
2798
- try {
2799
- command = validateTestCommand(command);
2800
- }
2801
- catch {
2802
- deps.log("Deferred: invalid test command.");
2803
- return COMMAND_NOT_ATTEMPTED;
2804
- }
2805
- return persistTestCommand(deps, config, command, "saved");
2806
- }
2807
- /**
2808
- * Fix: save or replace the test command the operator passed with
2809
- * `--test-command`. The validated flag IS the consent for this one write, so the
2810
- * command write never goes through {@link askConsent}. The same validation,
2811
- * single write, and server read-back apply.
2812
- */
2813
- async function fixExplicitTestCommand(deps, setup, access, command, hadStoredCommand) {
2814
- deps.log("");
2815
- deps.log("Test command");
2816
- deps.log(" saving the command you passed with --test-command; that flag is the consent for this write.");
2817
- return persistTestCommand(deps, setup.testingConfig(access), command, hadStoredCommand ? "replaced" : "saved");
2818
- }
2819
3145
  /** The one operator-only line for a readable stored command, then what CI installs for it. */
2820
3146
  function logStoredCommandAndToolchains(deps, storedCommand, toolchains) {
3147
+ if (storedCommand === null)
3148
+ return;
2821
3149
  deps.log("");
2822
- if (storedCommand !== null) {
2823
- 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}`);
2824
3155
  }
2825
- deps.log("What CI installs for it:");
2826
- for (const line of describeToolchainResolution(toolchains))
2827
- deps.log(` ${line}`);
2828
3156
  }
2829
3157
  /** Fix: open the one setup pull request through the artifact-set installer. */
2830
- 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) {
2831
3161
  deps.log("");
2832
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
+ }
2833
3169
  if (toolchains.status === "unknown") {
2834
3170
  // Uninspectable dependency files are a blocking inspection failure, never "no lockfile".
2835
3171
  const remedy = toolchainInspectionRemedy(toolchains);
2836
3172
  deps.log(` skipped — ${remedy}.`);
2837
- return { workflow: { state: "blocked", remedy }, pr: null };
3173
+ return { workflow: { state: "blocked", remedy }, pr: null, result: null };
2838
3174
  }
2839
3175
  let result;
2840
3176
  try {
2841
- // The setup pull request has its OWN consent, separate from the command write.
2842
- 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));
2843
3179
  }
2844
3180
  catch {
2845
3181
  deps.log(" the setup pull request could not be prepared; re-run setup.");
2846
- return { workflow: { state: "unknown" }, pr: null };
3182
+ return { workflow: { state: "unknown" }, pr: null, result: null };
2847
3183
  }
2848
3184
  switch (result.outcome) {
2849
3185
  case "installed-pr-opened":
2850
3186
  case "upgrade-pr-opened":
2851
3187
  deps.log(` opened the setup PR: ${result.prUrl}`);
2852
- return { workflow: { state: "pr_open", url: result.prUrl }, pr: null };
3188
+ return { workflow: { state: "pr_open", url: result.prUrl }, pr: null, result };
2853
3189
  case "existing-pr":
2854
3190
  deps.log(` the setup PR is already open: ${result.prUrl}`);
2855
- return { workflow: { state: "pr_open", url: result.prUrl }, pr: null };
3191
+ return { workflow: { state: "pr_open", url: result.prUrl }, pr: null, result };
2856
3192
  case "identical":
2857
3193
  deps.log(" the CI workflow is already in place — nothing to change.");
2858
- return { workflow: { state: "installed" }, pr: null };
3194
+ return { workflow: { state: "installed" }, pr: null, result };
2859
3195
  case "dry-run":
2860
- return { workflow: { state: "needs_pr" }, pr: null };
3196
+ return { workflow: result.upgrade ? { state: "needs_pr" } : { state: "absent" }, pr: null, result };
2861
3197
  case "failed": {
2862
3198
  if (result.reason === "consent_declined") {
2863
3199
  deps.log(" declined — no branch was pushed and no pull request was opened.");
2864
- return { workflow: { state: "needs_pr" }, pr: null };
3200
+ return { workflow: { state: "absent" }, pr: null, result };
2865
3201
  }
2866
3202
  deps.log(` the setup pull request was not opened (${result.reason}): ${result.remediation}`);
2867
3203
  if (result.prUrl !== undefined)
@@ -2871,8 +3207,8 @@ async function fixSetupPullRequest(deps, setup, testCommand, toolchains, reposit
2871
3207
  // An uncertain creation is re-read, never repeated.
2872
3208
  const pr = repository !== null ? await readSetupPullRequest(setup.runGh, repository) : null;
2873
3209
  if (pr?.state === "open")
2874
- return { workflow: { state: "pr_open", url: pr.url }, pr };
2875
- 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 };
2876
3212
  }
2877
3213
  }
2878
3214
  }
@@ -2880,7 +3216,11 @@ async function fixSetupPullRequest(deps, setup, testCommand, toolchains, reposit
2880
3216
  * Fix: store (or replace) the GitHub merge token for this repository, after its
2881
3217
  * own consent, read with no echo. Never printed, logged, committed, or sent.
2882
3218
  */
2883
- 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) {
2884
3224
  const repository = `${identity.owner}/${identity.repo}`;
2885
3225
  deps.log("");
2886
3226
  deps.log("GitHub merge token");
@@ -2893,31 +3233,66 @@ async function fixMergeToken(deps, setup, identity, replacing) {
2893
3233
  }
2894
3234
  const ok = await askConsent(deps, replacing
2895
3235
  ? `Replace the stored merge token for ${repository}? [y/N]: `
2896
- : `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");
2897
3237
  if (!ok) {
2898
3238
  deps.log(replacing
2899
3239
  ? " declined — the stored token was left as it is."
2900
3240
  : " declined — nothing was stored. You can set GITHUB_MERGE_TOKEN instead.");
2901
- return false;
2902
- }
2903
- if (!setup.promptSecret) {
2904
- deps.log(" skipped reading the token: there is no interactive terminal. Nothing was stored.");
2905
- return false;
3241
+ return { status: "declined" };
2906
3242
  }
2907
3243
  let token = "";
2908
- try {
2909
- token = (await setup.promptSecret("GitHub merge token (input is hidden): ")).trim();
2910
- }
2911
- catch {
2912
- token = "";
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
+ }
2913
3275
  }
2914
- if (token.length === 0) {
2915
- deps.log(" no token was entered; nothing was stored.");
2916
- 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
+ }
2917
3291
  }
2918
3292
  if (!isUsableMergeCredentialValue(token)) {
3293
+ token = "";
2919
3294
  deps.log(" that value cannot be a GitHub token (it has spaces or control characters); nothing was stored.");
2920
- return false;
3295
+ return { status: "failed", reason: "the referenced value cannot be a GitHub token" };
2921
3296
  }
2922
3297
  const result = await setup.storeMergeToken(identity, token);
2923
3298
  let stored = result.ok;
@@ -2929,19 +3304,18 @@ async function fixMergeToken(deps, setup, identity, replacing) {
2929
3304
  token = "";
2930
3305
  if (!stored) {
2931
3306
  deps.log(` the token could not be stored (${result.ok ? "unconfirmed" : result.kind}); nothing changed.`);
2932
- return false;
3307
+ return { status: "failed", reason: `the token could not be stored (${result.ok ? "unconfirmed" : result.kind})` };
2933
3308
  }
2934
3309
  deps.log(` stored the merge token for ${repository} on this computer.`);
2935
3310
  if (replacing) {
2936
3311
  deps.log(" A run already in progress keeps the token its executor started with until that executor restarts.");
2937
3312
  }
2938
- return true;
3313
+ return { status: "written" };
2939
3314
  }
2940
- /**
2941
- * Recovery stays unavailable until target-aware backend admission is wired.
2942
- * Never fall back to a repository-only parse from content relation evidence.
2943
- */
2944
- export async function fixReindex(deps, setup, access, initial) {
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) {
2945
3319
  deps.log("");
2946
3320
  deps.log("Repository indexing");
2947
3321
  const unresolved = (remedy, choice) => {
@@ -2950,8 +3324,9 @@ export async function fixReindex(deps, setup, access, initial) {
2950
3324
  };
2951
3325
  if (!initial?.supported || !setup.fetchRecoveryEvidence || !setup.correctBranch || !setup.admitRecovery)
2952
3326
  return unresolved("Upgrade the Bridge backend/client for target-aware recovery; nothing was queued.");
2953
- if (!deps.promptLine)
2954
- return unresolved("Branch recovery is deferred: there is no interactive terminal. Re-run setup interactively to review the exact effect; nothing was queued.", "deferred");
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");
2955
3330
  let current = initial.evidence;
2956
3331
  const knownUnverified = (e) => !e.canonical.verified
2957
3332
  && ["absent", "unverified"].includes(e.canonical_observation ?? "unknown");
@@ -2967,23 +3342,38 @@ export async function fixReindex(deps, setup, access, initial) {
2967
3342
  return unresolved("Configured branch ancestry is unknown; inspect it before retrying. Nothing was queued.");
2968
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}`);
2969
3344
  if (!["equal", "contains_target"].includes(current.configured_relation) || current.canonical_relation === "diverged") {
2970
- const decision = await askSetupQuestion({
2971
- purpose: "Choose how setup should recover the indexing branch.",
2972
- evidence: [`Stored branch: ${JSON.stringify(current.configured_branch)}. Proposed destination: ${current.destination_branch}.`,
2973
- `Required setup revision: ${current.required_commit_sha}; configured head: ${current.resolved_head_sha}; canonical content: ${current.canonical_relation}.`],
2974
- options: [{ id: "keep", label: "Keep current configuration" }, { id: "correct", label: "Correct to the demonstrated setup destination" }, { id: "defer", label: "Defer this choice" }],
2975
- consequences: [
2976
- `Correct changes the shared base from ${JSON.stringify(current.configured_branch)} to ${current.destination_branch}, then admits one tracked initial parse if its read-back and fresh target evidence agree.`,
2977
- "Parsing resolves the configured branch again at execution time; fetched evidence may drift from this preview.",
2978
- "The shared base affects future applicable deliveries. Existing PR bases and delivery policy are unchanged; already-bound/in-flight work may still use earlier state.",
2979
- "Keep preserves your branch. Setup can index it only if fresh evidence shows it contains the setup revision; otherwise integrate the setup changes there first.",
2980
- ], deferred: "Index recovery remains unresolved; independent completed setup work is retained.",
2981
- recovery: "Inspect the branch with the repository maintainer, then re-run setup interactively.",
2982
- }, { read: deps.promptLine, write: deps.log });
2983
- if (decision.status !== "selected" || decision.id === "defer")
2984
- return decision.status === "decline"
2985
- ? unresolved("Branch correction declined; the configured branch is retained and nothing was queued. Integrate the setup changes there before rerunning setup.", "declined")
2986
- : unresolved("Branch choice deferred; no correction or parse was submitted. Re-run setup interactively when ready.", "deferred");
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");
2987
3377
  if (decision.id === "keep" && !["equal", "contains_target"].includes(current.configured_relation))
2988
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");
2989
3379
  if (decision.id === "correct") {
@@ -3020,17 +3410,26 @@ export async function fixReindex(deps, setup, access, initial) {
3020
3410
  if (current.request) {
3021
3411
  if (current.retry_generation === null)
3022
3412
  return unresolved("The retained request has no verified retry generation; inspect its history with your Bridge administrator.");
3023
- const decision = await askSetupQuestion({
3024
- purpose: "Authorize one explicit setup retry.", evidence: [
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: [
3025
3424
  `Prior request ${current.request.id}, run ${current.request.parse_run_id ?? "retained"}, status ${current.request.status}.`,
3026
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.`,
3027
3426
  `Retry generation ${current.retry_generation} for branch ${JSON.stringify(current.configured_branch)} and configuration ${current.configuration_fingerprint}.`,
3028
- ], options: [{ id: "retry", label: "Authorize this retry generation" }, { id: "defer", label: "Defer retry" }],
3029
- consequences: ["One durable successor will resolve the configured branch at execution time. Replaying this same generation cannot create another request.", "This retry is separate from internal subprocess/worker recovery. Healthy active work is never cancelled."],
3030
- deferred: "The failed or ineffective attempt remains unresolved; independent setup work is retained.", recovery: "Inspect the prior attempt, then re-run interactive setup.",
3031
- }, { read: deps.promptLine, write: deps.log });
3032
- if (!(decision.status === "accept" || (decision.status === "selected" && decision.id === "retry")))
3033
- return decision.status === "decline"
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"
3034
3433
  ? unresolved("Retry declined; no request was submitted. Re-run setup after reviewing the prior attempt.", "declined")
3035
3434
  : unresolved("Retry deferred; no request was submitted. Re-run setup after reviewing the prior attempt.", "deferred");
3036
3435
  retry = current.retry_generation;
@@ -3110,8 +3509,12 @@ function localAdvisories(report) {
3110
3509
  return out;
3111
3510
  }
3112
3511
  /** Non-mutating boundary shared by explicit and converging setup actions. */
3113
- export async function assessEpicInstallerPrerequisites(deps, executorRequested = false) {
3114
- 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.");
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
+ }
3115
3518
  let observed = { claudeLoggedIn: null, githubSignIn: "unavailable", localRemote: null, toolsAvailable: false, platformSupported: false };
3116
3519
  try {
3117
3520
  if (deps.prerequisites)
@@ -3145,48 +3548,1223 @@ export async function assessEpicInstallerPrerequisites(deps, executorRequested =
3145
3548
  !observed.localRemote ? "supported github.com origin missing or unknown" : null,
3146
3549
  !observed.toolsAvailable ? "required tools missing or unknown" : null,
3147
3550
  !observed.platformSupported ? "host/platform unsupported or unknown" : null].filter(Boolean);
3148
- 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; general Bridge assets can be maintained separately.`);
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."}`);
3149
3552
  }
3150
3553
  return { ...observed, available };
3151
3554
  }
3152
- async function runConvergingSetup(options, deps, setup) {
3153
- if (options.removeMergeToken === true)
3154
- return runRemoveMergeToken(options, deps, setup);
3155
- const confirmed = await resolveAndConfirmBaseUrl(options, deps, "");
3156
- if (!confirmed.ok)
3157
- return confirmed.code;
3158
- const baseUrl = confirmed.baseUrl;
3159
- const prerequisites = await assessEpicInstallerPrerequisites(deps, Boolean(options.executorId));
3160
- if (!prerequisites.available && !options.dryRun)
3161
- return 1;
3162
- const { claudeLoggedIn, githubSignIn, localRemote } = prerequisites;
3163
- // ---- Repository: ask only when it is genuinely ambiguous ----------------
3164
- let accessResult = await deps.resolveAccess(options.repo, baseUrl);
3165
- if (!accessResult.ok && options.repo === undefined && deps.promptLine) {
3166
- const suggestion = localRemote?.split("/")[1] ?? null;
3167
- deps.log("");
3168
- deps.log("Which repository is this? Bridge could not tell from the environment or .bridge/config.");
3169
- const answer = (await deps.promptLine(suggestion !== null
3170
- ? `Bridge repository name [${suggestion}]: `
3171
- : "Bridge repository name (press Enter to skip): ")).trim();
3172
- const chosen = answer.length > 0 && !/^(y|yes|n|no)$/i.test(answer) ? answer : null;
3173
- if (chosen !== null)
3174
- accessResult = await deps.resolveAccess(chosen, baseUrl);
3175
- }
3176
- const access = accessResult.ok ? accessResult.access : null;
3177
- const accessError = accessResult.ok ? undefined : accessResult.error;
3178
- const earlyPreflight = await runExecutorPreflightPhase(options, deps, baseUrl, access);
3179
- if (earlyPreflight.kind === "refused")
3180
- return 1;
3181
- const gateIo = gateIoFor(deps);
3182
- const standalone = await runStandaloneGateAction(options, deps, gateIo, access, accessError, baseUrl);
3183
- if (standalone !== null)
3184
- return standalone;
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" };
4599
+ }
4600
+ /**
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.
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
+ }
4660
+ async function runConvergingSetup(options, deps, setup) {
4661
+ if (options.removeMergeToken === true)
4662
+ return runRemoveMergeToken(options, deps, setup);
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, "");
4682
+ if (!confirmed.ok)
4683
+ return confirmed.code;
4684
+ const baseUrl = confirmed.baseUrl;
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) {
4720
+ const suggestion = localRemote?.split("/")[1] ?? null;
4721
+ deps.log("");
4722
+ deps.log("Which repository is this? This folder is not bound to a Bridge project and Bridge could not tell from the environment.");
4723
+ const answer = (await deps.promptLine(suggestion !== null
4724
+ ? `Bridge repository name [${suggestion}]: `
4725
+ : "Bridge repository name (press Enter to skip): ")).trim();
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);
4729
+ if (chosen !== null)
4730
+ accessResult = await deps.resolveAccess(chosen, baseUrl);
4731
+ }
4732
+ const access = accessResult.ok ? accessResult.access : null;
4733
+ const accessError = accessResult.ok ? undefined : accessResult.error;
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
+ };
4751
+ const standalone = await runStandaloneGateAction(options, deps, gateIo, access, accessError, baseUrl);
4752
+ if (standalone !== null)
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
+ }
3185
4763
  // ---- Check 1: the read-only doctor (no deny probe yet) ------------------
3186
4764
  deps.log("");
3187
4765
  deps.log("Checking your setup (read-only)…");
3188
4766
  const storedContext = storedMergeContextFor(setup, null, localRemote);
3189
- const firstReport = await deps.runDoctor({
4767
+ const firstReport = await progress("checking readiness", () => deps.runDoctor({
3190
4768
  access,
3191
4769
  accessError,
3192
4770
  reviewPolicySource: options.reviewPolicy,
@@ -3194,7 +4772,7 @@ async function runConvergingSetup(options, deps, setup) {
3194
4772
  epicRunId: options.assessmentEpicRunId,
3195
4773
  skipDenyProbe: true,
3196
4774
  storedMergeCredential: storedContext,
3197
- });
4775
+ }));
3198
4776
  if (conductorInstallDoctorHasFatal(firstReport) || !access) {
3199
4777
  deps.log(formatConductorInstallDoctorReport(firstReport));
3200
4778
  deps.errorLog("");
@@ -3205,59 +4783,198 @@ async function runConvergingSetup(options, deps, setup) {
3205
4783
  return 1;
3206
4784
  }
3207
4785
  const executorPlans = earlyPreflight.plans;
3208
- // ---- The gate: explicit flags win; otherwise the CI check is added ------
3209
- const gatePhase = await resolveConductorGate(gateIo, access, options.gate, deps.gate, {
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, {
3210
4806
  dryRun: options.dryRun,
3211
4807
  planningOnly: true,
3212
- ...(hasExplicitGateInput(options.gate) ? {} : { ensureProviderCheck: EPIC_IMPLEMENTER_CI_CHECK_NAME }),
4808
+ inferCi: !hasExplicitGateInput(options.gate),
3213
4809
  });
3214
4810
  if (gatePhase.kind === "exit")
3215
4811
  return gatePhase.code;
3216
4812
  const gatePlan = gatePhase.kind === "plan" ? gatePhase.plan : null;
3217
- 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);
3218
4814
  const advisories = localAdvisories(firstReport);
3219
- const collectInputs = { claudeLoggedIn, githubSignIn, localRemote, gateChangeDeclined, advisories };
3220
- 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 }));
3221
4824
  const state = {
3222
4825
  evidence: first.evidence,
3223
4826
  identity: first.identity,
3224
4827
  repository: first.repository,
3225
4828
  storedCommand: first.storedCommand,
4829
+ snapshot,
3226
4830
  toolchains: first.toolchains,
3227
- commandChanged: false,
3228
- commandBlocked: false,
4831
+ ciPlan: undefined,
4832
+ commandUncertain: false,
4833
+ trial: null,
4834
+ promotedCommands: null,
3229
4835
  failedOperations: [],
3230
4836
  };
3231
- const firstItems = projectSetupItems(state.evidence);
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
+ ];
3232
4863
  deps.assessmentSink?.(firstItems.find(i => i.assessment)?.assessment);
3233
- for (const line of renderSetupAssessment(firstItems, "What setup found", "initial"))
3234
- deps.log(line);
3235
- // An explicit --test-command asks for a write unless the stored value already
3236
- // equals it. A stored value that could not be read is eligible for the write.
3237
- // Only this non-sensitive boolean reaches the planner; the text never does.
3238
- const explicitCommand = options.testCommand;
3239
- const commandAlreadyStored = explicitCommand !== undefined &&
3240
- state.evidence.testCommand.state === "stored" &&
3241
- state.storedCommand === explicitCommand;
3242
- const replaceTestCommandRequested = explicitCommand !== undefined && !commandAlreadyStored;
3243
- const policyRequired = gateOrDefaultsNeedWrite(gatePlan, firstReport.readiness);
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);
3244
4872
  const planContext = {
3245
- gateOrDefaultsNeedWrite: gateOrDefaultsNeedWrite(gatePlan, firstReport.readiness),
4873
+ gateOrDefaultsNeedWrite: gateOrDefaultsNeedWrite(gatePlan, firstReport.readiness, reviewDefault),
3246
4874
  suppliedPolicyInput: options.reviewPolicyExplicit || options.replaceDoneGate || hasExplicitGateInput(options.gate),
3247
- dryRun: options.dryRun,
4875
+ ...(options.epicServerChange === true ? { epicServerChangeRequested: true } : {}),
3248
4876
  };
3249
- let fixes = planSetupFixes(state.evidence, { ...planContext, replaceTestCommandRequested });
3250
- if (commandAlreadyStored) {
3251
- deps.log("");
3252
- deps.log("Test command unchanged — it already matches --test-command, so nothing was written.");
3253
- }
3254
- // ---- Dry run: preview only, before every write and write prompt ---------
3255
- if (options.dryRun) {
3256
- if (gatePlan !== null)
3257
- await fixGateAndDefaults(deps, options, access, gatePlan);
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 });
3258
4969
  logStoredCommandAndToolchains(deps, state.storedCommand, state.toolchains);
4970
+ renderDryRunCiPlan(deps, options, gatePlan);
4971
+ if (managedWorkflowInPlay(state, gateRequiresManagedCheck))
4972
+ await warnDefaultBranchRequiresManagedCheck(setup, state);
3259
4973
  deps.log("");
3260
- 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
+ }
3261
4978
  if (fixes.length === 0)
3262
4979
  deps.log(" No fix is needed.");
3263
4980
  for (const fix of fixes)
@@ -3266,106 +4983,289 @@ async function runConvergingSetup(options, deps, setup) {
3266
4983
  deps.log(` Would write executor unit: ${executorPlans.install.unitPath}`);
3267
4984
  deps.log(` Would start it with: ${executorPlans.start.manualCommand}`);
3268
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);
3269
5008
  deps.log("");
3270
5009
  deps.log(setupVerdictLine(firstItems));
3271
- deps.log("complete-with-manual-steps (dry run)");
3272
- return 0;
3273
- }
3274
- // ---- 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.
3275
5022
  if (fixes.length > 0) {
3276
5023
  deps.log("");
3277
5024
  deps.log("Fixing what is missing…");
3278
5025
  }
3279
- // Each fix runs at most once per invocation: re-planning after a command write
3280
- // can add the workflow fix, but never repeats a write, a declined prompt, or
3281
- // an independent setup operation.
3282
5026
  let policyResult = null;
3283
- const attempted = new Set();
3284
- while (fixes.length > 0) {
3285
- const fix = fixes.shift();
3286
- if (attempted.has(fix))
3287
- continue;
3288
- attempted.add(fix);
3289
- if (isTestCommandFix(fix)) {
3290
- const result = fix === "replace_test_command" && explicitCommand !== undefined
3291
- ? await fixExplicitTestCommand(deps, setup, access, explicitCommand, state.evidence.testCommand.state === "stored")
3292
- : await fixTestCommand(deps, setup, access);
3293
- if (result.failure !== null) {
3294
- // A write that was not confirmed: report it as a blocking operation, keep
3295
- // only the server's returned value, and block every later workflow step.
3296
- state.failedOperations.push(result.failure);
3297
- state.commandBlocked = true;
3298
- if (result.serverValue !== undefined) {
3299
- state.storedCommand = result.serverValue;
3300
- state.evidence = {
3301
- ...state.evidence,
3302
- testCommand: { state: result.serverValue === null ? "missing" : "stored" },
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" } } : {}),
3303
5225
  };
3304
5226
  }
3305
- state.evidence = { ...state.evidence, workflow: { state: "blocked", remedy: COMMAND_UNVERIFIED_WORKFLOW_REMEDY } };
3306
- }
3307
- else if (result.confirmed !== null) {
3308
- state.storedCommand = result.confirmed;
3309
- state.commandChanged = true;
3310
- state.evidence = { ...state.evidence, testCommand: { state: "stored" } };
3311
- // Reassess the workflow against the CONFIRMED value and the same
3312
- // toolchain snapshot, then derive what is left from the updated evidence.
3313
- const reassessed = state.evidence.githubSignIn === "signed_in"
3314
- ? await assessWorkflow(setup, result.confirmed, state.toolchains, true)
3315
- : { state: "unknown" };
3316
- state.evidence = { ...state.evidence, workflow: reassessed };
3317
- fixes = planSetupFixes(state.evidence, { ...planContext, replaceTestCommandRequested: false }).filter((kind) => !attempted.has(kind) && !isTestCommandFix(kind));
3318
- }
3319
- }
3320
- else if (fix === "setup_pr") {
3321
- if (state.commandBlocked) {
3322
5227
  deps.log("");
3323
- deps.log("CI workflow");
3324
- deps.log(" skipped — the test command could not be verified, so the workflow is not built from it.");
3325
- continue;
3326
- }
3327
- if (state.storedCommand === null) {
3328
- deps.log("");
3329
- deps.log("CI workflow");
3330
- deps.log(" skipped — it is built from the stored test command, which is not saved yet.");
3331
- continue;
3332
- }
3333
- const opened = await fixSetupPullRequest(deps, setup, state.storedCommand, state.toolchains, state.repository);
3334
- state.evidence = { ...state.evidence, workflow: opened.workflow };
3335
- }
3336
- else if (fix === "gate_and_defaults" && gatePlan !== null) {
3337
- policyResult = await fixGateAndDefaults(deps, options, access, gatePlan);
3338
- }
3339
- else if (fix === "merge_token" && state.identity !== null) {
3340
- await fixMergeToken(deps, setup, state.identity, state.evidence.mergeCredential.state === "stored_rejected");
3341
- }
3342
- else if (fix === "reindex") {
3343
- state.evidence = { ...state.evidence, index: await fixReindex(deps, setup, access, state.evidence.recovery) };
3344
- }
3345
- }
3346
- // ---- Explicit operations, each behind its own consent (unchanged) -------
3347
- if (options.gate.qualifyGate && gatePlan !== null && gatePlan.desired.localCommands.length > 0
3348
- && policyResult?.status !== "deferred" && policyResult?.status !== "unknown") {
3349
- await runConductorGateQualification(gateIo, access, deps.gate, {
3350
- revision: policyResult?.current?.state.revision ?? gatePlan.current.revision,
3351
- baseUrl,
3352
- });
3353
- }
3354
- if (options.epicBranchCiDecision !== undefined) {
3355
- const epicBranchCi = await runEpicBranchCiInspection(gateIo, access, deps.gate, {
3356
- decisionFlag: options.epicBranchCiDecision,
3357
- dryRun: false,
3358
- });
3359
- if (epicBranchCi.manualAction !== null)
3360
- state.evidence.advisories.push(epicBranchCi.manualAction);
3361
- }
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: [] };
3362
5262
  if (options.reviewPolicy === "verdict_protocol" && !options.skipWorkflow) {
3363
5263
  await runClaudeReviewWorkflowOperation(deps, options, state);
3364
5264
  }
3365
5265
  if (options.epicKey && options.planFile) {
3366
5266
  deps.log("");
3367
5267
  deps.log("Verifying the plan with `setup-epic --dry-run`…");
3368
- const verification = await deps.runSetupEpicDryRun([
5268
+ const verification = await progress("checking the plan", () => deps.runSetupEpicDryRun([
3369
5269
  "--dry-run",
3370
5270
  "--epic-key",
3371
5271
  options.epicKey,
@@ -3374,8 +5274,9 @@ async function runConvergingSetup(options, deps, setup) {
3374
5274
  "--review-policy",
3375
5275
  options.reviewPolicy,
3376
5276
  ...(options.repo ? ["--repo", options.repo] : []),
3377
- ]);
5277
+ ]));
3378
5278
  if (verification.exitCode !== 0) {
5279
+ deps.log(" Plan verification failed: `setup-epic --dry-run` reported plan problems (shown above).");
3379
5280
  state.failedOperations.push({
3380
5281
  id: "setup-epic-verification",
3381
5282
  label: "Plan verification",
@@ -3394,27 +5295,88 @@ async function runConvergingSetup(options, deps, setup) {
3394
5295
  deps.log("Executor service");
3395
5296
  observedReadiness = await runExecutorProvisioningPhase(deps, deps.executorProvisioning, executorPlans, access);
3396
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
+ }
3397
5308
  // ---- Check 2: the closing assessment (deny probe runs once, here) -------
3398
5309
  deps.log("");
3399
5310
  deps.log("Checking again…");
3400
- const finalReport = await deps.runDoctor({
5311
+ const finalReport = await progress("checking readiness", () => deps.runDoctor({
3401
5312
  access,
3402
- reviewPolicySource: options.reviewPolicy,
5313
+ reviewPolicySource: effectiveReviewPolicy(options, reviewDefault),
3403
5314
  assessmentVersion: 1,
3404
5315
  epicRunId: options.assessmentEpicRunId,
3405
5316
  storedMergeCredential: storedMergeContextFor(setup, firstReport.readiness?.provider_repository ?? null, localRemote),
3406
- });
5317
+ }));
3407
5318
  const finalReadiness = options.assessmentEpicRunId !== undefined
3408
5319
  ? finalReport.readiness
3409
5320
  : observedReadiness ?? finalReport.readiness;
3410
- const closing = await collectSetupEvidence(deps, setup, access, finalReadiness, {
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, {
3411
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,
3412
5328
  advisories: state.evidence.advisories,
3413
- commandChanged: state.commandChanged,
3414
- commandBlocked: state.commandBlocked,
3415
- });
5329
+ gateRequiresManagedCheck: gateRequiresManagedCheck || state.ciPlan === "managed",
5330
+ ...(state.ciPlan !== undefined ? { ciPlan: state.ciPlan } : {}),
5331
+ }));
3416
5332
  if (state.evidence.index.state === "recovery_unresolved" && closing.evidence.index.state !== "reached")
3417
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,
5373
+ });
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;
5379
+ }
3418
5380
  const items = [...projectSetupItems(closing.evidence), ...state.failedOperations];
3419
5381
  if (deniesEnforcementUnknown(finalReport)) {
3420
5382
  items.push({
@@ -3425,40 +5387,85 @@ async function runConvergingSetup(options, deps, setup) {
3425
5387
  remedy: "the worker safety check could not run; run `epic-implementer doctor` to see why",
3426
5388
  });
3427
5389
  }
3428
- // ---- BAPI-1260: the reusable launch profile (explicit) ------------------
3429
- if (options.launchProfile !== undefined) {
3430
- const launch = await runLaunchProfilePhase(deps, options, {
3431
- access,
3432
- baseUrl,
3433
- readiness: finalReadiness,
3434
- actorObserved: observedReadiness !== null || finalReadiness?.executor.ready === true,
3435
- 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",
3436
5397
  });
3437
- if (!launch.complete) {
3438
- items.push({
3439
- id: "launch-profile",
3440
- label: `Launch profile '${options.launchProfile}'`,
3441
- state: "needs_action",
3442
- blocking: true,
3443
- remedy: "finish the launch-profile steps listed above, then re-run setup with --launch-profile",
3444
- });
3445
- }
3446
5398
  }
3447
- // The latest authoritative command (after any replacement) and what CI installs
3448
- // for it. Operator-only: written through deps.log and nowhere else.
3449
- logStoredCommandAndToolchains(deps, closing.evidence.testCommand.state === "stored" ? closing.storedCommand : null, closing.toolchains);
3450
- if (policyResult?.status === "deferred" || policyResult?.status === "unknown") {
3451
- items.push({ id: "setup-policy", label: "Combined repository policy", state: "needs_action", blocking: policyRequired || policyResult.status === "unknown",
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",
3452
5408
  remedy: "rerun setup for a fresh preview; ask a bootstrap administrator if uncertainty persists" });
3453
5409
  }
5410
+ // The assessment sink and the verdict read the complete item list whatever the verbosity.
3454
5411
  deps.assessmentSink?.(items.find(i => i.assessment)?.assessment);
3455
- for (const line of renderSetupAssessment(items, "Where things stand", "final"))
3456
- deps.log(line);
3457
- for (const advisory of closing.evidence.advisories)
3458
- deps.log(` - ${advisory}`);
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
+ });
3459
5464
  deps.log("");
3460
- const ready = unmetBlockingItems(items).length === 0;
5465
+ const ready = unmet.length === 0 && (proposal === null || applyResult.complete);
3461
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])}`);
3462
5469
  deps.log(ready ? "complete" : "complete-with-manual-steps");
3463
5470
  return ready ? conductorInstallDoctorExitCode(finalReport) : 1;
3464
5471
  }
@@ -3467,15 +5474,333 @@ function deniesEnforcementUnknown(report) {
3467
5474
  const deny = report.legacyConductor?.deny_enforcement;
3468
5475
  return deny !== undefined && deny !== null && deny.enforced !== true;
3469
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
+ }
3470
5796
  /** Short previews of each fix for --dry-run. */
3471
5797
  const DRY_RUN_FIX_TEXT = Object.freeze({
3472
- save_test_command: "save the repository's test command (one question, then PUT /setup/testing-config)",
3473
- replace_test_command: "save the command you passed with --test-command (that flag is the consent; one write, then a read-back), " +
3474
- "then re-check the CI workflow against the stored value and offer the setup pull request",
3475
5798
  setup_pr: "open the setup pull request with the CI workflow (its own consent)",
3476
5799
  gate_and_defaults: "store the repository gate and the safe supervisor defaults (its own consent)",
3477
5800
  merge_token: "store a GitHub merge token on this computer (its own consent, read with no echo)",
3478
- reindex: "review keep/correct/defer for the displayed branch and setup revision; conditionally correct and read back only with consent, then admit one durable initial request or an explicitly authorized retry. Dry run writes no configuration, queue, retry, authorization record, or file",
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",
3479
5804
  });
3480
5805
  /**
3481
5806
  * The claude-review workflow, only for an explicit `--review-policy