@bridge_gpt/mcp-server 0.2.71 → 0.2.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +22 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +7 -7
  5. package/build/bridge-permissions.js +31 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/ci-system-detection.js +50 -0
  9. package/build/ci-trigger-adapters.js +631 -0
  10. package/build/ci-trigger-install.js +106 -0
  11. package/build/claude-review-workflow.js +1 -1
  12. package/build/cli-help.js +6 -0
  13. package/build/codex-auto-recovery.js +126 -0
  14. package/build/codex-launcher-pin.js +33 -2
  15. package/build/codex-skill-adapter.js +5 -1
  16. package/build/command-host.js +33 -0
  17. package/build/commands.generated.js +7 -6
  18. package/build/conductor/bridge-api-client.js +1352 -50
  19. package/build/conductor/bring-up-facts.js +18 -5
  20. package/build/conductor/command-drift-production.js +42 -17
  21. package/build/conductor/command-drift.js +47 -0
  22. package/build/conductor/declare-blocked.js +554 -0
  23. package/build/conductor/doctor.js +187 -28
  24. package/build/conductor/driver-commands.js +141 -0
  25. package/build/conductor/driver-guard.js +277 -0
  26. package/build/conductor/driver-lapse.js +321 -0
  27. package/build/conductor/driver-register.js +176 -0
  28. package/build/conductor/driver-release.js +174 -0
  29. package/build/conductor/driver-session-state.js +315 -0
  30. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  31. package/build/conductor/epic-implementer-cli.js +213 -13
  32. package/build/conductor/epic-server-database.js +162 -0
  33. package/build/conductor/epic-server-guidance.js +278 -0
  34. package/build/conductor/epic-server-journal.js +239 -0
  35. package/build/conductor/epic-server-processes.js +324 -0
  36. package/build/conductor/epic-server-recipe.js +397 -0
  37. package/build/conductor/epic-server-runtime.js +1207 -0
  38. package/build/conductor/epic-server-sfcc.js +107 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +594 -0
  41. package/build/conductor/gate-discovery.js +281 -10
  42. package/build/conductor/gate-settings-review.js +525 -5
  43. package/build/conductor/git-hooks-uninstall.js +112 -0
  44. package/build/conductor/git-hooks.js +81 -15
  45. package/build/conductor/guided-repair.js +10 -1
  46. package/build/conductor/install-doctor.js +2 -4
  47. package/build/conductor/launch-need-probes.js +6 -53
  48. package/build/conductor/launch-plan.js +318 -121
  49. package/build/conductor/local-merge.js +12 -1
  50. package/build/conductor/merge-execution-contract.js +1 -1
  51. package/build/conductor/merged-child-check.js +2 -1
  52. package/build/conductor/prerequisite-inputs.js +1213 -0
  53. package/build/conductor/readiness-assessment.js +93 -0
  54. package/build/conductor/readiness-cli.js +30 -9
  55. package/build/conductor/readiness-prerequisites.js +77 -5
  56. package/build/conductor/readiness-sections.js +146 -126
  57. package/build/conductor/readiness.js +21 -3
  58. package/build/conductor/recovery-cli.js +236 -15
  59. package/build/conductor/recovery-operations.js +34 -4
  60. package/build/conductor/repair-contract.js +33 -0
  61. package/build/conductor/tools.js +36 -4
  62. package/build/conductor/wait-run-attention.js +115 -0
  63. package/build/conductor/wait-run-cli.js +300 -21
  64. package/build/conductor/worker-database-doctor-inspector.js +34 -2
  65. package/build/conductor/worker-setup-tally.js +27 -0
  66. package/build/credential-store.js +96 -21
  67. package/build/dependency-install-declarations.js +212 -0
  68. package/build/docs.generated.js +4 -4
  69. package/build/doctor.js +91 -8
  70. package/build/drive-epic-help.js +23 -4
  71. package/build/drive-epic.js +1841 -340
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +140 -0
  74. package/build/epic-capability-statement.js +107 -0
  75. package/build/epic-ci-workflow-drift.js +30 -15
  76. package/build/epic-ci-workflow-install.js +110 -42
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow.js +38 -12
  79. package/build/epic-implementer-bin.js +2184 -52
  80. package/build/epic-launch-context.js +607 -0
  81. package/build/epic-launch-profile.js +1 -1
  82. package/build/epic-server-record.js +273 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/cli.js +2 -0
  87. package/build/executor/completion-contract.js +24 -1
  88. package/build/executor/credentials.js +1 -1
  89. package/build/executor/delivery-observations.js +113 -0
  90. package/build/executor/delivery-outcome.js +30 -0
  91. package/build/executor/dependency-refresh-runner.js +132 -0
  92. package/build/executor/dependency-refresh.js +530 -0
  93. package/build/executor/deps.js +4 -0
  94. package/build/executor/env.js +119 -17
  95. package/build/executor/epic-server-context.js +141 -0
  96. package/build/executor/gate-qualification-job.js +127 -26
  97. package/build/executor/harness-coverage.js +19 -0
  98. package/build/executor/http-client.js +87 -6
  99. package/build/executor/index.js +2 -1
  100. package/build/executor/install-preflight.js +1 -1
  101. package/build/executor/job-runner.js +659 -87
  102. package/build/executor/likely-tests.js +94 -97
  103. package/build/executor/observation.js +8 -0
  104. package/build/executor/pre-pr-checks.js +363 -0
  105. package/build/executor/prompt-spec.js +127 -5
  106. package/build/executor/reconcile-overlap-job.js +5 -3
  107. package/build/executor/required-verification.js +28 -0
  108. package/build/executor/required-work-diagnostics.js +32 -0
  109. package/build/executor/required-work-ledger.js +955 -39
  110. package/build/executor/results.js +100 -0
  111. package/build/executor/service-discovery.js +42 -0
  112. package/build/executor/service-lifecycle.js +109 -2
  113. package/build/executor/service-uninstall.js +205 -0
  114. package/build/executor/service-unit.js +5 -3
  115. package/build/executor/terminal-mutation.js +8 -0
  116. package/build/executor/test-clock.js +3 -0
  117. package/build/executor/verification-hints.js +179 -0
  118. package/build/executor/worker-command.js +126 -5
  119. package/build/executor/worker-database-config.js +281 -0
  120. package/build/executor/worker-database-target.js +16 -12
  121. package/build/executor/worker-database.js +575 -116
  122. package/build/executor/worker-finalization.js +71 -10
  123. package/build/executor/worker-guard-hook.js +10 -2
  124. package/build/executor/worker-resources.js +25 -3
  125. package/build/executor/worker-verification-guidance.js +55 -5
  126. package/build/executor/worktree-inspection.js +42 -0
  127. package/build/executor/worktree.js +20 -1
  128. package/build/executor-launch.js +54 -2
  129. package/build/generated-assets-catalog.js +2 -2
  130. package/build/github-sign-in.js +1 -1
  131. package/build/index.js +1111 -381
  132. package/build/init.js +29 -14
  133. package/build/install-bridge-conductor-answers.js +465 -0
  134. package/build/install-bridge-conductor-apply.js +259 -0
  135. package/build/install-bridge-conductor-assessment.js +895 -0
  136. package/build/install-bridge-conductor-compact.js +161 -0
  137. package/build/install-bridge-conductor-contracts.js +63 -0
  138. package/build/install-bridge-conductor-gate.js +1383 -188
  139. package/build/install-bridge-conductor-setup.js +637 -92
  140. package/build/install-bridge-conductor.js +3163 -740
  141. package/build/install-bridge.js +601 -128
  142. package/build/install-maintenance.js +127 -0
  143. package/build/install-reexec.js +1 -1
  144. package/build/launcher-config-inspection.js +162 -1
  145. package/build/local-cleanup.js +59 -0
  146. package/build/mcp-grant-candidates.js +767 -0
  147. package/build/mcp-grant-doctor.js +63 -0
  148. package/build/mcp-grant.js +288 -0
  149. package/build/mcp-host-targets.js +8 -0
  150. package/build/mcp-identity.js +23 -0
  151. package/build/mcp-install-state.js +68 -2
  152. package/build/mcp-invoke.js +126 -13
  153. package/build/mcp-presets.js +107 -0
  154. package/build/mcp-provisioning.js +134 -2
  155. package/build/mcp-registration-doctor.js +31 -2
  156. package/build/mcp-server-invocation.js +6 -1
  157. package/build/merge-workflow-install.js +236 -111
  158. package/build/package-script-semantics.js +10 -0
  159. package/build/pipeline-utils.js +1 -1
  160. package/build/pipelines.generated.js +6 -6
  161. package/build/plan-discovery.js +97 -4
  162. package/build/plan-execution-ledger.js +248 -9
  163. package/build/plan-generation-io.js +262 -0
  164. package/build/plan-generation.js +424 -0
  165. package/build/plane/build-freshness.js +6 -1
  166. package/build/plane/cli.js +75 -9
  167. package/build/plane/plane-freshness.js +23 -7
  168. package/build/plane/preflight.js +50 -10
  169. package/build/plane/shutdown.js +19 -0
  170. package/build/plane/terminal-run-cleanup.js +23 -5
  171. package/build/plane/terminal-run-status.js +4 -0
  172. package/build/printed-remedy-commands.js +229 -15
  173. package/build/readiness-check.js +1 -1
  174. package/build/readiness-prerequisites.generated.js +311 -4
  175. package/build/readme.generated.js +1 -1
  176. package/build/repository-state-paths.js +38 -0
  177. package/build/repository-toolchains.js +50 -8
  178. package/build/run-unit-tests-launcher.js +8 -1
  179. package/build/setup-change-policy.js +32 -0
  180. package/build/setup-epic.js +1192 -198
  181. package/build/setup-progress.js +44 -0
  182. package/build/setup-question.js +180 -0
  183. package/build/start-tickets.js +4 -0
  184. package/build/test-command-detection.js +32 -88
  185. package/build/test-support/notes-fs.js +40 -0
  186. package/build/third-party-mcp-targets.js +30 -0
  187. package/build/ticket-delivery-enrollment.js +30 -8
  188. package/build/ticket-delivery-run-scope.js +128 -0
  189. package/build/upgrade-cli.js +85 -2
  190. package/build/v2-readiness-requirements.js +28 -1
  191. package/build/version.generated.js +3 -3
  192. package/build/worker-guard-hook-bin.js +2 -2
  193. package/build/worktrees.js +105 -0
  194. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  195. package/docs/EPIC-IMPLEMENTER.md +5 -0
  196. package/docs/epic-implementer/getting-started.md +42 -15
  197. package/docs/epic-implementer/self-hosting.md +14 -1
  198. package/package.json +2 -2
@@ -1,3 +1,7 @@
1
+ import { readMcpInstallState } from "./mcp-install-state.js";
2
+ import { askSetupQuestion } from "./setup-question.js";
3
+ import { bindEpicLaunchCredential, normalizeBoundBaseUrl, readStoredBindingState, resolveEpicLaunchCredential } from "./credential-store.js";
4
+ import { settleMaintenanceCredential, authorizeMaintenanceEffect } from "./install-maintenance.js";
1
5
  import { validateBootstrapDisplayName, validateBootstrapServerIdentity } from "./bootstrap-project-identity.js";
2
6
  import { BRIDGE_SUPPORT_EMAIL, archiveAndReplaceModernBootstrapSignup, archiveExpiredLegacySignupAndInstallModern, lookupModernBootstrapRecord, mutateModernBootstrapRecord, prepareModernBootstrapInvite, prepareModernBootstrapSignup, transitionModernBootstrapSignup, lookupLegacyBootstrapInvite, checkpointModernBootstrapIdentity, promoteModernBootstrapCredential } from "./credential-store.js";
3
7
  import { collectFirstBuildAdvisory, formatFirstBuildAdvisory } from "./first-build-advisory.js";
@@ -140,22 +144,30 @@ import { collectFirstBuildAdvisory, formatFirstBuildAdvisory } from "./first-bui
140
144
  * 0600, fsync'd pending record as the `key_secret`, purely so the signup can be
141
145
  * replayed, and it is discarded when that record is promoted.
142
146
  */
143
- import { readFile, writeFile, mkdir, stat, rename, chmod, unlink, open, realpath } from "fs/promises";
147
+ import { readFile, writeFile, mkdir, stat, lstat, rename, chmod, unlink, open, realpath } from "fs/promises";
144
148
  import { spawn } from "child_process";
145
149
  import { randomBytes as cryptoRandomBytes, createHash } from "crypto";
146
150
  import os from "os";
147
151
  import path from "path";
152
+ import { discoverMcpGrantCandidates, publishMcpGrant } from "./mcp-grant-candidates.js";
153
+ import { readMcpGrant } from "./mcp-grant.js";
154
+ import { readEpicServerRecord, writeEpicServerRecord } from "./epic-server-record.js";
155
+ import { readEpicServerGuidance } from "./conductor/epic-server-guidance.js";
156
+ import { writeEpicCapabilityStatement } from "./conductor/bridge-api-client.js";
148
157
  import { detectClaudeLogin } from "./claude-login.js";
149
158
  import { checkGithubSignIn } from "./github-sign-in.js";
150
159
  import { readLocalGithubRemote } from "./conductor/stored-merge-credential.js";
151
160
  import { probeStoredMergeToken } from "./conductor/stored-merge-token-probe.js";
152
161
  import { readGithubMergeCredential, removeGithubMergeCredential, upsertGithubMergeCredential, } from "./credential-store.js";
153
162
  import { createBridgeApiUrls } from "./bridge-api-urls.js";
163
+ import { installCiTriggerEdit } from "./ci-trigger-install.js";
154
164
  import { installEpicCiWorkflow } from "./epic-ci-workflow-install.js";
155
- import { fetchParseStatus, triggerRepositoryParse, } from "./conductor/bridge-api-client.js";
165
+ import { fetchParseStatus, fetchSetupRecoveryEvidence, correctSetupBranch, admitSetupRecovery, } from "./conductor/bridge-api-client.js";
156
166
  import readline from "readline";
157
167
  import { runInit, InitPreflightError, buildBridgeApiEntry, buildBridgeConfigManifest, mergeBridgeApiProfileToken, resolveInitScaffoldAssets, refreshBridgeApiPackageSpec, currentBridgePackageSpec, classifyTrackedProbeExitCode, decideExistingProjectRoot, formatUndeterminedRootReplacedWarning, } from "./init.js";
158
168
  import { hasProjectRootMarker as sharedHasProjectRootMarker } from "./project-root.js";
169
+ import { resolveDocsDirForRoot } from "./project-root.js";
170
+ import { createSetupRecordWriter } from "./install-bridge-conductor-apply.js";
159
171
  import { VERSION } from "./version.generated.js";
160
172
  import { bridgeConfigPath, parseBridgeConfigToml, rewriteBridgeConfigRepoName, validateBridgeConfigRepoNameRepresentability, validateRepoName, } from "./bridge-config.js";
161
173
  import { renderDiagnosticValue } from "./diagnostic-text.js";
@@ -163,7 +175,9 @@ import { MCP_HOST_TARGETS, HOST_PLATFORM_ORDER, allHostTargets, agentForPlatform
163
175
  import { provisionHostTarget, createDefaultVendorProcessDeps, inspectBridgeApiProfileToken, } from "./mcp-host-config.js";
164
176
  import { adaptBridgeEntryForHostTarget, } from "./mcp-host-entry-adapter.js";
165
177
  import { MCP_SERVER_NAME, MCP_PACKAGE_NAME, resolveRegistrationKey, } from "./mcp-identity.js";
166
- import { DUPLICATE_REGISTRATION_GUIDANCE, discoverClaudeCodeEffectivePin } from "./launcher-config-inspection.js";
178
+ import { detectEffectiveBridgeDestination, DUPLICATE_REGISTRATION_GUIDANCE, discoverClaudeCodeEffectivePin } from "./launcher-config-inspection.js";
179
+ import { createCommandDriftInspector } from "./conductor/command-drift-production.js";
180
+ import { localBuildSetupLauncher } from "./install-bridge-conductor-setup.js";
167
181
  import { codexHome, configureBridgeCodexProfile, inspectBridgeCodexProfile } from "./codex-bridge-profile.js";
168
182
  import { recordInstalledConductorCapability, recordInstalledExecutorServiceUnit, recordInstalledProjectArtifact, writeMcpInstallState, } from "./mcp-install-state.js";
169
183
  // BAPI-1207: opt-in cross-platform agent notes (AGENTS.md / CLAUDE.md).
@@ -178,14 +192,14 @@ import { inspectExecutorServiceDurability, inspectExecutorServiceState, startExe
178
192
  import { executorLaunchdLabelForId, executorSystemdUnitNameForId, executorLaunchdPlistPathForId, executorSystemdUnitPathForId, resolvePackagedExecutorInvocation, writeExecutorServicePlan, EXECUTOR_SERVICE_UNIT_FILE_MODE, } from "./executor/service-unit.js";
179
193
  import { collectConductorNativeLedgerSafe, } from "./conductor/doctor.js";
180
194
  import { installConductorGitHooks, } from "./conductor/git-hooks.js";
181
- import { runInstallBridgeConductorCli, } from "./install-bridge-conductor.js";
195
+ import { runInstallBridgeConductorCli, parseInstallBridgeConductorArgs, } from "./install-bridge-conductor.js";
182
196
  import { createQualificationExecutorRunner, } from "./install-bridge-conductor-gate.js";
183
197
  import { createNodeGateDiscoveryFs } from "./conductor/gate-discovery.js";
184
198
  import { runExecutorCli } from "./executor/cli.js";
185
199
  import { runExecutor } from "./executor/runner.js";
186
200
  // BAPI-1136: the merge-workflow generate-and-PR installer. Domain logic lives in
187
201
  // its own module; this file supplies the parser and the process seams.
188
- import { parseGithubRemote, runMergeWorkflowInstall, } from "./merge-workflow-install.js";
202
+ import { captureDefaultBranchSnapshot, parseGithubRemote, readSnapshotFile, runMergeWorkflowInstall, } from "./merge-workflow-install.js";
189
203
  import { MERGE_WORKFLOW_CODEOWNER_INSTRUCTION, MERGE_WORKFLOW_REMEDY_COMMAND, } from "./conductor/merge-execution-contract.js";
190
204
  import { MERGE_WORKFLOW_API_KEY_SECRET_NAME, } from "./merge-workflow-config.js";
191
205
  import { runConductorInstallDoctor, EPIC_IMPLEMENTER_PROFILE_TOKEN, } from "./conductor/install-doctor.js";
@@ -588,7 +602,7 @@ export function getInstallBridgeUsage(baseUrl = DEFAULT_BAPI_BASE_URL) {
588
602
  " -h, --help Show this help.",
589
603
  "",
590
604
  "Subcommands:",
591
- " install conductor Bootstrap the Epic Implementer for this repository",
605
+ " install epic-implementer Bootstrap the Epic Implementer for this repository",
592
606
  " (BAPI-679). Runs a unified READ-ONLY doctor that",
593
607
  " composes the conductor, executor-preflight,",
594
608
  " install-status, and executor service-unit",
@@ -623,9 +637,9 @@ export function getInstallBridgeUsage(baseUrl = DEFAULT_BAPI_BASE_URL) {
623
637
  " operator-managed, so a run reports",
624
638
  " `complete-with-manual-steps` until a live",
625
639
  " executor is actually observed. See",
626
- " `install conductor --help`.",
640
+ " `install epic-implementer --help`.",
627
641
  "",
628
- " install conductor --merge-workflow --codeowner <@org/team|@user>",
642
+ " install epic-implementer --merge-workflow --codeowner <@org/team|@user>",
629
643
  " Generate the Epic Implementer merge workflow",
630
644
  " plus its CODEOWNERS fragment and repository-rule",
631
645
  " guidance, commit them on a managed branch, push",
@@ -1281,6 +1295,8 @@ export function buildInstallBridgeDefaultsSummary(input) {
1281
1295
  * as `install`'s missing-project-root confirmation (BAPI-818, R1).
1282
1296
  */
1283
1297
  export function promptLineViaReadline(promptText, input = process.stdin, output = process.stderr) {
1298
+ if (input === process.stdin && !process.stdin.isTTY)
1299
+ return Promise.resolve("");
1284
1300
  return new Promise((resolve) => {
1285
1301
  const rl = readline.createInterface({ input, output });
1286
1302
  // See promptSecretViaReadline: EOF must resolve rather than deadlock the
@@ -1389,6 +1405,7 @@ export function createDefaultInstallBridgeDeps() {
1389
1405
  // fetch when the caller did not override the resolver — see below.)
1390
1406
  const productionFetch = (...args) => fetch(...args);
1391
1407
  return {
1408
+ notesFs: { realpath, lstat, readBytes: (p) => readFile(p), open, unlink },
1392
1409
  env: process.env,
1393
1410
  cwd: process.cwd(),
1394
1411
  realpath: async (folder) => realpath(folder),
@@ -1441,12 +1458,14 @@ export function createDefaultInstallBridgeDeps() {
1441
1458
  if (process.env.BAPI_INSTALL_DEBUG)
1442
1459
  console.error(m);
1443
1460
  },
1444
- // ---- Nested `install-bridge conductor` seams (BAPI-679) ----
1461
+ // ---- Nested `install epic-implementer` seams (BAPI-679) ----
1445
1462
  conductorRunDoctor: (params) => runConductorInstallDoctor({
1446
1463
  access: params.access,
1447
1464
  accessError: params.accessError,
1448
1465
  fetch: params.fetch,
1449
1466
  reviewPolicySource: params.reviewPolicySource,
1467
+ assessmentVersion: params.assessmentVersion,
1468
+ epicRunId: params.epicRunId,
1450
1469
  readWorkflowFile: () => params.readFile(claudeReviewWorkflowPath(params.cwd)),
1451
1470
  // BAPI-941: read-only workflow-lineage classification. Runs only after
1452
1471
  // the file is confirmed present, uses the same command runner the rest
@@ -1654,7 +1673,7 @@ export function getMergeWorkflowInstallUsage() {
1654
1673
  * prompt can never hang an install. The resulting environment is never printed.
1655
1674
  */
1656
1675
  /**
1657
- * BAPI-1461 — the production seams for the converging `install conductor`.
1676
+ * BAPI-1461 — the production seams for the converging `install epic-implementer`.
1658
1677
  *
1659
1678
  * Each one is a thin adapter over an implementation that already exists: the
1660
1679
  * Claude login reader, one bounded `gh auth status`, the credential store's
@@ -1665,6 +1684,29 @@ export function getMergeWorkflowInstallUsage() {
1665
1684
  export function buildConductorSetupDeps(deps, log, errorLog) {
1666
1685
  const installerDeps = buildMergeWorkflowInstallDeps(deps, log, errorLog);
1667
1686
  const storeDeps = modernWriteDeps(deps);
1687
+ // BAPI-1636: one read-only discovery, used at assessment AND again at
1688
+ // publication, so the binding, every source config, the existing grant, and
1689
+ // local package identity are re-read just before anything is staged. A
1690
+ // conflicting or malformed destination is not a setup failure: its evidence
1691
+ // only makes the classifier exclude more.
1692
+ const discoverGrantCandidates = async (repoName) => {
1693
+ const binding = await readStoredBindingState(`bapi:${repoName}`, installerCredentialReadDeps(deps));
1694
+ const destination = detectEffectiveBridgeDestination({
1695
+ envBaseUrl: deps.env.BAPI_BASE_URL,
1696
+ binding,
1697
+ productionBaseUrl: DEFAULT_BAPI_BASE_URL,
1698
+ });
1699
+ return discoverMcpGrantCandidates({
1700
+ homedir: deps.homedir,
1701
+ platform: deps.platform,
1702
+ readFile: deps.readFile,
1703
+ cwd: deps.cwd,
1704
+ repoName,
1705
+ productionBaseUrl: DEFAULT_BAPI_BASE_URL,
1706
+ destination: destination.evidence,
1707
+ readGrant: () => readMcpGrant(repoName, { env: deps.env, homedir: deps.homedir, readFile: deps.readFile }),
1708
+ });
1709
+ };
1668
1710
  return {
1669
1711
  detectClaudeLogin: () => detectClaudeLogin({ homedir: deps.homedir, readFile: deps.readFile }),
1670
1712
  // An injected installer runner (tests) is used for these reads too, so a
@@ -1690,15 +1732,85 @@ export function buildConductorSetupDeps(deps, log, errorLog) {
1690
1732
  getGetHeaders: async () => ({ "X-API-Key": access.apiKey }),
1691
1733
  getPostHeaders: async () => ({ "X-API-Key": access.apiKey, "Content-Type": "application/json" }),
1692
1734
  }),
1735
+ // The person's working tree: optional test-command hints for the server only.
1693
1736
  readRepositoryFile: (relPath) => deps.readFile(path.join(deps.cwd, relPath)),
1694
- installCiWorkflow: (testCommand, toolchains, options, confirmWrite) => installEpicCiWorkflow(testCommand, toolchains, { dryRun: options.dryRun }, {
1737
+ // BAPI-1603: everything the workflow is built from comes from the remote
1738
+ // default branch. One quiet capture, one immutable head, bounded read-only reads at it.
1739
+ captureDefaultBranch: async () => {
1740
+ const captured = await captureDefaultBranchSnapshot({ ...installerDeps, log: () => { }, errorLog: () => { } });
1741
+ return captured.ok ? captured.snapshot : null;
1742
+ },
1743
+ readSnapshotFile: (snapshot, relPath) => readSnapshotFile(installerDeps, snapshot, relPath),
1744
+ installCiWorkflow: (testCommand, toolchains, options, confirmWrite) => installEpicCiWorkflow(testCommand, toolchains, {
1745
+ dryRun: options.dryRun,
1746
+ ...(options.snapshot !== undefined ? { snapshot: options.snapshot } : {}),
1747
+ ...(options.createOnly === true ? { createOnly: true } : {}),
1748
+ }, {
1695
1749
  ...installerDeps,
1696
1750
  ...(options.quiet === true ? { log: () => { }, errorLog: () => { } } : {}),
1697
1751
  confirmWrite,
1698
1752
  }),
1753
+ // BAPI-1654: the CI-only pull request for an approved trigger edit, through the same engine.
1754
+ installCiTriggerEdit: (edit, options, confirmWrite) => installCiTriggerEdit(edit, { dryRun: options.dryRun, ...(options.snapshot !== undefined ? { snapshot: options.snapshot } : {}) }, { ...installerDeps, confirmWrite }),
1699
1755
  runGh: installerDeps.runGh,
1756
+ // BAPI-1635: committed command, agent, and host-mirror drift, read-only (the probe
1757
+ // `doctor` and `readiness` already use, now over the installer's rendered asset catalog).
1758
+ inspectCommandDrift: createCommandDriftInspector({ env: deps.env, cwd: deps.cwd, fetch: deps.fetch }),
1759
+ // BAPI-1635: the local-build command form is chosen only from the same effective
1760
+ // destination detection the MCP grant uses (kind `local`) AND a validated local-build
1761
+ // entry. Anything else, including a conflict or malformed destination, prints the npm form.
1762
+ detectLauncher: async (repoName) => {
1763
+ const entry = process.argv[1];
1764
+ if (typeof entry !== "string")
1765
+ return null;
1766
+ const binding = await readStoredBindingState(`bapi:${repoName}`, installerCredentialReadDeps(deps));
1767
+ const destination = detectEffectiveBridgeDestination({
1768
+ envBaseUrl: deps.env.BAPI_BASE_URL,
1769
+ binding,
1770
+ productionBaseUrl: DEFAULT_BAPI_BASE_URL,
1771
+ });
1772
+ return destination.state === "resolved" && destination.kind === "local" ? localBuildSetupLauncher(entry) : null;
1773
+ },
1700
1774
  fetchParseStatus: (access) => fetchParseStatus(access, deps.fetch),
1701
- triggerParse: (access) => triggerRepositoryParse(access, deps.fetch),
1775
+ fetchRecoveryEvidence: (access, pr) => fetchSetupRecoveryEvidence(access, pr, deps.fetch),
1776
+ correctBranch: (access, expected, destination) => correctSetupBranch(access, expected, destination, deps.fetch),
1777
+ admitRecovery: (access, evidence, retry) => admitSetupRecovery(access, evidence, retry, deps.fetch),
1778
+ // BAPI-1545: the worker MCP grant and the advisory capability statement.
1779
+ mcpGrant: {
1780
+ discover: (repoName) => discoverGrantCandidates(repoName),
1781
+ readGrant: (repoName) => readMcpGrant(repoName, { env: deps.env, homedir: deps.homedir, readFile: deps.readFile }),
1782
+ readEpicServerRecord: (repoName) => readEpicServerRecord(repoName, { env: deps.env, homedir: deps.homedir, readFile: deps.readFile }),
1783
+ publish: (repoName, inventory, selectedIds, now) => publishMcpGrant(repoName, inventory, selectedIds, now, {
1784
+ rediscover: () => discoverGrantCandidates(repoName),
1785
+ credentialStore: storeDeps,
1786
+ grant: {
1787
+ env: deps.env,
1788
+ homedir: deps.homedir,
1789
+ platform: deps.platform,
1790
+ mkdir: deps.mkdir,
1791
+ chmod: deps.chmod,
1792
+ rename: deps.rename,
1793
+ open: deps.open,
1794
+ unlink: deps.unlink,
1795
+ },
1796
+ }),
1797
+ writeStatement: (access, statement) => writeEpicCapabilityStatement(access, statement, deps.fetch),
1798
+ },
1799
+ // BAPI-1546: the epic-server opt-in, its own record outside every worktree.
1800
+ epicServer: {
1801
+ readRecord: (repoName) => readEpicServerRecord(repoName, { env: deps.env, homedir: deps.homedir, readFile: deps.readFile }),
1802
+ writeRecord: (repoName, record) => writeEpicServerRecord(repoName, record, {
1803
+ env: deps.env,
1804
+ homedir: deps.homedir,
1805
+ platform: deps.platform,
1806
+ mkdir: deps.mkdir,
1807
+ chmod: deps.chmod,
1808
+ rename: deps.rename,
1809
+ open: deps.open,
1810
+ unlink: deps.unlink,
1811
+ }),
1812
+ guidancePresent: async () => (await readEpicServerGuidance((rel) => deps.readFile(path.join(deps.cwd, rel)))).state === "ok",
1813
+ },
1702
1814
  };
1703
1815
  }
1704
1816
  export function buildMergeWorkflowInstallDeps(deps, log, errorLog) {
@@ -2051,6 +2163,80 @@ export const INSTALL_REEXEC_KEY_SOURCE_FLAG = "flag";
2051
2163
  * function itself performs no classification; it only resolves which raw string
2052
2164
  * was entered.
2053
2165
  */
2166
+ function installerCredentialReadDeps(deps) {
2167
+ return { env: deps.env, homedir: deps.homedir, platform: deps.platform,
2168
+ readFile: deps.readFile, stat: async (p) => await deps.stat(p), stderr: deps.errorLog };
2169
+ }
2170
+ /**
2171
+ * BAPI-1650: for a dry run only, decide whether the credential resolver's result
2172
+ * means the owner has not yet approved a saved key for a non-production address.
2173
+ *
2174
+ * It runs after the one existing resolver call and reads only the stored binding
2175
+ * state, which holds an endpoint and no key. It never resolves a credential again,
2176
+ * compares key values, makes a network call, asks for consent, or writes. Only a
2177
+ * proven `absent` binding, or one bound to a different endpoint, counts; `invalid`,
2178
+ * `unreadable`, `no-entry`, and a binding that matches the target keep their
2179
+ * existing behavior. The metadata is built field by field, never spread.
2180
+ */
2181
+ async function classifyEndpointApproval(repoName, target, credential, readDeps) {
2182
+ const normalized = normalizeBoundBaseUrl(target);
2183
+ if (normalized === null || normalized === normalizeBoundBaseUrl(DEFAULT_BAPI_BASE_URL))
2184
+ return undefined;
2185
+ let kind;
2186
+ if (credential.ok) {
2187
+ if (credential.binding !== "env-paired")
2188
+ return undefined;
2189
+ kind = "env-paired";
2190
+ }
2191
+ else if (credential.kind === "binding-unbound" || credential.kind === "binding-mismatch") {
2192
+ kind = credential.kind;
2193
+ }
2194
+ else {
2195
+ return undefined;
2196
+ }
2197
+ const state = await readStoredBindingState(`bapi:${repoName}`, readDeps);
2198
+ if (state.state === "absent" || (state.state === "bound" && state.baseUrl !== normalized)) {
2199
+ return { needed: true, repoName, target: normalized, kind };
2200
+ }
2201
+ return undefined;
2202
+ }
2203
+ /** Project identity evidence is read before onboarding; folder names are never identity. */
2204
+ export async function observeInstalledIdentity(deps) {
2205
+ const candidates = [];
2206
+ try {
2207
+ const parsed = parseBridgeConfigToml(await deps.readFile(bridgeConfigPath(deps.cwd)));
2208
+ if (!parsed.ok)
2209
+ return { status: "unavailable" };
2210
+ candidates.push({ repo: parsed.manifest.repoName, source: ".bridge/config" });
2211
+ }
2212
+ catch (err) {
2213
+ if (!err || typeof err !== "object" || !("code" in err) || err.code !== "ENOENT")
2214
+ return { status: "unavailable" };
2215
+ }
2216
+ for (const target of hostConfigTargetsForPlatforms(["claude-code", "cursor", "copilot-vscode"])) {
2217
+ const result = await readHostConfig(deps, path.join(deps.cwd, target.relPath));
2218
+ if (result.state === "invalid")
2219
+ return { status: "unavailable" };
2220
+ if (result.state === "absent")
2221
+ continue;
2222
+ const top = asRecord(result.config[target.topLevelKey]);
2223
+ const registration = resolveRegistrationKey(top);
2224
+ if (registration.state === "conflict")
2225
+ return { status: "unavailable" };
2226
+ if (registration.state !== "absent") {
2227
+ const env = asRecord(asRecord(top?.[registration.key])?.env);
2228
+ const repo = env?.BAPI_REPO_NAME;
2229
+ if (typeof repo === "string" && repo.trim() && !repo.includes("<"))
2230
+ candidates.push({ repo: repo.trim(), source: target.relPath });
2231
+ }
2232
+ }
2233
+ const names = new Set(candidates.map(c => c.repo));
2234
+ if (!names.size)
2235
+ return { status: "absent" };
2236
+ if (names.size > 1)
2237
+ return { status: "conflicting", candidates };
2238
+ return { status: "resolved", repo: candidates[0].repo, sources: candidates.map(c => c.source) };
2239
+ }
2054
2240
  export async function resolveApiKey(options, deps) {
2055
2241
  if (typeof options.apiKey === "string" && options.apiKey.trim().length > 0) {
2056
2242
  return { ok: true, value: options.apiKey.trim(), source: "flag" };
@@ -2066,6 +2252,14 @@ export async function resolveApiKey(options, deps) {
2066
2252
  : "env";
2067
2253
  return { ok: true, value: fromEnv.trim(), source };
2068
2254
  }
2255
+ const repo = resolveConfiguredRepoName(options, deps.env);
2256
+ if (repo) {
2257
+ const stored = await resolveBapiCredentials(repo, installerCredentialReadDeps(deps));
2258
+ if (stored.ok)
2259
+ return { ok: true, value: stored.credentials.apiKey, source: stored.credentials.source === "env" ? "env" : "store" };
2260
+ if (stored.kind !== "not-found" && stored.kind !== "missing-key")
2261
+ return { ok: false, error: stored.error };
2262
+ }
2069
2263
  if (deps.isTTY && deps.promptSecret) {
2070
2264
  // BAPI-708 (A-3): the prompt no longer asks the user to pre-classify their own
2071
2265
  // credential ("Bridge API key or invite"). Classification is done from SHAPE
@@ -3144,37 +3338,24 @@ function asRecord(value) {
3144
3338
  ? value
3145
3339
  : undefined;
3146
3340
  }
3147
- /**
3148
- * Detect whether any resolved host config already carries a real (non-placeholder)
3149
- * `BAPI_API_KEY` for the `bridge-api` server — the trigger for overwrite consent.
3150
- * An `invalid` (present-but-unsafe) config conservatively returns `true` so the
3151
- * overwrite-consent gate assumes a real key MAY be present rather than silently
3152
- * replacing a file we could not inspect (BAPI-666).
3153
- */
3154
3341
  async function detectExistingRealKey(deps, targets) {
3342
+ const observations = [];
3155
3343
  for (const target of targets) {
3156
3344
  const result = await readHostConfig(deps, path.join(deps.cwd, target.relPath));
3157
- if (result.state === "invalid")
3158
- return true;
3159
- if (result.state === "absent")
3345
+ if (result.state !== "parsed")
3160
3346
  continue;
3161
- const topLevel = asRecord(result.config[target.topLevelKey]);
3162
- // BAPI-807: a real key under a legacy `bridge-api` entry is just as much a
3163
- // reason to ask for overwrite consent as one under `bridge`. A both-key
3164
- // config is conservatively treated as possibly key-bearing for the same
3165
- // reason `invalid` is.
3166
- const resolution = resolveRegistrationKey(topLevel);
3167
- if (resolution.state === "conflict")
3168
- return true;
3169
- if (resolution.state === "absent")
3347
+ const top = asRecord(result.config[target.topLevelKey]);
3348
+ const registration = resolveRegistrationKey(top);
3349
+ if (registration.state === "absent" || registration.state === "conflict")
3170
3350
  continue;
3171
- const entry = asRecord(topLevel?.[resolution.key]);
3172
- const env = asRecord(entry?.["env"]);
3173
- if (env && !isPlaceholderApiKey(env["BAPI_API_KEY"])) {
3174
- return true;
3351
+ const env = asRecord(asRecord(top?.[registration.key])?.env);
3352
+ if (env && typeof env.BAPI_API_KEY === "string" && !isPlaceholderApiKey(env.BAPI_API_KEY)) {
3353
+ observations.push({ source: target.relPath, key: env.BAPI_API_KEY,
3354
+ repo: typeof env.BAPI_REPO_NAME === "string" ? env.BAPI_REPO_NAME : undefined,
3355
+ baseUrl: typeof env.BAPI_BASE_URL === "string" ? env.BAPI_BASE_URL : undefined });
3175
3356
  }
3176
3357
  }
3177
- return false;
3358
+ return observations;
3178
3359
  }
3179
3360
  /** The fixed, secret-free hard warning shown for a git-tracked project config (BAPI-666). */
3180
3361
  function trackedConfigWarning(relPath) {
@@ -3346,6 +3527,7 @@ async function writeHostConfigs(deps, targets, entries, trackedState, ctx) {
3346
3527
  // for `absent` — decided AFTER the safety branches above so an absent file is
3347
3528
  // never initialized before its tracked-state consent is resolved.
3348
3529
  const config = read.state === "parsed" ? read.config : {};
3530
+ const originalConfig = JSON.stringify(config);
3349
3531
  const topLevel = asRecord(config[target.topLevelKey]) ?? {};
3350
3532
  // BAPI-807: resolve WHICH key this config's registration lives under before
3351
3533
  // writing. A legacy-only entry is replaced under `bridge-api`, a canonical-only
@@ -3379,6 +3561,8 @@ async function writeHostConfigs(deps, targets, entries, trackedState, ctx) {
3379
3561
  preserveProjectRoot: tracked,
3380
3562
  });
3381
3563
  config[target.topLevelKey] = topLevel;
3564
+ if (read.state === "parsed" && JSON.stringify(config) === originalConfig)
3565
+ continue;
3382
3566
  await deps.mkdir(path.dirname(fullPath), { recursive: true });
3383
3567
  await deps.writeFile(fullPath, JSON.stringify(config, null, 2) + "\n", {
3384
3568
  encoding: "utf-8",
@@ -3643,6 +3827,8 @@ const CONNECTIVITY_KEY_SOURCE_ATTRIBUTION = {
3643
3827
  "different one)",
3644
3828
  flag: " (this key came from the --api-key flag — omit it to be prompted for a different one)",
3645
3829
  prompt: "",
3830
+ store: " (this key came from the saved credential store; repair or explicitly replace that entry)",
3831
+ host: " (this key came from an existing host binding)",
3646
3832
  };
3647
3833
  /**
3648
3834
  * Verify connectivity. Distinguishes a rejected/expired credential (401) from a
@@ -3706,10 +3892,9 @@ export async function verifyConnectivity(deps, baseUrl, repoName, apiKey, apiKey
3706
3892
  catch {
3707
3893
  return { ok: false, message: CONNECTIVITY_ACCESS_DENIED_FALLBACK };
3708
3894
  }
3709
- if (typeof detail === "string" && detail.trim().length > 0) {
3710
- return { ok: false, message: detail.trim() };
3711
- }
3712
- return { ok: false, message: CONNECTIVITY_ACCESS_DENIED_FALLBACK };
3895
+ const safeDetail = typeof detail === "string" ? detail.trim() : "";
3896
+ return { ok: false, message: /^repository '[a-zA-Z0-9_.-]+' is not registered; verify the repo_name$/.test(safeDetail) && !safeDetail.includes(apiKey)
3897
+ ? safeDetail : CONNECTIVITY_ACCESS_DENIED_FALLBACK };
3713
3898
  }
3714
3899
  if (resp.status === 404) {
3715
3900
  return {
@@ -5339,7 +5524,7 @@ export function resolveInstallBridgeBaseUrl(env) {
5339
5524
  catch {
5340
5525
  return { ok: false, error: buildInstallBridgeBaseUrlError(candidate) };
5341
5526
  }
5342
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
5527
+ if ((parsed.protocol !== "http:" && parsed.protocol !== "https:") || parsed.username || parsed.password || parsed.search || parsed.hash) {
5343
5528
  return { ok: false, error: buildInstallBridgeBaseUrlError(candidate) };
5344
5529
  }
5345
5530
  // The TRIMMED candidate is returned, not `parsed.toString()`: the latter would
@@ -5464,8 +5649,54 @@ export function isMinttyNonInteractiveInstall(platform, env, isTTY) {
5464
5649
  const msystem = env.MSYSTEM;
5465
5650
  return (typeof msystem === "string" && msystem.trim().length > 0) || env.TERM_PROGRAM === "mintty";
5466
5651
  }
5652
+ async function refreshIndependentInstallAssets(deps, reason, presentation) {
5653
+ const compact = presentation?.mode === "compact";
5654
+ if (!compact)
5655
+ deps.errorLog(reason);
5656
+ try {
5657
+ await deps.runInit(deps.cwd, { assetsOnly: true, env: { ...deps.env, BAPI_API_KEY: undefined },
5658
+ stdout: compact && !presentation.verbose ? () => { } : deps.log, stderr: deps.errorLog });
5659
+ deps.log(compact
5660
+ ? "Bridge assets refreshed; your identity, host bindings and preferences were kept."
5661
+ : "Independent Bridge assets refreshed. Existing identity, host bindings and preferences preserved; requested identity-dependent capabilities remain unavailable.");
5662
+ }
5663
+ catch {
5664
+ deps.errorLog("Independent asset refresh failed; completed work was retained.");
5665
+ }
5666
+ return 1;
5667
+ }
5668
+ async function selectInstalledProject(options, deps) {
5669
+ const installed = await observeInstalledIdentity(deps);
5670
+ const explicit = resolveConfiguredRepoName(options, deps.env);
5671
+ const terminal = { write: deps.log, read: deps.isTTY ? deps.promptLine : undefined };
5672
+ if (installed.status === "unavailable")
5673
+ return false;
5674
+ if (installed.status === "conflicting" && !explicit) {
5675
+ const names = [...new Set(installed.candidates.map(c => c.repo))];
5676
+ const choice = await askSetupQuestion({ purpose: "Select the installed Bridge project",
5677
+ evidence: installed.candidates.map(c => `${c.source}: ${c.repo}`),
5678
+ options: names.map((repo, i) => ({ id: String(i + 1), label: repo })),
5679
+ consequences: ["Selected host bindings and future requests use the chosen project after credential validation."],
5680
+ deferred: "Conflicting bindings remain unchanged; independent assets can still be refreshed.",
5681
+ recovery: "Inspect the bindings and rerun with the intended --repo." }, terminal);
5682
+ if (choice.status !== "selected")
5683
+ return false;
5684
+ options.repo = names[Number(choice.id) - 1];
5685
+ }
5686
+ else if (explicit && ((installed.status === "resolved" && installed.repo !== explicit) || installed.status === "conflicting")) {
5687
+ const accepted = await authorizeMaintenanceEffect({ category: "credential", state: { status: "present", identity: explicit },
5688
+ unchanged: false, context: deps.cwd, effect: "Change the installed Bridge project binding?", repository: explicit, trusted: true }, terminal, [`Requested project: ${explicit}`, ...(installed.status === "conflicting" ? installed.candidates.map(c => `${c.source}: ${c.repo}`) : [`Installed project: ${installed.repo}`])], ["Selected host bindings and future requests will use the requested project after validation; other stored projects are preserved."]);
5689
+ if (!accepted)
5690
+ return false;
5691
+ }
5692
+ else if (!explicit && installed.status === "resolved")
5693
+ options.repo = installed.repo;
5694
+ return true;
5695
+ }
5467
5696
  export async function runInstallBridgeCli(argv, overrides = {}) {
5468
5697
  const deps = { ...createDefaultInstallBridgeDeps(), ...overrides };
5698
+ const originalEnvironment = { ...deps.env };
5699
+ deps.env = { ...deps.env };
5469
5700
  // When the caller overrode only `fetch` (the common test seam), bind the
5470
5701
  // default resolver to the FINAL merged fetch so server resolution still routes
5471
5702
  // through the override. An explicit `resolveRepoViaServer` override is honored.
@@ -5503,20 +5734,20 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
5503
5734
  // A rejected value cannot be interpolated into guidance, so usage falls back to
5504
5735
  // the documented default — the run is about to fail on it anyway.
5505
5736
  const usageBaseUrl = baseUrlResult.ok ? baseUrlResult.value : DEFAULT_BAPI_BASE_URL;
5506
- // ---- BAPI-679: nested `install-bridge conductor` -----------------------
5737
+ // ---- BAPI-679: nested `install epic-implementer` -----------------------
5507
5738
  // Intercepted HERE, before `parseInstallBridgeArgs`, because that parser
5508
5739
  // rejects ALL positional arguments — a bare `conductor` token would otherwise
5509
5740
  // be an argument error. Deliberately after the deps merge and the base-URL
5510
5741
  // resolution above, so the nested command inherits the same final merged deps
5511
5742
  // (including a test's `fetch` override) and the same normalized base URL.
5512
- // Note this is `install-bridge conductor`; it is UNRELATED to the top-level
5743
+ // Note this is `install epic-implementer`; it is UNRELATED to the top-level
5513
5744
  // `conductor`/`epic-implementer` CLI split (S4/BAPI-1080) — the bare
5514
5745
  // top-level `conductor` token is now a fixed migration stub and the real
5515
5746
  // event-ledger CLI routes through `runEpicImplementerCli` under the
5516
- // `epic-implementer` name. This nested `install-bridge conductor` surface is
5747
+ // `epic-implementer` name. This nested `install epic-implementer` surface is
5517
5748
  // untouched by that rename.
5518
- if (argv[0] === "conductor") {
5519
- // ---- BAPI-1136: `install-bridge conductor --merge-workflow` ----------
5749
+ if (argv[0] === "conductor" || argv[0] === "epic-implementer") {
5750
+ // ---- BAPI-1136: `install epic-implementer --merge-workflow` ----------
5520
5751
  //
5521
5752
  // Intercepted ahead of `parseInstallBridgeConductorArgs` on purpose. That
5522
5753
  // parser REQUIRES at least one `--required-check` because an empty done gate
@@ -5537,6 +5768,23 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
5537
5768
  return 1;
5538
5769
  }
5539
5770
  try {
5771
+ if (!mergeWorkflowArgs.options.dryRun) {
5772
+ const setup = deps.conductorSetup ?? buildConductorSetupDeps(deps, log, errorLog);
5773
+ log("Epic Implementer merge-workflow setup requires github.com, GitHub CLI sign-in, and Claude Code sign-in.");
5774
+ const remote = await setup.readLocalGithubRemote();
5775
+ const signedIn = await setup.checkGithubSignIn();
5776
+ const claude = await setup.detectClaudeLogin();
5777
+ if (!remote || signedIn !== "signed_in" || !claude.detected) {
5778
+ errorLog("Epic Implementer prerequisites unavailable. Check origin and sign in with gh auth login and claude auth login; rerun install epic-implementer. General Bridge maintenance is available separately.");
5779
+ return refreshIndependentInstallAssets(deps, "Epic Implementer prerequisites blocked; independent Bridge maintenance continues.");
5780
+ }
5781
+ const lookup = deps.lookupExecutable ?? defaultExecutablePresenceProbe;
5782
+ for (const tool of ["git", "gh", "claude"])
5783
+ if (!await lookup(tool)) {
5784
+ errorLog(`Epic Implementer requires ${tool} on PATH.`);
5785
+ return refreshIndependentInstallAssets(deps, "Epic Implementer tooling unavailable.");
5786
+ }
5787
+ }
5540
5788
  return await runMergeWorkflowInstall(deps.cwd, mergeWorkflowArgs.options, buildMergeWorkflowInstallDeps(deps, log, errorLog));
5541
5789
  }
5542
5790
  catch {
@@ -5555,15 +5803,81 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
5555
5803
  return 1;
5556
5804
  }
5557
5805
  const conductorBaseUrl = baseUrlResult.value;
5806
+ // In `--json` mode stdout is reserved for the single JSON document the
5807
+ // conductor writes through `conductorDeps.log`; human narration goes to stderr.
5808
+ const humanOutputSink = argv.includes("--json") ? errorLog : log;
5558
5809
  const conductorDeps = {
5810
+ prerequisites: async (executorRequested) => {
5811
+ const lookup = deps.lookupExecutable ?? defaultExecutablePresenceProbe;
5812
+ const tooling = await Promise.all(["git", "gh", "claude", ...(executorRequested ? ["wt"] : [])].map(async (name) => { try {
5813
+ return await lookup(name);
5814
+ }
5815
+ catch {
5816
+ return false;
5817
+ } }));
5818
+ return { claudeLoggedIn: null, githubSignIn: "unavailable", localRemote: null,
5819
+ toolsAvailable: tooling.every(Boolean), platformSupported: !executorRequested || deps.platform === "darwin" || deps.platform === "linux" };
5820
+ },
5821
+ isTTY: deps.isTTY,
5559
5822
  env: deps.env,
5560
5823
  cwd: deps.cwd,
5561
5824
  log: deps.log,
5562
5825
  errorLog: deps.errorLog,
5563
5826
  promptLine: deps.promptLine,
5564
5827
  resolveBaseUrl: () => ({ ok: true, value: conductorBaseUrl }),
5565
- resolveAccess: (repoName, resolvedBaseUrl) => (deps.conductorResolveAccess ??
5566
- (async () => ({ ok: false, error: "conductor access seam unavailable" })))(repoName, resolvedBaseUrl, deps),
5828
+ resolveAccess: async (repoName, resolvedBaseUrl) => {
5829
+ if (argv.includes("--dry-run")) {
5830
+ // Injected access providers own their already-settled identity. The production
5831
+ // preview uses the shared read-only endpoint resolver, with the original env.
5832
+ if (overrides.conductorResolveAccess)
5833
+ return overrides.conductorResolveAccess(repoName, resolvedBaseUrl, deps);
5834
+ const installed = await observeInstalledIdentity(deps);
5835
+ const project = repoName ?? originalEnvironment.BAPI_REPO_NAME ?? (installed.status === "resolved" ? installed.repo : undefined);
5836
+ if (!project || installed.status === "unavailable" || installed.status === "conflicting")
5837
+ return { ok: false, error: "Project identity deferred during preview." };
5838
+ const resolveDeps = { ...installerCredentialReadDeps(deps), env: originalEnvironment };
5839
+ const credential = await resolveEpicLaunchCredential(project, resolvedBaseUrl, resolveDeps, { productionBaseUrl: DEFAULT_BAPI_BASE_URL });
5840
+ // BAPI-1650: read-only approval evidence, attached only when proven.
5841
+ const endpointApproval = await classifyEndpointApproval(project, resolvedBaseUrl, credential, resolveDeps);
5842
+ const approval = endpointApproval !== undefined ? { endpointApproval } : {};
5843
+ return credential.ok ? { ok: true, access: { repoName: project, baseUrl: resolvedBaseUrl, apiKey: credential.apiKey }, ...approval }
5844
+ : { ok: false, error: "Credential validation and endpoint authorization deferred during dry run.", ...approval };
5845
+ }
5846
+ const parsedIdentity = parseInstallBridgeArgs(repoName ? ["--repo", repoName] : []);
5847
+ if (parsedIdentity.status !== "ok")
5848
+ return { ok: false, error: "Project selector unavailable." };
5849
+ if (!await selectInstalledProject(parsedIdentity.options, { ...deps, log: humanOutputSink })) {
5850
+ return { ok: false, error: "Project identity remains unresolved." };
5851
+ }
5852
+ const access = await (deps.conductorResolveAccess ?? (async () => ({ ok: false, error: "access seam unavailable" })))(parsedIdentity.options.repo ?? repoName, resolvedBaseUrl, deps);
5853
+ if (!access.ok)
5854
+ return access;
5855
+ const settled = await settleMaintenanceCredential({ repoName: access.access.repoName, baseUrl: resolvedBaseUrl,
5856
+ productionBaseUrl: DEFAULT_BAPI_BASE_URL,
5857
+ hosts: await detectExistingRealKey(deps, hostConfigTargetsForPlatforms(["claude-code", "cursor", "copilot-vscode"])),
5858
+ candidate: { key: access.access.apiKey, source: originalEnvironment.BAPI_API_KEY ? "env" : "store" },
5859
+ originalEnvironment, store: installerCredentialReadDeps(deps), report: humanOutputSink,
5860
+ terminal: { write: humanOutputSink, read: deps.isTTY ? deps.promptLine : undefined },
5861
+ validate: async (key) => (await verifyConnectivity(deps, resolvedBaseUrl, access.access.repoName, key)).ok });
5862
+ if (!settled.ok) {
5863
+ return { ok: false, error: settled.reason };
5864
+ }
5865
+ const identity = settled.identity;
5866
+ if (identity.persist) {
5867
+ const written = await deps.upsertCredential(identity.repoName, identity.apiKey, modernWriteDeps(deps), { observedKey: identity.observedKey });
5868
+ if (!written.ok)
5869
+ return { ok: false, error: "Saved identity changed; rerun setup before dependent work." };
5870
+ }
5871
+ if (identity.bindEndpoint) {
5872
+ const bound = await (deps.bindCredential ?? bindEpicLaunchCredential)(identity.repoName, resolvedBaseUrl, modernWriteDeps(deps), { observedKey: identity.apiKey });
5873
+ if (!bound.ok)
5874
+ return { ok: false, error: "Endpoint approval could not be saved; rerun setup." };
5875
+ }
5876
+ deps.env = { ...deps.env, BAPI_API_KEY: identity.apiKey, BAPI_REPO_NAME: identity.repoName };
5877
+ conductorDeps.env = deps.env;
5878
+ deps.startTicketsDeps = { ...deps.startTicketsDeps, env: deps.env };
5879
+ return { ok: true, access: { ...access.access, apiKey: identity.apiKey, baseUrl: resolvedBaseUrl } };
5880
+ },
5567
5881
  fetchJson: deps.fetch,
5568
5882
  postJson: deps.fetch,
5569
5883
  runDoctor: (params) => (deps.conductorRunDoctor ??
@@ -5606,7 +5920,20 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
5606
5920
  localProvisioning: buildConductorLocalDeps(deps),
5607
5921
  // BAPI-1461: the converging setup's seams (sign-ins, the stored merge token,
5608
5922
  // the stored test command, the CI workflow installer, and indexing).
5609
- setup: deps.conductorSetup ?? buildConductorSetupDeps(deps, log, errorLog),
5923
+ setup: deps.conductorSetup ?? buildConductorSetupDeps(deps, humanOutputSink, errorLog),
5924
+ // BAPI-1638: `--answers <file>` (relative to this checkout) or `-` for stdin.
5925
+ answersSource: {
5926
+ readFile: (answersPath) => readFile(path.resolve(deps.cwd, answersPath), "utf-8"),
5927
+ readStdin: readProcessStdin,
5928
+ },
5929
+ // BAPI-1638: the setup record lives under docs_dir, the same root `ping` reports.
5930
+ setupRecordWriter: createSetupRecordWriter(resolveDocsDirForRoot(deps.cwd, deps.env), {
5931
+ lstat: (p) => lstat(p),
5932
+ mkdir: (p, o) => mkdir(p, o),
5933
+ readFile: (p, e) => readFile(p, e),
5934
+ writeFile: (p, t, o) => writeFile(p, t, o),
5935
+ rename: (a, b) => rename(a, b),
5936
+ }, { join: path.join, dirname: path.dirname }),
5610
5937
  // BAPI-1391: the read-only discovery filesystem over THIS working tree, and
5611
5938
  // the short-lived qualifying executor (the existing executor CLI with a
5612
5939
  // `runExecutor` override limiting it to `gate_qualification` jobs).
@@ -5622,7 +5949,21 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
5622
5949
  }),
5623
5950
  },
5624
5951
  };
5625
- return runInstallBridgeConductorCli(argv.slice(1), conductorDeps);
5952
+ // Hold the verdict and next step so they print last, after the refresh output.
5953
+ let held;
5954
+ const result = await runInstallBridgeConductorCli(argv.slice(1), { ...conductorDeps, holdClosingResult: closing => { held = closing; } });
5955
+ const nested = parseInstallBridgeConductorArgs(argv.slice(1));
5956
+ let exitCode = result;
5957
+ if (result === 1 && nested.status === "ok" && !nested.options.dryRun) {
5958
+ exitCode = await refreshIndependentInstallAssets(nested.options.json ? { ...deps, log: errorLog } : deps, "Epic Implementer setup remains incomplete; refreshing independent Bridge assets.", { mode: "compact", verbose: nested.options.verbose === true });
5959
+ }
5960
+ const closing = held;
5961
+ if (closing !== undefined) {
5962
+ log(closing.verdict);
5963
+ if (closing.nextStep !== undefined)
5964
+ log(closing.nextStep);
5965
+ }
5966
+ return exitCode;
5626
5967
  }
5627
5968
  const parsed = parseInstallBridgeArgs(argv);
5628
5969
  if (parsed.status === "help") {
@@ -5700,6 +6041,7 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
5700
6041
  // returns before `resolveInviteToken`/`resolveSignupEmail` even run.
5701
6042
  if (options.dryRun) {
5702
6043
  log(`${INSTALL_BRIDGE_CWD_BANNER_PREFIX}${deps.cwd}`);
6044
+ log(`Bridge destination: ${baseUrl} (${deps.env.BAPI_BASE_URL === undefined ? "production default" : "BAPI_BASE_URL"}).`);
5703
6045
  const repo = typeof options.repo === "string" && options.repo.trim().length > 0
5704
6046
  ? { kind: "explicit", value: options.repo.trim() }
5705
6047
  : typeof deps.env.BAPI_REPO_NAME === "string" && deps.env.BAPI_REPO_NAME.trim().length > 0
@@ -5782,12 +6124,14 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
5782
6124
  })) {
5783
6125
  log(line);
5784
6126
  }
6127
+ log("Credential validation and consequential authorization are deferred until a live run.");
5785
6128
  return 0;
5786
6129
  }
5787
6130
  // ---- BAPI-669 (U2): working-directory banner + project-root gate ----
5788
6131
  // See the section comment on `hasProjectRootMarker`: read-only, and positioned
5789
6132
  // ahead of ALL credential and configuration work so a decline costs nothing.
5790
6133
  log(`${INSTALL_BRIDGE_CWD_BANNER_PREFIX}${deps.cwd}`);
6134
+ log(`Bridge destination: ${baseUrl} (${deps.env.BAPI_BASE_URL === undefined ? "production default" : "BAPI_BASE_URL"}).`);
5791
6135
  if (!(await hasProjectRootMarker(deps))) {
5792
6136
  if (deps.isTTY && deps.promptLine) {
5793
6137
  let answer = "";
@@ -5819,6 +6163,26 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
5819
6163
  // The selection is pure and deterministic for every explicit, env-driven, and
5820
6164
  // non-TTY invocation; only a BARE interactive run is asked which branch it wants
5821
6165
  // (BAPI-626 — otherwise a first-time user can never reach self-serve).
6166
+ if (!await selectInstalledProject(options, deps))
6167
+ return refreshIndependentInstallAssets(deps, "Installed project identity is unresolved or unreadable; existing bindings preserved.");
6168
+ const establishedRepo = resolveConfiguredRepoName(options, deps.env);
6169
+ const storedObservation = establishedRepo ? await resolveBapiCredentials(establishedRepo, {
6170
+ ...installerCredentialReadDeps(deps), env: { ...deps.env, BAPI_API_KEY: undefined },
6171
+ }) : undefined;
6172
+ if (storedObservation && !storedObservation.ok && !["not-found", "missing-key"].includes(storedObservation.kind)) {
6173
+ return refreshIndependentInstallAssets(deps, `Saved credential ${storedObservation.kind}. Repair the credential store; signup was not selected.`);
6174
+ }
6175
+ const hostObservations = await detectExistingRealKey(deps, hostConfigTargetsForPlatforms(["claude-code", "cursor", "copilot-vscode"]));
6176
+ if (hostObservations.some(host => !host.repo))
6177
+ return refreshIndependentInstallAssets(deps, "An installed host credential has no project identity. Repair its BAPI_REPO_NAME binding before reconnecting; existing bindings preserved.");
6178
+ const establishedHost = hostObservations.find(host => host.repo === establishedRepo);
6179
+ const storedInputSource = storedObservation?.ok ? "store" : establishedHost ? "host" : undefined;
6180
+ const explicitRoute = options.inviteMode || options.email || deps.env.BAPI_INVITE?.trim() || deps.env.BAPI_SIGNUP_EMAIL?.trim();
6181
+ const usingInstalledInput = !!(storedInputSource && !explicitRoute && !options.apiKey && !deps.env.BAPI_API_KEY?.trim());
6182
+ if (usingInstalledInput) {
6183
+ options.apiKey = storedObservation?.ok ? storedObservation.credentials.apiKey : establishedHost.key;
6184
+ log("Resuming installed project with its saved credential.");
6185
+ }
5822
6186
  const branchResult = await resolveInstallBridgeOnboardingBranchForRun(options, deps, argv, baseUrl);
5823
6187
  if (!branchResult.ok) {
5824
6188
  errorLog(`Error: ${branchResult.error}`);
@@ -6001,6 +6365,25 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
6001
6365
  // 404 is the BAPI-616 feature-detect for an older or self-hosted server, and
6002
6366
  // `error` covers a transient network failure or a 401. Collapsing these into
6003
6367
  // the hard stop would make a blip unrecoverable.
6368
+ let acceptedIdentity;
6369
+ const oldKey = storedObservation?.ok ? storedObservation.credentials.apiKey : establishedHost?.key;
6370
+ let acceptedReplacement = false;
6371
+ if (!bootstrapInviteMode && establishedRepo) {
6372
+ const settled = await settleMaintenanceCredential({ repoName: establishedRepo, baseUrl,
6373
+ productionBaseUrl: DEFAULT_BAPI_BASE_URL, hosts: hostObservations,
6374
+ candidate: { key: apiKey, source: usingInstalledInput ? storedInputSource : apiKeySource ?? "prompt" },
6375
+ originalEnvironment, store: installerCredentialReadDeps(deps),
6376
+ terminal: { write: log, read: deps.isTTY ? deps.promptLine : undefined }, report: log,
6377
+ validate: async (key) => (await verifyConnectivity(deps, baseUrl, establishedRepo, key)).ok });
6378
+ if (!settled.ok)
6379
+ return refreshIndependentInstallAssets(deps, settled.reason);
6380
+ acceptedIdentity = settled.identity;
6381
+ apiKey = acceptedIdentity.apiKey;
6382
+ apiKeySource = acceptedIdentity.source;
6383
+ acceptedReplacement = acceptedIdentity.replacementAccepted;
6384
+ }
6385
+ if (!bootstrapInviteMode)
6386
+ deps.env = { ...deps.env, BAPI_API_KEY: apiKey };
6004
6387
  if (!bootstrapInviteMode && options.displayName !== undefined) {
6005
6388
  errorLog("Error: --display-name applies only to creation; existing-key registration uses canonical selection.");
6006
6389
  return 1;
@@ -6106,6 +6489,22 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
6106
6489
  }
6107
6490
  }
6108
6491
  }
6492
+ // A server-resolved project may already have a saved identity from another
6493
+ // clone. Observe and settle it before any project-dependent writes.
6494
+ if (!bootstrapInviteMode && !modernAttempt && !acceptedIdentity) {
6495
+ const settled = await settleMaintenanceCredential({ repoName, baseUrl,
6496
+ productionBaseUrl: DEFAULT_BAPI_BASE_URL, hosts: hostObservations,
6497
+ candidate: { key: apiKey, source: apiKeySource ?? "prompt" }, originalEnvironment,
6498
+ store: installerCredentialReadDeps(deps), terminal: { write: log, read: deps.isTTY ? deps.promptLine : undefined },
6499
+ report: log, validate: async (key) => (await verifyConnectivity(deps, baseUrl, repoName, key)).ok });
6500
+ if (!settled.ok)
6501
+ return refreshIndependentInstallAssets(deps, settled.reason);
6502
+ acceptedIdentity = settled.identity;
6503
+ apiKey = acceptedIdentity.apiKey;
6504
+ apiKeySource = acceptedIdentity.source;
6505
+ acceptedReplacement = acceptedIdentity.replacementAccepted;
6506
+ deps.env = { ...deps.env, BAPI_API_KEY: apiKey };
6507
+ }
6109
6508
  const credentialStorePath = getPrimaryCredentialStorePath({
6110
6509
  env: deps.env,
6111
6510
  homedir: deps.homedir,
@@ -6116,19 +6515,64 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
6116
6515
  // set. The selected project JSON targets drive the read-merge-write path; a selected
6117
6516
  // global (Codex) or manual (Windsurf) target is provisioned by the
6118
6517
  // registry-driven emitter after the connectivity check.
6119
- const selectedPlatforms = await resolveSelectedHostPlatforms(deps, options);
6518
+ const savedPreferences = await readMcpInstallState(deps.cwd, { readFile: deps.readFile });
6519
+ const toolPreferenceState = options.tools !== undefined ? "explicit"
6520
+ : savedPreferences.status === "valid" ? "preserved" : savedPreferences.status === "missing" ? "missing" : "invalid";
6521
+ if (toolPreferenceState === "invalid") {
6522
+ const repair = await askSetupQuestion({ purpose: "Repair invalid saved tool preferences",
6523
+ evidence: [`Preference status: ${savedPreferences.status}`],
6524
+ options: [{ id: "yes", label: "Choose replacement tool preferences" }, { id: "no", label: "Preserve the saved file" }],
6525
+ consequences: ["A new tool selection replaces the invalid installer preferences and determines which host configurations are maintained."],
6526
+ deferred: "Host configuration and preference writes are deferred; generated assets can still be refreshed.",
6527
+ recovery: "Repair .bridge/install-state.json or rerun with an explicit --tools selection." }, { write: log, read: deps.isTTY ? deps.promptLine : undefined });
6528
+ if (repair.status !== "accept")
6529
+ return refreshIndependentInstallAssets(deps, "Saved tool preferences require repair; existing preferences preserved.");
6530
+ }
6531
+ const selectedPlatforms = options.tools === undefined && savedPreferences.status === "valid"
6532
+ ? savedPreferences.state.selectedPlatforms
6533
+ : await resolveSelectedHostPlatforms(deps, options);
6534
+ if (options.tools === undefined && savedPreferences.status === "valid")
6535
+ log("Preserved saved tool selections; unavailable tools remain selected.");
6120
6536
  // ---- BAPI-1221 (S2): capture the optimization-posture preference ----
6121
- // Asked immediately after tool selection, on every otherwise-eligible
6122
- // interactive install (including reinstalls and an explicit empty
6123
- // selection) — a prior posture is never read first. `--dry-run` already
6537
+ // Read established posture before offering a selection for missing or invalid
6538
+ // values. Valid preferences and indeterminate reads remain preserved. `--dry-run` already
6124
6539
  // returns long before this point (see the NOTE below), so this gate is
6125
6540
  // belt-and-suspenders, not the sole guard. The primary platform is
6126
6541
  // `selectedPlatforms[0]` exclusively, relying on the resolver's own
6127
6542
  // `HOST_PLATFORM_ORDER` normalization even when several tools were chosen.
6128
6543
  const optimizationPostureEligible = deps.isTTY && Boolean(deps.promptLine) && !options.dryRun;
6129
- const optimizationPostureSelection = optimizationPostureEligible
6130
- ? await promptOptimizationPosture(deps, selectedPlatforms[0])
6131
- : null;
6544
+ let savedPosture;
6545
+ let postureState = "missing";
6546
+ if (oldKey && !bootstrapInviteMode) {
6547
+ try {
6548
+ const response = await deps.fetch(`${buildOptimizationPostureUrl(baseUrl)}?repo_name=${encodeURIComponent(repoName)}`, {
6549
+ headers: { "X-API-Key": apiKey }, signal: AbortSignal.timeout(10_000)
6550
+ });
6551
+ if (response.ok) {
6552
+ const body = await response.json();
6553
+ if (body.value === "quality" || body.value === "speed" || body.value === "maximize_subscription") {
6554
+ savedPosture = body.value;
6555
+ postureState = "preserved";
6556
+ }
6557
+ else
6558
+ postureState = body.value == null ? "missing" : "invalid";
6559
+ }
6560
+ else
6561
+ postureState = response.status === 404 ? "missing" : "unavailable";
6562
+ }
6563
+ catch {
6564
+ postureState = "unavailable";
6565
+ }
6566
+ }
6567
+ let optimizationPostureSelection = null;
6568
+ if (optimizationPostureEligible && (postureState === "missing" || postureState === "invalid")) {
6569
+ const repairApproved = !oldKey || await authorizeMaintenanceEffect({ category: "bookkeeping",
6570
+ state: { status: "absent" }, unchanged: false, context: baseUrl, effect: "Select the missing or invalid optimization preference", repository: repoName, trusted: true }, { write: log, read: deps.promptLine }, [`Preference: ${postureState}`], ["Your selection will be saved for future optimization decisions."]);
6571
+ if (repairApproved)
6572
+ optimizationPostureSelection = await promptOptimizationPosture(deps, selectedPlatforms[0]);
6573
+ }
6574
+ if (oldKey)
6575
+ log(savedPosture ? `Preserved saved optimization posture: ${savedPosture}.` : postureState === "unavailable" ? "Optimization preference could not be read; existing preference preserved." : `Optimization preference is ${postureState}; only an intentional selection will be saved.`);
6132
6576
  if (options.codexProfile && !selectedPlatforms.includes("codex")) {
6133
6577
  errorLog("Error: --codex-profile requires Codex in --tools or the interactive selection.");
6134
6578
  return 1;
@@ -6286,24 +6730,8 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
6286
6730
  unlink: deps.unlink,
6287
6731
  open: deps.open,
6288
6732
  };
6289
- // ---- Overwrite consent: a real existing key requires --force or a prompt ----
6290
- const hasRealKey = await detectExistingRealKey(deps, targets);
6291
- let overwriteConsent = options.force;
6292
- if (hasRealKey && !options.force) {
6293
- if (deps.isTTY && deps.promptLine) {
6294
- const answer = (await deps.promptLine("A host config already contains a BAPI_API_KEY. Overwrite it? [y/N]: ")).trim().toLowerCase();
6295
- if (answer !== "y" && answer !== "yes") {
6296
- errorLog("Aborted: existing API key left unchanged (re-run with --force to overwrite).");
6297
- return 1;
6298
- }
6299
- overwriteConsent = true;
6300
- }
6301
- else {
6302
- errorLog("Error: a host config already contains a BAPI_API_KEY. Re-run with --force to overwrite it " +
6303
- "(refusing to overwrite a credential non-interactively without consent).");
6304
- return 1;
6305
- }
6306
- }
6733
+ // Only the explained replacement decision grants overwrite authority.
6734
+ let overwriteConsent = acceptedReplacement;
6307
6735
  // ---- BAPI-668 (R5-1): the guarded Step 1–5 execution region ----
6308
6736
  // Everything ABOVE this point — argument parsing, base-URL validation, input
6309
6737
  // resolution, the dry-run preview, and every deliberate pre-execution validation
@@ -6603,15 +7031,8 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
6603
7031
  }, credentialWriteDeps);
6604
7032
  // An existing bapi:<repo> credential is never clobbered without consent —
6605
7033
  // the self-serve arm uses the SAME gate as the ordinary-invite arm below.
6606
- const prep = await resolveCredentialConflictConsent(await prepareSelfServePending(overwriteConsent), {
6607
- isTTY: deps.isTTY,
6608
- promptLine: deps.promptLine,
6609
- errorLog,
6610
- grantConsent: () => {
6611
- overwriteConsent = true;
6612
- },
6613
- retry: () => prepareSelfServePending(true),
6614
- });
7034
+ // Creating replay proof does not authorize replacing the canonical credential.
7035
+ const prep = await prepareSelfServePending(true);
6615
7036
  if (prep === null)
6616
7037
  return false;
6617
7038
  if (!prep.ok) {
@@ -6681,15 +7102,8 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
6681
7102
  // An existing bapi:<repo> credential is never clobbered without consent. The
6682
7103
  // gate mirrors the host-config gate above: --force, else an interactive prompt,
6683
7104
  // else a hard non-interactive failure — all BEFORE the exchange.
6684
- const prepared = await resolveCredentialConflictConsent(await prepareInvitePending(overwriteConsent), {
6685
- isTTY: deps.isTTY,
6686
- promptLine: deps.promptLine,
6687
- errorLog,
6688
- grantConsent: () => {
6689
- overwriteConsent = true;
6690
- },
6691
- retry: () => prepareInvitePending(true),
6692
- });
7105
+ // Preserve replay proof independently of the later validated replacement decision.
7106
+ const prepared = await prepareInvitePending(true);
6693
7107
  if (prepared === null)
6694
7108
  return 1;
6695
7109
  // A pending record left by a DIFFERENT invite is that redemption's only replay
@@ -6893,21 +7307,62 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
6893
7307
  if (!reconciled.ok || reconciled.manifest.repoName !== repoName)
6894
7308
  return fatal("Installation incomplete: canonical configuration read-back failed. Preserve proof and resume from this folder.");
6895
7309
  }
7310
+ if (modernAttempt || bootstrapExchangeSucceeded) {
7311
+ const settled = await settleMaintenanceCredential({ repoName, baseUrl, productionBaseUrl: DEFAULT_BAPI_BASE_URL,
7312
+ candidate: { key: apiKey, source: "prompt" }, originalEnvironment,
7313
+ hosts: hostObservations, store: installerCredentialReadDeps(deps),
7314
+ terminal: { write: log, read: deps.isTTY ? deps.promptLine : undefined }, report: log,
7315
+ validate: async (key) => (await verifyConnectivity(deps, baseUrl, repoName, key)).ok });
7316
+ if (!settled.ok || settled.identity.apiKey !== apiKey) {
7317
+ return refreshIndependentInstallAssets(deps, "Bootstrap replacement deferred. Existing identity and durable replay proof were preserved; resume interactively from this folder.");
7318
+ }
7319
+ acceptedIdentity = settled.identity;
7320
+ overwriteConsent = acceptedIdentity.replacementAccepted;
7321
+ // Promote before writing host bindings; guarded failure preserves replay proof.
7322
+ currentStep = INSTALL_BRIDGE_STEP_LABELS.persistCredential;
7323
+ log(currentStep);
7324
+ if (modernAttempt) {
7325
+ const promoted = await promoteModernBootstrapCredential(modernAttempt.scope, modernAttempt.record, credentialWriteDeps, overwriteConsent, acceptedIdentity.observedKey);
7326
+ if (!promoted.ok)
7327
+ return fatal("Credential promotion changed or failed. Existing host bindings and replay proof preserved; rerun to re-evaluate.");
7328
+ }
7329
+ else {
7330
+ const promoted = await deps.promoteBootstrapPending({ repoName, inviteFingerprint,
7331
+ allowOverwriteExistingCredential: overwriteConsent, observedKey: acceptedIdentity.observedKey }, credentialWriteDeps);
7332
+ if (!promoted.ok)
7333
+ return fatal("Credential promotion changed or failed. Existing host bindings and replay proof preserved; rerun to re-evaluate.");
7334
+ }
7335
+ }
6896
7336
  // ---- BAPI-1221 (S2): persist the captured posture, now that connectivity
6897
- // is validated and `repoName`/`apiKey` are both final. Overwrites any
6898
- // existing value unconditionally — the old value is never read first. A
6899
- // no-answer (or a prompt/stream exception the picker already absorbed)
6900
- // reports the same fail-open remediation without ever attempting a write.
7337
+ // is validated and `repoName`/`apiKey` are final. Only an intentional
7338
+ // selection is persisted. Failed requested writes report incomplete; no
7339
+ // answer leaves the existing preference unchanged.
7340
+ let maintenanceFailed = false;
6901
7341
  let persistedPosture;
6902
7342
  if (optimizationPostureSelection) {
6903
7343
  const postureResult = await persistOptimizationPosture(deps, baseUrl, apiKey, repoName, optimizationPostureSelection);
6904
7344
  reportOptimizationPostureOutcome(log, postureResult, optimizationPostureSelection, selectedPlatforms[0]);
6905
7345
  if (postureResult.kind === "success")
6906
7346
  persistedPosture = optimizationPostureSelection;
7347
+ else
7348
+ maintenanceFailed = true;
6907
7349
  }
6908
7350
  else if (optimizationPostureEligible) {
6909
7351
  log(OPTIMIZATION_POSTURE_UNCHANGED_MESSAGE);
6910
7352
  }
7353
+ let maintenancePersistence;
7354
+ if (!modernAttempt && !bootstrapExchangeSucceeded && (acceptedIdentity?.persist ?? (!storedObservation?.ok || storedObservation.credentials.apiKey !== apiKey))) {
7355
+ maintenancePersistence = await deps.upsertCredential(repoName, apiKey, credentialWriteDeps, { observedKey: acceptedIdentity?.observedKey ?? (storedObservation?.ok ? storedObservation.credentials.apiKey : null) });
7356
+ if (!maintenancePersistence.ok)
7357
+ return fatal("Credential persistence failed or identity changed since authorization. Host bindings and launches were deferred; rerun to re-evaluate.");
7358
+ }
7359
+ if (acceptedIdentity?.bindEndpoint) {
7360
+ const bound = await (deps.bindCredential ?? bindEpicLaunchCredential)(repoName, baseUrl, credentialWriteDeps, { observedKey: apiKey });
7361
+ if (!bound.ok)
7362
+ return fatal("Endpoint approval changed or could not be saved. Host bindings and launches deferred; rerun to re-evaluate.");
7363
+ }
7364
+ deps.env = { ...deps.env, BAPI_API_KEY: apiKey, BAPI_REPO_NAME: repoName };
7365
+ deps.startTicketsDeps = { ...deps.startTicketsDeps, env: deps.env };
6911
7366
  const entry = buildInstallBridgeServerEntry(deps.cwd, repoName, apiKey, baseUrl, docsDir);
6912
7367
  // BAPI-666: the secret-free variant (no BAPI_API_KEY) is written instead of the
6913
7368
  // real entry into any git-tracked project config the user did not explicitly
@@ -7061,8 +7516,30 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
7061
7516
  // writeMcpInstallState catches its own I/O errors and returns { ok: false }
7062
7517
  // (it does NOT throw), so the failure warning must inspect the return value —
7063
7518
  // a try/catch alone would silently swallow a real persistence failure.
7519
+ let stateReadFile = deps.readFile;
7520
+ if (savedPreferences.status !== "valid" && savedPreferences.status !== "missing") {
7521
+ // An intentional selection may repair only the tool roster in a readable
7522
+ // schema-v1 document. Preserve and validate every other owned preference.
7523
+ const statePath = path.join(deps.cwd, INSTALL_BRIDGE_INSTALL_STATE_PATH);
7524
+ const observed = await deps.readFile(statePath);
7525
+ const prior = JSON.parse(observed);
7526
+ if (!prior || Array.isArray(prior) || prior.version !== 1)
7527
+ throw new Error("Preference repair requires a supported document");
7528
+ const repaired = JSON.stringify({ ...prior, selectedPlatforms });
7529
+ const check = await readMcpInstallState(deps.cwd, { readFile: async () => repaired });
7530
+ if (check.status !== "valid" || check.state.packagedAssetsStatus)
7531
+ throw new Error("Other preferences require repair");
7532
+ stateReadFile = async (p) => {
7533
+ const current = await deps.readFile(p);
7534
+ if (p !== statePath)
7535
+ return current;
7536
+ if (current !== observed)
7537
+ throw new Error("Preferences changed since selection");
7538
+ return repaired;
7539
+ };
7540
+ }
7064
7541
  const stateResult = await writeMcpInstallState(deps.cwd, { selectedPlatforms, projectConfigPaths: targets.map((t) => t.relPath) }, {
7065
- readFile: deps.readFile,
7542
+ readFile: stateReadFile,
7066
7543
  writeFile: (p, data) => deps.writeFile(p, data, { encoding: "utf-8" }),
7067
7544
  rename: deps.rename,
7068
7545
  mkdir: async (p, o) => {
@@ -7071,13 +7548,13 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
7071
7548
  unlink: deps.unlink,
7072
7549
  });
7073
7550
  if (!stateResult.ok) {
7074
- // Install-state persistence is advisory — never fail the install over it.
7075
- errorLog("Warning: could not persist the install-state file (non-fatal).");
7551
+ maintenanceFailed = true;
7552
+ errorLog("Installation incomplete: could not persist tool preferences; existing state preserved.");
7076
7553
  }
7077
7554
  }
7078
7555
  catch {
7079
- // ensureGitignored for the state file can still throw — also advisory.
7080
- errorLog("Warning: could not persist the install-state file (non-fatal).");
7556
+ maintenanceFailed = true;
7557
+ errorLog("Installation incomplete: could not persist tool preferences; existing state preserved.");
7081
7558
  }
7082
7559
  // ---- Step 4 — persist the credential ----
7083
7560
  // Gated on the post-exchange transition rather than the mode flag (BAPI-668):
@@ -7085,16 +7562,6 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
7085
7562
  // two are equivalent — but keying promotion to the same state that justifies the
7086
7563
  // catch block's resume guidance makes that invariant explicit and un-driftable.
7087
7564
  if (modernAttempt) {
7088
- currentStep = INSTALL_BRIDGE_STEP_LABELS.persistCredential;
7089
- log(currentStep);
7090
- let promoted = await promoteModernBootstrapCredential(modernAttempt.scope, modernAttempt.record, credentialWriteDeps, options.force);
7091
- if (!promoted.ok && promoted.needsConsent && deps.isTTY && deps.promptLine) {
7092
- const consent = (await deps.promptLine("Replace the existing canonical project credential? [y/N]: ")).trim().toLowerCase();
7093
- if (consent === "y" || consent === "yes")
7094
- promoted = await promoteModernBootstrapCredential(modernAttempt.scope, modernAttempt.record, credentialWriteDeps, true, promoted.observedKey);
7095
- }
7096
- if (!promoted.ok)
7097
- return fatal("Installation incomplete: credential promotion failed. Preserve proof and resume from the same folder.");
7098
7565
  log(formatProjectCredentialStoreLine(repoName, credentialStorePath));
7099
7566
  log(`Project '${modernAttempt.displayName}' installed successfully.`);
7100
7567
  }
@@ -7108,24 +7575,14 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
7108
7575
  // successful run prints exactly one Step 4 line and never narrates promotion
7109
7576
  // as a step of its own. Still assigned before the log, preserving the
7110
7577
  // log == record invariant the failure attribution depends on.
7111
- currentStep = INSTALL_BRIDGE_STEP_LABELS.persistCredential;
7112
- log(currentStep);
7113
- const promoted = await deps.promoteBootstrapPending({ repoName, inviteFingerprint, allowOverwriteExistingCredential: overwriteConsent }, credentialWriteDeps);
7114
- if (!promoted.ok) {
7115
- // Mode-aware (BAPI-667): a self-serve user has no invite to "re-present" —
7116
- // telling them to is an instruction they cannot follow.
7117
- return fatal(`Error: the project and API key were created, but the credential could not be stored ` +
7118
- `(${promoted.kind}). ${promoted.error} Your key is still saved locally as a pending ` +
7119
- `record. ${buildBootstrapRetryAdvice(selfServeSignupMode)}`);
7120
- }
7121
- log(formatProjectCredentialStoreLine(repoName, promoted.path));
7578
+ log(formatProjectCredentialStoreLine(repoName, credentialStorePath));
7122
7579
  }
7123
7580
  else {
7124
7581
  // ---- persist routing credential (non-blocking / fail-open) ----
7125
7582
  currentStep = INSTALL_BRIDGE_STEP_LABELS.persistCredential;
7126
7583
  log(currentStep);
7127
7584
  try {
7128
- const result = await deps.upsertCredential(repoName, apiKey, credentialWriteDeps);
7585
+ const result = maintenancePersistence ?? { ok: true, path: credentialStorePath, target: `bapi:${repoName}`, action: "unchanged", migratedFallback: false };
7129
7586
  if (result.ok) {
7130
7587
  log(formatProjectCredentialStoreLine(repoName, result.path));
7131
7588
  }
@@ -7195,6 +7652,7 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
7195
7652
  notesResult = await writeAgentNotes({
7196
7653
  cwd: deps.cwd,
7197
7654
  selectedPlatforms,
7655
+ fs: deps.notesFs,
7198
7656
  guidance: AGENT_GUIDANCE,
7199
7657
  readFile: deps.readFile,
7200
7658
  writeFile: deps.writeFile,
@@ -7202,6 +7660,7 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
7202
7660
  });
7203
7661
  for (const file of notesResult.files) {
7204
7662
  if (file.status === "failed") {
7663
+ maintenanceFailed = true;
7205
7664
  errorLog(` warning: could not update ${file.target} with agent notes (${file.reason}).`);
7206
7665
  errorLog(` Resolve the reported issue in ${file.target}, then rerun an interactive install to retry guidance.`);
7207
7666
  }
@@ -7211,6 +7670,7 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
7211
7670
  // Fail-open, mirroring the routing-credential persistence above: the
7212
7671
  // install itself is already complete and durable.
7213
7672
  notesWriteFailed = true;
7673
+ maintenanceFailed = true;
7214
7674
  errorLog(" warning: could not write agent notes (unexpected error).");
7215
7675
  }
7216
7676
  }
@@ -7330,7 +7790,7 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
7330
7790
  if (deps.platform === "darwin")
7331
7791
  errorLog(macosTerminalPermissionGuidance());
7332
7792
  log(buildManualInstallBridgeContinuation("configured", labelsForPlatforms(selectedPlatforms)));
7333
- return 0;
7793
+ return maintenanceFailed ? 1 : 0;
7334
7794
  }
7335
7795
  // BAPI-669 (U3): the handoff speaks the HOST TOOL'S display label, never the
7336
7796
  // raw agent binary name — computed once so all three sentences agree.
@@ -7351,18 +7811,18 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
7351
7811
  "once the repository reaches full parse readiness — there is no indexing question to answer. " +
7352
7812
  `Verify afterwards at ${setupUrl} (Get Started page — install status panel) or via the ` +
7353
7813
  "session's 'Applied N of M' summary.");
7354
- return 0;
7814
+ return maintenanceFailed ? 1 : 0;
7355
7815
  }
7356
7816
  // Declined (or non-TTY suppression): the deterministic setup is complete and durable.
7357
7817
  log(buildManualInstallBridgeContinuation("configured", labelsForPlatforms(selectedPlatforms)));
7358
- return 0;
7818
+ return maintenanceFailed ? 1 : 0;
7359
7819
  }
7360
7820
  // No launchable session (a no-launchable selection, or a non-TTY / declined chooser):
7361
7821
  // finalAgentName is null, so nothing was materialized. The configured hosts are
7362
7822
  // durable — print the shared continuation + limited-tools note (never the
7363
7823
  // empty-selection variant, which already returned above).
7364
7824
  log(buildManualInstallBridgeContinuation("configured", labelsForPlatforms(selectedPlatforms)));
7365
- return 0;
7825
+ return maintenanceFailed ? 1 : 0;
7366
7826
  }
7367
7827
  catch (error) {
7368
7828
  // BAPI-807: a launcher-config PREFLIGHT refusal is actionable, and the
@@ -7694,3 +8154,16 @@ async function redeemModernInstallAttempt(deps, options, baseUrl, token, signupE
7694
8154
  throw new ModernInstallRecoveryError("Canonical connectivity failed. Preserve proof and resume the same attempt.");
7695
8155
  return { scope, record: checkpoint.record, repoName: exchange.repoName, displayName: exchange.displayName };
7696
8156
  }
8157
+ /** BAPI-1638 — read all of stdin once, for `--answers -`. Bounded by the answers reader. */
8158
+ async function readProcessStdin() {
8159
+ const chunks = [];
8160
+ let total = 0;
8161
+ for await (const chunk of process.stdin) {
8162
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
8163
+ total += buffer.length;
8164
+ if (total > 512 * 1024)
8165
+ throw new Error("stdin answers exceed the size limit");
8166
+ chunks.push(buffer);
8167
+ }
8168
+ return Buffer.concat(chunks).toString("utf-8");
8169
+ }