@bridge_gpt/mcp-server 0.2.72 → 0.2.74

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 (181) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +15 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-config.js +7 -1
  5. package/build/bridge-permissions.js +30 -0
  6. package/build/ci-system-detection.js +50 -0
  7. package/build/ci-trigger-adapters.js +631 -0
  8. package/build/ci-trigger-install.js +106 -0
  9. package/build/codex-launcher-pin.js +33 -2
  10. package/build/codex-skill-adapter.js +3 -1
  11. package/build/command-host.js +33 -0
  12. package/build/command-provisioning.js +4 -3
  13. package/build/commands.generated.js +7 -6
  14. package/build/conductor/bridge-api-client.js +867 -35
  15. package/build/conductor/bring-up-facts.js +18 -5
  16. package/build/conductor/command-drift-production.js +42 -17
  17. package/build/conductor/command-drift.js +48 -1
  18. package/build/conductor/declare-blocked.js +554 -0
  19. package/build/conductor/declared-extras.js +335 -0
  20. package/build/conductor/doctor.js +108 -21
  21. package/build/conductor/driver-commands.js +141 -0
  22. package/build/conductor/driver-guard.js +277 -0
  23. package/build/conductor/driver-lapse.js +321 -0
  24. package/build/conductor/driver-pass-output.js +104 -0
  25. package/build/conductor/driver-pass.js +571 -0
  26. package/build/conductor/driver-register.js +176 -0
  27. package/build/conductor/driver-release.js +174 -0
  28. package/build/conductor/driver-session-state.js +315 -0
  29. package/build/conductor/epic-branch-ci-inspection.js +281 -43
  30. package/build/conductor/epic-implementer-cli.js +199 -15
  31. package/build/conductor/epic-server-database.js +162 -0
  32. package/build/conductor/epic-server-guidance.js +278 -0
  33. package/build/conductor/epic-server-journal.js +239 -0
  34. package/build/conductor/epic-server-processes.js +324 -0
  35. package/build/conductor/epic-server-recipe.js +397 -0
  36. package/build/conductor/epic-server-runtime.js +1207 -0
  37. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  38. package/build/conductor/epic-server-sfcc.js +85 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +647 -0
  41. package/build/conductor/gate-discovery.js +196 -11
  42. package/build/conductor/gate-settings-review.js +261 -4
  43. package/build/conductor/launch-need-probes.js +6 -53
  44. package/build/conductor/launch-plan.js +313 -156
  45. package/build/conductor/prerequisite-inputs.js +879 -45
  46. package/build/conductor/readiness-assessment.js +16 -1
  47. package/build/conductor/readiness-cli.js +20 -9
  48. package/build/conductor/readiness-prerequisites.js +28 -9
  49. package/build/conductor/readiness-sections.js +133 -126
  50. package/build/conductor/readiness.js +1 -1
  51. package/build/conductor/recovery-cli.js +13 -2
  52. package/build/conductor/tools.js +6 -5
  53. package/build/conductor/wait-run-attention.js +2 -2
  54. package/build/conductor/wait-run-cli.js +208 -22
  55. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  56. package/build/conductor/worker-setup-tally.js +27 -0
  57. package/build/credential-delivery.js +280 -0
  58. package/build/credential-launch-safety.js +142 -0
  59. package/build/credential-materialization.js +91 -16
  60. package/build/credential-references-node-deps.js +29 -0
  61. package/build/credential-references.js +1394 -0
  62. package/build/credential-references.test-fixtures.js +211 -0
  63. package/build/credential-scan-conventions.js +145 -0
  64. package/build/credential-scan.js +517 -0
  65. package/build/credential-store.js +121 -1
  66. package/build/credentials-cli.js +252 -3
  67. package/build/dependency-install-declarations.js +102 -1
  68. package/build/docs.generated.js +10 -3
  69. package/build/doctor.js +95 -3
  70. package/build/drive-epic-help.js +21 -2
  71. package/build/drive-epic.js +2095 -375
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +157 -0
  74. package/build/epic-capability-statement.js +175 -0
  75. package/build/epic-ci-workflow-drift.js +77 -23
  76. package/build/epic-ci-workflow-install.js +137 -44
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow-v3.js +273 -0
  79. package/build/epic-ci-workflow.js +165 -18
  80. package/build/epic-implementer-bin.js +2204 -56
  81. package/build/epic-launch-context.js +702 -0
  82. package/build/epic-server-record.js +288 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/completion-contract.js +8 -1
  87. package/build/executor/credential-delivery-step.js +168 -0
  88. package/build/executor/deps.js +3 -1
  89. package/build/executor/env.js +98 -23
  90. package/build/executor/epic-server-context.js +157 -0
  91. package/build/executor/gate-qualification-job.js +127 -26
  92. package/build/executor/guarded-fast-forward-push.js +13 -8
  93. package/build/executor/http-client.js +52 -5
  94. package/build/executor/job-runner.js +577 -81
  95. package/build/executor/observation.js +8 -0
  96. package/build/executor/permissions.js +85 -3
  97. package/build/executor/pre-pr-checks.js +363 -0
  98. package/build/executor/prompt-spec.js +149 -3
  99. package/build/executor/reconcile-overlap-job.js +5 -3
  100. package/build/executor/required-work-diagnostics.js +4 -2
  101. package/build/executor/required-work-ledger.js +936 -38
  102. package/build/executor/results.js +58 -0
  103. package/build/executor/terminal-mutation.js +8 -0
  104. package/build/executor/worker-command.js +72 -3
  105. package/build/executor/worker-database-config.js +281 -0
  106. package/build/executor/worker-database-target.js +16 -12
  107. package/build/executor/worker-database.js +320 -101
  108. package/build/executor/worker-finalization.js +7 -1
  109. package/build/executor/worker-resources.js +25 -3
  110. package/build/executor/worker-verification-guidance.js +18 -3
  111. package/build/executor/worktree.js +20 -1
  112. package/build/executor-launch.js +58 -4
  113. package/build/generated-assets-catalog.js +2 -2
  114. package/build/git-exclude-lock.js +187 -0
  115. package/build/index.js +824 -366
  116. package/build/init.js +26 -11
  117. package/build/install-bridge-conductor-answers.js +528 -0
  118. package/build/install-bridge-conductor-apply.js +288 -0
  119. package/build/install-bridge-conductor-assessment.js +1222 -0
  120. package/build/install-bridge-conductor-compact.js +186 -0
  121. package/build/install-bridge-conductor-contracts.js +72 -0
  122. package/build/install-bridge-conductor-gate.js +1312 -198
  123. package/build/install-bridge-conductor-setup.js +577 -83
  124. package/build/install-bridge-conductor.js +3381 -544
  125. package/build/install-bridge.js +280 -25
  126. package/build/install-doctor.js +38 -8
  127. package/build/install-maintenance.js +26 -3
  128. package/build/install-sfcc-detection.js +120 -0
  129. package/build/install-sfcc-setup.js +185 -0
  130. package/build/launcher-config-inspection.js +162 -1
  131. package/build/mcp-grant-candidates.js +779 -0
  132. package/build/mcp-grant-doctor.js +63 -0
  133. package/build/mcp-grant.js +288 -0
  134. package/build/mcp-host-targets.js +8 -0
  135. package/build/mcp-identity.js +23 -0
  136. package/build/mcp-invoke.js +292 -15
  137. package/build/mcp-presets.js +107 -0
  138. package/build/mcp-provisioning.js +155 -6
  139. package/build/mcp-registration-doctor.js +31 -2
  140. package/build/mcp-server-invocation.js +19 -1
  141. package/build/merge-workflow-install.js +243 -110
  142. package/build/pipelines.generated.js +7 -6
  143. package/build/plan-discovery.js +97 -4
  144. package/build/plan-execution-ledger.js +100 -7
  145. package/build/plan-generation-io.js +262 -0
  146. package/build/plan-generation.js +424 -0
  147. package/build/plane/build-freshness.js +6 -1
  148. package/build/plane/cli.js +75 -9
  149. package/build/plane/plane-freshness.js +17 -0
  150. package/build/plane/preflight.js +50 -10
  151. package/build/plane/shutdown.js +19 -0
  152. package/build/plane/status.js +8 -2
  153. package/build/plane/terminal-run-cleanup.js +18 -4
  154. package/build/printed-remedy-commands.js +211 -12
  155. package/build/project-root.js +40 -0
  156. package/build/readiness-check.js +77 -0
  157. package/build/readiness-prerequisites.generated.js +122 -14
  158. package/build/readme.generated.js +1 -1
  159. package/build/repository-state-paths.js +41 -0
  160. package/build/repository-toolchains.js +6 -3
  161. package/build/run-unit-tests-launcher.js +8 -1
  162. package/build/setup-epic.js +1305 -210
  163. package/build/setup-progress.js +44 -0
  164. package/build/setup-question.js +122 -4
  165. package/build/sfcc/credentials.js +3 -2
  166. package/build/sfcc/hostname.js +98 -2
  167. package/build/sfcc/tool-wrapper.js +6 -95
  168. package/build/start-tickets.js +193 -29
  169. package/build/test-support/executor-source-files.js +200 -0
  170. package/build/testing-config-client.js +25 -2
  171. package/build/third-party-mcp-targets.js +63 -2
  172. package/build/ticket-delivery-enrollment.js +9 -0
  173. package/build/upgrade-cli.js +85 -2
  174. package/build/v2-readiness-requirements.js +28 -1
  175. package/build/version.generated.js +3 -3
  176. package/build/with-credentials.js +208 -0
  177. package/build/worktree-credential-delivery.js +340 -0
  178. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  179. package/docs/epic-implementer/getting-started.md +3 -1
  180. package/docs/epic-implementer/self-hosting.md +14 -1
  181. 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, recommendEpicServer, buildInstallVerdict, buildProposalPresentation, classifyMergeTestProtection, dependencyInstallDetails, epicBranchCiIncludeRestsOnSetupPr, 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, describeUnopenedSetupCredit } from './epic-branch-ci-summary.js';
7
+ import { buildCompactApply, buildCompactAssessment, buildCompactProposal } from './install-bridge-conductor-compact.js';
8
+ import { decisionFor, normalizeInstallAnswers, parseAnswerValue, 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,51 @@ 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, planDeclarations, resolveEffectiveDependencyInstall, describeGateRestoration, desiredFromStored, emptyConductorGateFlags, hasExplicitGateInput, parseLocalCommandFlag, parseEpicBranchCiDecisionFlag, parseMigrationGuardFlag, planManagedProviderGate, reportLearnedCommandTrial, describePolicyChanges, resolveConductorGate, runEpicBranchCiInspection, runGateConsequenceSummary, runClearConductorGate, mapExemptionOutcomeToWriteResult, 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 { parseDependencyInstallStrict, sameDependencyInstall, } from "./dependency-install-declarations.js";
147
+ import { pyprojectPathFor, scanDeclaredExtras } from "./conductor/declared-extras.js";
148
+ import { discoverLocalTestCandidates } from "./conductor/gate-discovery.js";
149
+ import { readLearnedInstructions } from "./testing-config-client.js";
150
+ import { normalizeStorefrontOrigin, isValidCredentialReference, isValidSfccSandboxId, sameEpicServerRecord, } from "./epic-server-record.js";
151
+ import { detectSfccRepository } from "./install-sfcc-detection.js";
152
+ import { SANDBOX_SKIPPED_LINE, WORKER_UPLOAD_ADVISORY, collectCredentialEvidence, credentialQuestionLines, credentialReferenceAdvisories, describeSfccUpload, isSfccUploadCapable, recheckSfccSandboxId, runSfccUploadCheck, sfccRecommendedDefinitionIds, suggestedCredentialEntry, } from "./install-sfcc-setup.js";
153
+ import { CANDIDATE_EXCLUSION_TEXT, CANDIDATE_ORIGIN_LABEL, describeInventoryExclusions, GRANT_SELECTION_PROMPT, parseGrantSelection, } from "./mcp-grant-candidates.js";
154
+ import { buildEpicCapabilityStatement } from "./epic-capability-statement.js";
155
+ import { MCP_GRANT_MAX_SERVERS } from "./mcp-grant.js";
156
+ import { advisoryFindingLines, assessIndexFreshness, assessSetupIndex, catalogLabel, NPM_SETUP_LAUNCHER, closedSetupPullRequestNotice, compareIndexedToMerge, planSetupFixes, projectSetupItems, readSetupPullRequest, renderSetupAssessment, deriveCompactReadiness, setupItemRemedy, setupVerdictLine, unmetBlockingItems, } from "./install-bridge-conductor-setup.js";
122
157
  import { CONDUCTOR_BIN_UNRESOLVED_ERROR, MANAGED_HOOK_NAMES, } from "./conductor/git-hooks.js";
123
158
  import os from "node:os";
124
159
  import path from "node:path";
125
160
  import { readFile as readFileAsync, stat as statAsync } from "node:fs/promises";
126
161
  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";
162
+ 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
163
  import { DEFAULT_BAPI_BASE_URL } from "./executor/credentials.js";
129
164
  import { MCP_PACKAGE_NAME } from "./mcp-identity.js";
130
165
  import { LOCAL_MERGE_CREDENTIAL_ENV_KEYS } from "./conductor/merge-credential.js";
@@ -162,23 +197,42 @@ export function getInstallBridgeConductorUsage() {
162
197
  "(read-only), fixes only what is missing, checks again, and ends with one",
163
198
  "verdict: \"Ready for your first epic\" or \"Not ready: N steps left\" with the fix",
164
199
  "for each step. Interactive output ends with an advisory readiness verdict.",
165
- " --json Emit one installation result; unanswered interactive choices defer.",
200
+ " --json Emit one JSON document (schema version 2) on stdout: every setup item with its",
201
+ " fix, and every open choice with its options, consequences, recommended option,",
202
+ " and answer_key. With --dry-run it is read-only. Progress goes to stderr.",
203
+ " --compact Emit the smaller view of the --json document. It requires --json.",
204
+ " --answers <file> Apply the choices in a JSON answers file keyed by answer_key, with no",
205
+ " prompts. It must carry the top-level proposal_digest proposal mode returned, and",
206
+ " state every consequential choice; anything unstated or changed is refused before",
207
+ " any write. The merge token is accepted only as a reference, never a value.",
208
+ " --answers - --dry-run --json Read draft answers on stdin and return the normalized",
209
+ " proposal and its proposal_digest. Writes nothing.",
166
210
  " --assessment-epic-run-id <id> Observe this run's readiness (default: repository preview).",
167
211
  "It exits 0 when ready and 1 for unresolved requested capabilities (0 for --dry-run).",
168
212
  "",
169
213
  "It displays the destination and reads your Claude sign-in (~/.claude.json only)",
170
214
  "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;",
215
+ "writes. Otherwise it asks only what a missing item needs. Each question marks a",
216
+ "recommended option: press Enter to take it, or type ? for details. Consequential",
217
+ "questions (a pull request, a stored token, a merge-rule change) still need an",
218
+ "explicit yes. Setup applies these without asking:",
219
+ " - the project this folder is bound to (it asks which repository only when no",
220
+ " project is bound and it cannot tell);",
221
+ " - safe CI settings and the previewed policy, each printed with a receipt;",
222
+ " - the epic-branch CI choice, when a workflow is shown to run on epic-branch PRs",
223
+ " (otherwise it prints how to record the choice);",
224
+ " - the default indexing branch, when the repository's own default is shown.",
225
+ "It asks about:",
226
+ " - which indexing branch to use, only when an existing different branch makes",
227
+ " the choice unclear;",
228
+ " - adding Bridge's own GitHub workflow, once, only for a repository with no CI of",
229
+ " its own and a test command Bridge has proven (then the setup pull request has",
230
+ " its own consent);",
177
231
  " - 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",
232
+ "Setup never asks for a test command. The destination is displayed without a",
233
+ "redundant URL question. Without an interactive terminal every question is a",
234
+ "decline: no token is stored and no pull request is opened. When setup reports",
235
+ "that its setup pull request is waiting, merge it and run setup again. Recovery diagnoses the demonstrated",
182
236
  "target, offers keep/correct/defer when needed, and tracks one durable initial",
183
237
  "request. Failed or ineffective work needs an explicit retry; pending work is",
184
238
  "observed without cancellation. Unsupported backends require an upgrade;",
@@ -191,21 +245,51 @@ export function getInstallBridgeConductorUsage() {
191
245
  "local copy only; it does not revoke the token at GitHub, and a running executor",
192
246
  "keeps the token it started with until it restarts.",
193
247
  "",
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",
248
+ "Learned first: setup stops before any write if Bridge has not learned this",
249
+ "repository yet (`repository_not_learned`, exit 1). Run /learn-repository in",
250
+ "Claude Code, wait for it to finish, then run setup again; Bridge needs your",
251
+ "project's standards to write useful code. If setup cannot tell whether the",
252
+ "repository was learned, it warns once and continues. With --dry-run it reports the",
253
+ "stop and keeps previewing the rest.",
254
+ "",
255
+ "Test command: Bridge's server learns the command from your repository, and setup",
256
+ "proves it by running it once on this computer, in a clean checkout of your default",
257
+ "branch. The server stores it as the gate's local command only if it passes, so a",
258
+ "command that fails or cannot run is never stored. Nobody is asked for it. To use",
259
+ "your own, pass --test-command \"<command>\": the flag offers it for the same proof",
260
+ "(one line, no GitHub Actions expression, at most 500 characters) and it is stored",
261
+ "only if it passes. The flag does NOT authorize credential endpoint transfer and",
201
262
  "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.",
263
+ "--dry-run nothing is requested or run. Do not put a credential in a command: setup",
264
+ "prints it and the workflow file contains it.",
265
+ "",
266
+ "Existing CI is watched, not required: checks your CI has already reported are",
267
+ "stored as watched members of the gate. A red watched check stops a merge; a",
268
+ "missing one only warns. A gate you already confirmed is kept as it is.",
269
+ "",
270
+ "Bridge's workflow is optional: for a repository with no CI of its own and a proven",
271
+ "test command, setup offers it once (default no). It runs only for pull requests",
272
+ "into epic/** branches, and its check is added to the gate only after the setup",
273
+ "pull request is open. The pull request is built from a clean copy of your default",
274
+ "branch, so uncommitted or unpushed changes in your folder never block it or enter it.",
275
+ "",
276
+ "What setup stops on: the one stop this adds is a repository that has not been",
277
+ "learned. It no longer asks for a test command and no longer refuses a folder with",
278
+ "uncommitted changes. Stops added: one. Push targets, the default-branch push",
279
+ "refusal, merge-credential checks, and the human-gated integration pull request",
280
+ "are unchanged.",
204
281
  "",
205
282
  "Options:",
206
- " --test-command <command> Save or replace the repository's test command.",
283
+ " --test-command <command> Offer your own test command for Bridge to prove once;",
284
+ " it replaces the stored local command only if it passes.",
207
285
  " Not combinable with --remove-merge-token or",
208
286
  " --clear-gate; may be given once.",
287
+ " --verbose Print the full assessment, routine advisories, and",
288
+ " command detail. Without it setup prints blocking",
289
+ " problems, a one-line verdict, and one next step.",
290
+ " --review-ci-settings Review each discovered CI setting one by one. Without",
291
+ " it, safe settings are applied and a committed literal",
292
+ " that needs your typed yes is skipped, by name only.",
209
293
  " --remove-merge-token Remove the merge token stored on this computer for",
210
294
  " this repository (its own consent), then exit.",
211
295
  " --repo <name> Repository name (default: BAPI_REPO_NAME / .bridge/config)",
@@ -214,11 +298,12 @@ export function getInstallBridgeConductorUsage() {
214
298
  " --required-checks a,b Comma-separated form of --required-check",
215
299
  "",
216
300
  "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.",
301
+ "required: provider checks, local commands, both (mixed), watched checks, or none.",
302
+ "Explicit gate flags are the complete requested gate. Otherwise a confirmed gate",
303
+ "already stored is used unchanged; otherwise setup decides from facts, with no",
304
+ "question: checks your CI has really reported become watched members, and the",
305
+ "server adds a proven local command. Nothing is stored until you authorize the",
306
+ "combined policy change that setup previews.",
222
307
  " --provider-check <name> An exact provider-reported check name (repeatable).",
223
308
  " Admission refuses one that has never reported.",
224
309
  " --local-command <cmd> A local command the executor runs before each merge",
@@ -231,8 +316,6 @@ export function getInstallBridgeConductorUsage() {
231
316
  " child merge. Exclusive with the member flags.",
232
317
  " --customized-command <n> A packaged command this repository customizes, stored",
233
318
  " 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
319
  " --clear-gate Clear the confirmed gate (its own consent), then exit.",
237
320
  " --qualify-gate Qualify a confirmed local or mixed gate: queue the",
238
321
  " qualification job and drain it with a short-lived",
@@ -241,10 +324,12 @@ export function getInstallBridgeConductorUsage() {
241
324
  " without the offer prompt.",
242
325
  "",
243
326
  ` --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",
327
+ " Omitted, setup keeps a project default that is already",
328
+ " stored. With none stored it stores verdict_protocol when",
329
+ " .github/workflows/claude-review.yml exists on your default",
330
+ " branch, and repository_policy when it does not or cannot",
331
+ " be read. It scaffolds no Claude review workflow unless you",
332
+ " pass --review-policy verdict_protocol. Supplying any value",
248
333
  " persists it as the project default, stamped into a new",
249
334
  " run that carries no review policy of its own.",
250
335
  " --epic-key <KEY> Epic key for the setup-epic verification phase",
@@ -254,6 +339,9 @@ export function getInstallBridgeConductorUsage() {
254
339
  " --secret-name <NAME> claude-review workflow: OAuth token secret NAME",
255
340
  " --branches a,b claude-review workflow: PR branch triggers",
256
341
  " --skip-workflow Never offer the claude-review workflow",
342
+ " --epic-server Ask again which epic server Epic Implementer runs use",
343
+ " (none, local, or sfcc_shared_active), behind its own",
344
+ " consent. Without it, an unchanged choice asks nothing.",
257
345
  " --replace-done-gate Replace an EXISTING done gate with the CI-only gate",
258
346
  " built from --required-check. Without it, a repeat",
259
347
  " install keeps the stored gate and only adds missing",
@@ -267,8 +355,8 @@ export function getInstallBridgeConductorUsage() {
267
355
  " no POST, no file write, no host MCP config write,",
268
356
  " no Git hook write, no install-state or capability",
269
357
  " 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",
358
+ " start-consent prompt. Still displays the resolved",
359
+ " base URL first — its readiness read carries the",
272
360
  " repo API key.",
273
361
  " -h, --help Show this help",
274
362
  "",
@@ -286,10 +374,10 @@ export function getInstallBridgeConductorUsage() {
286
374
  " --executor-id, otherwise local).",
287
375
  " --policy-file <path> Run policy the profile references.",
288
376
  "",
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.",
377
+ "The resolved BAPI_BASE_URL is displayed BEFORE any network call",
378
+ "(BAPI_BASE_URL silently defaults to production when unset). In a terminal,",
379
+ "setup then applies the previewed bootstrap policy. Without a TTY it shows",
380
+ "the preview and writes no policy.",
293
381
  "",
294
382
  "Tool visibility (its own consent): adds the `epic_implementer` token to the",
295
383
  "BRIDGE_MCP_PROFILE of the Bridge entry in host MCP configurations that",
@@ -327,8 +415,10 @@ export function parseInstallBridgeConductorArgs(argv) {
327
415
  let repo;
328
416
  let dryRun = false;
329
417
  let json = false;
418
+ let compact = false;
330
419
  let skipWorkflow = false;
331
420
  let replaceDoneGate = false;
421
+ let epicServerChange = false;
332
422
  let reviewPolicy = DEFAULT_CONDUCTOR_REVIEW_POLICY;
333
423
  let reviewPolicyExplicit = false;
334
424
  let epicKey;
@@ -350,6 +440,9 @@ export function parseInstallBridgeConductorArgs(argv) {
350
440
  let removeMergeToken = false;
351
441
  let testCommand;
352
442
  let testCommandSeen = false;
443
+ let answers;
444
+ let verbose = false;
445
+ let reviewCiSettings = false;
353
446
  const takeValue = (arg, inline, next) => {
354
447
  if (inline !== undefined) {
355
448
  if (inline.trim().length === 0)
@@ -372,6 +465,24 @@ export function parseInstallBridgeConductorArgs(argv) {
372
465
  return { status: "error", message: "--json takes no value" };
373
466
  json = true;
374
467
  break;
468
+ case "--compact":
469
+ if (inline !== undefined)
470
+ return { status: "error", message: "--compact takes no value" };
471
+ compact = true;
472
+ break;
473
+ case "--answers": {
474
+ // `-` is the stdin source, so it is taken as a value here (unlike other flags).
475
+ const next = argv[i + 1];
476
+ const value = inline !== undefined ? inline.trim() : next === "-" ? "-" : next !== undefined && !next.startsWith("-") ? next.trim() : "";
477
+ if (value.length === 0)
478
+ return { status: "error", message: "--answers requires a file path, or - for stdin" };
479
+ if (answers !== undefined)
480
+ return { status: "error", message: "--answers may be given once" };
481
+ answers = value;
482
+ if (inline === undefined)
483
+ i++;
484
+ break;
485
+ }
375
486
  case "--dry-run":
376
487
  if (inline !== undefined)
377
488
  return { status: "error", message: "--dry-run takes no value" };
@@ -382,11 +493,27 @@ export function parseInstallBridgeConductorArgs(argv) {
382
493
  return { status: "error", message: "--skip-workflow takes no value" };
383
494
  skipWorkflow = true;
384
495
  break;
496
+ case "--verbose":
497
+ if (inline !== undefined)
498
+ return { status: "error", message: "--verbose takes no value" };
499
+ verbose = true;
500
+ break;
501
+ case "--review-ci-settings":
502
+ if (inline !== undefined) {
503
+ return { status: "error", message: "--review-ci-settings takes no value" };
504
+ }
505
+ reviewCiSettings = true;
506
+ break;
385
507
  case "--replace-done-gate":
386
508
  if (inline !== undefined)
387
509
  return { status: "error", message: "--replace-done-gate takes no value" };
388
510
  replaceDoneGate = true;
389
511
  break;
512
+ case "--epic-server":
513
+ if (inline !== undefined)
514
+ return { status: "error", message: "--epic-server takes no value" };
515
+ epicServerChange = true;
516
+ break;
390
517
  case "--repo-wide":
391
518
  if (inline !== undefined)
392
519
  return { status: "error", message: "--repo-wide takes no value" };
@@ -436,6 +563,7 @@ export function parseInstallBridgeConductorArgs(argv) {
436
563
  return { status: "error", message: `${flag} takes no value` };
437
564
  if (flag === "--gate-none")
438
565
  gate.gateNone = true;
566
+ // No effect today; this name is reserved for a later step where an agent relays the user's consent.
439
567
  else if (flag === "--confirm-gate")
440
568
  gate.confirmGate = true;
441
569
  else if (flag === "--clear-gate")
@@ -633,6 +761,9 @@ export function parseInstallBridgeConductorArgs(argv) {
633
761
  message: "--test-command cannot be combined with --clear-gate: clearing the gate is a standalone action.",
634
762
  };
635
763
  }
764
+ // BAPI-1653 — checked on the completed argument set, so flag order never matters.
765
+ if (compact && !json)
766
+ return { status: "error", message: "--compact requires --json" };
636
767
  // BAPI-1461 — token removal is its own action: only --repo and --dry-run may
637
768
  // accompany it, so it can never be mistaken for, or followed by, setup writes.
638
769
  if (removeMergeToken) {
@@ -656,6 +787,8 @@ export function parseInstallBridgeConductorArgs(argv) {
656
787
  allowedBot !== undefined ||
657
788
  secretName !== undefined ||
658
789
  testCommand !== undefined ||
790
+ reviewCiSettings ||
791
+ answers !== undefined ||
659
792
  branches !== undefined;
660
793
  if (conflicting) {
661
794
  return {
@@ -684,6 +817,7 @@ export function parseInstallBridgeConductorArgs(argv) {
684
817
  repo,
685
818
  dryRun,
686
819
  json,
820
+ ...(compact ? { compact: true } : {}),
687
821
  requiredChecks: normalizedChecks,
688
822
  gate,
689
823
  reviewPolicy,
@@ -695,6 +829,7 @@ export function parseInstallBridgeConductorArgs(argv) {
695
829
  branches,
696
830
  skipWorkflow,
697
831
  ...(replaceDoneGate ? { replaceDoneGate: true } : {}),
832
+ ...(epicServerChange ? { epicServerChange: true } : {}),
698
833
  executorId,
699
834
  ...(epicRunIds.length > 0 ? { epicRunIds } : {}),
700
835
  ...(assessmentEpicRunId !== undefined ? { assessmentEpicRunId } : {}),
@@ -708,9 +843,59 @@ export function parseInstallBridgeConductorArgs(argv) {
708
843
  ...(epicBranchCiDecision ? { epicBranchCiDecision } : {}),
709
844
  ...(removeMergeToken ? { removeMergeToken: true } : {}),
710
845
  ...(testCommand !== undefined ? { testCommand } : {}),
846
+ ...(verbose ? { verbose: true } : {}),
847
+ ...(reviewCiSettings ? { reviewCiSettings: true } : {}),
848
+ ...(answers !== undefined ? { answers } : {}),
711
849
  },
712
850
  };
713
851
  }
852
+ /** Collect the snapshot. Nothing here throws, refuses, or writes. */
853
+ export async function collectEpicServerSnapshot(deps, epicDeps, repoName, inventory) {
854
+ const fs = deps.gate?.discoveryFs;
855
+ const check = epicDeps.sfccUploadCheck;
856
+ const detection = fs === undefined || check === undefined ? null : await detectSfccRepository(fs, inventory);
857
+ const readCredentials = epicDeps.readCredentialReferences;
858
+ const credentials = readCredentials === undefined ? null : await collectCredentialEvidence(() => readCredentials(repoName));
859
+ let guidancePresent = false;
860
+ try {
861
+ guidancePresent = await epicDeps.guidancePresent();
862
+ }
863
+ catch {
864
+ guidancePresent = false;
865
+ }
866
+ let existingSandbox = null;
867
+ try {
868
+ const read = await epicDeps.readRecord(repoName);
869
+ if (read.state === "ok")
870
+ existingSandbox = read.record.sfcc ?? null;
871
+ }
872
+ catch {
873
+ existingSandbox = null;
874
+ }
875
+ const uploadCheck = detection?.detected === true && check !== undefined
876
+ ? await runSfccUploadCheck(check, { approvedSandboxId: existingSandbox?.sandbox_id ?? null, credentials })
877
+ : null;
878
+ return { detection, uploadCheck, credentials, guidancePresent, existingSandbox };
879
+ }
880
+ /** The same evidence for both setup paths, so their recommendation cannot differ. */
881
+ export function epicServerDecisionEvidence(current, applicable, snapshot, sandboxRecorded) {
882
+ if (snapshot === null)
883
+ return { current, applicable };
884
+ return {
885
+ current,
886
+ applicable,
887
+ guidancePresent: snapshot.guidancePresent,
888
+ ...(snapshot.detection !== null
889
+ ? { devScript: snapshot.detection.dev_script === true, sfcc: { detected: snapshot.detection.detected, uploadCheck: snapshot.uploadCheck } }
890
+ : {}),
891
+ ...(snapshot.credentials !== null ? { credentialReferences: snapshot.credentials.rows } : {}),
892
+ ...(sandboxRecorded ? { sandboxRecorded: true } : {}),
893
+ };
894
+ }
895
+ /** The definition ids to recommend, only for a confirmed SFCC repository. */
896
+ export function sfccGrantIds(snapshot, inventory) {
897
+ return snapshot?.detection?.detected === true && inventory !== null ? sfccRecommendedDefinitionIds(inventory) : [];
898
+ }
714
899
  /** Real host-local implementations of the launch-profile seams. */
715
900
  export function createDefaultLaunchProfileDeps(env) {
716
901
  const store = createNodeEpicLaunchStoreDeps(env);
@@ -1502,6 +1687,57 @@ function assessNotification(policy, attended, targetBaseUrl, readiness) {
1502
1687
  "delivers a verification to it at approval, and a failure there holds activation.",
1503
1688
  };
1504
1689
  }
1690
+ /**
1691
+ * BAPI-1635 — the selected launch profile's escalation evidence, for setup's
1692
+ * effective escalation item.
1693
+ *
1694
+ * The profile is chosen the way `drive-epic` chooses it: `--launch-profile` first,
1695
+ * then `BAPI_EPIC_LAUNCH_PROFILE`. It is read through the one validated reader and
1696
+ * its policy is judged by {@link assessNotification}; no second policy parser exists.
1697
+ * Account email is deliberately not counted here (readiness is passed as null): a
1698
+ * live-email route is the server row's own fact and is kept independently.
1699
+ *
1700
+ * Only bounded state leaves this function: the profile name and the policy file's
1701
+ * path. A missing profile (not yet saved) and an attended policy are "no evidence";
1702
+ * a profile or policy that cannot be read is `unreadable`, never a confirmed absence.
1703
+ * Policy contents, a webhook value, an email address, and raw reader errors are
1704
+ * never returned.
1705
+ */
1706
+ async function collectNotificationEvidence(deps, options, baseUrl) {
1707
+ const fromEnv = deps.env.BAPI_EPIC_LAUNCH_PROFILE?.trim();
1708
+ const name = options.launchProfile ?? (fromEnv !== undefined && fromEnv !== "" ? fromEnv : undefined);
1709
+ if (name === undefined)
1710
+ return undefined;
1711
+ const lp = deps.launchProfiles ?? createDefaultLaunchProfileDeps(deps.env);
1712
+ let read;
1713
+ try {
1714
+ read = await lp.readProfile(name);
1715
+ }
1716
+ catch {
1717
+ return { state: "unreadable", profile: name };
1718
+ }
1719
+ if (!read.ok)
1720
+ return read.kind === "profile-missing" ? undefined : { state: "unreadable", profile: name };
1721
+ const policyPath = read.profile.policyRef?.path;
1722
+ if (policyPath === undefined)
1723
+ return { state: "absent", profile: name };
1724
+ let policy;
1725
+ try {
1726
+ const parsed = JSON.parse(await lp.readPolicyFile(policyPath));
1727
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
1728
+ return { state: "unreadable", profile: name };
1729
+ policy = parsed;
1730
+ }
1731
+ catch {
1732
+ return { state: "unreadable", profile: name };
1733
+ }
1734
+ const assessed = assessNotification(policy, policy.posture === "attended", baseUrl, null);
1735
+ if (assessed.status === "not-applicable")
1736
+ return undefined;
1737
+ return assessed.status === "ok"
1738
+ ? { state: "declared", profile: name, policyFile: policyPath }
1739
+ : { state: "absent", profile: name, policyFile: policyPath };
1740
+ }
1505
1741
  /** BAPI-1461 — whether a stored profile already records exactly this launch. */
1506
1742
  function launchProfileMatches(prior, next) {
1507
1743
  return (prior.baseUrl === next.baseUrl &&
@@ -1770,8 +2006,34 @@ async function runStandaloneGateAction(options, deps, gateIo, access, accessErro
1770
2006
  ? runClearConductorGate(gateIo, access, { dryRun: options.dryRun })
1771
2007
  : runQualifyConductorGate(gateIo, access, deps.gate, { dryRun: options.dryRun, baseUrl });
1772
2008
  }
1773
- function renderReviewPolicy(deps, options) {
2009
+ /**
2010
+ * Explain the review policy. With a decision (the converging setup) it says whether
2011
+ * the source is explicit, preserved, or inferred from the remote default branch;
2012
+ * without one (a caller with no setup seams) it keeps the original install text.
2013
+ */
2014
+ function renderReviewPolicy(deps, options, decision) {
1774
2015
  deps.log("");
2016
+ if (decision !== undefined) {
2017
+ if (decision.kind === "preserve") {
2018
+ deps.log(decision.basis === "stored"
2019
+ ? `Review policy: kept as the project default already stored (${terminalSafeText(decision.stored ?? "unrecognized")}). ` +
2020
+ "Pass --review-policy to change it."
2021
+ : "Review policy: Bridge could not read the stored review settings, so it leaves them as they are this time.");
2022
+ return;
2023
+ }
2024
+ deps.log(`Review policy: ${decision.source}`);
2025
+ deps.log(decision.basis === "explicit"
2026
+ ? " Explicitly selected with --review-policy, so it is ALSO persisted as the supervisor project " +
2027
+ "default and stamped into a new run that sets no review policy of its own. An explicit per-run " +
2028
+ "policy always wins, and changing this later never alters an already-approved run."
2029
+ : decision.basis === "workflow_present"
2030
+ ? ` Inferred: ${CLAUDE_REVIEW_WORKFLOW_RELPATH} exists on your default branch. It is stored as the ` +
2031
+ "project default, and a stored default is never overwritten by a later run. Pass --review-policy to choose another."
2032
+ : ` Inferred: no ${CLAUDE_REVIEW_WORKFLOW_RELPATH} was found on your default branch, so no Claude review ` +
2033
+ "workflow is needed. It is stored as the project default, and a stored default is never overwritten by a " +
2034
+ "later run. Pass --review-policy verdict_protocol to opt in to AI review.");
2035
+ return;
2036
+ }
1775
2037
  deps.log(`Review policy: ${options.reviewPolicy}`);
1776
2038
  deps.log(options.reviewPolicyExplicit
1777
2039
  ? " Explicitly selected, so it is ALSO persisted as the supervisor project " +
@@ -1783,6 +2045,10 @@ function renderReviewPolicy(deps, options) {
1783
2045
  "repository_policy at first approval when nothing else sets one — pass " +
1784
2046
  "--review-policy verdict_protocol to opt in to AI review.");
1785
2047
  }
2048
+ /** A stored value printed on one line: control characters and over-long text never reach the terminal. */
2049
+ function terminalSafeText(value) {
2050
+ return value.replace(/[\u0000-\u001F\u007F]/g, "?").slice(0, 80);
2051
+ }
1786
2052
  /**
1787
2053
  * The executor preflight (BAPI-779): AFTER the URL consent, BEFORE any
1788
2054
  * mutation, and before the dry-run return, so `--dry-run` reports the same
@@ -1832,17 +2098,23 @@ async function runExecutorPreflightPhase(options, deps, baseUrl, access) {
1832
2098
  }
1833
2099
  return { kind: "ok", plans: null };
1834
2100
  }
1835
- /** One output finalizer for success, deferment, dry run, and contained failures. */
1836
2101
  export async function runInstallBridgeConductorCli(argv, deps) {
1837
2102
  const parsed = parseInstallBridgeConductorArgs(argv);
1838
2103
  const machine = argv.includes('--json');
1839
2104
  const human = !machine && deps.isTTY === true;
1840
2105
  let verdict;
2106
+ // BAPI-1604: the compact summary's single next step, held so it prints after the verdict.
2107
+ let nextStep;
1841
2108
  let outcome = 'complete-with-manual-steps';
1842
2109
  let assessment;
2110
+ // BAPI-1603: a named stop outcome, kept apart from the numeric exit code so the
2111
+ // result can say WHICH refusal happened without changing the return convention.
2112
+ let namedOutcome;
2113
+ let parts = {};
1843
2114
  const inner = { ...deps,
1844
2115
  get promptLine() { return deps.promptLine; },
1845
2116
  assessmentSink: (value) => { assessment = value; deps.assessmentSink?.(value); },
2117
+ installDocumentSink: (value) => { parts = { ...parts, ...value }; deps.installDocumentSink?.(value); },
1846
2118
  log: (line) => {
1847
2119
  if (/^complete(?:-with-manual-steps)?(?: \(dry run\))?$/.test(line)) {
1848
2120
  outcome = line === 'complete' ? 'complete' : 'complete-with-manual-steps';
@@ -1856,12 +2128,24 @@ export async function runInstallBridgeConductorCli(argv, deps) {
1856
2128
  deps.log(line);
1857
2129
  return;
1858
2130
  }
2131
+ if (human && /^Next step: /.test(line)) {
2132
+ nextStep = line;
2133
+ return;
2134
+ }
1859
2135
  if (machine)
1860
2136
  deps.errorLog(line);
1861
2137
  else
1862
2138
  deps.log(line);
1863
2139
  },
1864
- errorLog: (line) => { deps.errorLog(line); },
2140
+ errorLog: (line) => {
2141
+ // BAPI-1650: a fixed two-token set. The approval stop outranks the learned stop and,
2142
+ // once captured, is never replaced; no other line becomes an outcome.
2143
+ if (line === CREDENTIAL_ENDPOINT_UNAPPROVED_OUTCOME)
2144
+ namedOutcome = line;
2145
+ else if (line === REPOSITORY_NOT_LEARNED_OUTCOME && namedOutcome !== CREDENTIAL_ENDPOINT_UNAPPROVED_OUTCOME)
2146
+ namedOutcome = line;
2147
+ deps.errorLog(line);
2148
+ },
1865
2149
  };
1866
2150
  let exitCode;
1867
2151
  try {
@@ -1872,12 +2156,68 @@ export async function runInstallBridgeConductorCli(argv, deps) {
1872
2156
  outcome = 'complete-with-manual-steps';
1873
2157
  deps.errorLog('Setup stopped unexpectedly. Completed independent work is retained; rerun setup to inspect it.');
1874
2158
  }
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.');
2159
+ if (machine) {
2160
+ // BAPI-1638: schema version 2 keeps every version 1 field, with the same meaning.
2161
+ let text;
2162
+ try {
2163
+ const document = {
2164
+ ...buildInstallAssessment({
2165
+ legacy: {
2166
+ outcome,
2167
+ exitCode,
2168
+ dryRun: parsed.status === 'ok' && parsed.options.dryRun,
2169
+ ...(namedOutcome ? { namedOutcome } : {}),
2170
+ ...(assessment ? { assessment, advisoryVerdict: verdict ?? 'Readiness not confirmed' } : {}),
2171
+ },
2172
+ items: parts.items ?? [],
2173
+ decisions: parts.decisions ?? null,
2174
+ ...(parts.choices !== undefined ? { choices: parts.choices } : {}),
2175
+ }),
2176
+ ...(parts.proposal !== undefined ? { proposal: parts.proposal } : {}),
2177
+ ...(parts.digest !== undefined ? { proposal_digest: parts.digest } : {}),
2178
+ ...(parts.refusal !== undefined ? { refusal: parts.refusal } : {}),
2179
+ ...(parts.apply !== undefined ? { apply: parts.apply } : {}),
2180
+ ...(parts.proposalPresentation !== undefined ? { proposal_presentation: parts.proposalPresentation } : {}),
2181
+ ...(parts.applyPresentation !== undefined ? { apply_presentation: parts.applyPresentation } : {}),
2182
+ ...(namedOutcome === REPOSITORY_NOT_LEARNED_OUTCOME && parts.missingLearnedFields !== undefined && parts.missingLearnedFields.length > 0
2183
+ ? { missing_learned_fields: parts.missingLearnedFields }
2184
+ : {}),
2185
+ };
2186
+ // BAPI-1653: the compact view is chosen here, at the JSON-output boundary, from the
2187
+ // invocation mode. A refused apply still gets the apply view.
2188
+ if (parsed.status === 'ok' && parsed.options.compact === true) {
2189
+ const options = parsed.options;
2190
+ const view = options.answers === undefined
2191
+ ? buildCompactAssessment(document)
2192
+ : options.dryRun
2193
+ ? buildCompactProposal(document)
2194
+ : buildCompactApply(document);
2195
+ text = JSON.stringify(view);
2196
+ }
2197
+ else {
2198
+ text = JSON.stringify(document);
2199
+ }
2200
+ }
2201
+ catch {
2202
+ exitCode = 1;
2203
+ text = JSON.stringify({ schemaVersion: INSTALL_ASSESSMENT_SCHEMA_VERSION, outcome: 'complete-with-manual-steps', exitCode,
2204
+ dryRun: parsed.status === 'ok' && parsed.options.dryRun, items: [], choices: [],
2205
+ repository_facts: { ci_workflows: null, package_manager: null, mcp_configs: null } });
2206
+ deps.errorLog('The setup result could not be rendered as JSON; rerun setup.');
2207
+ }
2208
+ await writeJsonDocument(text, { log: deps.log, flush: deps.isTTY === undefined ? async () => true : flushProcessStdout });
2209
+ }
2210
+ else if (human && parsed.status === 'ok') {
2211
+ const closingVerdict = verdict ?? 'Readiness not confirmed — setup did not establish all required evidence; advisory only.';
2212
+ if (deps.holdClosingResult !== undefined) {
2213
+ deps.holdClosingResult({ verdict: closingVerdict, ...(nextStep !== undefined ? { nextStep } : {}) });
2214
+ }
2215
+ else {
2216
+ deps.log(closingVerdict);
2217
+ if (nextStep !== undefined)
2218
+ deps.log(nextStep);
2219
+ }
2220
+ }
1881
2221
  return exitCode;
1882
2222
  }
1883
2223
  async function runInstallBridgeConductorCore(argv, deps) {
@@ -1974,7 +2314,7 @@ async function runInstallBridgeConductorCore(argv, deps) {
1974
2314
  deps.log("");
1975
2315
  deps.log("Dry run — no writes will be performed.");
1976
2316
  if (gatePlan !== null)
1977
- await fixGateAndDefaults(deps, options, access, gatePlan);
2317
+ await fixGateAndDefaults(deps, options, access, gatePlan, legacyReviewDefault(options));
1978
2318
  if (gatePlan === null) {
1979
2319
  deps.log(" Repository gate: none confirmed — a real run asks you to confirm one before any write.");
1980
2320
  }
@@ -2000,7 +2340,7 @@ async function runInstallBridgeConductorCore(argv, deps) {
2000
2340
  deps.log(" - done_gate_config.required_checks " +
2001
2341
  `(${bootstrapChecks.length} check(s))`);
2002
2342
  if (options.reviewPolicyExplicit)
2003
- deps.log(" - review_policy");
2343
+ deps.log(" - defaults.review_policy");
2004
2344
  if (options.replaceDoneGate)
2005
2345
  deps.log(" - replace_done_gate");
2006
2346
  deps.log(" - auto_merge_enabled");
@@ -2062,7 +2402,7 @@ async function runInstallBridgeConductorCore(argv, deps) {
2062
2402
  // replacing bootstrap when the server cannot preview.
2063
2403
  deps.log("");
2064
2404
  deps.log("Phase 2/8 — bootstrapping supervisor project defaults…");
2065
- const combined = await fixGateAndDefaults(deps, options, access, gatePlan);
2405
+ const combined = await fixGateAndDefaults(deps, options, access, gatePlan, legacyReviewDefault(options));
2066
2406
  if (combined.status === "deferred" || combined.status === "unknown")
2067
2407
  return 1;
2068
2408
  const storedGate = combined.current
@@ -2102,6 +2442,8 @@ async function runInstallBridgeConductorCore(argv, deps) {
2102
2442
  });
2103
2443
  if (epicBranchCi.manualAction !== null)
2104
2444
  manualActions.push(epicBranchCi.manualAction);
2445
+ // BAPI-1637: say what the STORED gate means for merges, from readiness's own facts.
2446
+ await runGateConsequenceSummary(gateIo, access, deps.gate);
2105
2447
  if (options.reviewPolicy === "verdict_protocol") {
2106
2448
  // ---- Phase 3: optional workflow scaffold -------------------------------
2107
2449
  deps.log("");
@@ -2316,12 +2658,34 @@ async function runInstallBridgeConductorCore(argv, deps) {
2316
2658
  * Ask for consent to one write surface. A missing prompt seam (no terminal) is
2317
2659
  * a decline, never a default yes, and says so in one line naming the step.
2318
2660
  */
2319
- async function askConsent(deps, promptText, step) {
2661
+ async function askConsent(deps, promptText, step, recordingHint = "rerun setup in an interactive terminal; no flag records this consent.",
2662
+ /** BAPI-1638 — a decision the shared apply already holds. Only an explicit one skips the question. */
2663
+ decision) {
2664
+ if (decision !== undefined)
2665
+ return decision;
2320
2666
  if (!deps.promptLine) {
2321
2667
  deps.log(` skipped ${step}: there is no interactive terminal, so this counts as declined.`);
2322
2668
  return false;
2323
2669
  }
2324
- return confirm(deps, promptText);
2670
+ // The safe answer to a consequential write is No, so Enter declines.
2671
+ return askPlainConsent(promptText, recordingHint, plainTerminalFor(deps), "no");
2672
+ }
2673
+ /** The terminal a converted EI question reads from; availability is explicit, never inferred from the reader. */
2674
+ function plainTerminalFor(deps) {
2675
+ return { read: deps.promptLine, write: deps.log, isTTY: deps.isTTY };
2676
+ }
2677
+ function snapshotToolchainReader(setup, snapshot) {
2678
+ let pending = null;
2679
+ return () => {
2680
+ if (pending === null) {
2681
+ const read = setup.readSnapshotFile;
2682
+ pending =
2683
+ snapshot === null || read === undefined
2684
+ ? Promise.resolve(null)
2685
+ : resolveRepositoryToolchains((relPath) => read(snapshot, relPath));
2686
+ }
2687
+ return pending;
2688
+ };
2325
2689
  }
2326
2690
  /**
2327
2691
  * Collect every independent read-only finding. A failed read becomes an
@@ -2336,7 +2700,8 @@ async function collectSetupEvidence(deps, setup, access, readiness, inputs) {
2336
2700
  });
2337
2701
  const identity = identityResult.ok ? identityResult.identity : null;
2338
2702
  const repository = identity !== null ? `${identity.owner}/${identity.repo}` : null;
2339
- // The stored test command, read back from the server.
2703
+ // The stored test command, read back from the server. Evidence only: nothing
2704
+ // here asks for one, and a missing command is not a setup item.
2340
2705
  let storedCommand = null;
2341
2706
  let testCommand = { state: "unknown" };
2342
2707
  try {
@@ -2349,23 +2714,15 @@ async function collectSetupEvidence(deps, setup, access, readiness, inputs) {
2349
2714
  catch {
2350
2715
  testCommand = { state: "unknown" };
2351
2716
  }
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.
2717
+ // The managed workflow, through the installer's own read-only preflight. It can
2718
+ // only be compared with a command that is stored, and it is built from the
2719
+ // remote default branch, never from the person's checkout.
2720
+ const workflowWanted = inputs.ciPlan === "managed" || inputs.gateRequiresManagedCheck;
2357
2721
  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);
2722
+ let toolchains = null;
2723
+ if (storedCommand !== null && inputs.githubSignIn === "signed_in") {
2724
+ toolchains = await inputs.readToolchains();
2725
+ workflow = await assessWorkflow(setup, storedCommand, toolchains, inputs.snapshot, workflowWanted, inputs.dependencyInstall ?? []);
2369
2726
  }
2370
2727
  // The setup pull request and, once it merged, the index.
2371
2728
  let setupPullRequest = { state: "unknown" };
@@ -2393,6 +2750,35 @@ async function collectSetupEvidence(deps, setup, access, readiness, inputs) {
2393
2750
  }
2394
2751
  }
2395
2752
  const mergeCredential = await assessMergeCredential(deps, setup, readiness, identity);
2753
+ // BAPI-1635: default-branch index lag, committed-asset drift, and the launcher form.
2754
+ // Each is a read-only fact; a failed read leaves the fact out, never aborts the collection.
2755
+ let freshness;
2756
+ if (repository !== null && inputs.githubSignIn === "signed_in" && inputs.snapshot !== null) {
2757
+ try {
2758
+ freshness = await assessIndexFreshness(inputs.snapshot.defaultBranchSha, () => setup.fetchParseStatus(access), (targetSha, indexedSha) => compareIndexedToMerge(setup.runGh, repository, targetSha, indexedSha));
2759
+ }
2760
+ catch {
2761
+ freshness = undefined;
2762
+ }
2763
+ }
2764
+ let drift;
2765
+ if (setup.inspectCommandDrift !== undefined) {
2766
+ try {
2767
+ drift = await setup.inspectCommandDrift();
2768
+ }
2769
+ catch {
2770
+ drift = undefined;
2771
+ }
2772
+ }
2773
+ let launcher = null;
2774
+ if (setup.detectLauncher !== undefined) {
2775
+ try {
2776
+ launcher = await setup.detectLauncher(access.repoName);
2777
+ }
2778
+ catch {
2779
+ launcher = null;
2780
+ }
2781
+ }
2396
2782
  return {
2397
2783
  evidence: {
2398
2784
  readiness,
@@ -2400,12 +2786,18 @@ async function collectSetupEvidence(deps, setup, access, readiness, inputs) {
2400
2786
  githubSignIn: inputs.githubSignIn,
2401
2787
  repositoryIdentity: identityResult.ok ? "resolved" : identityResult.reason,
2402
2788
  testCommand,
2789
+ ...(inputs.ciPlan !== undefined ? { ciPlan: inputs.ciPlan } : {}),
2790
+ ...(inputs.gateRequiresManagedCheck ? { gateRequiresManagedCheck: true } : {}),
2791
+ ...(inputs.plannedGateWrite === true ? { plannedGateWrite: true } : {}),
2403
2792
  workflow,
2404
2793
  setupPullRequest,
2405
2794
  index,
2406
2795
  ...(recovery ? { recovery } : {}),
2407
2796
  mergeCredential,
2408
- gateChangeDeclined: inputs.gateChangeDeclined,
2797
+ ...(freshness !== undefined ? { freshness } : {}),
2798
+ ...(drift !== undefined ? { drift } : {}),
2799
+ ...(launcher !== null ? { launcher } : {}),
2800
+ ...(inputs.path !== undefined ? { path: inputs.path } : {}),
2409
2801
  advisories: inputs.advisories,
2410
2802
  },
2411
2803
  identity,
@@ -2414,8 +2806,6 @@ async function collectSetupEvidence(deps, setup, access, readiness, inputs) {
2414
2806
  toolchains,
2415
2807
  };
2416
2808
  }
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
2809
  /** The remedy when the repository's dependency files could not be inspected. Names files, never content. */
2420
2810
  function toolchainInspectionRemedy(resolution) {
2421
2811
  const files = resolution.failures.map((f) => f.file).join(", ");
@@ -2423,20 +2813,27 @@ function toolchainInspectionRemedy(resolution) {
2423
2813
  "Fix the file or its permissions, then re-run setup");
2424
2814
  }
2425
2815
  /**
2426
- * Classify the managed workflow with the installer's read-only dry run.
2816
+ * Classify the managed workflow with the installer's read-only dry run, against
2817
+ * the remote default branch snapshot (never the person's checkout).
2427
2818
  *
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.
2819
+ * `workflowWanted` says whether the workflow matters to this run: the plan is
2820
+ * `managed`, or the gate already requires its check. A repository that does not
2821
+ * want it is not blocked because its dependency files could not be read, since no
2822
+ * workflow is going to be generated from them.
2432
2823
  */
2433
- async function assessWorkflow(setup, testCommand, toolchains, commandChanged = false) {
2824
+ async function assessWorkflow(setup, testCommand, toolchains, snapshot, workflowWanted,
2825
+ /** BAPI-1677 — the sealed install entries. Never derived here. */
2826
+ dependencyInstall = []) {
2827
+ // No snapshot (or no way to read it) is uncertainty, never a reason to guess
2828
+ // the toolchains from the person's folder.
2829
+ if (toolchains === null || snapshot === null)
2830
+ return { state: "unknown" };
2434
2831
  if (toolchains.status === "unknown") {
2435
- return { state: "blocked", remedy: toolchainInspectionRemedy(toolchains) };
2832
+ return workflowWanted ? { state: "blocked", remedy: toolchainInspectionRemedy(toolchains) } : { state: "unknown" };
2436
2833
  }
2437
2834
  let result;
2438
2835
  try {
2439
- result = await setup.installCiWorkflow(testCommand, toolchains.toolchains, { dryRun: true, quiet: true });
2836
+ result = await setup.installCiWorkflow(testCommand, toolchains.toolchains, { dryRun: true, quiet: true, snapshot, ...dependencyInstallOption(dependencyInstall) });
2440
2837
  }
2441
2838
  catch {
2442
2839
  return { state: "unknown" };
@@ -2447,17 +2844,13 @@ async function assessWorkflow(setup, testCommand, toolchains, commandChanged = f
2447
2844
  case "existing-pr":
2448
2845
  return { state: "pr_open", url: result.prUrl };
2449
2846
  case "dry-run":
2450
- return { state: "needs_pr" };
2847
+ // An installed Bridge workflow that differs is an upgrade; nothing installed is just absent.
2848
+ return result.upgrade ? { state: "needs_pr" } : { state: "absent" };
2451
2849
  case "installed-pr-opened":
2452
2850
  case "upgrade-pr-opened":
2453
2851
  // A dry run never opens one; treat an impossible answer as unknown.
2454
2852
  return { state: "unknown" };
2455
2853
  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
2854
  return result.prUrl !== undefined &&
2462
2855
  (result.reason === "existing_pr_differs" || result.reason === "historical_managed_pr_open")
2463
2856
  ? { state: "blocked", remedy: `${result.remediation} (${result.prUrl})` }
@@ -2534,19 +2927,93 @@ function storedMergeContextFor(setup, providerRepository, localRemote) {
2534
2927
  };
2535
2928
  }
2536
2929
  /** Whether the gate or the supervisor defaults would change (no POST needed). */
2537
- function gateOrDefaultsNeedWrite(gatePlan, readiness) {
2930
+ function gateOrDefaultsNeedWrite(gatePlan, readiness, reviewDefault) {
2538
2931
  if (gatePlan === null)
2539
2932
  return false;
2540
2933
  if (gatePlan.write !== null)
2541
2934
  return true;
2935
+ // A review default that is missing, or that an explicit flag changes, is a write
2936
+ // of its own: supervisor row presence alone says nothing about it.
2937
+ if (reviewDefault.kind === "send" && reviewDefault.stored !== reviewDefault.source)
2938
+ return true;
2542
2939
  if (readiness === null)
2543
2940
  return false;
2544
2941
  return !readiness.supervisor.setup_present || !readiness.supervisor.config_present;
2545
2942
  }
2546
- function bootstrapRequestFor(options, plan) {
2943
+ /** The review source a stored project default names, or `null` when none is stored. */
2944
+ function storedReviewSource(policy) {
2945
+ const stored = policy.policy.setup.review_policy;
2946
+ if (stored === null || stored === undefined)
2947
+ return null;
2948
+ if (typeof stored === "object" && typeof stored.source === "string") {
2949
+ return stored.source;
2950
+ }
2951
+ // A stored value this client cannot interpret is still a stored choice.
2952
+ return "unrecognized";
2953
+ }
2954
+ /** Whether `.github/workflows/claude-review.yml` exists on the remote default branch snapshot. */
2955
+ async function remoteReviewWorkflowExists(setup, snapshot) {
2956
+ if (snapshot === null || setup.readSnapshotFile === undefined)
2957
+ return false;
2958
+ try {
2959
+ await setup.readSnapshotFile(snapshot, CLAUDE_REVIEW_WORKFLOW_RELPATH);
2960
+ return true;
2961
+ }
2962
+ catch {
2963
+ // Absent and unreadable both fall back to repository_policy, which needs no workflow.
2964
+ return false;
2965
+ }
2966
+ }
2967
+ /**
2968
+ * Decide the review default: explicit `--review-policy` first; otherwise none when
2969
+ * a project default is already stored (or cannot be read); otherwise
2970
+ * `verdict_protocol` when the claude-review workflow exists on the remote default
2971
+ * branch and `repository_policy` when it is absent or cannot be read. The remote
2972
+ * snapshot decides, never the person's checkout. Reads only.
2973
+ */
2974
+ async function resolveReviewDefault(deps, options, setup, access, snapshot) {
2975
+ let stored;
2976
+ try {
2977
+ stored = storedReviewSource(await fetchConductorSetupPolicy(access, deps.fetchJson));
2978
+ }
2979
+ catch {
2980
+ stored = undefined;
2981
+ }
2982
+ if (options.reviewPolicyExplicit) {
2983
+ return { kind: "send", source: options.reviewPolicy, basis: "explicit", stored: stored ?? null };
2984
+ }
2985
+ if (stored === undefined)
2986
+ return { kind: "preserve", basis: "unreadable", stored: null };
2987
+ if (stored !== null)
2988
+ return { kind: "preserve", basis: "stored", stored };
2989
+ const exists = await remoteReviewWorkflowExists(setup, snapshot);
2990
+ return {
2991
+ kind: "send",
2992
+ source: exists ? "verdict_protocol" : "repository_policy",
2993
+ basis: exists ? "workflow_present" : "workflow_absent",
2994
+ stored: null,
2995
+ };
2996
+ }
2997
+ /**
2998
+ * The review default for a caller that supplies no setup seams: only an explicit
2999
+ * `--review-policy` is sent, exactly as before BAPI-1603.
3000
+ */
3001
+ function legacyReviewDefault(options) {
3002
+ return options.reviewPolicyExplicit
3003
+ ? { kind: "send", source: options.reviewPolicy, basis: "explicit", stored: null }
3004
+ : { kind: "preserve", basis: "stored", stored: null };
3005
+ }
3006
+ /** The review source the readiness doctor should assume: the one this run sends or keeps. */
3007
+ function effectiveReviewPolicy(options, reviewDefault) {
3008
+ if (reviewDefault.kind === "send")
3009
+ return reviewDefault.source;
3010
+ const stored = CONDUCTOR_REVIEW_POLICY_SOURCES.find((source) => source === reviewDefault.stored);
3011
+ return stored ?? options.reviewPolicy;
3012
+ }
3013
+ function bootstrapRequestFor(options, plan, reviewDefault) {
2547
3014
  const { action, confirm, expected_revision, ...gate } = plan.write ?? confirmRequestFor(plan.desired, plan.current.revision, plan.current.profile);
2548
3015
  return { protocol: SETUP_POLICY_PROTOCOL, ...(plan.write !== null ? { gate } : {}),
2549
- defaults: { ...(options.reviewPolicyExplicit ? { review_policy: { source: options.reviewPolicy } } : {}),
3016
+ defaults: { ...(reviewDefault.kind === "send" ? { review_policy: { source: reviewDefault.source } } : {}),
2550
3017
  merge_approval_required: "true" }, replace_done_gate: options.replaceDoneGate === true };
2551
3018
  }
2552
3019
  function policyMatches(expected, actual) {
@@ -2559,8 +3026,61 @@ function policyMatches(expected, actual) {
2559
3026
  };
2560
3027
  return canonical(expected) === canonical(actual);
2561
3028
  }
2562
- async function fixGateAndDefaults(deps, options, access, gatePlan) {
2563
- const request = bootstrapRequestFor(options, gatePlan);
3029
+ /**
3030
+ * BAPI-1604 — a policy effect as text, with worker-variable VALUES removed. A gate
3031
+ * projection can carry `worker_env` entries, and an automatic receipt must never
3032
+ * print a value that setup did not ask the owner to read.
3033
+ */
3034
+ function policyEffectText(value) {
3035
+ return JSON.stringify(value, (key, inner) => key === "worker_env" && Array.isArray(inner)
3036
+ ? inner.map((entry) => (entry !== null && typeof entry === "object" && "name" in entry ? { name: entry.name } : entry))
3037
+ : inner);
3038
+ }
3039
+ /** BAPI-1658 — the line shown for an effect whose shared description comes back empty, by category. */
3040
+ const PLANNED_CHANGE_FALLBACKS = {
3041
+ gate: "Gate settings changed",
3042
+ setup: "Review settings changed",
3043
+ config: "Merge settings changed",
3044
+ sources: "Settings sources changed",
3045
+ qualification: "Gate qualification changed",
3046
+ };
3047
+ /**
3048
+ * BAPI-1658 — the complete, ordered list of changes the automatic path is about to apply.
3049
+ *
3050
+ * One call per server effect, in the server's order, appending every returned line
3051
+ * with no merging or de-duplication, so its length is the count the owner sees. An
3052
+ * effect that describes to nothing still gets one fixed fallback line (never its
3053
+ * token or contents). Presentation only: it describes effects the server already
3054
+ * established, performs no I/O, and must not influence request construction,
3055
+ * consent, persistence, or the proposal digest.
3056
+ */
3057
+ function describePlannedPolicyChanges(effects, ciFacts) {
3058
+ const planned = [];
3059
+ for (const effect of effects) {
3060
+ const described = describePolicyChanges([effect], ciFacts, { brief: true });
3061
+ if (described.length > 0)
3062
+ planned.push(...described);
3063
+ else
3064
+ planned.push(PLANNED_CHANGE_FALLBACKS[effect.category] ?? "Setup policy changed");
3065
+ }
3066
+ return planned;
3067
+ }
3068
+ async function fixGateAndDefaults(deps, options, access, gatePlan, reviewDefault,
3069
+ /** BAPI-1604 — the converging setup applies the previewed policy without a question; the phase-based sequence still asks. */
3070
+ applyWithoutQuestion = false,
3071
+ /**
3072
+ * BAPI-1638 — the approved `gate` answer. `approve` applies the previewed policy with no
3073
+ * terminal; `decline` writes nothing. Absent keeps the terminal rule below unchanged.
3074
+ */
3075
+ decision) {
3076
+ if (decision === "decline" && !options.dryRun) {
3077
+ deps.log("Declined: the combined policy was not approved, so the gate and defaults are unchanged.");
3078
+ return { status: "deferred", declined: true };
3079
+ }
3080
+ const request = bootstrapRequestFor(options, gatePlan, reviewDefault);
3081
+ // In the converging setup the previewed policy is applied without a question, but only in an
3082
+ // available terminal. Without one the preview is shown and nothing is written, as before.
3083
+ const automatic = applyWithoutQuestion && (decision === "approve" || (deps.isTTY === true && deps.promptLine !== undefined));
2564
3084
  for (let attempt = 0; attempt < 2; attempt++) {
2565
3085
  let preview;
2566
3086
  try {
@@ -2570,32 +3090,65 @@ async function fixGateAndDefaults(deps, options, access, gatePlan) {
2570
3090
  deps.log("Deferred: combined setup policy is unavailable or unsupported. Rerun with a compatible server; ask a bootstrap administrator if this persists.");
2571
3091
  return { status: "deferred" };
2572
3092
  }
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)}`);
3093
+ // One plain line per changed setting. The before → after JSON is a diagnostic, shown only under --verbose.
3094
+ const logEffects = (effects) => {
3095
+ for (const line of describePolicyChanges(effects))
3096
+ deps.log(line);
3097
+ if (options.verbose)
3098
+ for (const effect of effects)
3099
+ deps.log(`${effect.category}: ${policyEffectText(effect.before)} → ${policyEffectText(effect.after)}`);
3100
+ };
3101
+ const printEffects = () => {
3102
+ deps.log(`Proposed required checks: ${gatePlan.desired.providerChecks.join(", ") || "none"}`);
3103
+ if ((gatePlan.desired.watchedChecks ?? []).length > 0) {
3104
+ deps.log(`Proposed watched checks: ${(gatePlan.desired.watchedChecks ?? []).join(", ")}`);
3105
+ }
3106
+ logEffects(preview.effects);
3107
+ };
2576
3108
  if (options.dryRun) {
3109
+ printEffects();
2577
3110
  deps.log("Dry run: combined preview only; no policy was applied.");
2578
3111
  return { status: "deferred" };
2579
3112
  }
2580
3113
  if (!preview.approval_required) {
3114
+ printEffects();
2581
3115
  deps.log("No change: combined policy already matches.");
2582
3116
  return { status: "unchanged" };
2583
3117
  }
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") {
3118
+ if (!applyWithoutQuestion) {
3119
+ printEffects();
3120
+ const decision = await askSetupQuestion({
3121
+ purpose: "Authorize exactly the combined repository policy changes shown above.",
3122
+ prompt: "Apply these consequential policy changes? [y/N]: ",
3123
+ evidence: ["The server computed these effects from one locked policy snapshot.",
3124
+ "Existing epic overrides keep precedence. Failed or unknown CI evidence does not relax admission."],
3125
+ options: [{ id: "yes", label: "Apply this exact policy" }, { id: "no", label: "Keep policy unchanged" }],
3126
+ consequences: ["Required checks can prevent merges. Local commands require qualification; changed commands can invalidate it.",
3127
+ "Gate and supervisor defaults commit together, preserving omitted settings."],
3128
+ deferred: "Coupled policy remains unchanged; independent setup work can continue.",
3129
+ recovery: "Rerun setup for a fresh preview; contact the bootstrap administrator if unavailable.",
3130
+ }, { read: deps.promptLine, write: deps.log });
3131
+ if (decision.status !== "accept") {
3132
+ deps.log("Deferred: combined policy was not approved.");
3133
+ return { status: "deferred" };
3134
+ }
3135
+ }
3136
+ else if (!automatic) {
3137
+ printEffects();
2596
3138
  deps.log("Deferred: combined policy was not approved.");
2597
3139
  return { status: "deferred" };
2598
3140
  }
3141
+ else {
3142
+ // BAPI-1658: list what is about to be applied. Built per attempt from this attempt's own preview;
3143
+ // every visible count comes from this list, never from the number of effect categories.
3144
+ const planned = describePlannedPolicyChanges(preview.effects);
3145
+ if (planned.length > 0) {
3146
+ deps.log(planned.length === 1 ? "Setup will apply this change:" : `Setup will apply these ${planned.length} changes:`);
3147
+ for (const line of planned)
3148
+ deps.log(` ${line}`);
3149
+ }
3150
+ deps.log(`Applying ${planned.length} previewed policy change${planned.length === 1 ? "" : "s"}…`);
3151
+ }
2599
3152
  let current;
2600
3153
  let appliedState;
2601
3154
  let uncertain = false;
@@ -2604,8 +3157,10 @@ async function fixGateAndDefaults(deps, options, access, gatePlan) {
2604
3157
  }
2605
3158
  catch (error) {
2606
3159
  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.");
3160
+ if (error instanceof ConductorSetupPolicyError && error.reason === "stale" && attempt === 0 && (applyWithoutQuestion || deps.promptLine)) {
3161
+ deps.log(applyWithoutQuestion
3162
+ ? "The policy changed since the preview. Setup is refreshing the effects once."
3163
+ : "Policy changed: refreshing the preview once. The new effects require a new answer.");
2609
3164
  continue;
2610
3165
  }
2611
3166
  if (error instanceof ConductorSetupPolicyError && ["refused", "stale", "unsupported"].includes(error.reason)) {
@@ -2627,241 +3182,88 @@ async function fixGateAndDefaults(deps, options, access, gatePlan) {
2627
3182
  deps.log("Unknown—verify before retrying: coherent read-back does not confirm the intended complete policy.");
2628
3183
  return { status: "unknown" };
2629
3184
  }
2630
- deps.log("Completed: coherent server state matches the intended policy.");
3185
+ if (applyWithoutQuestion) {
3186
+ deps.log("Policy applied (confirmed by reading it back).");
3187
+ // Describe what the read-back shows, not what was proposed.
3188
+ logEffects(preview.effects.map((effect) => ({ category: effect.category, before: effect.before, after: current.policy[effect.category] })));
3189
+ }
3190
+ else {
3191
+ deps.log("Completed: coherent server state matches the intended policy.");
3192
+ }
3193
+ // Report removals only now that the read-back confirmed the policy was applied.
3194
+ const priorProfile = gatePlan.current.profile;
3195
+ if (gatePlan.removals.length > 0 && gatePlan.current.confirmed && priorProfile !== null) {
3196
+ deps.log(`Removed from the repository gate: ${gatePlan.removals.join("; ")}.`);
3197
+ deps.log("Those checks no longer gate child merges in your Epic Implementer runs.");
3198
+ for (const line of describeGateRestoration(desiredFromStored(priorProfile)))
3199
+ deps.log(line);
3200
+ }
2631
3201
  return { status: "completed", current };
2632
3202
  }
2633
3203
  return { status: "deferred" };
2634
3204
  }
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
3205
  /** The one operator-only line for a readable stored command, then what CI installs for it. */
2820
3206
  function logStoredCommandAndToolchains(deps, storedCommand, toolchains) {
3207
+ if (storedCommand === null)
3208
+ return;
2821
3209
  deps.log("");
2822
- if (storedCommand !== null) {
2823
- deps.log(`Test command: \`${storedCommand}\` (stored). Change it with --test-command "...".`);
3210
+ deps.log(`Test command: \`${storedCommand}\` (stored). Change it with --test-command "<your command>".`);
3211
+ if (toolchains !== null) {
3212
+ deps.log("What CI installs for it:");
3213
+ for (const line of describeToolchainResolution(toolchains))
3214
+ deps.log(` ${line}`);
2824
3215
  }
2825
- deps.log("What CI installs for it:");
2826
- for (const line of describeToolchainResolution(toolchains))
2827
- deps.log(` ${line}`);
3216
+ }
3217
+ /** The installer option for sealed entries. None means the workflow's toolchain install lines. */
3218
+ function dependencyInstallOption(entries) {
3219
+ return entries.length > 0 ? { dependencyInstall: entries } : {};
2828
3220
  }
2829
3221
  /** Fix: open the one setup pull request through the artifact-set installer. */
2830
- async function fixSetupPullRequest(deps, setup, testCommand, toolchains, repository) {
3222
+ async function fixSetupPullRequest(deps, setup, testCommand, toolchains, snapshot, repository,
3223
+ /** BAPI-1638 — the approved `setup_pr` answer, which stands in for the installer's own question. */
3224
+ consent,
3225
+ /** BAPI-1677 — the sealed install entries, read back from the stored gate. */
3226
+ dependencyInstall = []) {
2831
3227
  deps.log("");
2832
3228
  deps.log("CI workflow");
3229
+ if (toolchains === null || snapshot === null) {
3230
+ // No snapshot of the default branch is uncertainty, never a reason to read the
3231
+ // person's folder instead. Only workflow generation is skipped.
3232
+ deps.log(" skipped — Bridge could not read your default branch to choose what CI installs, and it will not guess.");
3233
+ return { workflow: { state: "unknown" }, pr: null, result: null };
3234
+ }
2833
3235
  if (toolchains.status === "unknown") {
2834
3236
  // Uninspectable dependency files are a blocking inspection failure, never "no lockfile".
2835
3237
  const remedy = toolchainInspectionRemedy(toolchains);
2836
3238
  deps.log(` skipped — ${remedy}.`);
2837
- return { workflow: { state: "blocked", remedy }, pr: null };
3239
+ return { workflow: { state: "blocked", remedy }, pr: null, result: null };
2838
3240
  }
2839
3241
  let result;
2840
3242
  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"));
3243
+ // The setup pull request has its OWN consent: it pushes a branch and opens a PR.
3244
+ result = await setup.installCiWorkflow(testCommand, toolchains.toolchains, { dryRun: false, snapshot, ...dependencyInstallOption(dependencyInstall) }, (promptText) => askConsent(deps, promptText, "opening the setup pull request", undefined, consent));
2843
3245
  }
2844
3246
  catch {
2845
3247
  deps.log(" the setup pull request could not be prepared; re-run setup.");
2846
- return { workflow: { state: "unknown" }, pr: null };
3248
+ return { workflow: { state: "unknown" }, pr: null, result: null };
2847
3249
  }
2848
3250
  switch (result.outcome) {
2849
3251
  case "installed-pr-opened":
2850
3252
  case "upgrade-pr-opened":
2851
3253
  deps.log(` opened the setup PR: ${result.prUrl}`);
2852
- return { workflow: { state: "pr_open", url: result.prUrl }, pr: null };
3254
+ return { workflow: { state: "pr_open", url: result.prUrl }, pr: null, result };
2853
3255
  case "existing-pr":
2854
3256
  deps.log(` the setup PR is already open: ${result.prUrl}`);
2855
- return { workflow: { state: "pr_open", url: result.prUrl }, pr: null };
3257
+ return { workflow: { state: "pr_open", url: result.prUrl }, pr: null, result };
2856
3258
  case "identical":
2857
3259
  deps.log(" the CI workflow is already in place — nothing to change.");
2858
- return { workflow: { state: "installed" }, pr: null };
3260
+ return { workflow: { state: "installed" }, pr: null, result };
2859
3261
  case "dry-run":
2860
- return { workflow: { state: "needs_pr" }, pr: null };
3262
+ return { workflow: result.upgrade ? { state: "needs_pr" } : { state: "absent" }, pr: null, result };
2861
3263
  case "failed": {
2862
3264
  if (result.reason === "consent_declined") {
2863
3265
  deps.log(" declined — no branch was pushed and no pull request was opened.");
2864
- return { workflow: { state: "needs_pr" }, pr: null };
3266
+ return { workflow: { state: "absent" }, pr: null, result };
2865
3267
  }
2866
3268
  deps.log(` the setup pull request was not opened (${result.reason}): ${result.remediation}`);
2867
3269
  if (result.prUrl !== undefined)
@@ -2871,8 +3273,8 @@ async function fixSetupPullRequest(deps, setup, testCommand, toolchains, reposit
2871
3273
  // An uncertain creation is re-read, never repeated.
2872
3274
  const pr = repository !== null ? await readSetupPullRequest(setup.runGh, repository) : null;
2873
3275
  if (pr?.state === "open")
2874
- return { workflow: { state: "pr_open", url: pr.url }, pr };
2875
- return { workflow: { state: "blocked", remedy: result.remediation }, pr };
3276
+ return { workflow: { state: "pr_open", url: pr.url }, pr, result };
3277
+ return { workflow: { state: "blocked", remedy: result.remediation }, pr, result };
2876
3278
  }
2877
3279
  }
2878
3280
  }
@@ -2880,7 +3282,11 @@ async function fixSetupPullRequest(deps, setup, testCommand, toolchains, reposit
2880
3282
  * Fix: store (or replace) the GitHub merge token for this repository, after its
2881
3283
  * own consent, read with no echo. Never printed, logged, committed, or sent.
2882
3284
  */
2883
- async function fixMergeToken(deps, setup, identity, replacing) {
3285
+ /** BAPI-1638 — the non-secret name of this repository's merge-token entry, as answers reference it. */
3286
+ export function mergeTokenStoreTarget(identity) {
3287
+ return `merge_token:${identity.owner}/${identity.repo}`;
3288
+ }
3289
+ async function fixMergeToken(deps, setup, identity, replacing, answer) {
2884
3290
  const repository = `${identity.owner}/${identity.repo}`;
2885
3291
  deps.log("");
2886
3292
  deps.log("GitHub merge token");
@@ -2893,31 +3299,66 @@ async function fixMergeToken(deps, setup, identity, replacing) {
2893
3299
  }
2894
3300
  const ok = await askConsent(deps, replacing
2895
3301
  ? `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");
3302
+ : `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
3303
  if (!ok) {
2898
3304
  deps.log(replacing
2899
3305
  ? " declined — the stored token was left as it is."
2900
3306
  : " 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;
3307
+ return { status: "declined" };
2906
3308
  }
2907
3309
  let token = "";
2908
- try {
2909
- token = (await setup.promptSecret("GitHub merge token (input is hidden): ")).trim();
2910
- }
2911
- catch {
2912
- token = "";
3310
+ if (answer?.decision === "reference") {
3311
+ // The token is resolved from its approved reference here, at apply time, and never echoed.
3312
+ const reference = answer.reference;
3313
+ if (reference.kind === "env") {
3314
+ token = (deps.env[reference.name] ?? "").trim();
3315
+ if (token.length === 0) {
3316
+ deps.log(` the environment variable ${reference.name} is not set; nothing was stored.`);
3317
+ return { status: "failed", reason: `the environment variable ${reference.name} is not set` };
3318
+ }
3319
+ }
3320
+ else {
3321
+ if (reference.target !== mergeTokenStoreTarget(identity)) {
3322
+ deps.log(` setup reads only this repository's own credential-store entry (${mergeTokenStoreTarget(identity)}); nothing was stored.`);
3323
+ return { status: "failed", reason: `the reference must name ${mergeTokenStoreTarget(identity)}` };
3324
+ }
3325
+ let stored;
3326
+ try {
3327
+ stored = await setup.readMergeToken(identity);
3328
+ }
3329
+ catch {
3330
+ return { status: "failed", reason: "the credential store could not be read" };
3331
+ }
3332
+ if (stored.status !== "present") {
3333
+ deps.log(" the referenced credential-store entry holds no token for this repository; nothing was stored.");
3334
+ return { status: "failed", reason: "the referenced credential-store entry holds no token for this repository" };
3335
+ }
3336
+ // The repository's own store entry is the only credential-store target setup reads.
3337
+ if (isUsableMergeCredentialValue(stored.token))
3338
+ return replacing ? { status: "failed", reason: "the stored token is the one GitHub rejected" } : { status: "unchanged" };
3339
+ return { status: "failed", reason: "the referenced credential-store entry is not a usable token" };
3340
+ }
2913
3341
  }
2914
- if (token.length === 0) {
2915
- deps.log(" no token was entered; nothing was stored.");
2916
- return false;
3342
+ else {
3343
+ if (!setup.promptSecret) {
3344
+ deps.log(" skipped reading the token: there is no interactive terminal. Nothing was stored.");
3345
+ return { status: "declined" };
3346
+ }
3347
+ try {
3348
+ token = (await setup.promptSecret("GitHub merge token (input is hidden): ")).trim();
3349
+ }
3350
+ catch {
3351
+ token = "";
3352
+ }
3353
+ if (token.length === 0) {
3354
+ deps.log(" no token was entered; nothing was stored.");
3355
+ return { status: "declined" };
3356
+ }
2917
3357
  }
2918
3358
  if (!isUsableMergeCredentialValue(token)) {
3359
+ token = "";
2919
3360
  deps.log(" that value cannot be a GitHub token (it has spaces or control characters); nothing was stored.");
2920
- return false;
3361
+ return { status: "failed", reason: "the referenced value cannot be a GitHub token" };
2921
3362
  }
2922
3363
  const result = await setup.storeMergeToken(identity, token);
2923
3364
  let stored = result.ok;
@@ -2929,19 +3370,18 @@ async function fixMergeToken(deps, setup, identity, replacing) {
2929
3370
  token = "";
2930
3371
  if (!stored) {
2931
3372
  deps.log(` the token could not be stored (${result.ok ? "unconfirmed" : result.kind}); nothing changed.`);
2932
- return false;
3373
+ return { status: "failed", reason: `the token could not be stored (${result.ok ? "unconfirmed" : result.kind})` };
2933
3374
  }
2934
3375
  deps.log(` stored the merge token for ${repository} on this computer.`);
2935
3376
  if (replacing) {
2936
3377
  deps.log(" A run already in progress keeps the token its executor started with until that executor restarts.");
2937
3378
  }
2938
- return true;
3379
+ return { status: "written" };
2939
3380
  }
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) {
3381
+ /** The refusal remedy when fresh recovery evidence asks a question the answers did not state. */
3382
+ const REINDEX_REFUSED_REMEDY = "Refused: the recovery evidence now asks a question the answers did not state, so nothing was queued. " +
3383
+ "Run --answers - --dry-run --json for a fresh proposal, then rerun with its answers.";
3384
+ export async function fixReindex(deps, setup, access, initial, answers) {
2945
3385
  deps.log("");
2946
3386
  deps.log("Repository indexing");
2947
3387
  const unresolved = (remedy, choice) => {
@@ -2950,8 +3390,9 @@ export async function fixReindex(deps, setup, access, initial) {
2950
3390
  };
2951
3391
  if (!initial?.supported || !setup.fetchRecoveryEvidence || !setup.correctBranch || !setup.admitRecovery)
2952
3392
  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");
3393
+ // Terminal availability is explicit: a reader alone is not an interactive terminal.
3394
+ if (answers === undefined && (!deps.promptLine || deps.isTTY !== true))
3395
+ 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
3396
  let current = initial.evidence;
2956
3397
  const knownUnverified = (e) => !e.canonical.verified
2957
3398
  && ["absent", "unverified"].includes(e.canonical_observation ?? "unknown");
@@ -2967,23 +3408,38 @@ export async function fixReindex(deps, setup, access, initial) {
2967
3408
  return unresolved("Configured branch ancestry is unknown; inspect it before retrying. Nothing was queued.");
2968
3409
  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
3410
  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");
3411
+ // The demonstrated default branch with nothing else configured is not a choice: take it,
3412
+ // say so, and continue through the same correction and verification path.
3413
+ const unambiguous = current.destination_branch === current.provider_default
3414
+ && (current.configured_branch === null || current.configured_branch === "" || current.configured_branch === current.destination_branch);
3415
+ if (!unambiguous && answers !== undefined && answers.branch === undefined)
3416
+ return unresolved(REINDEX_REFUSED_REMEDY, "refused");
3417
+ const decision = unambiguous
3418
+ ? { status: "selected", id: "correct" }
3419
+ : answers?.branch !== undefined
3420
+ ? { status: "selected", id: answers.branch }
3421
+ : await askPlainSetupQuestion({
3422
+ question: `Which branch should Bridge index? Your stored branch is ${JSON.stringify(current.configured_branch)} and the setup used ${current.destination_branch}.`,
3423
+ options: [
3424
+ { id: "correct", label: `Use the default branch (${current.destination_branch})` },
3425
+ { id: "keep", label: `Keep the current branch (${JSON.stringify(current.configured_branch)})` },
3426
+ ],
3427
+ recommended: "correct",
3428
+ recordingFlag: "no flag records this choice; rerun setup in an interactive terminal.",
3429
+ evidence: [`Stored branch: ${JSON.stringify(current.configured_branch)}. Proposed destination: ${current.destination_branch}.`,
3430
+ `Required setup revision: ${current.required_commit_sha}; configured head: ${current.resolved_head_sha}; canonical content: ${current.canonical_relation}.`],
3431
+ consequences: [
3432
+ `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.`,
3433
+ "Parsing picks the configured branch again when it runs, so what it reads can differ from this preview.",
3434
+ "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.",
3435
+ "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.",
3436
+ ],
3437
+ recovery: "Check the branch with the repository maintainer, then re-run setup interactively.",
3438
+ }, plainTerminalFor(deps));
3439
+ if (unambiguous)
3440
+ deps.log(` The repository's default branch is ${current.destination_branch}, so setup uses it for indexing.`);
3441
+ if (decision.status !== "selected")
3442
+ return unresolved("Branch choice deferred; no correction or parse was submitted. Re-run setup interactively when ready.", "deferred");
2987
3443
  if (decision.id === "keep" && !["equal", "contains_target"].includes(current.configured_relation))
2988
3444
  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
3445
  if (decision.id === "correct") {
@@ -3020,17 +3476,26 @@ export async function fixReindex(deps, setup, access, initial) {
3020
3476
  if (current.request) {
3021
3477
  if (current.retry_generation === null)
3022
3478
  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: [
3479
+ if (answers !== undefined && answers.retry === undefined)
3480
+ return unresolved(REINDEX_REFUSED_REMEDY, "refused");
3481
+ const decision = answers?.retry !== undefined ? { status: "selected", id: answers.retry } : await askPlainSetupQuestion({
3482
+ question: "The earlier indexing attempt did not finish the job. Retry it once?",
3483
+ options: [
3484
+ { id: "retry", label: "Retry once" },
3485
+ { id: "no_retry", label: "Do not retry" },
3486
+ ],
3487
+ recommended: "retry",
3488
+ recordingFlag: "no flag records this choice; rerun setup in an interactive terminal.",
3489
+ evidence: [
3025
3490
  `Prior request ${current.request.id}, run ${current.request.parse_run_id ?? "retained"}, status ${current.request.status}.`,
3026
3491
  `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
3492
  `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"
3493
+ ],
3494
+ 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."],
3495
+ recovery: "Look at the earlier attempt, then re-run interactive setup.",
3496
+ }, plainTerminalFor(deps));
3497
+ if (!(decision.status === "selected" && decision.id === "retry"))
3498
+ return decision.status === "selected"
3034
3499
  ? unresolved("Retry declined; no request was submitted. Re-run setup after reviewing the prior attempt.", "declined")
3035
3500
  : unresolved("Retry deferred; no request was submitted. Re-run setup after reviewing the prior attempt.", "deferred");
3036
3501
  retry = current.retry_generation;
@@ -3110,8 +3575,12 @@ function localAdvisories(report) {
3110
3575
  return out;
3111
3576
  }
3112
3577
  /** 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.");
3578
+ export async function assessEpicInstallerPrerequisites(deps, executorRequested = false,
3579
+ /** BAPI-1604 — print only general asset-maintenance commentary under `--verbose`; failures and remedies always print. */
3580
+ quietGeneralCommentary = false) {
3581
+ if (!quietGeneralCommentary) {
3582
+ 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.");
3583
+ }
3115
3584
  let observed = { claudeLoggedIn: null, githubSignIn: "unavailable", localRemote: null, toolsAvailable: false, platformSupported: false };
3116
3585
  try {
3117
3586
  if (deps.prerequisites)
@@ -3145,48 +3614,1394 @@ export async function assessEpicInstallerPrerequisites(deps, executorRequested =
3145
3614
  !observed.localRemote ? "supported github.com origin missing or unknown" : null,
3146
3615
  !observed.toolsAvailable ? "required tools missing or unknown" : null,
3147
3616
  !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.`);
3617
+ 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
3618
  }
3150
3619
  return { ...observed, available };
3151
3620
  }
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;
3621
+ // ---------------------------------------------------------------------------
3622
+ // BAPI-1603: learned first
3623
+ // ---------------------------------------------------------------------------
3624
+ /**
3625
+ * The named outcome of the one stop this change adds. The first line of the
3626
+ * refusal, so it is greppable and survives into the machine-readable result.
3627
+ */
3628
+ export const REPOSITORY_NOT_LEARNED_OUTCOME = "repository_not_learned";
3629
+ /**
3630
+ * BAPI-1650: the named outcome for a saved key that needs the owner's one-time
3631
+ * approval at a non-production address. It outranks {@link REPOSITORY_NOT_LEARNED_OUTCOME}.
3632
+ */
3633
+ export const CREDENTIAL_ENDPOINT_UNAPPROVED_OUTCOME = "credential_endpoint_unapproved";
3634
+ /** The fixed id of the one blocking item that carries the owner's bind command. */
3635
+ export const CREDENTIAL_ENDPOINT_APPROVAL_ITEM_ID = "local.credential-endpoint-approval";
3636
+ /**
3637
+ * BAPI-1657: the default profile for a bind command the owner has not given one. It
3638
+ * comes from the repository segment after the last `/`, never the checkout directory.
3639
+ * Invalid characters become `-`, edge hyphens are trimmed, and the result is capped at
3640
+ * 57 characters. An empty or unusable name falls back to `local`.
3641
+ */
3642
+ export function generatedLaunchProfileName(repoName) {
3643
+ const segment = repoName.split("/").pop() ?? "";
3644
+ const normalized = segment
3645
+ .toLowerCase()
3646
+ .replace(/[^a-z0-9._-]/g, "-")
3647
+ .replace(/^-+|-+$/g, "")
3648
+ .slice(0, 57);
3649
+ return EPIC_LAUNCH_PROFILE_NAME_PATTERN.test(normalized) ? normalized : "local";
3650
+ }
3651
+ /**
3652
+ * Build the bind command through the CLI's own launcher. A nonblank `BAPI_MCP_CLI`
3653
+ * stays a command prefix (never quoted as a whole); otherwise the detected launcher,
3654
+ * then the published package. The profile follows `--launch-profile`, then
3655
+ * `BAPI_EPIC_LAUNCH_PROFILE`, then the generated default from the repository name.
3656
+ * Profile and target are quoted independently. No key value is read or printed.
3657
+ */
3658
+ async function endpointApprovalCommand(deps, options, approval) {
3659
+ const override = deps.env.BAPI_MCP_CLI?.trim();
3660
+ let base;
3661
+ if (override !== undefined && override !== "") {
3662
+ base = override.split(/\s+/).join(" ");
3663
+ }
3664
+ else {
3665
+ base = await detectedLauncherBase(deps, approval.repoName);
3666
+ }
3667
+ const profile = explicitLaunchProfile(deps, options) ?? generatedLaunchProfileName(approval.repoName);
3668
+ return `${base} install epic-implementer --launch-profile ${shellQuote(profile)} --base-url ${shellQuote(approval.target)}`;
3669
+ }
3670
+ /** The launch profile the owner supplied, from `--launch-profile` or then `BAPI_EPIC_LAUNCH_PROFILE`. */
3671
+ function explicitLaunchProfile(deps, options) {
3672
+ const fromEnv = deps.env.BAPI_EPIC_LAUNCH_PROFILE?.trim();
3673
+ return options.launchProfile ?? (fromEnv !== undefined && fromEnv !== "" ? fromEnv : undefined);
3674
+ }
3675
+ /** The one blocking item for an unapproved endpoint, with the command as one back-quoted span. */
3676
+ async function endpointApprovalItem(deps, options, approval) {
3677
+ const command = await endpointApprovalCommand(deps, options, approval);
3678
+ const generatedProfile = explicitLaunchProfile(deps, options) === undefined ? generatedLaunchProfileName(approval.repoName) : null;
3679
+ const profileNote = generatedProfile === null
3680
+ ? ""
3681
+ : ` \`${generatedProfile}\` is the name this approval is saved under on this computer; to launch an epic against this server later, pass \`--launch-profile ${generatedProfile}\`.`;
3682
+ return {
3683
+ id: CREDENTIAL_ENDPOINT_APPROVAL_ITEM_ID,
3684
+ label: "Saved Bridge key approval for this address",
3685
+ state: "needs_action",
3686
+ blocking: true,
3687
+ remedy: `Your saved Bridge key cannot safely be used at ${approval.target} until you approve that address once. ` +
3688
+ "Sending it to an address you have not approved could hand your key to the wrong server. " +
3689
+ `In your own terminal, run \`${command}\`, answer yes to the one-time approval question, ` +
3690
+ `then run /install-epic-implementer again.${profileNote}`,
3691
+ };
3692
+ }
3693
+ /** Report the approval stop: the greppable token first, then the plain reason. */
3694
+ function reportCredentialEndpointUnapproved(deps) {
3695
+ deps.errorLog(CREDENTIAL_ENDPOINT_UNAPPROVED_OUTCOME);
3696
+ deps.errorLog("Your saved Bridge key has not been approved for this address yet.");
3697
+ }
3698
+ /** Plain labels for the ten learned instruction identifiers (BAPI-1680). */
3699
+ const LEARNED_FIELD_LABELS = {
3700
+ architecture_instructions: "Architecture instructions",
3701
+ design_principles: "Design principles",
3702
+ review_instructions: "Code review instructions",
3703
+ documentation_instructions: "Documentation instructions",
3704
+ unit_testing_instructions: "Unit testing instructions",
3705
+ e2e_testing_instructions: "End-to-end testing instructions",
3706
+ frontend_correctness_standards: "Front-end code standards",
3707
+ backend_correctness_standards: "Back-end code standards",
3708
+ template_correctness_standards: "Template standards",
3709
+ style_correctness_standards: "Code style standards",
3710
+ };
3711
+ /** A plain label for a learned field identifier; a valid unknown one reads with spaces. */
3712
+ function learnedFieldLabel(name) {
3713
+ return Object.prototype.hasOwnProperty.call(LEARNED_FIELD_LABELS, name)
3714
+ ? LEARNED_FIELD_LABELS[name]
3715
+ : name.replace(/_/g, " ");
3716
+ }
3717
+ /** Print the plain stop for a repository that has not been (fully) learned. */
3718
+ function reportRepositoryNotLearned(deps, fieldsSet, missingFields = []) {
3719
+ deps.errorLog(REPOSITORY_NOT_LEARNED_OUTCOME);
3720
+ deps.errorLog(fieldsSet > 0
3721
+ ? "Bridge has not finished learning this repository."
3722
+ : "Bridge has not learned this repository yet.");
3723
+ deps.errorLog(`${fieldsSet > 0 ? "Finish" : "Run"} /learn-repository in Claude Code, wait for it to finish, then run this ` +
3724
+ "setup again. Bridge needs your project's standards to write useful code.");
3725
+ if (missingFields.length > 0) {
3726
+ deps.errorLog("These instructions are still missing:");
3727
+ for (const name of missingFields)
3728
+ deps.errorLog(` - ${learnedFieldLabel(name)}`);
3729
+ }
3730
+ deps.errorLog("Bridge uses its stored copy of these instructions. Editing local standards files, such as " +
3731
+ "docs/standards/*.md, does not update that copy.");
3732
+ deps.errorLog("To fill in one item by hand instead, use /teach-bridge and explain it in plain words. " +
3733
+ "Then run this setup again.");
3734
+ }
3735
+ /**
3736
+ * Read whether the repository has been learned. Returns `true` only for a
3737
+ * validated `learned: false`. An unknown reading (an older server, a 503, a bad
3738
+ * body, a failed transport) warns once and returns `false`: an unknown never
3739
+ * becomes a stop.
3740
+ */
3741
+ async function repositoryNotLearned(deps, access) {
3742
+ const learning = await fetchConductorRepositoryLearning(access, deps.fetchJson);
3743
+ if (learning.status === "unknown") {
3744
+ deps.log("Bridge could not check whether this repository has been learned, so setup continues. If you have not " +
3745
+ "run /learn-repository in Claude Code yet, run it.");
3746
+ return false;
3747
+ }
3748
+ if (learning.learned)
3749
+ return false;
3750
+ reportRepositoryNotLearned(deps, learning.learned_fields_set, learning.missing_fields);
3751
+ if (learning.missing_fields.length > 0) {
3752
+ deps.installDocumentSink?.({ missingLearnedFields: [...learning.missing_fields] });
3753
+ }
3754
+ return true;
3755
+ }
3756
+ // ---------------------------------------------------------------------------
3757
+ // BAPI-1603: the test command, proven by the server's trial
3758
+ // ---------------------------------------------------------------------------
3759
+ /** What file detection found, as optional hints for the server. Detection never stores anything. */
3760
+ async function learnedCommandHints(setup, access) {
3761
+ let detection;
3762
+ try {
3763
+ detection = await detectTestCommand({ skipStoredRead: true }, { config: setup.testingConfig(access), readFile: (relPath) => setup.readRepositoryFile(relPath) });
3764
+ }
3765
+ catch {
3766
+ return [];
3767
+ }
3768
+ if (detection.status === "failed")
3769
+ return [];
3770
+ // The command text is sent as detected. A command that belongs to a
3771
+ // subdirectory is named as one in its source, and is never rewritten into a
3772
+ // guessed root command.
3773
+ return detection.candidates.map((candidate) => ({
3774
+ command: candidate.command,
3775
+ source: candidate.workingDirectory !== undefined && candidate.workingDirectory !== "."
3776
+ ? `${candidate.provenance}; directory ${candidate.workingDirectory}`
3777
+ : candidate.provenance,
3778
+ }));
3779
+ }
3780
+ /**
3781
+ * BAPI-1677 — whether a test trial can be offered. The candidates are the ones the
3782
+ * client can see: file detection first, then the repository's local commands, in
3783
+ * their fixed order. With none, no trial is recommended. A failed trial stores
3784
+ * nothing, so it never stops a later offer, and a stored command is never cleared.
3785
+ */
3786
+ async function resolveTestCommandTrial(deps, setup, access, gatePlan, storedCommand) {
3787
+ const none = { eligible: false, candidates: [] };
3788
+ const inferred = gatePlan.inferred;
3789
+ const storedGateRetry = inferred === undefined && gatePlan.origin === "stored" && gatePlan.current.confirmed &&
3790
+ storedCommand === null && (gatePlan.current.profile?.local_commands.length ?? 0) === 0;
3791
+ if (!storedGateRetry && inferred?.trialEligible !== true)
3792
+ return none;
3793
+ const candidates = [];
3794
+ const add = (candidate) => {
3795
+ if (!candidates.some((c) => c.command === candidate.command))
3796
+ candidates.push(candidate);
3797
+ };
3798
+ if (inferred !== undefined && storedCommand !== null)
3799
+ add({ command: storedCommand, source: "stored configuration" });
3800
+ for (const hint of await learnedCommandHints(setup, access))
3801
+ add(hint);
3802
+ const fs = deps.gate?.discoveryFs;
3803
+ if (fs !== undefined) {
3804
+ try {
3805
+ for (const local of await discoverLocalTestCandidates(fs))
3806
+ add({ command: local.argv.join(" "), source: "repository files" });
3807
+ }
3808
+ catch {
3809
+ // An unreadable file adds no candidate. It is never a stop.
3810
+ }
3811
+ }
3812
+ return { eligible: candidates.length > 0, candidates };
3813
+ }
3814
+ /**
3815
+ * Ask the server for the learned (or the owner's) test command and prove it.
3816
+ *
3817
+ * Runs only after the initial gate write, bound to the gate's refreshed revision:
3818
+ * the server's promotion then adds the local member to the stored profile and keeps
3819
+ * the watched checks. An automatic trial is allowed only for a newly inferred plan;
3820
+ * a `--test-command` goes through the same route as the owner's command, on any
3821
+ * gate. Nothing here writes a local member, and an uncertain outcome is reported,
3822
+ * never retried.
3823
+ */
3824
+ async function runTestCommandPhase(deps, options, setup, access, baseUrl, state, gatePlan, policyResult,
3825
+ /**
3826
+ * BAPI-1638 — the approved `test_command` answer. `learn` runs the bounded
3827
+ * discovery-and-promotion trial; `skip`/`keep` run nothing; a command is the
3828
+ * owner's own. Absent keeps the flag-and-inference rule below.
3829
+ */
3830
+ answer) {
3831
+ if (answer !== undefined && (answer.decision === "skip" || answer.decision === "keep"))
3832
+ return;
3833
+ const ownerCommand = answer?.decision === "command" ? answer.command : options.testCommand;
3834
+ const automatic = ownerCommand === undefined && gatePlan?.testCommandTrial?.eligible === true;
3835
+ if (ownerCommand === undefined && !automatic)
3836
+ return;
3837
+ deps.log("");
3838
+ deps.log("Test command");
3839
+ let current;
3840
+ try {
3841
+ current = await fetchConductorGateProfile(access, deps.fetchJson);
3842
+ }
3843
+ catch {
3844
+ deps.log(" skipped — the stored gate could not be read, so nothing was started.");
3845
+ return;
3846
+ }
3847
+ // A policy change the owner deferred only holds the trial back when it WAS the gate the
3848
+ // command attaches to; an unrelated deferral never stops a confirmed gate's command proof.
3849
+ if ((policyResult?.status === "deferred" || policyResult?.status === "unknown") && !current.confirmed) {
3850
+ deps.log(" skipped — the gate and defaults were not stored, so there is no stored gate to attach a proven command to.");
3851
+ return;
3852
+ }
3853
+ const candidates = automatic ? gatePlan?.testCommandTrial?.candidates : undefined;
3854
+ const io = gateIoFor(deps);
3855
+ const trialGateDeps = deps.gate !== undefined && deps.progressTimer !== undefined && deps.gate.progressTimer === undefined
3856
+ ? { ...deps.gate, progressTimer: deps.progressTimer }
3857
+ : deps.gate;
3858
+ const result = await runLearnedTestCommandTrial(io, access, trialGateDeps, {
3859
+ baseUrl,
3860
+ current,
3861
+ ...(candidates !== undefined ? { candidates } : {}),
3862
+ ...(ownerCommand !== undefined ? { ownerCommand } : {}),
3863
+ });
3864
+ reportLearnedCommandTrial(io, result);
3865
+ state.trial = result;
3866
+ if (result.status === "uncertain")
3867
+ state.commandUncertain = true;
3868
+ if (result.status === "promoted")
3869
+ state.promotedCommands = result.commands;
3870
+ }
3871
+ /**
3872
+ * Settle the inferred CI plan once the trial is known, and print its plain
3873
+ * explanation once. Only an inferred plan has one: a stored or explicit gate keeps
3874
+ * its own provenance. `none` needs both no reported checks AND no proven command,
3875
+ * and an unknown completion is never described as `none`.
3876
+ */
3877
+ function settleCiPlan(deps, state, gatePlan) {
3878
+ const inferred = gatePlan?.inferred;
3879
+ if (inferred === undefined || inferred.storedUnreadable)
3880
+ return;
3881
+ // Unknown CI history stored nothing and ran no trial: there is no plan to describe.
3882
+ if (!inferred.trialEligible && inferred.reportedChecks.length === 0)
3883
+ return;
3884
+ const promoted = state.trial?.status === "promoted";
3885
+ if (inferred.reportedChecks.length > 0) {
3886
+ state.ciPlan = "watched";
3887
+ }
3888
+ else if (promoted) {
3889
+ state.ciPlan = "local";
3890
+ }
3891
+ else if (state.commandUncertain) {
3892
+ return;
3893
+ }
3894
+ else {
3895
+ state.ciPlan = "none";
3896
+ }
3897
+ for (const reason of inferred.reasons) {
3898
+ if (state.ciPlan !== "none")
3899
+ deps.log(reason);
3900
+ }
3901
+ if (state.ciPlan === "none") {
3167
3902
  deps.log("");
3168
- deps.log("Which repository is this? Bridge could not tell from the environment or .bridge/config.");
3903
+ // BAPI-1654: "no CI" is said only when no CI files exist. No reported checks is not no CI.
3904
+ const systems = state.ciSystems ?? [];
3905
+ deps.log(systems.length > 0
3906
+ ? `Bridge found CI configuration (${[...new Set(systems.map((s) => s.name))].join(", ")}) but no checks have ` +
3907
+ "reported from it yet, and it could not prove a test command. Child pull requests will merge into the epic " +
3908
+ "branch without a test gate. You review everything in the final pull request."
3909
+ : "Bridge found no CI and could not prove a test command. Child pull requests will merge into the epic " +
3910
+ "branch without a test gate. You review everything in the final pull request.");
3911
+ }
3912
+ }
3913
+ // ---------------------------------------------------------------------------
3914
+ // BAPI-1603: Bridge's own workflow, an option on a proven local plan
3915
+ // ---------------------------------------------------------------------------
3916
+ /** The review default a managed-gate write leaves alone: it changes the gate only. */
3917
+ const MANAGED_WRITE_REVIEW_DEFAULT = { kind: "preserve", basis: "stored", stored: null };
3918
+ /**
3919
+ * The one yes/no about CI: add Bridge's GitHub workflow. Default No. Asked at most
3920
+ * once per invocation; No, Enter, and a deferred or unanswerable question all leave
3921
+ * the plan local, open no pull request, and store no permanent decline.
3922
+ */
3923
+ async function offerManagedWorkflow(deps) {
3924
+ let readFailed = false;
3925
+ const read = deps.promptLine;
3926
+ const decision = await askPlainSetupQuestion({
3927
+ question: "Also add Bridge's GitHub workflow, so your tests also run on GitHub for each epic pull request?",
3928
+ options: [
3929
+ { id: "yes", label: "Add the workflow (a setup pull request you review and merge)", aliases: ["y"] },
3930
+ { id: "no", label: "Keep the local test gate only", aliases: ["n"] },
3931
+ ],
3932
+ // Opening a pull request is consequential, so the safe answer stays No.
3933
+ recommended: "no",
3934
+ recordingFlag: "no flag records this choice; rerun setup in an interactive terminal to be asked again.",
3935
+ evidence: [
3936
+ "Bridge already runs your proven test command before each merge, so the gate works without it.",
3937
+ "The workflow runs the same command on GitHub, only for pull requests into epic branches.",
3938
+ ],
3939
+ consequences: [
3940
+ "Yes opens a setup pull request built from a clean copy of your default branch. You merge it yourself.",
3941
+ "Once the pull request is open, Bridge adds the workflow's check to the gate and checks the gate again.",
3942
+ ],
3943
+ recovery: "Run setup again to be asked once more.",
3944
+ }, {
3945
+ read: read === undefined
3946
+ ? undefined
3947
+ : async (promptText) => {
3948
+ try {
3949
+ return await read(promptText);
3950
+ }
3951
+ catch (error) {
3952
+ readFailed = true;
3953
+ throw error;
3954
+ }
3955
+ },
3956
+ write: deps.log,
3957
+ isTTY: deps.isTTY,
3958
+ });
3959
+ if (decision.status === "selected" && decision.id === "yes")
3960
+ return true;
3961
+ if (decision.status === "defer" && (read === undefined || readFailed || deps.isTTY !== true)) {
3962
+ deps.log(" The workflow was not added because nobody could answer.");
3963
+ }
3964
+ else {
3965
+ deps.log(" Kept the local test gate only. No workflow was added.");
3966
+ }
3967
+ return false;
3968
+ }
3969
+ /**
3970
+ * After the setup pull request is open: add the workflow's check to the CURRENT
3971
+ * gate (so the server-promoted local member and any watched checks are kept),
3972
+ * through the same revision-aware policy writer, then qualify the new revision
3973
+ * with the short-lived executor. Managed readiness is claimed only after a
3974
+ * validated passing qualification; a failure or an uncertain answer keeps the
3975
+ * authoritative state and says why.
3976
+ */
3977
+ async function promoteManagedGate(deps, options, access, baseUrl, state,
3978
+ /**
3979
+ * BAPI-1638 — adding the workflow's check to the gate is part of the approved
3980
+ * setup-PR effect, so an approved `setup_pr` answer applies it with no terminal.
3981
+ */
3982
+ decision) {
3983
+ deps.log("");
3984
+ deps.log("Gate");
3985
+ let fresh;
3986
+ try {
3987
+ fresh = await fetchConductorGateProfile(access, deps.fetchJson);
3988
+ }
3989
+ catch {
3990
+ 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.");
3991
+ return;
3992
+ }
3993
+ const plan = planManagedProviderGate(fresh, EPIC_IMPLEMENTER_CI_CHECK_NAME);
3994
+ if (plan !== null) {
3995
+ const written = await fixGateAndDefaults(deps, options, access, plan, MANAGED_WRITE_REVIEW_DEFAULT, true, decision);
3996
+ if (written.status === "deferred" || written.status === "unknown") {
3997
+ deps.log(" Bridge's workflow check was not added to the gate. The local test gate stays as it is.");
3998
+ return;
3999
+ }
4000
+ }
4001
+ state.ciPlan = "managed";
4002
+ let after;
4003
+ try {
4004
+ after = await fetchConductorGateProfile(access, deps.fetchJson);
4005
+ }
4006
+ catch {
4007
+ 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.");
4008
+ return;
4009
+ }
4010
+ if (after.profile === null || after.profile.local_commands.length === 0)
4011
+ return;
4012
+ const report = await runConductorGateQualification(gateIoFor(deps), access, deps.gate, {
4013
+ revision: after.revision,
4014
+ baseUrl,
4015
+ });
4016
+ if (report === "qualified") {
4017
+ deps.log(" Bridge's workflow check is part of the gate, and the gate passed its check at the new revision.");
4018
+ }
4019
+ else {
4020
+ 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.");
4021
+ }
4022
+ }
4023
+ /**
4024
+ * The optional managed workflow, in one place: assess it against the remote
4025
+ * default branch with the command the gate now holds, upgrade an installed Bridge
4026
+ * workflow that differs, or offer a first one once (a proven single-command local
4027
+ * plan with no CI of its own, never an explicit gate request, never a watched or
4028
+ * `none` plan). The check is added to the gate only after the installer opened or
4029
+ * reused the setup pull request. A command whose proof is unknown, a missing
4030
+ * snapshot, or an installer failure skips only this step.
4031
+ */
4032
+ async function runWorkflowPhase(deps, options, setup, access, baseUrl, state, readToolchains, gateRequiresManagedCheck,
4033
+ /** BAPI-1638 — the approved `setup_pr` answer. Absent keeps today's questions. */
4034
+ setupPrDecision) {
4035
+ const none = { status: "none" };
4036
+ if (state.evidence.githubSignIn !== "signed_in" || state.repository === null)
4037
+ return none;
4038
+ if (state.commandUncertain) {
4039
+ deps.log("");
4040
+ deps.log("CI workflow");
4041
+ deps.log(" skipped — it is built from the test command, and Bridge cannot tell yet whether that command was stored.");
4042
+ return { status: "unattempted", reason: "Bridge cannot tell yet whether the test command was stored" };
4043
+ }
4044
+ // The setup PR's effect is conditional: it opens only if the approved check passed.
4045
+ const trial = state.trial;
4046
+ if (setupPrDecision === "approve" && trial !== null && trial.status !== "promoted" && trial.status !== "not_needed") {
4047
+ const phase = "evidence" in trial && trial.evidence !== undefined ? trial.evidence.phase : null;
4048
+ deps.log("");
4049
+ deps.log("CI workflow");
4050
+ // BAPI-1657: the owner never sees the raw `no_command` token; the plain reason stands in for it.
4051
+ deps.log(trial.status === "no_command"
4052
+ ? ` not opened — the setup pull request opens only if the test-command check passes, and ${NO_TEST_COMMAND_REASON}.`
4053
+ : ` not opened — the setup pull request opens only if the test-command check passes, and it did not (${trial.status}${phase !== null ? `, phase ${phase}` : ""}).`);
4054
+ const reason = trial.status === "no_command" ? NO_TEST_COMMAND_REASON : `the test-command check did not pass (${trial.status})`;
4055
+ return { status: "declined", reason, phase };
4056
+ }
4057
+ let profile = null;
4058
+ try {
4059
+ profile = await fetchConductorGateProfile(access, deps.fetchJson);
4060
+ }
4061
+ catch {
4062
+ profile = null;
4063
+ }
4064
+ if (profile === null || !profile.confirmed || profile.profile === null)
4065
+ return none;
4066
+ // BAPI-1677: the read-back is what the workflow installs, not what discovery found.
4067
+ const sealedChanged = !sameDependencyInstall(profile.profile.dependency_install ?? [], state.sealedDependencyInstall);
4068
+ const sealedDependencyInstall = profile.profile.dependency_install ?? [];
4069
+ state.sealedDependencyInstall = sealedDependencyInstall;
4070
+ // The command the workflow runs is the one the server proved this run, else the stored one.
4071
+ let command = state.promotedCommands?.length === 1 ? state.promotedCommands[0].command : null;
4072
+ if (command === null) {
4073
+ try {
4074
+ const read = await readStoredTestCommand(setup.testingConfig(access));
4075
+ if (read.ok)
4076
+ command = read.testCommand;
4077
+ }
4078
+ catch {
4079
+ command = null;
4080
+ }
4081
+ }
4082
+ if (command === null)
4083
+ return none;
4084
+ const toolchains = await readToolchains();
4085
+ state.toolchains = toolchains;
4086
+ // The first read already assessed the workflow against this very command when no
4087
+ // trial changed it this run; only a command that may have changed is assessed again.
4088
+ const assessed = state.trial === null && !sealedChanged && command === state.storedCommand && state.evidence.workflow.state !== "unknown"
4089
+ ? state.evidence.workflow
4090
+ : await assessWorkflow(setup, command, toolchains, state.snapshot, true, sealedDependencyInstall);
4091
+ state.evidence = { ...state.evidence, workflow: assessed };
4092
+ const localOnly = profile.profile.kind === "local" &&
4093
+ profile.profile.provider_checks.length === 0 &&
4094
+ (profile.profile.watched_checks ?? []).length === 0;
4095
+ const oneCommand = profile.profile.local_commands.length === 1;
4096
+ const offerEligible = localOnly &&
4097
+ !hasExplicitGateInput(options.gate) &&
4098
+ (assessed.state === "absent" || assessed.state === "pr_open");
4099
+ let install = false;
4100
+ if (assessed.state === "needs_pr" || (assessed.state === "absent" && gateRequiresManagedCheck)) {
4101
+ // An installed Bridge workflow that differs is offered as an upgrade, and a gate that
4102
+ // already requires the workflow's check needs the workflow itself: the installer's own
4103
+ // consent is the only question.
4104
+ install = true;
4105
+ }
4106
+ else if (offerEligible) {
4107
+ if (!oneCommand) {
4108
+ deps.log("");
4109
+ deps.log("CI workflow");
4110
+ deps.log(" not offered — the workflow runs one command and this gate has more than one.");
4111
+ return none;
4112
+ }
4113
+ try {
4114
+ validateTestCommand(command);
4115
+ }
4116
+ catch (error) {
4117
+ if (!(error instanceof TestCommandValidationError))
4118
+ throw error;
4119
+ deps.log("");
4120
+ deps.log("CI workflow");
4121
+ deps.log(" not offered — the workflow cannot run this test command as written (one line, no GitHub Actions expression, at most 500 characters).");
4122
+ return none;
4123
+ }
4124
+ install = setupPrDecision !== undefined ? setupPrDecision === "approve" : await offerManagedWorkflow(deps);
4125
+ if (setupPrDecision === "decline")
4126
+ deps.log(" Kept the local test gate only. No workflow was added.");
4127
+ }
4128
+ if (!install)
4129
+ return setupPrDecision === "decline" ? { status: "declined" } : none;
4130
+ const outcome = await fixSetupPullRequest(deps, setup, command, toolchains, state.snapshot, state.repository, setupPrDecision === undefined ? undefined : setupPrDecision === "approve", sealedDependencyInstall);
4131
+ state.evidence = { ...state.evidence, workflow: outcome.workflow };
4132
+ const result = outcome.result;
4133
+ const opened = result !== null &&
4134
+ (result.outcome === "installed-pr-opened" || result.outcome === "upgrade-pr-opened" || result.outcome === "existing-pr");
4135
+ // Only a first workflow adds the managed check; an upgrade of an installed one does not touch the gate.
4136
+ if (opened && offerEligible) {
4137
+ await promoteManagedGate(deps, options, access, baseUrl, state, setupPrDecision === "approve" ? "approve" : undefined);
4138
+ }
4139
+ if (result === null)
4140
+ return { status: "failed", reason: "the setup pull request could not be prepared" };
4141
+ switch (result.outcome) {
4142
+ case "installed-pr-opened":
4143
+ case "upgrade-pr-opened":
4144
+ return { status: "written", url: result.prUrl };
4145
+ case "existing-pr":
4146
+ return { status: "unchanged", url: result.prUrl };
4147
+ case "identical":
4148
+ return { status: "unchanged" };
4149
+ case "dry-run":
4150
+ return none;
4151
+ case "failed":
4152
+ return result.reason === "consent_declined" ? { status: "declined" } : { status: "failed", reason: result.reason };
4153
+ }
4154
+ }
4155
+ /**
4156
+ * Warn, never stop, when the default branch's rules require the managed workflow's
4157
+ * check. The workflow runs only for pull requests into `epic/**`, so the final
4158
+ * pull request into the default branch would wait for a check that never starts.
4159
+ * Any inspection that gives no reliable answer is silent: unknown is not "no rule".
4160
+ */
4161
+ async function warnDefaultBranchRequiresManagedCheck(setup, state) {
4162
+ if (state.repository === null || state.evidence.githubSignIn !== "signed_in")
4163
+ return;
4164
+ const runGh = setup.runGh;
4165
+ const found = await readDefaultBranchRequiredChecksViaGh(async (args) => {
4166
+ const result = await runGh(args);
4167
+ return { exitCode: result.status ?? 1, stdout: result.stdout, stderr: result.stderr };
4168
+ }, state.repository, state.snapshot?.defaultBranch);
4169
+ if (found.status !== "known" || !found.requiredChecks.includes(EPIC_IMPLEMENTER_CI_CHECK_NAME))
4170
+ return;
4171
+ state.evidence.advisories.push(`Your rules for ${found.defaultBranch} require \`${EPIC_IMPLEMENTER_CI_CHECK_NAME}\`. Bridge's workflow runs only ` +
4172
+ `for pull requests into epic branches, so the final pull request into ${found.defaultBranch} would wait for a ` +
4173
+ "check that never starts. Remove that required check from the branch protection rule or ruleset that applies to it.");
4174
+ }
4175
+ /** Whether Bridge's own workflow is in play, so its default-branch rule warning can matter. */
4176
+ function managedWorkflowInPlay(state, gateRequiresManagedCheck) {
4177
+ const workflow = state.evidence.workflow.state;
4178
+ return (state.ciPlan === "managed" ||
4179
+ gateRequiresManagedCheck ||
4180
+ workflow === "installed" ||
4181
+ workflow === "pr_open" ||
4182
+ workflow === "needs_pr");
4183
+ }
4184
+ /** What a dry run says about the CI plan: conditional outcomes, nothing requested or started. */
4185
+ function renderDryRunCiPlan(deps, options, gatePlan) {
4186
+ deps.log("");
4187
+ if (options.testCommand !== undefined) {
4188
+ deps.log(" Test command: a real run offers your --test-command to Bridge's server and proves it by running it once on " +
4189
+ "this computer. Dry run requested nothing and started nothing.");
4190
+ }
4191
+ else if (gatePlan?.testCommandTrial?.eligible === true) {
4192
+ deps.log(" Test command: a real run asks Bridge's server to learn it from this repository and proves it by running it " +
4193
+ "once on this computer, and nobody is asked for it. Dry run requested nothing and started nothing.");
4194
+ }
4195
+ const inferred = gatePlan?.inferred;
4196
+ if (inferred !== undefined && !inferred.storedUnreadable) {
4197
+ deps.log(inferred.reportedChecks.length > 0
4198
+ ? ` CI plan: watch the ${inferred.reportedChecks.length} check(s) your CI already reports. A local test gate ` +
4199
+ "is added only if the command passes."
4200
+ : " CI plan: no CI reported. A local test gate is stored only if the command passes; otherwise the gate has " +
4201
+ "no members.");
4202
+ deps.log(" Bridge's workflow: offered once, only for a proven local plan, and only added if you say yes and the setup " +
4203
+ "pull request opens. Dry run asked nothing and opened nothing.");
4204
+ }
4205
+ }
4206
+ /** Read the folder's project binding. Only an absent file counts as "not bound". */
4207
+ async function resolveFolderBinding(deps) {
4208
+ const read = await readBridgeConfig(deps.cwd, {
4209
+ readFile: deps.readBindingFile ?? ((filePath) => readFileAsync(filePath, "utf-8")),
4210
+ });
4211
+ if (read.ok)
4212
+ return { status: "bound", repo: read.manifest.repoName };
4213
+ return read.kind === "missing" ? { status: "absent" } : { status: "unresolved" };
4214
+ }
4215
+ // ---------------------------------------------------------------------------
4216
+ // BAPI-1638: decision evidence and the shared apply's adapters
4217
+ // ---------------------------------------------------------------------------
4218
+ // ---------------------------------------------------------------------------
4219
+ // BAPI-1654: the CI change setup can offer (read-only)
4220
+ // ---------------------------------------------------------------------------
4221
+ /** The domain-separated identity of a file that does not exist yet. Never the hash of an empty file. */
4222
+ export function absentSourceSha256(path) {
4223
+ return sha256Hex(`bapi-ci-absent-source/v1\u0000${path}`);
4224
+ }
4225
+ /**
4226
+ * Collect the CI change on offer, from the remote default-branch snapshot (the
4227
+ * same head the pull request is built from), never from the person's checkout.
4228
+ * At most one remedy: none when coverage is confirmed, else one eligible trigger
4229
+ * edit, else Bridge's managed workflow when a stored test command is known.
4230
+ * Read-only.
4231
+ */
4232
+ async function collectCiOffer(input) {
4233
+ const { setup, state, collected } = input;
4234
+ const ciSystems = state.ciSystems === undefined ? undefined : state.ciSystems === null ? null : state.ciSystems.map((c) => ({ name: c.name, path: c.path }));
4235
+ const base = { evidence: { ...(ciSystems !== undefined ? { ciSystems } : {}) }, delivery: null };
4236
+ if (collected === undefined || collected.status !== "collected")
4237
+ return base;
4238
+ const snapshot = state.snapshot;
4239
+ const read = setup.readSnapshotFile;
4240
+ const coverage = collected.coverage;
4241
+ const sources = new Map();
4242
+ const classified = [];
4243
+ const epicResults = [];
4244
+ const targetCoverages = [];
4245
+ let unread = false;
4246
+ const paths = [...new Set(coverage.workflows.map((w) => w.path))].sort();
4247
+ if (snapshot !== null && read !== undefined) {
4248
+ for (const path of paths) {
4249
+ let text;
4250
+ try {
4251
+ text = await read(snapshot, path);
4252
+ }
4253
+ catch {
4254
+ text = null;
4255
+ }
4256
+ if (typeof text !== "string") {
4257
+ unread = true;
4258
+ continue;
4259
+ }
4260
+ sources.set(path, text);
4261
+ classified.push(GITHUB_ACTIONS_TRIGGER_ADAPTER.classify(path, text));
4262
+ const body = text.startsWith("\uFEFF") ? text.slice(1) : text;
4263
+ epicResults.push({ path, ...classifyEpicPullRequestTrigger(body) });
4264
+ targetCoverages.push(classifyEpicPullRequestTrigger(body, { targetBranch: snapshot.defaultBranch }).coverage);
4265
+ }
4266
+ }
4267
+ // Snapshot-bound coverage: when every listed workflow was read at the default-branch head, its
4268
+ // bytes decide, not the person's checkout. Otherwise the inspection's own answer stands.
4269
+ const snapshotComplete = snapshot !== null && read !== undefined && !unread && paths.length > 0 && coverage.reason !== "file_limit_reached";
4270
+ const epicCoverages = epicResults.map((r) => r.coverage);
4271
+ const excludedWorkflows = (snapshotComplete ? epicResults : coverage.workflows)
4272
+ .filter((w) => w.coverage === "does_not_cover" && w.reason === "branch_filter_excludes_epic")
4273
+ .map((w) => {
4274
+ const c = classified.find((x) => x.path === w.path);
4275
+ const branches = c === undefined ? null : c.kind === "eligible" ? c.edit.branchesBefore : c.kind === "ineligible" ? c.branches : null;
4276
+ return { path: w.path, branches };
4277
+ });
4278
+ const integrationTarget = snapshot === null || read === undefined
4279
+ ? null
4280
+ : {
4281
+ branch: snapshot.defaultBranch,
4282
+ coverage: (targetCoverages.includes("covers")
4283
+ ? "covers"
4284
+ : unread || targetCoverages.includes("could_not_tell") || coverage.coverage === "could_not_tell"
4285
+ ? "could_not_tell"
4286
+ : "does_not_cover"),
4287
+ };
4288
+ const effectiveCoverage = !snapshotComplete
4289
+ ? coverage.coverage
4290
+ : epicCoverages.includes("covers") ? "covers" : epicCoverages.includes("could_not_tell") ? "could_not_tell" : "does_not_cover";
4291
+ const evidence = {
4292
+ ...base.evidence, excludedWorkflows, integrationTarget, ciOffer: null,
4293
+ ...(snapshotComplete ? { coverage: effectiveCoverage } : {}),
4294
+ };
4295
+ if (effectiveCoverage === "covers") {
4296
+ // A replay: an approved change already in place keeps its identity, so the same answers hash the same.
4297
+ for (const [path, text] of sources) {
4298
+ const applied = recognizeAppliedEdit(path, text);
4299
+ if (applied !== null) {
4300
+ evidence.ciOffer = {
4301
+ identity: { action_class: "trigger_edit", path, source_sha256: applied.sourceSha256, patch_sha256: applied.patchSha256 },
4302
+ applicable: false,
4303
+ branchesBefore: applied.branchesBefore,
4304
+ };
4305
+ return { evidence, delivery: null };
4306
+ }
4307
+ }
4308
+ const managed = await managedWorkflowIdentity(input, "installed");
4309
+ if (managed !== null)
4310
+ evidence.ciOffer = { identity: managed.identity, applicable: false };
4311
+ return { evidence, delivery: null };
4312
+ }
4313
+ if (setup.installCiTriggerEdit !== undefined) {
4314
+ const edit = selectTriggerEdit(classified, sources, state.storedCommand);
4315
+ if (edit !== null) {
4316
+ evidence.ciOffer = {
4317
+ identity: { action_class: "trigger_edit", path: edit.path, source_sha256: edit.sourceSha256, patch_sha256: edit.patchSha256 },
4318
+ applicable: true,
4319
+ branchesBefore: edit.branchesBefore,
4320
+ };
4321
+ return { evidence, delivery: { kind: "trigger_edit", edit } };
4322
+ }
4323
+ }
4324
+ // BAPI-1659: offered whether or not the setup pull request could also add the workflow. The CI
4325
+ // choice delivers it on its own; when both are approved the installer reuses the one open pull request.
4326
+ const managed = await managedWorkflowIdentity(input, "absent");
4327
+ if (managed !== null) {
4328
+ evidence.ciOffer = { identity: managed.identity, applicable: true };
4329
+ return { evidence, delivery: { kind: "managed_workflow", command: managed.command, toolchains: managed.toolchains, dependencyInstall: input.dependencyInstall ?? [] } };
4330
+ }
4331
+ return { evidence, delivery: null };
4332
+ }
4333
+ /**
4334
+ * The managed fallback's identity: the absent-source marker and the hash of the
4335
+ * renderer's exact output for the stored command and snapshot toolchains. Only
4336
+ * when the managed workflow is in the wanted state (`absent` to offer it,
4337
+ * `installed` for a replay), on a signed-in GitHub repository with a snapshot
4338
+ * and a valid stored command. The renderer itself is unchanged.
4339
+ */
4340
+ async function managedWorkflowIdentity(input, wanted) {
4341
+ const { state } = input;
4342
+ if (state.evidence.githubSignIn !== "signed_in" || state.repository === null || state.snapshot === null)
4343
+ return null;
4344
+ if (state.evidence.workflow.state !== wanted)
4345
+ return null;
4346
+ const command = state.storedCommand;
4347
+ if (command === null)
4348
+ return null;
4349
+ try {
4350
+ validateTestCommand(command);
4351
+ }
4352
+ catch {
4353
+ return null;
4354
+ }
4355
+ let resolution;
4356
+ try {
4357
+ resolution = await input.readToolchains();
4358
+ }
4359
+ catch {
4360
+ resolution = null;
4361
+ }
4362
+ if (resolution === null || resolution.status !== "resolved")
4363
+ return null;
4364
+ let rendered;
4365
+ try {
4366
+ // The same entries are delivered, so the approved hash matches the delivered bytes.
4367
+ rendered = renderEpicImplementerCiWorkflow(command, resolution.toolchains, input.dependencyInstall ?? []);
4368
+ }
4369
+ catch {
4370
+ return null;
4371
+ }
4372
+ return {
4373
+ identity: {
4374
+ action_class: "managed_workflow",
4375
+ path: EPIC_CI_WORKFLOW_PATH,
4376
+ source_sha256: absentSourceSha256(EPIC_CI_WORKFLOW_PATH),
4377
+ patch_sha256: sha256Hex(rendered),
4378
+ },
4379
+ command,
4380
+ toolchains: resolution.toolchains,
4381
+ };
4382
+ }
4383
+ /** Read-only: build the decision evidence every open choice is projected from. */
4384
+ async function collectDecisionEvidence(input) {
4385
+ const { deps, options, access, gatePlan, state, fixes, grantInventory } = input;
4386
+ const identity = {
4387
+ repo_name: access.repoName,
4388
+ provider_repository: state.repository,
4389
+ destination: access.baseUrl.replace(/\/+$/, ""),
4390
+ // Which binding supplied the key, never the key: the parent env first, then the store target.
4391
+ credential_binding: (deps.env.BAPI_API_KEY ?? "").trim().length > 0 ? "env:BAPI_API_KEY" : `credential_store:bapi:${access.repoName}`,
4392
+ };
4393
+ const desired = gatePlan?.desired ?? null;
4394
+ const ciFacts = input.firstReport.readiness?.epic_branch_ci ?? null;
4395
+ // The gate's own effect names only the members the gate write sets. A command the
4396
+ // learned trial promotes (`test_command`) and the managed check the setup PR adds
4397
+ // (`setup_pr`) are their own approved effects, so a replay after both hashes the same.
4398
+ // Explicit gate flags are the owner's literal members and are always named.
4399
+ const fromFlags = gatePlan?.origin === "flags";
4400
+ const gate = gatePlan === null || desired === null ? null : {
4401
+ writeNeeded: fixes.includes("gate_and_defaults"),
4402
+ kind: fromFlags ? desired.kind : null,
4403
+ providerChecks: desired.providerChecks.filter((c) => fromFlags || c !== EPIC_IMPLEMENTER_CI_CHECK_NAME),
4404
+ watchedChecks: [...(desired.watchedChecks ?? [])],
4405
+ localCommands: fromFlags ? desired.localCommands.map((c) => c.name) : [],
4406
+ origin: gatePlan.origin,
4407
+ consequence: describeGateConsequence({ kind: desired.kind, hasWatchedChecks: (desired.watchedChecks ?? []).length > 0 }, ciFacts),
4408
+ currentKind: gatePlan.current.profile?.kind ?? null,
4409
+ };
4410
+ const stored = gatePlan?.current.profile ?? null;
4411
+ const installFacts = input.dependencyInstallFacts ?? null;
4412
+ const installDetails = installFacts === null ? undefined : dependencyInstallDetails({
4413
+ commands: input.correctedDependencyInstall === true ? input.effectiveDependencyInstall ?? [] : installFacts.planned,
4414
+ stored: installFacts.stored,
4415
+ differs: input.correctedDependencyInstall === true || installFacts.drift !== "same",
4416
+ evidence: input.correctedDependencyInstall === true ? [] : installFacts.evidence,
4417
+ limitations: installFacts.limitations,
4418
+ });
4419
+ const declarations = input.declarationPlan.map((entry) => ({
4420
+ key: entry.key,
4421
+ summary: entry.summary,
4422
+ value: declarationValue(entry.fields),
4423
+ ...(entry.key === "dependency_install" && installFacts !== null
4424
+ ? { recommendDecline: installFacts.drift === "replacing", ...(installDetails !== undefined ? { dependencyInstall: installDetails } : {}) }
4425
+ : {}),
4426
+ }));
4427
+ // A settled declaration still names its stored value, so a replay hashes the same.
4428
+ for (const [key, value] of [
4429
+ ["dependency_install", stored?.dependency_install],
4430
+ ["ci_database", stored?.ci_database],
4431
+ ["must_order_paths", stored?.must_order_paths],
4432
+ ["worker_database", stored?.worker_database],
4433
+ ]) {
4434
+ const empty = value === undefined || value === null || (Array.isArray(value) && value.length === 0) || value === "unknown";
4435
+ if (!empty && !declarations.some((d) => d.key === key)) {
4436
+ declarations.push({
4437
+ key, summary: [], value: declarationValue({ [declarationField(key)]: value }), applicable: false,
4438
+ ...(key === "dependency_install" && installDetails !== undefined ? { dependencyInstall: installDetails } : {}),
4439
+ });
4440
+ }
4441
+ }
4442
+ // Nothing stored and nothing on offer can still have something to say, such as a failed read.
4443
+ if (installDetails !== undefined && !declarations.some((d) => d.key === "dependency_install") && installDetails.limitations.length > 0) {
4444
+ declarations.push({ key: "dependency_install", summary: [], value: null, applicable: false, dependencyInstall: installDetails });
4445
+ }
4446
+ const workflowState = state.evidence.workflow.state;
4447
+ const trialEligible = gatePlan?.testCommandTrial?.eligible === true;
4448
+ const recovery = state.evidence.recovery?.supported ? state.evidence.recovery.evidence : undefined;
4449
+ const branchQuestion = fixes.includes("reindex") && recovery !== undefined && recovery.destination_branch
4450
+ && (!["equal", "contains_target"].includes(recovery.configured_relation) || recovery.canonical_relation === "diverged")
4451
+ && !(recovery.destination_branch === recovery.provider_default
4452
+ && (recovery.configured_branch === null || recovery.configured_branch === "" || recovery.configured_branch === recovery.destination_branch))
4453
+ ? { configured: recovery.configured_branch, destination: recovery.destination_branch }
4454
+ : undefined;
4455
+ const retryQuestion = fixes.includes("reindex") && recovery?.request && !["queued", "in_progress"].includes(recovery.request.status ?? "") && recovery.retry_generation !== null
4456
+ ? { requestId: recovery.request.id, generation: recovery.retry_generation }
4457
+ : undefined;
4458
+ const label = (origin) => CANDIDATE_ORIGIN_LABEL[origin];
4459
+ const epicServerSnapshot = input.epicServerSnapshot ?? null;
4460
+ const sfccGrant = new Set(sfccGrantIds(epicServerSnapshot, grantInventory));
4461
+ const mcpGrant = grantInventory === null ? null : {
4462
+ current: state.evidence.mcpGrant?.state === "needs_action" ? state.evidence.mcpGrant.reason : state.evidence.mcpGrant?.state ?? "unknown",
4463
+ applicable: fixes.includes("mcp_grant"),
4464
+ candidates: grantInventory.candidates.flatMap((c) => c.definitions.map((d) => ({ id: d.id, name: c.name, origins: d.origins.map(label), ...(sfccGrant.has(d.id) ? { sfcc_recommended: true } : {}) }))),
4465
+ excluded: grantInventory.exclusions.map((e) => ({ name: e.name, origin: label(e.origin), reason: CANDIDATE_EXCLUSION_TEXT[e.reason] })),
4466
+ invalidExisting: grantInventory.existingGrant?.state === "ok"
4467
+ ? grantInventory.existingGrant.findings.map((f) => ({ name: f.name, reason: CANDIDATE_EXCLUSION_TEXT[f.reason] }))
4468
+ : [],
4469
+ fingerprint: grantInventory.fingerprint,
4470
+ };
4471
+ const epicServerEvidence = state.evidence.epicServer;
4472
+ const collected = input.epicBranchCollected;
4473
+ const ciOffer = input.ciOffer ?? null;
4474
+ return {
4475
+ identity,
4476
+ gate,
4477
+ declarations,
4478
+ testCommand: {
4479
+ stored: state.storedCommand !== null,
4480
+ trialEligible,
4481
+ candidate: gatePlan?.testCommandTrial?.candidates[0]?.command ?? null,
4482
+ ownerCommandSupplied: options.testCommand !== undefined,
4483
+ },
4484
+ setupPr: {
4485
+ applicable: setupPrOffersWorkflow(input),
4486
+ workflowState,
4487
+ commandSource: trialEligible ? "learned" : state.storedCommand !== null ? "stored" : null,
4488
+ },
4489
+ mergeToken: {
4490
+ state: state.evidence.mergeCredential.state,
4491
+ storeTarget: state.identity !== null ? mergeTokenStoreTarget(state.identity) : null,
4492
+ },
4493
+ reindex: {
4494
+ planned: fixes.includes("reindex"),
4495
+ // Display only: an unknown or unverified index is never described as current.
4496
+ indexStatus: indexDisplayStatus(input.firstItems, state.evidence.index),
4497
+ ...(branchQuestion ? { branchQuestion } : {}), ...(retryQuestion ? { retryQuestion } : {}),
4498
+ },
4499
+ mcpGrant,
4500
+ epicServer: epicServerEvidence === undefined ? null : epicServerDecisionEvidence(epicServerEvidence.state === "met" ? epicServerEvidence.mode : null, fixes.includes("epic_server"), epicServerSnapshot, epicServerSnapshot?.existingSandbox !== null && epicServerSnapshot?.existingSandbox !== undefined),
4501
+ // The decision readiness reports as recorded is shown on the choice only; it never sets
4502
+ // `recommended` or `applicable`, so it cannot move a digest.
4503
+ epicBranchCi: collected === undefined || collected.status === "skipped_no_seams" ? null : {
4504
+ ...(collected.status === "collected"
4505
+ ? { coverage: collected.coverage.coverage, approvalsRequired: collected.rules?.approvalsRequired ?? "could_not_tell", ownerRepo: collected.ownerRepo, recordedDecision: ciFacts?.decision ?? null }
4506
+ : { coverage: null, approvalsRequired: null, ownerRepo: null, recordedDecision: ciFacts?.decision ?? null }),
4507
+ // BAPI-1654: the CI change on offer and the facts the honest wording reads.
4508
+ ...(ciOffer !== null ? ciOffer.evidence : {}),
4509
+ ...(setupPrOffersWorkflow(input) && workflowState !== "installed" ? { managedWorkflowViaSetupPr: true } : {}),
4510
+ },
4511
+ launchProfile: { selected: options.launchProfile ?? null, notification: state.evidence.notification?.state ?? null },
4512
+ repositoryFacts: {
4513
+ ...(await collectRepositoryFacts(deps, grantInventory, input.readToolchains)),
4514
+ ...(state.ciSystems !== undefined
4515
+ ? { ci_systems: state.ciSystems === null ? null : state.ciSystems.map((c) => ({ name: c.name, path: c.path })) }
4516
+ : {}),
4517
+ // BAPI-1667: from the same snapshot, so nothing is read or checked a second time.
4518
+ ...(epicServerSnapshot?.detection !== null && epicServerSnapshot?.detection !== undefined
4519
+ ? {
4520
+ sfcc: {
4521
+ detected: epicServerSnapshot.detection.detected,
4522
+ signals: epicServerSnapshot.detection.signals,
4523
+ dev_script: epicServerSnapshot.detection.dev_script,
4524
+ upload_check: epicServerSnapshot.uploadCheck,
4525
+ },
4526
+ }
4527
+ : {}),
4528
+ },
4529
+ };
4530
+ }
4531
+ /**
4532
+ * Whether the setup pull request opens Bridge's own workflow this run (an
4533
+ * upgrade, a required workflow, or a first offer). A first workflow is offered
4534
+ * only on a proven local plan: an inferred `none` plan with no explicit gate
4535
+ * input (a watched plan already has CI of its own and is never offered one).
4536
+ */
4537
+ function setupPrOffersWorkflow(input) {
4538
+ const { options, gatePlan, state, fixes } = input;
4539
+ const workflowState = state.evidence.workflow.state;
4540
+ const trialEligible = gatePlan?.testCommandTrial?.eligible === true;
4541
+ return state.evidence.githubSignIn === "signed_in" && state.repository !== null
4542
+ && (fixes.includes("setup_pr") || (trialEligible && gatePlan?.inferred?.ciPlan === "none" && !hasExplicitGateInput(options.gate)
4543
+ && (workflowState === "absent" || workflowState === "unknown")));
4544
+ }
4545
+ function declarationField(key) {
4546
+ return key === "dependency_install" ? "dependencyInstall" : key === "ci_database" ? "ciDatabase" : key === "must_order_paths" ? "mustOrderPaths" : "workerDatabase";
4547
+ }
4548
+ /** The declaration's canonical value, for the digest. Worker-database credentials are names, never values. */
4549
+ function declarationValue(fields) {
4550
+ return JSON.parse(JSON.stringify(Object.values(fields)[0] ?? null));
4551
+ }
4552
+ /** Read-only repository facts: workflow branch filters, package manager and lockfile, MCP config names and origins. */
4553
+ async function collectRepositoryFacts(deps, grantInventory, readToolchains) {
4554
+ let ciWorkflows = null;
4555
+ const fs = deps.gate?.discoveryFs;
4556
+ if (fs !== undefined) {
4557
+ try {
4558
+ const entries = (await fs.listDir(".github/workflows")) ?? [];
4559
+ ciWorkflows = [];
4560
+ for (const name of [...entries].filter((n) => /^[^/\\]+\.ya?ml$/.test(n)).sort().slice(0, 50)) {
4561
+ const path = `.github/workflows/${name}`;
4562
+ let text = null;
4563
+ try {
4564
+ text = await fs.readText(path);
4565
+ }
4566
+ catch {
4567
+ text = null;
4568
+ }
4569
+ const filters = text === null ? { kind: "could_not_tell" } : readPullRequestBranchFilters(text);
4570
+ if (filters.kind === "filters")
4571
+ ciWorkflows.push({ path, pull_request_branches: filters.branches });
4572
+ }
4573
+ }
4574
+ catch {
4575
+ ciWorkflows = null;
4576
+ }
4577
+ }
4578
+ let packageManager = null;
4579
+ try {
4580
+ const resolution = await readToolchains();
4581
+ const js = resolution?.status === "resolved" ? resolution.toolchains.javascript : null;
4582
+ const py = resolution?.status === "resolved" ? resolution.toolchains.python : null;
4583
+ if (js !== null && js !== undefined)
4584
+ packageManager = { name: js.manager, lockfile: js.dependencyFile };
4585
+ else if (py !== null && py !== undefined)
4586
+ packageManager = { name: py.manager, lockfile: py.dependencyFile };
4587
+ }
4588
+ catch {
4589
+ packageManager = null;
4590
+ }
4591
+ let mcpConfigs = null;
4592
+ if (grantInventory !== null) {
4593
+ const seen = new Set();
4594
+ mcpConfigs = [];
4595
+ const push = (name, origin) => {
4596
+ const key = `${name}\u0000${origin}`;
4597
+ if (seen.has(key))
4598
+ return;
4599
+ seen.add(key);
4600
+ mcpConfigs.push({ name, origin });
4601
+ };
4602
+ for (const c of grantInventory.candidates)
4603
+ for (const d of c.definitions)
4604
+ for (const o of d.origins)
4605
+ push(c.name, CANDIDATE_ORIGIN_LABEL[o]);
4606
+ for (const e of grantInventory.exclusions)
4607
+ push(e.name, CANDIDATE_ORIGIN_LABEL[e.origin]);
4608
+ }
4609
+ return { ci_workflows: ciWorkflows, package_manager: packageManager, mcp_configs: mcpConfigs };
4610
+ }
4611
+ /**
4612
+ * BAPI-1677 — one plain note when the default branch, which a workflow is committed
4613
+ * onto, lacks a named lockfile or a kept extra. Only a file proven absent counts: an
4614
+ * unreadable one is unknown. A note changes nothing and stops nothing.
4615
+ */
4616
+ async function defaultBranchInstallNote(setup, snapshot, facts) {
4617
+ const read = setup.readSnapshotFile;
4618
+ if (snapshot === null || read === undefined)
4619
+ return null;
4620
+ const textOf = async (relPath) => {
4621
+ try {
4622
+ return await read(snapshot, relPath);
4623
+ }
4624
+ catch (err) {
4625
+ return err?.code === "ENOENT" ? null : undefined;
4626
+ }
4627
+ };
4628
+ const lacking = "Your default branch does not have everything these install commands use yet, so CI could fail there until it does.";
4629
+ for (const entry of facts.planned) {
4630
+ for (const lockfile of entry.lockfiles) {
4631
+ if ((await textOf(lockfile)) === null)
4632
+ return lacking;
4633
+ }
4634
+ }
4635
+ if (facts.evidence.length === 0)
4636
+ return null;
4637
+ const pyproject = await textOf(pyprojectPathFor("."));
4638
+ if (typeof pyproject !== "string")
4639
+ return pyproject === null ? lacking : null;
4640
+ const manager = facts.planned.some((e) => e.argv[0] === "poetry") ? "poetry" : "uv";
4641
+ const declared = scanDeclaredExtras(pyproject, manager);
4642
+ if (declared.status !== "known")
4643
+ return null;
4644
+ return facts.evidence.every((e) => declared.extras.includes(e.extra)) ? null : lacking;
4645
+ }
4646
+ /** Merge the approved declarations into the gate plan, rebuilding its PUT from the same desired gate. */
4647
+ function applyApprovedDeclarations(plan, approved) {
4648
+ if (approved.length === 0)
4649
+ return plan;
4650
+ const desired = approved.reduce((acc, entry) => ({ ...acc, ...entry.fields }), plan.desired);
4651
+ return { ...plan, desired, write: confirmRequestFor(desired, plan.current.revision, plan.current.profile) };
4652
+ }
4653
+ /** A gate and declarations that already match: every approved one reports unchanged. */
4654
+ function settledGateResults(proposal) {
4655
+ return proposal.actions
4656
+ .filter((a) => (a.key === "gate" || DECLARATION_KEYS.includes(a.key)) && a.intent === "write")
4657
+ .map((a) => ({ key: a.key, status: "unchanged", target: a.effect?.target ?? "repository_gate" }));
4658
+ }
4659
+ const DECLARATION_KEYS = ["dependency_install", "ci_database", "must_order_paths", "worker_database"];
4660
+ function gateWriteResults(result, proposal, plan,
4661
+ /** BAPI-1677 — the install commands read back after the write; `null` when they could not be confirmed. */
4662
+ installReadBack) {
4663
+ const readBack = result.current !== undefined ? { revision: result.current.state.revision } : undefined;
4664
+ const status = result.status === "completed" ? "written"
4665
+ : result.status === "unchanged" ? "unchanged"
4666
+ : result.status === "unknown" ? "uncertain"
4667
+ : result.declined ? "declined" : "refused";
4668
+ const gate = {
4669
+ key: "gate",
4670
+ status,
4671
+ target: "repository_gate",
4672
+ ...(readBack !== undefined ? { read_back: readBack } : {}),
4673
+ ...(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." } : {}),
4674
+ ...(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." } : {}),
4675
+ };
4676
+ if (proposal === null)
4677
+ return [gate];
4678
+ const declarations = plan.map((entry) => {
4679
+ const decision = decisionFor(proposal, entry.key);
4680
+ const approved = (decision?.kind === "option" && decision.option === "approve") || decision?.kind === "dependency_install_entries";
4681
+ const inPlace = status === "written" || status === "unchanged";
4682
+ const install = approved && entry.key === "dependency_install" && inPlace && installReadBack !== undefined;
4683
+ return {
4684
+ key: entry.key,
4685
+ status: !approved ? "declined" : status === "declined" ? "unattempted" : install && installReadBack === null ? "uncertain" : status,
4686
+ target: `repository_gate.${entry.key}`,
4687
+ ...(approved && status === "declined" ? { reason: "the gate it is stored with was declined" } : {}),
4688
+ ...(install && installReadBack === null ? { reason: "the install commands could not be read back after the write", fix: "Read the gate with `epic-implementer doctor` before retrying." } : {}),
4689
+ ...(install && installReadBack !== null ? { read_back: { commands: installReadBack ?? [] } } : {}),
4690
+ };
4691
+ });
4692
+ return [gate, ...declarations];
4693
+ }
4694
+ function testCommandAnswer(d) {
4695
+ if (d === undefined)
4696
+ return undefined;
4697
+ if (d.kind === "command")
4698
+ return { decision: "command", command: d.command };
4699
+ if (d.kind === "option" && (d.option === "learn" || d.option === "skip" || d.option === "keep"))
4700
+ return { decision: d.option };
4701
+ return undefined;
4702
+ }
4703
+ /** BAPI-1657: the plain owner-facing reason when the repository has no test command to try. */
4704
+ export const NO_TEST_COMMAND_REASON = "Bridge found no test command in this repository";
4705
+ /** BAPI-1657: the plain owner-facing reason when the server could not read the testing instructions. */
4706
+ export const NO_COMMAND_RETRY_REASON = "the server could not read the repository's testing instructions just now";
4707
+ /**
4708
+ * BAPI-1657: the launcher text for an owner-run command. The detected launcher wins,
4709
+ * then the published package. A detection failure falls back to the published package.
4710
+ */
4711
+ async function detectedLauncherBase(deps, repoName) {
4712
+ let detected = null;
4713
+ try {
4714
+ detected = (await deps.setup?.detectLauncher?.(repoName)) ?? null;
4715
+ }
4716
+ catch {
4717
+ detected = null;
4718
+ }
4719
+ return (detected ?? NPM_SETUP_LAUNCHER).base;
4720
+ }
4721
+ /** The learned check's own entry, carrying child 3's phase. `null` when no trial ran and none was asked for. */
4722
+ export function trialWriteResult(trial, asked, launcher) {
4723
+ const target = "repository_gate.local_commands";
4724
+ if (trial === null)
4725
+ return asked ? { key: "test_command", status: "unchanged", target, reason: "no trial was needed for the stored gate" } : null;
4726
+ const phase = "evidence" in trial && trial.evidence !== undefined ? trial.evidence.phase : null;
4727
+ switch (trial.status) {
4728
+ case "no_command":
4729
+ // BAPI-1657: the owner-facing remedy names the launcher the owner runs in their own terminal.
4730
+ if (trial.reason === "llm_unavailable") {
4731
+ return { key: "test_command", status: "failed", target, reason: NO_COMMAND_RETRY_REASON, fix: "Rerun setup to try reading the repository's testing instructions again." };
4732
+ }
4733
+ return {
4734
+ key: "test_command",
4735
+ status: "failed",
4736
+ target,
4737
+ reason: NO_TEST_COMMAND_REASON,
4738
+ 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.`,
4739
+ };
4740
+ case "promoted":
4741
+ return { key: "test_command", status: "written", target, phase, read_back: { commands: trial.commands.map((c) => c.name), ran: trial.commands.map((c) => c.command) } };
4742
+ case "not_needed":
4743
+ return { key: "test_command", status: "unchanged", target };
4744
+ case "uncertain":
4745
+ 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." };
4746
+ case "unqualified":
4747
+ case "stale":
4748
+ case "could_not_run":
4749
+ 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." };
4750
+ default:
4751
+ 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`." };
4752
+ }
4753
+ }
4754
+ export function workflowWriteResult(outcome, asked, decision) {
4755
+ const target = "github.default_branch";
4756
+ // BAPI-1678: the owner's decline stands, whatever the phase found to do. A write or a
4757
+ // failure that really happened still reports as itself below.
4758
+ if (decision === "decline" && (outcome.status === "none" || outcome.status === "unchanged")) {
4759
+ return { key: "setup_pr", status: "declined", target };
4760
+ }
4761
+ switch (outcome.status) {
4762
+ case "none":
4763
+ return asked ? { key: "setup_pr", status: "unchanged", target, reason: "no setup pull request was needed" } : null;
4764
+ case "written":
4765
+ case "unchanged":
4766
+ return { key: "setup_pr", status: outcome.status, target, ...(outcome.url !== undefined ? { read_back: { url: outcome.url } } : {}) };
4767
+ case "declined":
4768
+ return { key: "setup_pr", status: "declined", target, ...(outcome.reason !== undefined ? { reason: outcome.reason } : {}), ...(outcome.phase !== undefined ? { phase: outcome.phase } : {}) };
4769
+ case "failed":
4770
+ case "unattempted":
4771
+ return { key: "setup_pr", status: outcome.status, target, reason: outcome.reason, fix: "Rerun setup once the cause above is fixed." };
4772
+ }
4773
+ }
4774
+ function fixOutcomeResult(key, target, outcome) {
4775
+ if (outcome.status === "failed") {
4776
+ return { key, status: "failed", target, reason: outcome.reason, fix: "Fix the cause above, then rerun setup with the same answers." };
4777
+ }
4778
+ // BAPI-1667: fixed advisory text only. It reports; it never changes the status.
4779
+ const advisories = [...new Set(outcome.advisories ?? [])];
4780
+ return { key, status: outcome.status, target, ...(advisories.length > 0 ? { reason: advisories.join(" ") } : {}) };
4781
+ }
4782
+ function indexProgress(index) {
4783
+ if (index.state === "reached")
4784
+ return "current";
4785
+ if (index.state === "recovery_pending")
4786
+ return index.runId === null ? "requested" : "running";
4787
+ if (index.state === "queued_by_setup")
4788
+ return "requested";
4789
+ if (index.state === "in_progress")
4790
+ return "running";
4791
+ return undefined;
4792
+ }
4793
+ function reindexWriteResult(index) {
4794
+ const target = "repository_index";
4795
+ const progress = indexProgress(index);
4796
+ if (progress !== undefined)
4797
+ return { key: "reindex", status: progress === "current" ? "unchanged" : "written", target, progress };
4798
+ if (index.state === "recovery_unresolved") {
4799
+ const status = index.choice === "refused" ? "refused" : index.choice === "kept" || index.choice === "declined" ? "declined" : "failed";
4800
+ return { key: "reindex", status, target, reason: index.remedy, ...(status !== "declined" ? { fix: index.remedy } : {}) };
4801
+ }
4802
+ return { key: "reindex", status: "uncertain", target, reason: "the index state could not be read", fix: "Rerun setup to read it again." };
4803
+ }
4804
+ /**
4805
+ * The approved epic-server answer as a record. A local mode records whether guidance
4806
+ * is present. BAPI-1667: a plain `local` or `none` keeps an approved sandbox, because
4807
+ * upload needs it in every mode; only a structured answer replaces it. An entered
4808
+ * sandbox id is re-checked, and a mismatch only adds an advisory.
4809
+ */
4810
+ export async function epicServerAnswer(epicDeps, d, snapshot = null) {
4811
+ const recipeOf = async () => {
4812
+ try {
4813
+ return (await epicDeps.guidancePresent()) ? "present" : "absent";
4814
+ }
4815
+ catch {
4816
+ return "absent";
4817
+ }
4818
+ };
4819
+ const kept = snapshot?.existingSandbox ?? null;
4820
+ if (d.kind === "epic_server_sfcc") {
4821
+ const { mode, sandbox_id, credential_ref, storefront_origin } = d.value;
4822
+ const check = epicDeps.sfccUploadCheck;
4823
+ const credentials = snapshot?.credentials ?? null;
4824
+ const mismatch = snapshot?.detection?.detected === true && check !== undefined
4825
+ ? await recheckSfccSandboxId(check, sandbox_id, { credentials })
4826
+ : [];
4827
+ const sfcc = { sandbox_id, credential_ref, ...(storefront_origin !== undefined ? { storefront_origin } : {}) };
4828
+ return {
4829
+ decision: "record",
4830
+ record: { version: 1, mode, ...(mode === "local" ? { recipe: await recipeOf() } : {}), sfcc },
4831
+ advisories: [...mismatch, ...credentialReferenceAdvisories(credentials, credential_ref)],
4832
+ };
4833
+ }
4834
+ if (d.kind === "option" && d.option === "local") {
4835
+ return { decision: "record", record: { version: 1, mode: "local", recipe: await recipeOf(), ...(kept !== null ? { sfcc: kept } : {}) } };
4836
+ }
4837
+ if (d.kind === "option" && d.option === "none") {
4838
+ return { decision: "record", record: { version: 1, mode: "none", ...(kept !== null ? { sfcc: kept } : {}) } };
4839
+ }
4840
+ return { decision: "keep" };
4841
+ }
4842
+ /**
4843
+ * BAPI-1654 — the CI change's own result. An opened or reused pull request is
4844
+ * PROPOSED, never coverage; a merged change is `unchanged` and in place. A
4845
+ * changed source is refused untouched, and an unreadable remote state is
4846
+ * uncertain, so a retry reconciles instead of opening a second pull request.
4847
+ */
4848
+ function ciChangeWriteResult(actionClass, target, result) {
4849
+ const key = "epic_ci_change";
4850
+ switch (result.outcome) {
4851
+ case "installed-pr-opened":
4852
+ case "upgrade-pr-opened":
4853
+ return { key, status: "written", target, reason: describeProposedCiChange(actionClass, target, result.prUrl), read_back: { path: target, pull_request: result.prUrl, state: "proposed" } };
4854
+ case "existing-pr":
4855
+ return { key, status: "unchanged", target, reason: describeProposedCiChange(actionClass, target, result.prUrl), read_back: { path: target, pull_request: result.prUrl, state: "proposed" } };
4856
+ case "identical":
4857
+ return { key, status: "unchanged", target, reason: "the CI change is already merged", read_back: { path: target, state: "in_place" } };
4858
+ case "dry-run":
4859
+ return { key, status: "unattempted", target, reason: "a dry run opens nothing" };
4860
+ case "failed":
4861
+ if (result.reason === "consent_declined")
4862
+ return { key, status: "declined", target };
4863
+ if (result.reason === "workflow_modified_or_unrecognized" || result.reason === "default_branch_moved") {
4864
+ 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." };
4865
+ }
4866
+ if (result.reason === "remote_state_unverifiable" || result.reason === "existing_pr_unverifiable" || result.reason === "managed_branch_without_pr" || result.reason === "pr_open_failed") {
4867
+ return {
4868
+ key, status: "uncertain", target,
4869
+ reason: "the CI pull request could not be confirmed",
4870
+ 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.",
4871
+ ...(result.prUrl !== undefined ? { read_back: { path: target, pull_request: result.prUrl, state: "proposed" } } : {}),
4872
+ };
4873
+ }
4874
+ if (result.reason === "existing_pr_differs") {
4875
+ 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." };
4876
+ }
4877
+ return { key, status: "failed", target, reason: `the CI pull request could not be opened (${result.reason.replace(/_/g, " ")})`, fix: result.remediation };
4878
+ }
4879
+ }
4880
+ function epicBranchWriteResults(step, report, note) {
4881
+ if (!report)
4882
+ return null;
4883
+ const results = [];
4884
+ if (step.status !== "completed")
4885
+ return [{ key: "epic_branch_ci", status: "unchanged", target: "epic_branch_ci", reason: `inspection ${step.status.replace(/_/g, " ")}` }];
4886
+ results.push(step.decision === null
4887
+ ? { key: "epic_branch_ci", status: "declined", target: "epic_branch_ci", reason: "no decision was recorded; runs behave as include" }
4888
+ : step.recorded
4889
+ ? { key: "epic_branch_ci", status: step.unchanged ? "unchanged" : "written", target: "epic_branch_ci", read_back: { decision: step.decision }, ...(note !== undefined ? { reason: note } : {}) }
4890
+ : { key: "epic_branch_ci", status: "failed", target: "epic_branch_ci", reason: "the decision could not be recorded", fix: step.manualAction ?? "Rerun setup." });
4891
+ const outcome = step.exemptionOutcome;
4892
+ if (outcome !== null) {
4893
+ results.push(mapExemptionOutcomeToWriteResult(outcome));
4894
+ }
4895
+ return results;
4896
+ }
4897
+ async function runConvergingSetup(options, deps, setup) {
4898
+ if (options.removeMergeToken === true)
4899
+ return runRemoveMergeToken(options, deps, setup);
4900
+ // One input session per run: a pasted answer's trailing line ending cannot answer the next
4901
+ // question. It wraps only the line reader; ambient stdin and the no-echo secret reader are untouched.
4902
+ // The proxy keeps every other dependency live and re-wraps if the reader is swapped mid-run.
4903
+ const bare = deps;
4904
+ let session;
4905
+ deps = new Proxy(bare, {
4906
+ get(target, property, receiver) {
4907
+ if (property !== "promptLine")
4908
+ return Reflect.get(target, property, receiver);
4909
+ const source = target.promptLine;
4910
+ if (source === undefined)
4911
+ return undefined;
4912
+ if (session?.source !== source)
4913
+ session = { source, read: createPlainInputSession(source, { now: target.plainInputClock }) };
4914
+ return session.read;
4915
+ },
4916
+ });
4917
+ const progress = (activity, operation) => withSetupProgress(activity, operation, { errorLog: deps.errorLog, timer: deps.progressTimer });
4918
+ const confirmed = await resolveAndConfirmBaseUrl(options, deps, "");
4919
+ if (!confirmed.ok)
4920
+ return confirmed.code;
4921
+ const baseUrl = confirmed.baseUrl;
4922
+ // BAPI-1638: `--answers` is read once, here, and validated in full before any write.
4923
+ // With `--dry-run` it is the read-only proposal mode; without it, the answers apply.
4924
+ let answersEnvelope = null;
4925
+ if (options.answers !== undefined) {
4926
+ const refuse = (refusal) => {
4927
+ deps.installDocumentSink?.({ refusal });
4928
+ for (const reason of refusal.reasons)
4929
+ deps.errorLog(`Refused (${reason.reason}${reason.keys.length > 0 ? `: ${reason.keys.join(", ")}` : ""}): ${reason.detail}`);
4930
+ deps.errorLog(`Nothing was written. ${refusal.fix}`);
4931
+ return 1;
4932
+ };
4933
+ if (deps.answersSource === undefined) {
4934
+ 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." });
4935
+ }
4936
+ const read = await readAnswersSource(options.answers, deps.answersSource);
4937
+ if (!read.ok)
4938
+ return refuse(read.refusal);
4939
+ const parsedAnswers = parseAnswersText(read.text);
4940
+ if (!parsedAnswers.ok)
4941
+ return refuse(parsedAnswers.refusal);
4942
+ answersEnvelope = parsedAnswers.envelope;
4943
+ }
4944
+ const proposalMode = options.answers !== undefined && options.dryRun;
4945
+ const answersApply = options.answers !== undefined && !options.dryRun;
4946
+ // BAPI-1635: `--json` is read-only like `--dry-run`, so it continues past an unavailable tool to report it.
4947
+ // BAPI-1638: with `--answers` (and no `--dry-run`), `--json` only shapes the output of an apply.
4948
+ const readOnlyRun = options.dryRun || (options.json === true && !answersApply);
4949
+ const prerequisites = await assessEpicInstallerPrerequisites(deps, Boolean(options.executorId), options.verbose !== true);
4950
+ if (!prerequisites.available && !readOnlyRun)
4951
+ return 1;
4952
+ const { claudeLoggedIn, githubSignIn, localRemote } = prerequisites;
4953
+ // ---- Repository: the folder's own binding first; ask only when genuinely unbound ----
4954
+ const binding = options.repo === undefined ? await resolveFolderBinding(deps) : { status: "explicit" };
4955
+ let accessResult = await deps.resolveAccess(options.repo ?? (binding.status === "bound" ? binding.repo : undefined), baseUrl);
4956
+ if (!accessResult.ok && binding.status === "absent" && deps.promptLine && !readOnlyRun && options.answers === undefined) {
4957
+ const suggestion = localRemote?.split("/")[1] ?? null;
4958
+ deps.log("");
4959
+ deps.log("Which repository is this? This folder is not bound to a Bridge project and Bridge could not tell from the environment.");
3169
4960
  const answer = (await deps.promptLine(suggestion !== null
3170
4961
  ? `Bridge repository name [${suggestion}]: `
3171
4962
  : "Bridge repository name (press Enter to skip): ")).trim();
3172
- const chosen = answer.length > 0 && !/^(y|yes|n|no)$/i.test(answer) ? answer : null;
4963
+ const typed = answer.length > 0 && !/^(y|yes|n|no)$/i.test(answer) ? answer : null;
4964
+ // Enter accepts the suggested name when there is one; without one it stays unresolved.
4965
+ const chosen = typed ?? (answer.length === 0 ? suggestion : null);
3173
4966
  if (chosen !== null)
3174
4967
  accessResult = await deps.resolveAccess(chosen, baseUrl);
3175
4968
  }
3176
4969
  const access = accessResult.ok ? accessResult.access : null;
3177
4970
  const accessError = accessResult.ok ? undefined : accessResult.error;
4971
+ // ---- BAPI-1650: an unapproved non-production address, reported before any refusal ----
4972
+ // Dry-run only: the metadata exists only on that path. The item is recorded now so the
4973
+ // access refusal below keeps it; a successful preview continues and carries it forward.
4974
+ let endpointApprovalItemForRun = null;
4975
+ if (options.dryRun && accessResult.endpointApproval !== undefined) {
4976
+ endpointApprovalItemForRun = await endpointApprovalItem(deps, options, accessResult.endpointApproval);
4977
+ reportCredentialEndpointUnapproved(deps);
4978
+ deps.installDocumentSink?.({ items: [endpointApprovalItemForRun] });
4979
+ }
3178
4980
  const earlyPreflight = await runExecutorPreflightPhase(options, deps, baseUrl, access);
3179
4981
  if (earlyPreflight.kind === "refused")
3180
4982
  return 1;
3181
- const gateIo = gateIoFor(deps);
4983
+ const gateIo = {
4984
+ ...gateIoFor(deps),
4985
+ isTTY: deps.isTTY,
4986
+ reviewCiSettings: options.reviewCiSettings === true,
4987
+ };
3182
4988
  const standalone = await runStandaloneGateAction(options, deps, gateIo, access, accessError, baseUrl);
3183
4989
  if (standalone !== null)
3184
4990
  return standalone;
4991
+ // ---- Learned first: before any ordinary gate, default, command, workflow, branch, or PR write ----
4992
+ // Only a validated "not learned" stops a real run; a dry run reports it and keeps previewing.
4993
+ const notLearned = access !== null ? await repositoryNotLearned(deps, access) : false;
4994
+ if (notLearned && !readOnlyRun) {
4995
+ deps.log("");
4996
+ deps.log("Not ready: 1 step left");
4997
+ deps.log("complete-with-manual-steps");
4998
+ return 1;
4999
+ }
3185
5000
  // ---- Check 1: the read-only doctor (no deny probe yet) ------------------
3186
5001
  deps.log("");
3187
5002
  deps.log("Checking your setup (read-only)…");
3188
5003
  const storedContext = storedMergeContextFor(setup, null, localRemote);
3189
- const firstReport = await deps.runDoctor({
5004
+ const firstReport = await progress("checking readiness", () => deps.runDoctor({
3190
5005
  access,
3191
5006
  accessError,
3192
5007
  reviewPolicySource: options.reviewPolicy,
@@ -3194,7 +5009,7 @@ async function runConvergingSetup(options, deps, setup) {
3194
5009
  epicRunId: options.assessmentEpicRunId,
3195
5010
  skipDenyProbe: true,
3196
5011
  storedMergeCredential: storedContext,
3197
- });
5012
+ }));
3198
5013
  if (conductorInstallDoctorHasFatal(firstReport) || !access) {
3199
5014
  deps.log(formatConductorInstallDoctorReport(firstReport));
3200
5015
  deps.errorLog("");
@@ -3205,59 +5020,243 @@ async function runConvergingSetup(options, deps, setup) {
3205
5020
  return 1;
3206
5021
  }
3207
5022
  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, {
5023
+ // ---- The remote default branch, captured once -----------------------------
5024
+ // Every workflow input derives from this head, never from the person's folder.
5025
+ let snapshot = null;
5026
+ if (githubSignIn === "signed_in" && setup.captureDefaultBranch !== undefined) {
5027
+ try {
5028
+ snapshot = await setup.captureDefaultBranch();
5029
+ }
5030
+ catch {
5031
+ snapshot = null;
5032
+ }
5033
+ }
5034
+ const readToolchains = snapshotToolchainReader(setup, snapshot);
5035
+ // ---- The review default: explicit flag, then what is stored, then the remote workflow ----
5036
+ const reviewDefault = await resolveReviewDefault(deps, options, setup, access, snapshot);
5037
+ renderReviewPolicy(deps, options, reviewDefault);
5038
+ // ---- The gate: explicit flags win, a stored gate is kept, otherwise facts decide ----
5039
+ // BAPI-1638: the answers path plans the gate without a terminal, so no discovered
5040
+ // declaration joins it unless its own answer approves it below.
5041
+ const planIo = options.answers !== undefined ? { ...gateIo, isTTY: false, promptLine: undefined } : gateIo;
5042
+ // BAPI-1677: one read of the learned text per run, shared by everything that needs it.
5043
+ if (deps.gate !== undefined && deps.gate.learnedInstructions === undefined) {
5044
+ let learned;
5045
+ const readLearned = () => {
5046
+ learned ??= readLearnedInstructions(setup.testingConfig(access)).catch(() => null);
5047
+ return learned;
5048
+ };
5049
+ deps = { ...deps, gate: { ...deps.gate, learnedInstructions: readLearned } };
5050
+ }
5051
+ const gatePhase = await resolveConductorGate(planIo, access, options.gate, deps.gate, {
3210
5052
  dryRun: options.dryRun,
3211
5053
  planningOnly: true,
3212
- ...(hasExplicitGateInput(options.gate) ? {} : { ensureProviderCheck: EPIC_IMPLEMENTER_CI_CHECK_NAME }),
5054
+ inferCi: !hasExplicitGateInput(options.gate),
3213
5055
  });
3214
5056
  if (gatePhase.kind === "exit")
3215
5057
  return gatePhase.code;
3216
5058
  const gatePlan = gatePhase.kind === "plan" ? gatePhase.plan : null;
3217
- const gateChangeDeclined = gatePhase.kind === "plan" && gatePhase.ensureDeclined === true;
5059
+ const gateRequiresManagedCheck = gatePlan !== null && gatePlan.inferred === undefined && gatePlan.desired.providerChecks.includes(EPIC_IMPLEMENTER_CI_CHECK_NAME);
3218
5060
  const advisories = localAdvisories(firstReport);
3219
- const collectInputs = { claudeLoggedIn, githubSignIn, localRemote, gateChangeDeclined, advisories };
3220
- const first = await collectSetupEvidence(deps, setup, access, firstReport.readiness, collectInputs);
5061
+ // The evidence shares this array and later pushes material advisories onto it, so the routine set is copied now.
5062
+ const routineAdvisories = [...advisories];
5063
+ // The agent route is `--json` or `--answers`; the same decision gates the choice catalog below.
5064
+ const collectDecisions = options.json === true || options.answers !== undefined;
5065
+ const setupPath = collectDecisions ? "agent" : "terminal";
5066
+ // BAPI-1657: the gate plan is resolved above, so its planned write is known before any setup item is projected.
5067
+ const plannedGateWrite = gatePlan !== null && gatePlan.write !== null;
5068
+ const storedDependencyInstall = gatePlan?.current.profile?.dependency_install ?? [];
5069
+ const collectInputs = { claudeLoggedIn, githubSignIn, localRemote, snapshot, readToolchains, gateRequiresManagedCheck, plannedGateWrite, path: setupPath, dependencyInstall: storedDependencyInstall };
5070
+ const first = await progress("checking readiness", () => collectSetupEvidence(deps, setup, access, firstReport.readiness, { ...collectInputs, advisories }));
3221
5071
  const state = {
3222
5072
  evidence: first.evidence,
3223
5073
  identity: first.identity,
3224
5074
  repository: first.repository,
3225
5075
  storedCommand: first.storedCommand,
5076
+ snapshot,
3226
5077
  toolchains: first.toolchains,
3227
- commandChanged: false,
3228
- commandBlocked: false,
5078
+ ciPlan: undefined,
5079
+ commandUncertain: false,
5080
+ trial: null,
5081
+ promotedCommands: null,
3229
5082
  failedOperations: [],
5083
+ sealedDependencyInstall: storedDependencyInstall,
3230
5084
  };
3231
- const firstItems = projectSetupItems(state.evidence);
5085
+ // BAPI-1677: whether a test trial can be offered, known before anything reads it.
5086
+ if (gatePlan !== null)
5087
+ gatePlan.testCommandTrial = await resolveTestCommandTrial(deps, setup, access, gatePlan, state.storedCommand);
5088
+ // BAPI-1654: which CI systems the repository's files configure, read-only, independent of the remote host.
5089
+ if (deps.gate?.discoveryFs !== undefined) {
5090
+ const detected = await detectCiSystems(deps.gate.discoveryFs);
5091
+ state.ciSystems = detected.complete || detected.systems.length > 0 ? detected.systems : null;
5092
+ }
5093
+ // BAPI-1545: the worker MCP grant, read-only here. Its item is advisory.
5094
+ let grantInventory = null;
5095
+ if (setup.mcpGrant !== undefined) {
5096
+ const assessed = await assessMcpGrant(setup.mcpGrant, access.repoName);
5097
+ grantInventory = assessed.inventory;
5098
+ state.evidence = { ...state.evidence, mcpGrant: assessed.evidence };
5099
+ }
5100
+ // BAPI-1546: the epic-server record, read-only here. Its item is advisory.
5101
+ if (setup.epicServer !== undefined) {
5102
+ state.evidence = { ...state.evidence, epicServer: await assessEpicServer(setup.epicServer, access.repoName) };
5103
+ }
5104
+ // BAPI-1635: the selected profile's escalation declaration, read-only.
5105
+ {
5106
+ const notification = await collectNotificationEvidence(deps, options, baseUrl);
5107
+ if (notification !== undefined)
5108
+ state.evidence = { ...state.evidence, notification };
5109
+ }
5110
+ const firstItems = [
5111
+ ...projectSetupItems(state.evidence),
5112
+ ...(endpointApprovalItemForRun !== null ? [endpointApprovalItemForRun] : []),
5113
+ ];
3232
5114
  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);
5115
+ // The full first assessment is detail; a failure or refusal below always prints on its own.
5116
+ if (options.verbose === true || options.dryRun) {
5117
+ for (const line of renderSetupAssessment(firstItems, "What setup found", "initial"))
5118
+ deps.log(line);
5119
+ }
5120
+ // A review default the run would add or change is worth offering; only a missing gate or
5121
+ // missing supervisor rows make a deferred policy block readiness.
5122
+ const policyRequired = gateOrDefaultsNeedWrite(gatePlan, firstReport.readiness, MANAGED_WRITE_REVIEW_DEFAULT);
3244
5123
  const planContext = {
3245
- gateOrDefaultsNeedWrite: gateOrDefaultsNeedWrite(gatePlan, firstReport.readiness),
5124
+ gateOrDefaultsNeedWrite: gateOrDefaultsNeedWrite(gatePlan, firstReport.readiness, reviewDefault),
3246
5125
  suppliedPolicyInput: options.reviewPolicyExplicit || options.replaceDoneGate || hasExplicitGateInput(options.gate),
3247
- dryRun: options.dryRun,
5126
+ ...(options.epicServerChange === true ? { epicServerChangeRequested: true } : {}),
3248
5127
  };
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.");
5128
+ const fixes = planSetupFixes(state.evidence, planContext);
5129
+ // BAPI-1667: one read-only snapshot for both setup paths. An ordinary interactive run
5130
+ // reads it only when it will ask a question that uses it.
5131
+ const epicServerSnapshot = setup.epicServer !== undefined && (collectDecisions || fixes.includes("epic_server") || fixes.includes("mcp_grant"))
5132
+ ? await collectEpicServerSnapshot(deps, setup.epicServer, access.repoName, grantInventory)
5133
+ : null;
5134
+ // ---- BAPI-1638: the decision evidence behind every open choice (read-only) ----
5135
+ // Collected for `--json` and `--answers` only: an ordinary interactive run asks at
5136
+ // each decision point exactly as before and needs no catalog.
5137
+ const epicBranchCiWanted = options.epicBranchCiDecision !== undefined || deps.gate?.epicBranchCi !== undefined;
5138
+ const epicBranchCollected = collectDecisions && epicBranchCiWanted ? await collectEpicBranchCi(deps.gate) : undefined;
5139
+ const declarationPlanning = collectDecisions && gatePlan !== null
5140
+ ? await planDeclarations(gatePlan.current, gatePlan.desired, deps.gate)
5141
+ : { entries: [], dependencyInstall: null };
5142
+ const declarationPlan = declarationPlanning.entries;
5143
+ // BAPI-1677: the install answer is resolved here, before anything hashes the workflow,
5144
+ // so the approved hash and the delivered bytes come from one list. A refused value
5145
+ // reads as no answer; normalization refuses the whole file below.
5146
+ const dependencyAnswerParsed = answersEnvelope !== null && answersEnvelope.dependency_install !== undefined
5147
+ ? parseAnswerValue("dependency_install", answersEnvelope.dependency_install)
5148
+ : null;
5149
+ const dependencyCorrection = dependencyAnswerParsed?.ok === true && dependencyAnswerParsed.decision.kind === "dependency_install_entries"
5150
+ ? dependencyAnswerParsed.decision.entries
5151
+ : null;
5152
+ const effectiveDependencyInstall = resolveEffectiveDependencyInstall(declarationPlanning.dependencyInstall, storedDependencyInstall, dependencyCorrection !== null
5153
+ ? { entries: dependencyCorrection }
5154
+ : dependencyAnswerParsed?.ok === true ? answersEnvelope?.dependency_install : undefined);
5155
+ if (declarationPlanning.dependencyInstall !== null) {
5156
+ const note = await defaultBranchInstallNote(setup, state.snapshot, declarationPlanning.dependencyInstall);
5157
+ if (note !== null)
5158
+ declarationPlanning.dependencyInstall.limitations.push(note);
5159
+ if (parseDependencyInstallStrict(effectiveDependencyInstall) === null) {
5160
+ declarationPlanning.dependencyInstall.limitations.push("Bridge will not offer its CI workflow, because an install command cannot be written into it safely.");
5161
+ }
3253
5162
  }
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);
5163
+ // BAPI-1654: the one CI change on offer, from the default-branch snapshot (read-only).
5164
+ const ciOfferCollection = collectDecisions && epicBranchCollected !== undefined
5165
+ ? await collectCiOffer({
5166
+ setup, state, collected: epicBranchCollected, readToolchains, dependencyInstall: effectiveDependencyInstall,
5167
+ })
5168
+ : null;
5169
+ const decisionEvidence = collectDecisions
5170
+ ? await collectDecisionEvidence({
5171
+ deps, options, access, gatePlan, state, fixes, grantInventory, firstReport,
5172
+ declarationPlan, epicBranchCollected, readToolchains, firstItems, ciOffer: ciOfferCollection, epicServerSnapshot,
5173
+ dependencyInstallFacts: declarationPlanning.dependencyInstall, effectiveDependencyInstall,
5174
+ correctedDependencyInstall: dependencyCorrection !== null,
5175
+ })
5176
+ : null;
5177
+ const choices = decisionEvidence === null ? [] : buildInstallChoices(decisionEvidence);
5178
+ // ---- BAPI-1638: proposal mode — normalize the draft answers and return; nothing is written ----
5179
+ let proposal = null;
5180
+ let proposalDigest = null;
5181
+ let resolvedChoices;
5182
+ if (options.answers !== undefined && decisionEvidence !== null) {
5183
+ const normalized = normalizeInstallAnswers({
5184
+ envelope: answersEnvelope,
5185
+ choices,
5186
+ identity: decisionEvidence.identity,
5187
+ flags: {
5188
+ ...(options.testCommand !== undefined ? { testCommand: options.testCommand } : {}),
5189
+ ...(options.epicBranchCiDecision !== undefined ? { epicBranchCiDecision: options.epicBranchCiDecision } : {}),
5190
+ ...(options.launchProfile !== undefined ? { launchProfile: options.launchProfile } : {}),
5191
+ },
5192
+ mode: proposalMode ? "proposal" : "apply",
5193
+ recommendationContext: {
5194
+ setupSuppliesWorkflow: decisionEvidence.epicBranchCi?.managedWorkflowViaSetupPr === true,
5195
+ stateText: epicBranchCiStateText(decisionEvidence.epicBranchCi ?? null),
5196
+ },
5197
+ });
5198
+ if (proposalMode) {
5199
+ deps.installDocumentSink?.({
5200
+ items: firstItems,
5201
+ decisions: decisionEvidence,
5202
+ choices: normalized.choices,
5203
+ ...(normalized.proposal !== undefined
5204
+ ? { proposalPresentation: plannedPresentation(normalized.proposal, gatePlan, fixes.includes("gate_and_defaults"), decisionEvidence.gate?.consequence ?? "", firstReport.readiness ?? null, state.evidence) }
5205
+ : {}),
5206
+ ...(normalized.proposal !== undefined ? { proposal: normalized.proposal } : {}),
5207
+ ...(normalized.digest !== undefined ? { digest: normalized.digest } : {}),
5208
+ ...(!normalized.ok ? { refusal: normalized.refusal } : {}),
5209
+ });
5210
+ deps.log("");
5211
+ deps.log("Proposal (read-only) — nothing was written and nothing was asked.");
5212
+ if (normalized.proposal !== undefined) {
5213
+ for (const action of normalized.proposal.actions) {
5214
+ if (action.intent === "write")
5215
+ deps.log(` ${action.key}: ${action.consequence}`);
5216
+ }
5217
+ }
5218
+ if (normalized.digest !== undefined)
5219
+ deps.log(` proposal_digest: ${normalized.digest}`);
5220
+ if (!normalized.ok) {
5221
+ for (const reason of normalized.refusal.reasons)
5222
+ deps.log(` Needs an answer (${reason.reason}): ${reason.keys.join(", ")}`);
5223
+ }
5224
+ deps.log("complete-with-manual-steps (dry run)");
5225
+ return normalized.ok ? 0 : 1;
5226
+ }
5227
+ if (!normalized.ok) {
5228
+ deps.installDocumentSink?.({ items: firstItems, decisions: decisionEvidence, choices: normalized.choices, refusal: normalized.refusal });
5229
+ for (const reason of normalized.refusal.reasons) {
5230
+ deps.errorLog(`Refused (${reason.reason}: ${reason.keys.join(", ")}): ${reason.detail}`);
5231
+ }
5232
+ deps.errorLog(`Nothing was written. ${normalized.refusal.fix}`);
5233
+ deps.log("");
5234
+ deps.log("Not ready: the answers were refused before any write");
5235
+ deps.log("complete-with-manual-steps");
5236
+ return 1;
5237
+ }
5238
+ proposal = normalized.proposal;
5239
+ proposalDigest = normalized.digest;
5240
+ resolvedChoices = normalized.choices;
5241
+ }
5242
+ // ---- Read-only: preview only, before every write and write prompt -------
5243
+ // BAPI-1635: `--json` is a read-only assessment like `--dry-run`. Both return here,
5244
+ // before the fix loop, the launch-profile save, credential writes, MCP grants, policy
5245
+ // changes, setup pull requests, and re-indexing.
5246
+ if (readOnlyRun && !proposalMode) {
5247
+ // BAPI-1638: `--json` reads only, so it skips the policy preview POST a plain dry run shows.
5248
+ if (options.dryRun && options.json !== true && gatePlan !== null)
5249
+ await fixGateAndDefaults(deps, options, access, gatePlan, reviewDefault, true);
5250
+ deps.installDocumentSink?.({ items: firstItems, decisions: decisionEvidence });
3258
5251
  logStoredCommandAndToolchains(deps, state.storedCommand, state.toolchains);
5252
+ renderDryRunCiPlan(deps, options, gatePlan);
5253
+ if (managedWorkflowInPlay(state, gateRequiresManagedCheck))
5254
+ await warnDefaultBranchRequiresManagedCheck(setup, state);
3259
5255
  deps.log("");
3260
- deps.log("Dry run — nothing was written and nothing was asked.");
5256
+ deps.log(options.dryRun ? "Dry run — nothing was written and nothing was asked." : "Read-only assessment — nothing was written and nothing was asked.");
5257
+ if (notLearned) {
5258
+ deps.log(" A real run would stop here: this repository has not been learned (see repository_not_learned above).");
5259
+ }
3261
5260
  if (fixes.length === 0)
3262
5261
  deps.log(" No fix is needed.");
3263
5262
  for (const fix of fixes)
@@ -3266,106 +5265,348 @@ async function runConvergingSetup(options, deps, setup) {
3266
5265
  deps.log(` Would write executor unit: ${executorPlans.install.unitPath}`);
3267
5266
  deps.log(` Would start it with: ${executorPlans.start.manualCommand}`);
3268
5267
  }
5268
+ for (const advisory of state.evidence.advisories)
5269
+ deps.log(` - ${advisory}`);
5270
+ // `--json` keeps the closing summary it always printed: what still needs attention (with the
5271
+ // closed setup PR named once), then the verdict and the one next step.
5272
+ const readOnlyUnmet = unmetBlockingItems(firstItems);
5273
+ if (!options.dryRun) {
5274
+ const readOnlyPr = state.evidence.setupPullRequest;
5275
+ const notice = readOnlyPr.state === "closed_unmerged" && state.evidence.workflow.state !== "installed"
5276
+ ? closedSetupPullRequestNotice(readOnlyPr)
5277
+ : undefined;
5278
+ const printNotice = notice !== undefined && !readOnlyUnmet.some((item) => item.remedy === notice);
5279
+ if (readOnlyUnmet.length > 0 || printNotice) {
5280
+ deps.log("");
5281
+ deps.log("What still needs attention");
5282
+ for (const item of readOnlyUnmet)
5283
+ deps.log(` - ${item.label}: ${setupItemRemedy(item)}`);
5284
+ if (printNotice)
5285
+ deps.log(` - ${notice}`);
5286
+ }
5287
+ }
5288
+ for (const line of advisoryFindingLines(firstItems))
5289
+ deps.log(line);
3269
5290
  deps.log("");
3270
5291
  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 ---------------------------
5292
+ if (!options.dryRun) {
5293
+ deps.log(`Next step: ${readOnlyUnmet.length === 0 ? "Run drive-epic to start your first epic" : setupItemRemedy(readOnlyUnmet[0])}`);
5294
+ }
5295
+ deps.log(options.dryRun ? "complete-with-manual-steps (dry run)" : "complete-with-manual-steps");
5296
+ // A dry run always exits 0. A read-only `--json` assessment keeps the exit code of a
5297
+ // normal one: 1 while a blocking step is left, otherwise the doctor's own code.
5298
+ // An unlearned repository also keeps exit 1: a real run would have stopped there with 1.
5299
+ return options.dryRun ? 0 : notLearned || unmetBlockingItems(firstItems).length > 0 ? 1 : conductorInstallDoctorExitCode(firstReport);
5300
+ }
5301
+ // ---- Fix only what is missing, once, in order: the shared apply (BAPI-1638) ----
5302
+ // Both paths reach the same apply. On the answers path each decision point reads
5303
+ // its stated answer; on the interactive path it asks its question as before.
3275
5304
  if (fixes.length > 0) {
3276
5305
  deps.log("");
3277
5306
  deps.log("Fixing what is missing…");
3278
5307
  }
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
5308
  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" },
5309
+ let epicServerChanged = false;
5310
+ const answerOf = (key) => decisionFor(proposal, key);
5311
+ const optionOf = (key) => {
5312
+ const d = answerOf(key);
5313
+ return d === undefined ? undefined : d.kind === "decline" ? "decline" : d.kind === "option" ? d.option : undefined;
5314
+ };
5315
+ // BAPI-1659: whether the setup pull request really opened this run. Only then may a declined CI
5316
+ // change say the workflow still arrives through it; an approved answer alone proves nothing.
5317
+ // BAPI-1679: `opened` covers a pull request this run opened or found already open, and
5318
+ // `in_place` a workflow already identical on the default branch. A rerun must not read either as nothing.
5319
+ let setupWorkflowDelivery = "none";
5320
+ const operations = [
5321
+ {
5322
+ key: "gate",
5323
+ run: async () => {
5324
+ if (gatePlan === null)
5325
+ return null;
5326
+ // BAPI-1677: a correction replaces the planned list before the PUT is built. It is
5327
+ // validated already, and it never merges with what discovery found.
5328
+ const corrected = answerOf("dependency_install");
5329
+ const correctionEntry = corrected?.kind === "dependency_install_entries"
5330
+ ? { key: "dependency_install", proposalKeys: [], fields: { dependencyInstall: corrected.entries }, summary: [] }
5331
+ : null;
5332
+ const resultPlan = correctionEntry === null ? declarationPlan : [...declarationPlan.filter((e) => e.key !== "dependency_install"), correctionEntry];
5333
+ const approvedDeclarations = proposal === null ? [] : resultPlan.filter((e) => optionOf(e.key) === "approve" || e === correctionEntry);
5334
+ const gateOpen = fixes.includes("gate_and_defaults");
5335
+ if (!gateOpen && approvedDeclarations.length === 0) {
5336
+ if (proposal === null)
5337
+ return null;
5338
+ return settledGateResults(proposal);
5339
+ }
5340
+ const gateAnswer = proposal === null ? undefined : gateOpen ? (optionOf("gate") === "decline" ? "decline" : "approve") : "approve";
5341
+ const plan = applyApprovedDeclarations(gatePlan, approvedDeclarations);
5342
+ policyResult = await fixGateAndDefaults(deps, options, access, plan, reviewDefault, true, gateAnswer);
5343
+ // BAPI-1677: what is stored is read back; what discovery found never stands in for it.
5344
+ let installReadBack;
5345
+ const installApproved = approvedDeclarations.some((e) => e.key === "dependency_install");
5346
+ if (installApproved && (policyResult.status === "completed" || policyResult.status === "unchanged")) {
5347
+ try {
5348
+ const back = await fetchConductorGateProfile(access, deps.fetchJson);
5349
+ const entries = back.profile?.dependency_install ?? [];
5350
+ state.sealedDependencyInstall = entries;
5351
+ const wanted = approvedDeclarations.find((e) => e.key === "dependency_install")?.fields.dependencyInstall ?? [];
5352
+ installReadBack = !sameDependencyInstall(entries, wanted) ? null
5353
+ : entries.map((e) => `${e.argv.join(" ")} (in ${e.cwd}; runs again when ${e.lockfiles.join(", ")} changes)`);
5354
+ }
5355
+ catch {
5356
+ installReadBack = null;
5357
+ }
5358
+ }
5359
+ return gateWriteResults(policyResult, proposal, resultPlan, installReadBack);
5360
+ },
5361
+ },
5362
+ {
5363
+ key: "test_command",
5364
+ // The interactive path keeps each phase's own skip rule; only approved answers chain.
5365
+ ...(proposal !== null ? { dependsOn: ["gate"] } : {}),
5366
+ run: async () => {
5367
+ const answer = proposal === null ? undefined : testCommandAnswer(answerOf("test_command"));
5368
+ await runTestCommandPhase(deps, options, setup, access, baseUrl, state, gatePlan, policyResult, answer);
5369
+ settleCiPlan(deps, state, gatePlan);
5370
+ // BAPI-1657: only the no-command remedy needs the launcher text, so detection runs only for that outcome.
5371
+ const launcher = state.trial?.status === "no_command" ? await detectedLauncherBase(deps, access.repoName) : undefined;
5372
+ const trialResult = trialWriteResult(state.trial, proposal !== null && answer !== undefined && answer.decision !== "skip" && answer.decision !== "keep", launcher);
5373
+ // BAPI-1677: a replay names what the trial proved, so the setup record reads the same. The
5374
+ // gate's local commands are that proof. The separate stored test command can still be unset.
5375
+ const proven = gatePlan?.current.profile?.local_commands.map((c) => c.argv.join(" ")) ?? [];
5376
+ const ran = proven.length > 0 ? proven : state.storedCommand !== null ? [state.storedCommand] : [];
5377
+ return trialResult?.status === "unchanged" && ran.length > 0
5378
+ ? { ...trialResult, read_back: { ran } }
5379
+ : trialResult;
5380
+ },
5381
+ },
5382
+ {
5383
+ key: "setup_pr",
5384
+ // It depends on the gate. A learned check that ran and failed is not a blocker here:
5385
+ // the workflow phase reports the PR `declined` with the check's phase.
5386
+ ...(proposal !== null ? { dependsOn: ["gate"] } : {}),
5387
+ run: async () => {
5388
+ const setupPr = proposal === null ? undefined : optionOf("setup_pr") === "approve" ? "approve" : optionOf("setup_pr") === "decline" ? "decline" : undefined;
5389
+ // BAPI-1659: the setup choice is asked only for real setup-workflow work. When none was proposed
5390
+ // (the CI change has its own pull request), this step opens nothing and never touches the gate.
5391
+ if (proposal !== null && setupPr !== undefined && decisionEvidence !== null && !decisionEvidence.setupPr.applicable
5392
+ && decisionEvidence.epicBranchCi?.ciOffer?.applicable === true) {
5393
+ return setupPr === "decline"
5394
+ ? { key: "setup_pr", status: "declined", target: "github.default_branch" }
5395
+ : { key: "setup_pr", status: "unchanged", target: "github.default_branch", reason: "no setup pull request was needed" };
5396
+ }
5397
+ const outcome = await runWorkflowPhase(deps, options, setup, access, baseUrl, state, readToolchains, gateRequiresManagedCheck, setupPr);
5398
+ if (managedWorkflowInPlay(state, gateRequiresManagedCheck))
5399
+ await warnDefaultBranchRequiresManagedCheck(setup, state);
5400
+ const written = workflowWriteResult(outcome, proposal !== null && setupPr !== undefined, setupPr);
5401
+ if (written?.status === "written")
5402
+ setupWorkflowDelivery = "opened";
5403
+ else if (written?.status === "unchanged" && outcome.status === "unchanged")
5404
+ setupWorkflowDelivery = outcome.url !== undefined ? "opened" : "in_place";
5405
+ // A creation with an uncertain result is read again; an open pull request is a fact.
5406
+ else if (outcome.status === "failed" && state.evidence.workflow.state === "pr_open")
5407
+ setupWorkflowDelivery = "opened";
5408
+ return written;
5409
+ },
5410
+ },
5411
+ {
5412
+ key: "test_command",
5413
+ run: async () => {
5414
+ // ---- Explicit operations, each behind its own consent (unchanged) -------
5415
+ if (options.gate.qualifyGate && gatePlan !== null && gatePlan.desired.localCommands.length > 0
5416
+ && policyResult?.status !== "deferred" && policyResult?.status !== "unknown") {
5417
+ await runConductorGateQualification(gateIo, access, deps.gate, {
5418
+ revision: policyResult?.current?.state.revision ?? gatePlan.current.revision,
5419
+ baseUrl,
5420
+ });
5421
+ }
5422
+ return null;
5423
+ },
5424
+ },
5425
+ {
5426
+ key: "merge_token",
5427
+ run: async () => {
5428
+ if (!fixes.includes("merge_token") || state.identity === null) {
5429
+ return proposal === null || answerOf("merge_token")?.kind !== "reference" ? null
5430
+ : { key: "merge_token", status: "unchanged", target: "merge_token" };
5431
+ }
5432
+ const d = answerOf("merge_token");
5433
+ const answer = proposal === null || d === undefined ? undefined
5434
+ : d.kind === "reference" ? { decision: "reference", reference: d.reference } : { decision: "decline" };
5435
+ const outcome = await fixMergeToken(deps, setup, state.identity, state.evidence.mergeCredential.state === "stored_rejected", answer);
5436
+ return fixOutcomeResult("merge_token", "merge_token", outcome);
5437
+ },
5438
+ },
5439
+ {
5440
+ key: "reindex",
5441
+ run: async () => {
5442
+ if (!fixes.includes("reindex")) {
5443
+ return proposal === null || optionOf("reindex") !== "approve" ? null
5444
+ : { key: "reindex", status: "unchanged", target: "repository_index", progress: indexProgress(state.evidence.index) ?? "current" };
5445
+ }
5446
+ if (proposal !== null && optionOf("reindex") === "skip") {
5447
+ return { key: "reindex", status: "declined", target: "repository_index" };
5448
+ }
5449
+ const answers = proposal === null ? undefined : {
5450
+ ...(optionOf("reindex_branch") === "correct" || optionOf("reindex_branch") === "keep" ? { branch: optionOf("reindex_branch") } : {}),
5451
+ ...(optionOf("reindex_retry") === "retry" || optionOf("reindex_retry") === "no_retry" ? { retry: optionOf("reindex_retry") } : {}),
5452
+ };
5453
+ state.evidence = { ...state.evidence, index: await fixReindex(deps, setup, access, state.evidence.recovery, answers) };
5454
+ return reindexWriteResult(state.evidence.index);
5455
+ },
5456
+ },
5457
+ {
5458
+ key: "worker_mcp_grant",
5459
+ run: async () => {
5460
+ if (!fixes.includes("mcp_grant") || setup.mcpGrant === undefined || grantInventory === null) {
5461
+ return proposal === null || answerOf("worker_mcp_grant")?.kind !== "selection" ? null
5462
+ : { key: "worker_mcp_grant", status: "unchanged", target: "mcp_grant" };
5463
+ }
5464
+ const d = answerOf("worker_mcp_grant");
5465
+ const answer = proposal === null || d === undefined ? undefined
5466
+ : d.kind === "selection" ? { decision: "select", ids: d.ids } : { decision: "decline" };
5467
+ const outcome = await fixMcpGrant(deps, setup.mcpGrant, access.repoName, grantInventory, answer, sfccGrantIds(epicServerSnapshot, grantInventory));
5468
+ return fixOutcomeResult("worker_mcp_grant", "mcp_grant", outcome);
5469
+ },
5470
+ },
5471
+ {
5472
+ key: "epic_server",
5473
+ run: async () => {
5474
+ if (setup.epicServer === undefined)
5475
+ return null;
5476
+ const d = answerOf("epic_server");
5477
+ if (!fixes.includes("epic_server")) {
5478
+ if (proposal === null || d === undefined || (d.kind === "option" && d.option === "keep"))
5479
+ return null;
5480
+ }
5481
+ const answer = proposal === null || d === undefined ? undefined : await epicServerAnswer(setup.epicServer, d, epicServerSnapshot);
5482
+ const outcome = await fixEpicServer(deps, setup.epicServer, access.repoName, answer, epicServerSnapshot);
5483
+ epicServerChanged = outcome.status === "written";
5484
+ return fixOutcomeResult("epic_server", "epic_server_record", outcome);
5485
+ },
5486
+ },
5487
+ {
5488
+ key: "epic_branch_ci",
5489
+ run: async (completed) => {
5490
+ // The inspection runs once on every ordinary run: an explicit flag wins, a confirmed
5491
+ // workflow on epic-branch PRs is recorded as include, and anything else is only reported.
5492
+ if (!epicBranchCiWanted)
5493
+ return null;
5494
+ const exemption = optionOf("approval_exemption");
5495
+ // BAPI-1679: a recommended `include` whose only support was the setup pull request stands
5496
+ // only if that pull request delivered. A stated answer or flag is never touched, and the
5497
+ // proposal and its digest stay as approved: only what this step stores changes.
5498
+ const lostSetupCredit = proposal !== null && resolvedChoices !== undefined && setupWorkflowDelivery === "none"
5499
+ && proposal.decisions.find((d) => d.key === "epic_branch_ci")?.source === "recommended"
5500
+ && optionOf("epic_branch_ci") === "include"
5501
+ && epicBranchCiIncludeRestsOnSetupPr(resolvedChoices, optionOf, { setupSuppliesWorkflow: decisionEvidence?.epicBranchCi?.managedWorkflowViaSetupPr === true });
5502
+ const setupPrStatus = completed.get("setup_pr")?.status;
5503
+ const creditNote = lostSetupCredit
5504
+ ? describeUnopenedSetupCredit({
5505
+ confirmed: setupPrStatus !== "failed" && setupPrStatus !== "uncertain",
5506
+ coverage: decisionEvidence?.epicBranchCi?.coverage ?? null,
5507
+ integrationTarget: ciOfferCollection?.evidence.integrationTarget ?? null,
5508
+ })
5509
+ : undefined;
5510
+ const ci = lostSetupCredit ? "decline" : optionOf("epic_branch_ci");
5511
+ const epicBranchCi = await runEpicBranchCiInspection(gateIo, access, deps.gate, {
5512
+ decisionFlag: proposal !== null && (ci === "include" || ci === "decline") ? ci : options.epicBranchCiDecision ?? null,
5513
+ dryRun: false,
5514
+ inferFromCoverage: true,
5515
+ ...(epicBranchCollected !== undefined ? { collected: epicBranchCollected } : {}),
5516
+ ...(proposal !== null ? { exemptionDecision: exemption === "approve" ? "approve" : "decline" } : {}),
5517
+ // On the answers path a decision readiness already reports is not written again.
5518
+ ...(proposal !== null ? { recordedDecision: firstReport.readiness?.epic_branch_ci?.decision ?? null } : {}),
5519
+ ...(creditNote !== undefined ? { decisionNote: creditNote } : {}),
5520
+ });
5521
+ if (epicBranchCi.manualAction !== null)
5522
+ state.evidence.advisories.push(epicBranchCi.manualAction);
5523
+ // BAPI-1637: once per run, after the CI step, from readiness's own facts.
5524
+ await runGateConsequenceSummary(gateIo, access, deps.gate);
5525
+ // BAPI-1654: the plain state, in the same words the choice used.
5526
+ const stateText = epicBranchCiStateText(decisionEvidence?.epicBranchCi ?? null);
5527
+ // The note already replaced it when the credit fell through: this text is from before the apply.
5528
+ if (proposal !== null && stateText !== null && creditNote === undefined)
5529
+ deps.log(` ${stateText}`);
5530
+ return epicBranchWriteResults(epicBranchCi, proposal !== null, creditNote);
5531
+ },
5532
+ },
5533
+ {
5534
+ // BAPI-1654: the approved CI change, delivered only as a pull request, independently of
5535
+ // the setup pull request's own result. Opening it changes no gate and adds no hold.
5536
+ key: "epic_ci_change",
5537
+ run: async () => {
5538
+ if (proposal === null)
5539
+ return null;
5540
+ const d = answerOf("epic_ci_change");
5541
+ if (d === undefined)
5542
+ return null;
5543
+ const offer = ciOfferCollection?.evidence.ciOffer ?? null;
5544
+ const target = offer?.identity.path ?? "github.default_branch";
5545
+ if (d.kind === "decline") {
5546
+ const text = describeDeclinedCiChange({
5547
+ coverage: decisionEvidence?.epicBranchCi?.coverage ?? null,
5548
+ integrationTarget: ciOfferCollection?.evidence.integrationTarget ?? null,
5549
+ coverageViaApprovedSetup: decisionEvidence?.epicBranchCi?.managedWorkflowViaSetupPr === true && setupWorkflowDelivery === "opened",
5550
+ });
5551
+ deps.log("");
5552
+ deps.log("CI change for epic branches");
5553
+ deps.log(` ${text}`);
5554
+ return { key: "epic_ci_change", status: "declined", target, reason: text };
5555
+ }
5556
+ const delivery = ciOfferCollection?.delivery ?? null;
5557
+ if (offer === null || !offer.applicable || delivery === null) {
5558
+ return {
5559
+ key: "epic_ci_change", status: "unchanged", target,
5560
+ reason: offer === null ? "no CI change is needed now" : "the CI change is already in place",
5561
+ ...(offer !== null ? { read_back: { path: target, state: "in_place" } } : {}),
3303
5562
  };
3304
5563
  }
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
- 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
5564
  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
- }
5565
+ deps.log("CI change for epic branches");
5566
+ // The approved answer is this pull request's consent; nothing else is asked.
5567
+ const approved = async () => true;
5568
+ const snapshotOption = state.snapshot !== null ? { snapshot: state.snapshot } : {};
5569
+ let result;
5570
+ try {
5571
+ if (delivery.kind === "trigger_edit") {
5572
+ if (setup.installCiTriggerEdit === undefined) {
5573
+ return { key: "epic_ci_change", status: "unattempted", target, reason: "this caller cannot open the CI pull request", fix: "Run setup from the packaged CLI." };
5574
+ }
5575
+ result = await setup.installCiTriggerEdit(delivery.edit, { dryRun: false, ...snapshotOption }, approved);
5576
+ }
5577
+ else {
5578
+ // BAPI-1677: a workflow never installs commands the gate did not store.
5579
+ if (!sameDependencyInstall(delivery.dependencyInstall, state.sealedDependencyInstall)) {
5580
+ return { key: "epic_ci_change", status: "unattempted", target, reason: "the install commands this workflow uses were not stored", fix: "Rerun setup; nothing was opened." };
5581
+ }
5582
+ result = await setup.installCiWorkflow(delivery.command, delivery.toolchains, { dryRun: false, createOnly: true, ...snapshotOption, ...dependencyInstallOption(delivery.dependencyInstall) }, approved);
5583
+ }
5584
+ }
5585
+ catch {
5586
+ 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." };
5587
+ }
5588
+ const written = ciChangeWriteResult(offer.identity.action_class, target, result);
5589
+ if (written.reason !== undefined)
5590
+ deps.log(` ${written.reason}`);
5591
+ return written;
5592
+ },
5593
+ },
5594
+ ];
5595
+ // The interactive path keeps its original question order: the missing-item fixes
5596
+ // (merge token, re-index, grant, epic server) come right after the gate and before
5597
+ // the learned check, the setup PR, and qualification. The answers path runs the
5598
+ // array as written so the learned check and setup PR chain on the gate.
5599
+ const ordered = proposal !== null ? operations
5600
+ : [operations[0], ...operations.slice(4, 8), ...operations.slice(1, 4), operations[8], operations[9]];
5601
+ const firstApply = await applyInstallProposal({ proposal, digest: proposalDigest, refusal: null }, { operations: ordered });
5602
+ const applied = firstApply.kind === "applied" ? firstApply.result : { complete: false, results: [] };
3362
5603
  if (options.reviewPolicy === "verdict_protocol" && !options.skipWorkflow) {
3363
5604
  await runClaudeReviewWorkflowOperation(deps, options, state);
3364
5605
  }
3365
5606
  if (options.epicKey && options.planFile) {
3366
5607
  deps.log("");
3367
5608
  deps.log("Verifying the plan with `setup-epic --dry-run`…");
3368
- const verification = await deps.runSetupEpicDryRun([
5609
+ const verification = await progress("checking the plan", () => deps.runSetupEpicDryRun([
3369
5610
  "--dry-run",
3370
5611
  "--epic-key",
3371
5612
  options.epicKey,
@@ -3374,8 +5615,9 @@ async function runConvergingSetup(options, deps, setup) {
3374
5615
  "--review-policy",
3375
5616
  options.reviewPolicy,
3376
5617
  ...(options.repo ? ["--repo", options.repo] : []),
3377
- ]);
5618
+ ]));
3378
5619
  if (verification.exitCode !== 0) {
5620
+ deps.log(" Plan verification failed: `setup-epic --dry-run` reported plan problems (shown above).");
3379
5621
  state.failedOperations.push({
3380
5622
  id: "setup-epic-verification",
3381
5623
  label: "Plan verification",
@@ -3394,27 +5636,89 @@ async function runConvergingSetup(options, deps, setup) {
3394
5636
  deps.log("Executor service");
3395
5637
  observedReadiness = await runExecutorProvisioningPhase(deps, deps.executorProvisioning, executorPlans, access);
3396
5638
  }
5639
+ // ---- BAPI-1545: the advisory capability statement, on every real run ----
5640
+ // Built from the grant and epic-server record as they are NOW (after any
5641
+ // approval above), never from an unapproved proposal. A failed write warns
5642
+ // once and never changes the verdict. A dry run returned long before this.
5643
+ // BAPI-1546: the same write follows an epic-server change, so the server sees
5644
+ // the current mode; a failure after a change is reported on that item only.
5645
+ let statementError = null;
5646
+ if (setup.mcpGrant !== undefined) {
5647
+ statementError = await publishCapabilityStatement(deps, setup.mcpGrant, access, options.verbose === true);
5648
+ }
3397
5649
  // ---- Check 2: the closing assessment (deny probe runs once, here) -------
3398
5650
  deps.log("");
3399
5651
  deps.log("Checking again…");
3400
- const finalReport = await deps.runDoctor({
5652
+ const finalReport = await progress("checking readiness", () => deps.runDoctor({
3401
5653
  access,
3402
- reviewPolicySource: options.reviewPolicy,
5654
+ reviewPolicySource: effectiveReviewPolicy(options, reviewDefault),
3403
5655
  assessmentVersion: 1,
3404
5656
  epicRunId: options.assessmentEpicRunId,
3405
5657
  storedMergeCredential: storedMergeContextFor(setup, firstReport.readiness?.provider_repository ?? null, localRemote),
3406
- });
5658
+ }));
3407
5659
  const finalReadiness = options.assessmentEpicRunId !== undefined
3408
5660
  ? finalReport.readiness
3409
5661
  : observedReadiness ?? finalReport.readiness;
3410
- const closing = await collectSetupEvidence(deps, setup, access, finalReadiness, {
5662
+ // The closing read carries this run's plan and warnings forward, reads the
5663
+ // toolchains it already has, and never repeats a trial or an offer.
5664
+ const closing = await progress("checking readiness", () => collectSetupEvidence(deps, setup, access, finalReadiness, {
3411
5665
  ...collectInputs,
5666
+ dependencyInstall: state.sealedDependencyInstall,
5667
+ // BAPI-1657: after an apply, approval has already happened, so a gate still unknown is not
5668
+ // "stored on approval". Only a dry run's closing preview keeps that promise.
5669
+ plannedGateWrite: plannedGateWrite && options.dryRun === true,
3412
5670
  advisories: state.evidence.advisories,
3413
- commandChanged: state.commandChanged,
3414
- commandBlocked: state.commandBlocked,
3415
- });
5671
+ gateRequiresManagedCheck: gateRequiresManagedCheck || state.ciPlan === "managed",
5672
+ ...(state.ciPlan !== undefined ? { ciPlan: state.ciPlan } : {}),
5673
+ }));
3416
5674
  if (state.evidence.index.state === "recovery_unresolved" && closing.evidence.index.state !== "reached")
3417
5675
  closing.evidence.index = state.evidence.index;
5676
+ if (setup.mcpGrant !== undefined) {
5677
+ // A discovery that failed on the first check stays "could not be checked"
5678
+ // in the closing assessment instead of silently dropping the item.
5679
+ closing.evidence.mcpGrant =
5680
+ grantInventory !== null
5681
+ ? await closingMcpGrantState(setup.mcpGrant, access.repoName, grantInventory)
5682
+ : { state: "unknown" };
5683
+ }
5684
+ if (setup.epicServer !== undefined) {
5685
+ const closingEpicServer = await assessEpicServer(setup.epicServer, access.repoName);
5686
+ closing.evidence.epicServer =
5687
+ epicServerChanged && statementError !== null && closingEpicServer.state === "met"
5688
+ ? { ...closingEpicServer, statementError }
5689
+ : closingEpicServer;
5690
+ }
5691
+ // ---- BAPI-1260: the reusable launch profile (explicit) ------------------
5692
+ // BAPI-1635: this runs BEFORE the final items are projected, so a profile saved by
5693
+ // this invocation is read back and judged for escalation, not left as pre-save evidence.
5694
+ // BAPI-1638: the late stage of the same shared apply, which also writes the setup record.
5695
+ let launch;
5696
+ const lateApply = await applyInstallProposal({ proposal, digest: proposalDigest, refusal: null, prior: applied }, {
5697
+ operations: [{
5698
+ key: "launch_profile",
5699
+ run: async () => {
5700
+ if (options.launchProfile === undefined || (proposal !== null && optionOf("launch_profile") === "skip"))
5701
+ return null;
5702
+ launch = await runLaunchProfilePhase(deps, options, {
5703
+ access,
5704
+ baseUrl,
5705
+ readiness: finalReadiness,
5706
+ actorObserved: observedReadiness !== null || finalReadiness?.executor.ready === true,
5707
+ runtime: resolveLaunchRuntime(deps.executorProvisioning, options.executionMode ?? "local"),
5708
+ });
5709
+ return launch.complete
5710
+ ? { key: "launch_profile", status: "written", target: `launch_profile:${options.launchProfile}` }
5711
+ : { 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." };
5712
+ },
5713
+ }],
5714
+ setupRecord: deps.setupRecordWriter ?? null,
5715
+ });
5716
+ const applyResult = lateApply.kind === "applied" ? lateApply.result : applied;
5717
+ {
5718
+ const notification = await collectNotificationEvidence(deps, options, baseUrl);
5719
+ if (notification !== undefined)
5720
+ closing.evidence.notification = notification;
5721
+ }
3418
5722
  const items = [...projectSetupItems(closing.evidence), ...state.failedOperations];
3419
5723
  if (deniesEnforcementUnknown(finalReport)) {
3420
5724
  items.push({
@@ -3425,57 +5729,590 @@ async function runConvergingSetup(options, deps, setup) {
3425
5729
  remedy: "the worker safety check could not run; run `epic-implementer doctor` to see why",
3426
5730
  });
3427
5731
  }
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"),
5732
+ if (launch !== undefined && !launch.complete) {
5733
+ items.push({
5734
+ id: "launch-profile",
5735
+ label: `Launch profile '${options.launchProfile}'`,
5736
+ state: "needs_action",
5737
+ blocking: true,
5738
+ remedy: "finish the launch-profile steps listed above, then re-run setup with --launch-profile",
3436
5739
  });
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
5740
  }
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",
5741
+ // The latest authoritative command and what CI installs for it. Operator-only:
5742
+ // written through deps.log and nowhere else. Detail, so it waits for --verbose.
5743
+ if (options.verbose === true) {
5744
+ logStoredCommandAndToolchains(deps, closing.evidence.testCommand.state === "stored" ? closing.storedCommand : null, closing.toolchains);
5745
+ }
5746
+ // Assigned inside the shared apply's adapters, so the compiler cannot follow it here.
5747
+ const finalPolicy = policyResult;
5748
+ if (finalPolicy?.status === "deferred" || finalPolicy?.status === "unknown") {
5749
+ items.push({ id: "setup-policy", label: "Combined repository policy", state: "needs_action", blocking: policyRequired || finalPolicy.status === "unknown",
3452
5750
  remedy: "rerun setup for a fresh preview; ask a bootstrap administrator if uncertainty persists" });
3453
5751
  }
5752
+ // The assessment sink and the verdict read the complete item list whatever the verbosity.
3454
5753
  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}`);
5754
+ const unmet = unmetBlockingItems(items);
5755
+ // A closed-unmerged setup PR is named once. The legacy path already carries the
5756
+ // notice as a blocking item's remedy, so only print it when no blocking item does.
5757
+ const closedPr = closing.evidence.setupPullRequest;
5758
+ const notice = closedPr.state === "closed_unmerged" && closing.evidence.workflow.state !== "installed" ? closedSetupPullRequestNotice(closedPr) : undefined;
5759
+ const printNotice = notice !== undefined && !unmetBlockingItems(items).some((item) => item.remedy === notice);
5760
+ if (options.verbose === true) {
5761
+ for (const line of renderSetupAssessment(items, "Where things stand", "final"))
5762
+ deps.log(line);
5763
+ for (const advisory of closing.evidence.advisories)
5764
+ deps.log(` - ${advisory}`);
5765
+ if (printNotice)
5766
+ deps.log(` - ${notice}`);
5767
+ }
5768
+ else {
5769
+ // Without --verbose the list is short, but nothing material is hidden: every unmet blocking
5770
+ // step and failed operation prints with its remedy, and so does every advisory that is not
5771
+ // routine editor/hook housekeeping.
5772
+ const problems = [...state.failedOperations, ...unmet].filter((item, index, all) => all.findIndex(o => o.id === item.id) === index);
5773
+ if (problems.length > 0 || printNotice) {
5774
+ deps.log("");
5775
+ deps.log("What still needs attention");
5776
+ for (const item of problems)
5777
+ deps.log(` - ${item.label}: ${setupItemRemedy(item)}`);
5778
+ if (printNotice)
5779
+ deps.log(` - ${notice}`);
5780
+ }
5781
+ for (const advisory of closing.evidence.advisories.filter(a => !routineAdvisories.includes(a)))
5782
+ deps.log(` - ${advisory}`);
5783
+ for (const line of advisoryFindingLines(items))
5784
+ deps.log(line);
5785
+ }
5786
+ // BAPI-1638: each write's own result, then the read-back-driven verdict.
5787
+ if (proposal !== null) {
5788
+ const incomplete = applyResult.results.filter((r) => r.status === "failed" || r.status === "refused" || r.status === "uncertain" || r.status === "unattempted");
5789
+ deps.log("");
5790
+ deps.log("What the answers applied");
5791
+ for (const r of applyResult.results) {
5792
+ deps.log(` - ${r.key}: ${r.status}${r.progress !== undefined ? ` (${r.progress})` : ""}${r.reason !== undefined ? ` — ${r.reason}` : ""}`);
5793
+ }
5794
+ for (const r of incomplete)
5795
+ if (r.fix !== undefined)
5796
+ deps.log(` ${r.key}: ${r.fix}`);
5797
+ }
5798
+ deps.installDocumentSink?.({
5799
+ items,
5800
+ decisions: decisionEvidence,
5801
+ ...(resolvedChoices !== undefined ? { choices: resolvedChoices } : {}),
5802
+ ...(proposal !== null ? { proposal } : {}),
5803
+ ...(proposalDigest !== null ? { digest: proposalDigest } : {}),
5804
+ ...(proposal !== null ? { apply: applyResult, applyPresentation: confirmedPresentation(finalReadiness, closing.evidence, items, unmet, applyResult) } : {}),
5805
+ });
3459
5806
  deps.log("");
3460
- const ready = unmetBlockingItems(items).length === 0;
5807
+ const ready = unmet.length === 0 && (proposal === null || applyResult.complete);
3461
5808
  deps.log(setupVerdictLine(items));
5809
+ // Exactly one next step: the first unmet blocking item's remedy, or the start command.
5810
+ 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
5811
  deps.log(ready ? "complete" : "complete-with-manual-steps");
3463
5812
  return ready ? conductorInstallDoctorExitCode(finalReport) : 1;
3464
5813
  }
5814
+ /** BAPI-1678 — a readable stored gate, with required and watched checks apart. Anything else is unknown. */
5815
+ function storedGateEvidence(profile) {
5816
+ if (profile === null || profile === undefined || profile.read_failed || profile.stored_malformed || profile.kind === null)
5817
+ return null;
5818
+ if (profile.source !== "stored" && profile.source !== "legacy")
5819
+ return null;
5820
+ return {
5821
+ kind: profile.kind,
5822
+ requiredChecks: profile.provider_checks.filter((c) => c.watched !== true).map((c) => c.name),
5823
+ watchedChecks: profile.provider_checks.filter((c) => c.watched === true).map((c) => c.name),
5824
+ };
5825
+ }
5826
+ function storedCommandEvidence(evidence, profile) {
5827
+ if ((profile?.local_commands.length ?? 0) > 0)
5828
+ return true;
5829
+ return evidence.testCommand.state === "unknown" ? null : evidence.testCommand.state === "stored";
5830
+ }
5831
+ function managedWorkflowEvidence(evidence) {
5832
+ const { state } = evidence.workflow;
5833
+ return state === "unknown" || state === "blocked" ? null : state === "installed";
5834
+ }
5835
+ /** BAPI-1678 — the proposal's wording, from evidence this run already read. No further read. */
5836
+ function plannedPresentation(proposal, gatePlan, gateWriteNeeded, plannedConsequence, readiness, evidence) {
5837
+ const stored = readiness?.gate_profile;
5838
+ const gateDecision = decisionFor(proposal, "gate");
5839
+ const approved = gatePlan !== null && gateWriteNeeded && gateDecision?.kind === "option" && gateDecision.option === "approve";
5840
+ const desired = approved ? gatePlan.desired : null;
5841
+ const gate = desired === null
5842
+ ? storedGateEvidence(stored)
5843
+ : {
5844
+ kind: desired.kind,
5845
+ requiredChecks: desired.providerChecks.filter((c) => !(desired.watchedChecks ?? []).includes(c)),
5846
+ watchedChecks: [...(desired.watchedChecks ?? [])],
5847
+ };
5848
+ // A command this gate write would add is not stored yet, and it is not proof of absence either.
5849
+ const storedCommand = storedCommandEvidence(evidence, stored);
5850
+ const localCommandStored = storedCommand !== true && (desired?.localCommands.length ?? 0) > 0 ? null : storedCommand;
5851
+ const ciFacts = readiness?.epic_branch_ci ?? null;
5852
+ const ciDecision = decisionFor(proposal, "epic_branch_ci");
5853
+ const decision = ciDecision?.kind === "decline" || (ciDecision?.kind === "option" && ciDecision.option === "decline")
5854
+ ? "decline"
5855
+ : ciDecision?.kind === "option" && ciDecision.option === "include" ? "include" : ciFacts?.decision ?? null;
5856
+ const testDecision = decisionFor(proposal, "test_command");
5857
+ const trialSelected = testDecision?.kind === "command" || (testDecision?.kind === "option" && testDecision.option === "learn");
5858
+ const consequence = desired !== null
5859
+ ? plannedConsequence
5860
+ : gate === null ? "" : describeGateConsequence({ kind: gate.kind, hasWatchedChecks: gate.watchedChecks.length > 0 }, ciFacts);
5861
+ return buildProposalPresentation({
5862
+ evidence: {
5863
+ gate,
5864
+ localCommandStored,
5865
+ managedWorkflowInstalled: managedWorkflowEvidence(evidence),
5866
+ // A stated decline is known without the server's facts. Anything else needs them.
5867
+ epicBranchCi: ciFacts !== null
5868
+ ? { decision, noCiReasons: ciFacts.no_ci_reasons }
5869
+ : decision === "decline" ? { decision, noCiReasons: [] } : null,
5870
+ },
5871
+ trialPending: trialSelected && storedCommand !== true,
5872
+ consequence,
5873
+ });
5874
+ }
5875
+ /** BAPI-1678 — the verdict, from the readiness and evidence the closing check already captured. */
5876
+ function confirmedPresentation(readiness, evidence, items, unmet, applyResult) {
5877
+ const ready = deriveCompactReadiness({ readinessObserved: readiness !== null, items });
5878
+ const stored = readiness?.gate_profile;
5879
+ const ciFacts = readiness?.epic_branch_ci ?? null;
5880
+ const protection = classifyMergeTestProtection({
5881
+ gate: storedGateEvidence(stored),
5882
+ localCommandStored: storedCommandEvidence(evidence, stored),
5883
+ managedWorkflowInstalled: managedWorkflowEvidence(evidence),
5884
+ epicBranchCi: ciFacts === null ? null : { decision: ciFacts.decision, noCiReasons: ciFacts.no_ci_reasons },
5885
+ });
5886
+ return {
5887
+ verdict: buildInstallVerdict({
5888
+ ready,
5889
+ blockers: unmet.map((item) => ({ label: item.label, fix: setupItemRemedy(item) })),
5890
+ results: applyResult.results,
5891
+ protection,
5892
+ }),
5893
+ ...(ready !== undefined ? { ready } : {}),
5894
+ ...(protection !== undefined ? { merge_test_protection: protection } : {}),
5895
+ };
5896
+ }
3465
5897
  /** The deny probe could not answer: an advisory, never readiness. */
3466
5898
  function deniesEnforcementUnknown(report) {
3467
5899
  const deny = report.legacyConductor?.deny_enforcement;
3468
5900
  return deny !== undefined && deny !== null && deny.enforced !== true;
3469
5901
  }
5902
+ // ---------------------------------------------------------------------------
5903
+ // BAPI-1545: the worker MCP grant and the capability statement
5904
+ // ---------------------------------------------------------------------------
5905
+ /** Compare the published grant with the current inventory. Read-only; never throws. */
5906
+ async function assessMcpGrant(grantDeps, repoName) {
5907
+ let inventory;
5908
+ try {
5909
+ inventory = await grantDeps.discover(repoName);
5910
+ }
5911
+ catch {
5912
+ return { evidence: { state: "unknown" }, inventory: null };
5913
+ }
5914
+ return { evidence: await closingMcpGrantState(grantDeps, repoName, inventory), inventory };
5915
+ }
5916
+ async function closingMcpGrantState(grantDeps, repoName, inventory) {
5917
+ let grant;
5918
+ try {
5919
+ grant = await grantDeps.readGrant(repoName);
5920
+ }
5921
+ catch {
5922
+ return { state: "unknown" };
5923
+ }
5924
+ if (grant.state === "absent")
5925
+ return { state: "needs_action", reason: "no_grant" };
5926
+ if (grant.state === "unusable")
5927
+ return { state: "needs_action", reason: "unusable" };
5928
+ return grant.grant.candidate_fingerprint === inventory.fingerprint
5929
+ ? { state: "met" }
5930
+ : { state: "needs_action", reason: "changed" };
5931
+ }
5932
+ export async function fixMcpGrant(deps, grantDeps, repoName, inventory, answer, sfccRecommendedIds = []) {
5933
+ deps.log("");
5934
+ deps.log("Worker MCP servers");
5935
+ deps.log(` Epic Implementer workers in ${repoName} always get Bridge. You can approve extra MCP servers for them, ` +
5936
+ "once for this repository. Workers then load exactly Bridge plus what you approve here.");
5937
+ const offered = inventory.candidates;
5938
+ if (offered.length === 0) {
5939
+ deps.log(" Offered: none.");
5940
+ }
5941
+ else {
5942
+ deps.log(" Offered:");
5943
+ offered.forEach((candidate, index) => {
5944
+ if (candidate.definitions.length === 1) {
5945
+ const origins = candidate.definitions[0].origins.map((o) => CANDIDATE_ORIGIN_LABEL[o]).join(", ");
5946
+ deps.log(` ${index + 1}. ${candidate.name} (${origins})`);
5947
+ }
5948
+ else {
5949
+ deps.log(` ${index + 1}. ${candidate.name}: ${candidate.definitions.length} different definitions, you choose one`);
5950
+ }
5951
+ });
5952
+ }
5953
+ const exclusions = describeInventoryExclusions(inventory);
5954
+ if (exclusions.length > 0) {
5955
+ deps.log(" Not offered:");
5956
+ for (const line of exclusions)
5957
+ deps.log(` - ${line}`);
5958
+ }
5959
+ if (answer?.decision === "decline") {
5960
+ // Declining preserves the stored grant byte for byte; invalid entries stay listed above.
5961
+ deps.log(" declined — nothing changed. Any earlier approval stays in force.");
5962
+ return { status: "declined" };
5963
+ }
5964
+ if (answer?.decision === "select")
5965
+ return publishApprovedGrant(deps, grantDeps, repoName, inventory, answer.ids);
5966
+ if (!deps.promptLine) {
5967
+ deps.log(" skipped approving MCP servers: there is no interactive terminal, so this counts as declined. Nothing changed.");
5968
+ return { status: "declined" };
5969
+ }
5970
+ // BAPI-1667: a pointer to the numbers. How an answer is read does not change.
5971
+ const recommendedNumbers = offered.flatMap((candidate, index) => candidate.definitions.some((definition) => sfccRecommendedIds.includes(definition.id)) ? [index + 1] : []);
5972
+ if (recommendedNumbers.length > 0)
5973
+ deps.log(` Recommended for this SFCC repository: ${recommendedNumbers.join(", ")}`);
5974
+ let positions = [];
5975
+ if (offered.length > 0) {
5976
+ const answer = await deps.promptLine(GRANT_SELECTION_PROMPT);
5977
+ const parsed = parseGrantSelection(answer, offered.length);
5978
+ if (parsed === null) {
5979
+ deps.log(" That answer was not a list of offered numbers. Nothing changed; re-run setup to try again.");
5980
+ return { status: "declined" };
5981
+ }
5982
+ positions = parsed;
5983
+ }
5984
+ if (positions.length > MCP_GRANT_MAX_SERVERS) {
5985
+ deps.log(` At most ${MCP_GRANT_MAX_SERVERS} servers can be approved. Nothing changed; re-run setup and pick fewer.`);
5986
+ return { status: "declined" };
5987
+ }
5988
+ const selectedIds = [];
5989
+ const selectedNames = [];
5990
+ for (const position of positions) {
5991
+ const candidate = offered[position];
5992
+ let definition = candidate.definitions[0];
5993
+ if (candidate.definitions.length > 1) {
5994
+ deps.log(` ${candidate.name} is defined differently in more than one place:`);
5995
+ candidate.definitions.forEach((def, i) => {
5996
+ deps.log(` ${String.fromCharCode(97 + i)}. ${def.origins.map((o) => CANDIDATE_ORIGIN_LABEL[o]).join(", ")}`);
5997
+ });
5998
+ const letters = candidate.definitions.map((_, i) => String.fromCharCode(97 + i));
5999
+ const choice = (await deps.promptLine(` Which definition of ${candidate.name}? [${letters.join("/")}, Enter skips it]: `))
6000
+ .trim()
6001
+ .toLowerCase();
6002
+ const index = letters.indexOf(choice);
6003
+ if (index === -1) {
6004
+ deps.log(` ${candidate.name} skipped: no definition was chosen.`);
6005
+ continue;
6006
+ }
6007
+ definition = candidate.definitions[index];
6008
+ }
6009
+ selectedIds.push(definition.id);
6010
+ selectedNames.push(candidate.name);
6011
+ }
6012
+ deps.log(` Workers in ${repoName} would get: Bridge${selectedNames.length > 0 ? ` + ${selectedNames.join(", ")}` : " only"}.`);
6013
+ const ok = await askConsent(deps, `Approve these MCP servers for every Epic Implementer worker in ${repoName}? [y/N]: `, "approving MCP servers");
6014
+ if (!ok) {
6015
+ deps.log(" declined — nothing changed. Any earlier approval stays in force.");
6016
+ return { status: "declined" };
6017
+ }
6018
+ return publishGrant(deps, grantDeps, repoName, inventory, selectedIds);
6019
+ }
6020
+ /**
6021
+ * Publish through child 2's path: a fresh rediscovery, revalidation of every
6022
+ * selected definition, staging, then `writeMcpGrant`. A refusal or failure
6023
+ * leaves the earlier grant as it is.
6024
+ */
6025
+ async function publishGrant(deps, grantDeps, repoName, inventory, selectedIds) {
6026
+ const now = grantDeps.now?.() ?? new Date();
6027
+ let published;
6028
+ try {
6029
+ published = await grantDeps.publish(repoName, inventory, selectedIds, now);
6030
+ }
6031
+ catch {
6032
+ published = { ok: false, error: "the grant could not be saved" };
6033
+ }
6034
+ if (published.ok) {
6035
+ deps.log(" approved — saved outside every worktree. New worker spawns use it.");
6036
+ return { status: "written" };
6037
+ }
6038
+ deps.log(` Warning: ${published.error}. Any earlier approval was left as it is.`);
6039
+ return { status: "failed", reason: published.error };
6040
+ }
6041
+ /**
6042
+ * BAPI-1638 — the answers path: the selection is the approved option ids.
6043
+ * A grant that already holds exactly these servers, for the same inventory, is
6044
+ * `unchanged` and is not rewritten.
6045
+ */
6046
+ async function publishApprovedGrant(deps, grantDeps, repoName, inventory, ids) {
6047
+ const names = inventory.candidates
6048
+ .filter((c) => c.definitions.some((d) => ids.includes(d.id)))
6049
+ .map((c) => c.name)
6050
+ .sort();
6051
+ try {
6052
+ const current = await grantDeps.readGrant(repoName);
6053
+ if (current.state === "ok" && current.grant.candidate_fingerprint === inventory.fingerprint) {
6054
+ const stored = current.grant.servers.map((server) => server.name).filter((name) => name !== "playwright" || names.includes(name)).sort();
6055
+ if (stored.length === names.length && stored.every((name, i) => name === names[i])) {
6056
+ deps.log(" unchanged — the stored approval already says this.");
6057
+ return { status: "unchanged" };
6058
+ }
6059
+ }
6060
+ }
6061
+ catch {
6062
+ // An unreadable grant is replaced through the same revalidated publication below.
6063
+ }
6064
+ deps.log(` Workers in ${repoName} would get: Bridge${names.length > 0 ? ` + ${names.join(", ")}` : " only"}.`);
6065
+ return publishGrant(deps, grantDeps, repoName, inventory, ids);
6066
+ }
6067
+ /**
6068
+ * Build the advisory capability statement from the grant and epic-server record
6069
+ * as they stand now, and PUT it. One warning on failure; never the verdict.
6070
+ */
6071
+ async function publishCapabilityStatement(deps, grantDeps, access, verbose) {
6072
+ try {
6073
+ const [grant, record] = await Promise.all([
6074
+ grantDeps.readGrant(access.repoName),
6075
+ grantDeps.readEpicServerRecord(access.repoName),
6076
+ ]);
6077
+ const statement = buildEpicCapabilityStatement(grant, record, grantDeps.now?.() ?? new Date());
6078
+ await grantDeps.writeStatement(access, statement);
6079
+ if (verbose)
6080
+ deps.log("Capability statement saved to Bridge (advisory; used by plan generation and workers).");
6081
+ return null;
6082
+ }
6083
+ catch {
6084
+ deps.log("Warning: the capability statement could not be saved to Bridge. Setup continues; plans and workers go without it.");
6085
+ return "the capability statement could not be saved to Bridge";
6086
+ }
6087
+ }
6088
+ // ---------------------------------------------------------------------------
6089
+ // BAPI-1546: the epic-server item
6090
+ // ---------------------------------------------------------------------------
6091
+ /** Read the record and map it to setup evidence. Read-only; never throws. */
6092
+ async function assessEpicServer(epicDeps, repoName) {
6093
+ let read;
6094
+ try {
6095
+ read = await epicDeps.readRecord(repoName);
6096
+ }
6097
+ catch {
6098
+ return { state: "unknown" };
6099
+ }
6100
+ if (read.state === "absent")
6101
+ return { state: "needs_action", reason: "no_record" };
6102
+ if (read.state === "unusable")
6103
+ return { state: "needs_action", reason: "unusable" };
6104
+ return { state: "met", mode: read.record.mode };
6105
+ }
6106
+ const EPIC_SERVER_MODE_ANSWERS = Object.freeze({
6107
+ "1": "none",
6108
+ none: "none",
6109
+ "": "none",
6110
+ "2": "local",
6111
+ local: "local",
6112
+ "3": "sfcc_shared_active",
6113
+ sfcc: "sfcc_shared_active",
6114
+ sfcc_shared_active: "sfcc_shared_active",
6115
+ });
6116
+ export async function fixEpicServer(deps, epicDeps, repoName, answer, snapshot = null) {
6117
+ deps.log("");
6118
+ deps.log("Epic server for UI checks");
6119
+ deps.log(` An Epic Implementer run in ${repoName} can get one epic server: the driver starts the epic's code with a ` +
6120
+ "throwaway test login, and workers borrow it in turns for browser tests and rendered-UI review. " +
6121
+ "SFCC repositories use one approved sandbox instead. Off by default; a missing server only hands UI checks off.");
6122
+ if (answer?.decision === "keep") {
6123
+ deps.log(" kept — nothing changed. Any earlier choice stays in force.");
6124
+ return { status: "declined" };
6125
+ }
6126
+ if (answer?.decision === "record") {
6127
+ // The apply summary prints these from the write's `reason`, so they appear once.
6128
+ const outcome = await writeApprovedEpicServer(deps, epicDeps, repoName, answer.record);
6129
+ return outcome.status === "failed" || answer.advisories === undefined ? outcome : { ...outcome, advisories: answer.advisories };
6130
+ }
6131
+ if (!deps.promptLine) {
6132
+ deps.log(" skipped configuring the epic server: there is no interactive terminal, so this counts as declined. Nothing changed.");
6133
+ return { status: "declined" };
6134
+ }
6135
+ let stored = null;
6136
+ try {
6137
+ const read = await epicDeps.readRecord(repoName);
6138
+ stored = read.state === "ok" ? read.record : null;
6139
+ }
6140
+ catch {
6141
+ stored = null;
6142
+ }
6143
+ const hasRecord = stored !== null;
6144
+ const existingSandbox = stored?.sfcc ?? null;
6145
+ const recommendation = recommendEpicServer(epicServerDecisionEvidence(stored?.mode ?? null, true, snapshot, existingSandbox !== null));
6146
+ const detected = snapshot?.detection?.detected === true;
6147
+ // The worker advisory prints once, in the sandbox follow-up, so it is left out of these two lines.
6148
+ const uploadText = detected && snapshot?.uploadCheck?.state !== "possible_with_advisory" ? describeSfccUpload(snapshot?.uploadCheck ?? { state: "unknown", missing: [] }) : "";
6149
+ const canAddSandbox = detected && isSfccUploadCapable(snapshot?.uploadCheck);
6150
+ const sandboxNext = canAddSandbox ? " You can approve a sandbox next, so cartridge changes upload in this mode too." : "";
6151
+ // A recommendation other than the safe default says why, and what is still owed, up front.
6152
+ if (!hasRecord && recommendation.recommended !== "none")
6153
+ deps.log(` Recommended: ${recommendation.recommended}. ${recommendation.why.replace(` ${WORKER_UPLOAD_ADVISORY}`, "")}`);
6154
+ const decision = await askPlainSetupQuestion({
6155
+ question: `Which epic server mode should Epic Implementer runs in ${repoName} use?`,
6156
+ options: [
6157
+ { 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.${sandboxNext}` },
6158
+ { 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.${sandboxNext}` },
6159
+ { id: "sfcc_shared_active", label: `sfcc_shared_active: one approved shared SFCC sandbox. Choose this for SFCC storefronts; you will name the sandbox next.${uploadText !== "" ? ` ${uploadText}` : ""}`, aliases: ["sfcc"] },
6160
+ {
6161
+ id: "keep",
6162
+ label: hasRecord
6163
+ ? "keep: keep the current choice and change nothing."
6164
+ : "keep: skip this and change nothing. No epic server is set up.",
6165
+ aliases: ["skip", "n", "no"],
6166
+ },
6167
+ ],
6168
+ recommended: recommendation.recommended,
6169
+ recordingFlag: "no flag records this choice; rerun setup in an interactive terminal.",
6170
+ 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."],
6171
+ consequences: [hasRecord
6172
+ ? "keep is recommended because a choice is already stored and pressing Enter should not replace it."
6173
+ : recommendation.recommended === "none"
6174
+ ? "none is recommended because it needs nothing set up and is the safe default."
6175
+ : `${recommendation.recommended} is recommended: ${recommendation.why}`,
6176
+ "Nothing changes if you stop here."],
6177
+ recovery: "Rerun setup to choose again. Any earlier choice stays in force until then.",
6178
+ }, plainTerminalFor(deps));
6179
+ const mode = decision.status === "selected" ? EPIC_SERVER_MODE_ANSWERS[decision.id] : undefined;
6180
+ if (mode === undefined) {
6181
+ deps.log(" No epic server mode was chosen. Nothing changed; re-run setup to try again.");
6182
+ return { status: "declined" };
6183
+ }
6184
+ const record = { version: 1, mode };
6185
+ if (mode === "local") {
6186
+ let present = false;
6187
+ try {
6188
+ present = await epicDeps.guidancePresent();
6189
+ }
6190
+ catch {
6191
+ present = false;
6192
+ }
6193
+ record.recipe = present ? "present" : "absent";
6194
+ }
6195
+ const sandbox = await askApprovedSandbox(deps, epicDeps, mode, existingSandbox, snapshot);
6196
+ if (sandbox === "declined")
6197
+ return { status: "declined" };
6198
+ if (sandbox !== null)
6199
+ record.sfcc = sandbox;
6200
+ return writeApprovedEpicServer(deps, epicDeps, repoName, record);
6201
+ }
6202
+ /**
6203
+ * BAPI-1667 — the sandbox follow-up, after the mode. `sfcc_shared_active` always asks
6204
+ * and needs all three fields. `local` and `none` ask when upload can work or a sandbox
6205
+ * is already recorded, and Enter keeps a recorded one or skips. A failed check is
6206
+ * never consent to drop a recorded sandbox. Returns the target to store, null for no
6207
+ * sandbox, or "declined" when an answer was unusable.
6208
+ */
6209
+ async function askApprovedSandbox(deps, epicDeps, mode, existing, snapshot) {
6210
+ const required = mode === "sfcc_shared_active";
6211
+ const detected = snapshot?.detection?.detected === true;
6212
+ if (!required && existing === null && !(detected && isSfccUploadCapable(snapshot?.uploadCheck)))
6213
+ return null;
6214
+ const promptLine = deps.promptLine;
6215
+ const credentials = snapshot?.credentials ?? null;
6216
+ deps.log(" Approved sandbox");
6217
+ deps.log(" Only non-secret values are asked for here. The sandbox account's secret stays in the credential store.");
6218
+ deps.log(" The id is the sandbox host's first DNS label (for example zzzz-001 in zzzz-001.dx.commercecloud.salesforce.com).");
6219
+ if (detected && snapshot?.uploadCheck?.state === "possible_with_advisory")
6220
+ deps.log(` ${WORKER_UPLOAD_ADVISORY}`);
6221
+ const idHint = existing !== null
6222
+ ? required ? ` [Enter keeps ${existing.sandbox_id}]` : ` [Enter keeps ${existing.sandbox_id}, "remove" drops it]`
6223
+ : required ? "" : " (Enter skips)";
6224
+ const typedId = (await promptLine(` Approved sandbox instance id${idHint}: `)).trim();
6225
+ if (!required && typedId === "") {
6226
+ if (existing !== null)
6227
+ return existing;
6228
+ deps.log(` ${SANDBOX_SKIPPED_LINE}`);
6229
+ return null;
6230
+ }
6231
+ if (!required && existing !== null && typedId === "remove") {
6232
+ deps.log(` ${SANDBOX_SKIPPED_LINE}`);
6233
+ return null;
6234
+ }
6235
+ const sandboxId = typedId === "" && existing !== null ? existing.sandbox_id : typedId;
6236
+ if (!isValidSfccSandboxId(sandboxId)) {
6237
+ deps.log(" That is not a usable sandbox id. Nothing changed; re-run setup to try again.");
6238
+ return "declined";
6239
+ }
6240
+ // After the prompt, never inside it: a mismatch advises and the id is stored as entered.
6241
+ if (typedId !== "" && detected && epicDeps.sfccUploadCheck !== undefined) {
6242
+ for (const line of await recheckSfccSandboxId(epicDeps.sfccUploadCheck, sandboxId, { credentials }))
6243
+ deps.log(` ${line}`);
6244
+ }
6245
+ const defaultRef = existing?.credential_ref ?? suggestedCredentialEntry(credentials);
6246
+ for (const line of credentialQuestionLines(credentials, defaultRef))
6247
+ deps.log(` ${line}`);
6248
+ const typedRef = (await promptLine(" Worker credential entry: ")).trim();
6249
+ const credentialRef = typedRef === "" ? defaultRef : typedRef;
6250
+ if (credentialRef === null && !required) {
6251
+ deps.log(` ${SANDBOX_SKIPPED_LINE}`);
6252
+ return null;
6253
+ }
6254
+ if (!isValidCredentialReference(credentialRef)) {
6255
+ deps.log(" That is not a usable credential reference. Nothing changed; re-run setup to try again.");
6256
+ return "declined";
6257
+ }
6258
+ // An absent or unusable record was already said once, above the question.
6259
+ if (credentials?.recordState === "ok") {
6260
+ for (const line of credentialReferenceAdvisories(credentials, credentialRef))
6261
+ deps.log(` ${line}`);
6262
+ }
6263
+ const sameSandbox = existing !== null && existing.sandbox_id === sandboxId;
6264
+ if (!required) {
6265
+ return {
6266
+ sandbox_id: sandboxId,
6267
+ credential_ref: credentialRef,
6268
+ ...(sameSandbox && existing.storefront_origin !== undefined ? { storefront_origin: existing.storefront_origin } : {}),
6269
+ };
6270
+ }
6271
+ const originDefault = sameSandbox ? existing.storefront_origin ?? null : null;
6272
+ const typedOrigin = (await promptLine(originDefault !== null
6273
+ ? ` Approved storefront origin [Enter keeps ${originDefault}]: `
6274
+ : " Approved storefront origin (for example https://sandbox.example.com): ")).trim();
6275
+ const origin = normalizeStorefrontOrigin(typedOrigin === "" && originDefault !== null ? originDefault : typedOrigin);
6276
+ if (origin === null) {
6277
+ deps.log(" That is not an http or https origin without a path, query, or credentials. Nothing changed.");
6278
+ return "declined";
6279
+ }
6280
+ return { sandbox_id: sandboxId, credential_ref: credentialRef, storefront_origin: origin };
6281
+ }
6282
+ /** Write one approved record through `writeEpicServerRecord`, after the no-change check. */
6283
+ async function writeApprovedEpicServer(deps, epicDeps, repoName, record) {
6284
+ try {
6285
+ const current = await epicDeps.readRecord(repoName);
6286
+ if (current.state === "ok" && sameEpicServerRecord(current.record, record)) {
6287
+ deps.log(" unchanged — the stored choice already says this.");
6288
+ return { status: "unchanged" };
6289
+ }
6290
+ }
6291
+ catch {
6292
+ /* an unreadable current record is simply replaced */
6293
+ }
6294
+ let written;
6295
+ try {
6296
+ written = await epicDeps.writeRecord(repoName, record);
6297
+ }
6298
+ catch {
6299
+ written = { ok: false, error: "the epic-server record could not be written" };
6300
+ }
6301
+ if (!written.ok) {
6302
+ deps.log(` Warning: ${written.error}. Any earlier choice was left as it is.`);
6303
+ return { status: "failed", reason: written.error };
6304
+ }
6305
+ deps.log(` saved — epic server mode ${record.mode}, stored outside every worktree. The driver reads it at run start.`);
6306
+ return { status: "written" };
6307
+ }
3470
6308
  /** Short previews of each fix for --dry-run. */
3471
6309
  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
6310
  setup_pr: "open the setup pull request with the CI workflow (its own consent)",
3476
6311
  gate_and_defaults: "store the repository gate and the safe supervisor defaults (its own consent)",
3477
6312
  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",
6313
+ mcp_grant: "approve which extra MCP servers Epic Implementer workers get in this repository (one consent; the grant is stored outside every worktree)",
6314
+ 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)",
6315
+ 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
6316
  });
3480
6317
  /**
3481
6318
  * The claude-review workflow, only for an explicit `--review-policy