@bridge_gpt/mcp-server 0.2.71 → 0.2.72

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 (116) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +19 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +4 -4
  5. package/build/bridge-permissions.js +4 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/claude-review-workflow.js +1 -1
  9. package/build/cli-help.js +6 -0
  10. package/build/codex-auto-recovery.js +126 -0
  11. package/build/codex-skill-adapter.js +2 -0
  12. package/build/commands.generated.js +5 -5
  13. package/build/conductor/bridge-api-client.js +518 -23
  14. package/build/conductor/doctor.js +84 -10
  15. package/build/conductor/epic-implementer-cli.js +51 -2
  16. package/build/conductor/gate-discovery.js +136 -10
  17. package/build/conductor/gate-settings-review.js +305 -5
  18. package/build/conductor/git-hooks-uninstall.js +112 -0
  19. package/build/conductor/git-hooks.js +81 -15
  20. package/build/conductor/guided-repair.js +10 -1
  21. package/build/conductor/install-doctor.js +2 -4
  22. package/build/conductor/launch-plan.js +42 -2
  23. package/build/conductor/local-merge.js +12 -1
  24. package/build/conductor/merge-execution-contract.js +1 -1
  25. package/build/conductor/merged-child-check.js +2 -1
  26. package/build/conductor/prerequisite-inputs.js +379 -0
  27. package/build/conductor/readiness-assessment.js +78 -0
  28. package/build/conductor/readiness-cli.js +10 -0
  29. package/build/conductor/readiness-prerequisites.js +53 -0
  30. package/build/conductor/readiness-sections.js +21 -8
  31. package/build/conductor/readiness.js +20 -2
  32. package/build/conductor/recovery-cli.js +223 -13
  33. package/build/conductor/recovery-operations.js +34 -4
  34. package/build/conductor/repair-contract.js +33 -0
  35. package/build/conductor/tools.js +34 -3
  36. package/build/conductor/wait-run-attention.js +115 -0
  37. package/build/conductor/wait-run-cli.js +96 -3
  38. package/build/conductor/worker-database-doctor-inspector.js +1 -0
  39. package/build/credential-store.js +25 -20
  40. package/build/dependency-install-declarations.js +157 -0
  41. package/build/docs.generated.js +4 -4
  42. package/build/doctor.js +37 -5
  43. package/build/drive-epic-help.js +2 -2
  44. package/build/drive-epic.js +52 -11
  45. package/build/epic-implementer-bin.js +118 -43
  46. package/build/epic-launch-profile.js +1 -1
  47. package/build/executor/cli.js +2 -0
  48. package/build/executor/completion-contract.js +16 -0
  49. package/build/executor/credentials.js +1 -1
  50. package/build/executor/delivery-observations.js +113 -0
  51. package/build/executor/delivery-outcome.js +30 -0
  52. package/build/executor/dependency-refresh-runner.js +132 -0
  53. package/build/executor/dependency-refresh.js +530 -0
  54. package/build/executor/deps.js +4 -0
  55. package/build/executor/env.js +67 -2
  56. package/build/executor/harness-coverage.js +19 -0
  57. package/build/executor/http-client.js +35 -1
  58. package/build/executor/index.js +2 -1
  59. package/build/executor/install-preflight.js +1 -1
  60. package/build/executor/job-runner.js +246 -28
  61. package/build/executor/likely-tests.js +94 -97
  62. package/build/executor/prompt-spec.js +13 -3
  63. package/build/executor/required-verification.js +28 -0
  64. package/build/executor/required-work-diagnostics.js +30 -0
  65. package/build/executor/required-work-ledger.js +19 -1
  66. package/build/executor/results.js +42 -0
  67. package/build/executor/service-discovery.js +42 -0
  68. package/build/executor/service-lifecycle.js +109 -2
  69. package/build/executor/service-uninstall.js +205 -0
  70. package/build/executor/service-unit.js +5 -3
  71. package/build/executor/test-clock.js +3 -0
  72. package/build/executor/verification-hints.js +179 -0
  73. package/build/executor/worker-command.js +54 -2
  74. package/build/executor/worker-database.js +271 -31
  75. package/build/executor/worker-finalization.js +65 -10
  76. package/build/executor/worker-guard-hook.js +10 -2
  77. package/build/executor/worker-verification-guidance.js +37 -2
  78. package/build/executor/worktree-inspection.js +42 -0
  79. package/build/github-sign-in.js +1 -1
  80. package/build/index.js +679 -278
  81. package/build/init.js +3 -3
  82. package/build/install-bridge-conductor-gate.js +236 -42
  83. package/build/install-bridge-conductor-setup.js +115 -26
  84. package/build/install-bridge-conductor.js +448 -350
  85. package/build/install-bridge.js +418 -123
  86. package/build/install-maintenance.js +104 -0
  87. package/build/install-reexec.js +1 -1
  88. package/build/local-cleanup.js +59 -0
  89. package/build/mcp-install-state.js +68 -2
  90. package/build/merge-workflow-install.js +2 -2
  91. package/build/package-script-semantics.js +10 -0
  92. package/build/pipeline-utils.js +1 -1
  93. package/build/pipelines.generated.js +5 -5
  94. package/build/plan-execution-ledger.js +148 -2
  95. package/build/plane/plane-freshness.js +6 -7
  96. package/build/plane/terminal-run-cleanup.js +5 -1
  97. package/build/plane/terminal-run-status.js +4 -0
  98. package/build/printed-remedy-commands.js +24 -4
  99. package/build/readiness-check.js +1 -78
  100. package/build/readiness-prerequisites.generated.js +199 -0
  101. package/build/readme.generated.js +1 -1
  102. package/build/repository-toolchains.js +50 -8
  103. package/build/setup-change-policy.js +32 -0
  104. package/build/setup-epic.js +2 -2
  105. package/build/setup-question.js +62 -0
  106. package/build/start-tickets.js +4 -0
  107. package/build/test-command-detection.js +32 -88
  108. package/build/test-support/notes-fs.js +40 -0
  109. package/build/ticket-delivery-enrollment.js +21 -8
  110. package/build/ticket-delivery-run-scope.js +128 -0
  111. package/build/version.generated.js +3 -3
  112. package/build/worker-guard-hook-bin.js +2 -2
  113. package/build/worktrees.js +105 -0
  114. package/docs/EPIC-IMPLEMENTER.md +5 -0
  115. package/docs/epic-implementer/getting-started.md +40 -15
  116. package/package.json +1 -1
@@ -1,3 +1,7 @@
1
+ import { readMcpInstallState } from "./mcp-install-state.js";
2
+ import { askSetupQuestion } from "./setup-question.js";
3
+ import { bindEpicLaunchCredential, 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,7 +144,7 @@ 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";
@@ -152,7 +156,7 @@ import { probeStoredMergeToken } from "./conductor/stored-merge-token-probe.js";
152
156
  import { readGithubMergeCredential, removeGithubMergeCredential, upsertGithubMergeCredential, } from "./credential-store.js";
153
157
  import { createBridgeApiUrls } from "./bridge-api-urls.js";
154
158
  import { installEpicCiWorkflow } from "./epic-ci-workflow-install.js";
155
- import { fetchParseStatus, triggerRepositoryParse, } from "./conductor/bridge-api-client.js";
159
+ import { fetchParseStatus, triggerRepositoryParse, fetchSetupRecoveryEvidence, correctSetupBranch, admitSetupRecovery, } from "./conductor/bridge-api-client.js";
156
160
  import readline from "readline";
157
161
  import { runInit, InitPreflightError, buildBridgeApiEntry, buildBridgeConfigManifest, mergeBridgeApiProfileToken, resolveInitScaffoldAssets, refreshBridgeApiPackageSpec, currentBridgePackageSpec, classifyTrackedProbeExitCode, decideExistingProjectRoot, formatUndeterminedRootReplacedWarning, } from "./init.js";
158
162
  import { hasProjectRootMarker as sharedHasProjectRootMarker } from "./project-root.js";
@@ -178,7 +182,7 @@ import { inspectExecutorServiceDurability, inspectExecutorServiceState, startExe
178
182
  import { executorLaunchdLabelForId, executorSystemdUnitNameForId, executorLaunchdPlistPathForId, executorSystemdUnitPathForId, resolvePackagedExecutorInvocation, writeExecutorServicePlan, EXECUTOR_SERVICE_UNIT_FILE_MODE, } from "./executor/service-unit.js";
179
183
  import { collectConductorNativeLedgerSafe, } from "./conductor/doctor.js";
180
184
  import { installConductorGitHooks, } from "./conductor/git-hooks.js";
181
- import { runInstallBridgeConductorCli, } from "./install-bridge-conductor.js";
185
+ import { runInstallBridgeConductorCli, parseInstallBridgeConductorArgs, } from "./install-bridge-conductor.js";
182
186
  import { createQualificationExecutorRunner, } from "./install-bridge-conductor-gate.js";
183
187
  import { createNodeGateDiscoveryFs } from "./conductor/gate-discovery.js";
184
188
  import { runExecutorCli } from "./executor/cli.js";
@@ -588,7 +592,7 @@ export function getInstallBridgeUsage(baseUrl = DEFAULT_BAPI_BASE_URL) {
588
592
  " -h, --help Show this help.",
589
593
  "",
590
594
  "Subcommands:",
591
- " install conductor Bootstrap the Epic Implementer for this repository",
595
+ " install epic-implementer Bootstrap the Epic Implementer for this repository",
592
596
  " (BAPI-679). Runs a unified READ-ONLY doctor that",
593
597
  " composes the conductor, executor-preflight,",
594
598
  " install-status, and executor service-unit",
@@ -623,9 +627,9 @@ export function getInstallBridgeUsage(baseUrl = DEFAULT_BAPI_BASE_URL) {
623
627
  " operator-managed, so a run reports",
624
628
  " `complete-with-manual-steps` until a live",
625
629
  " executor is actually observed. See",
626
- " `install conductor --help`.",
630
+ " `install epic-implementer --help`.",
627
631
  "",
628
- " install conductor --merge-workflow --codeowner <@org/team|@user>",
632
+ " install epic-implementer --merge-workflow --codeowner <@org/team|@user>",
629
633
  " Generate the Epic Implementer merge workflow",
630
634
  " plus its CODEOWNERS fragment and repository-rule",
631
635
  " guidance, commit them on a managed branch, push",
@@ -1281,6 +1285,8 @@ export function buildInstallBridgeDefaultsSummary(input) {
1281
1285
  * as `install`'s missing-project-root confirmation (BAPI-818, R1).
1282
1286
  */
1283
1287
  export function promptLineViaReadline(promptText, input = process.stdin, output = process.stderr) {
1288
+ if (input === process.stdin && !process.stdin.isTTY)
1289
+ return Promise.resolve("");
1284
1290
  return new Promise((resolve) => {
1285
1291
  const rl = readline.createInterface({ input, output });
1286
1292
  // See promptSecretViaReadline: EOF must resolve rather than deadlock the
@@ -1389,6 +1395,7 @@ export function createDefaultInstallBridgeDeps() {
1389
1395
  // fetch when the caller did not override the resolver — see below.)
1390
1396
  const productionFetch = (...args) => fetch(...args);
1391
1397
  return {
1398
+ notesFs: { realpath, lstat, readBytes: (p) => readFile(p), open, unlink },
1392
1399
  env: process.env,
1393
1400
  cwd: process.cwd(),
1394
1401
  realpath: async (folder) => realpath(folder),
@@ -1441,12 +1448,14 @@ export function createDefaultInstallBridgeDeps() {
1441
1448
  if (process.env.BAPI_INSTALL_DEBUG)
1442
1449
  console.error(m);
1443
1450
  },
1444
- // ---- Nested `install-bridge conductor` seams (BAPI-679) ----
1451
+ // ---- Nested `install epic-implementer` seams (BAPI-679) ----
1445
1452
  conductorRunDoctor: (params) => runConductorInstallDoctor({
1446
1453
  access: params.access,
1447
1454
  accessError: params.accessError,
1448
1455
  fetch: params.fetch,
1449
1456
  reviewPolicySource: params.reviewPolicySource,
1457
+ assessmentVersion: params.assessmentVersion,
1458
+ epicRunId: params.epicRunId,
1450
1459
  readWorkflowFile: () => params.readFile(claudeReviewWorkflowPath(params.cwd)),
1451
1460
  // BAPI-941: read-only workflow-lineage classification. Runs only after
1452
1461
  // the file is confirmed present, uses the same command runner the rest
@@ -1654,7 +1663,7 @@ export function getMergeWorkflowInstallUsage() {
1654
1663
  * prompt can never hang an install. The resulting environment is never printed.
1655
1664
  */
1656
1665
  /**
1657
- * BAPI-1461 — the production seams for the converging `install conductor`.
1666
+ * BAPI-1461 — the production seams for the converging `install epic-implementer`.
1658
1667
  *
1659
1668
  * Each one is a thin adapter over an implementation that already exists: the
1660
1669
  * Claude login reader, one bounded `gh auth status`, the credential store's
@@ -1699,6 +1708,9 @@ export function buildConductorSetupDeps(deps, log, errorLog) {
1699
1708
  runGh: installerDeps.runGh,
1700
1709
  fetchParseStatus: (access) => fetchParseStatus(access, deps.fetch),
1701
1710
  triggerParse: (access) => triggerRepositoryParse(access, deps.fetch),
1711
+ fetchRecoveryEvidence: (access, pr) => fetchSetupRecoveryEvidence(access, pr, deps.fetch),
1712
+ correctBranch: (access, expected, destination) => correctSetupBranch(access, expected, destination, deps.fetch),
1713
+ admitRecovery: (access, evidence, retry) => admitSetupRecovery(access, evidence, retry, deps.fetch),
1702
1714
  };
1703
1715
  }
1704
1716
  export function buildMergeWorkflowInstallDeps(deps, log, errorLog) {
@@ -2051,6 +2063,47 @@ export const INSTALL_REEXEC_KEY_SOURCE_FLAG = "flag";
2051
2063
  * function itself performs no classification; it only resolves which raw string
2052
2064
  * was entered.
2053
2065
  */
2066
+ function installerCredentialReadDeps(deps) {
2067
+ return { env: deps.env, homedir: deps.homedir, platform: deps.platform,
2068
+ readFile: deps.readFile, stat: async (p) => await deps.stat(p), stderr: deps.errorLog };
2069
+ }
2070
+ /** Project identity evidence is read before onboarding; folder names are never identity. */
2071
+ export async function observeInstalledIdentity(deps) {
2072
+ const candidates = [];
2073
+ try {
2074
+ const parsed = parseBridgeConfigToml(await deps.readFile(bridgeConfigPath(deps.cwd)));
2075
+ if (!parsed.ok)
2076
+ return { status: "unavailable" };
2077
+ candidates.push({ repo: parsed.manifest.repoName, source: ".bridge/config" });
2078
+ }
2079
+ catch (err) {
2080
+ if (!err || typeof err !== "object" || !("code" in err) || err.code !== "ENOENT")
2081
+ return { status: "unavailable" };
2082
+ }
2083
+ for (const target of hostConfigTargetsForPlatforms(["claude-code", "cursor", "copilot-vscode"])) {
2084
+ const result = await readHostConfig(deps, path.join(deps.cwd, target.relPath));
2085
+ if (result.state === "invalid")
2086
+ return { status: "unavailable" };
2087
+ if (result.state === "absent")
2088
+ continue;
2089
+ const top = asRecord(result.config[target.topLevelKey]);
2090
+ const registration = resolveRegistrationKey(top);
2091
+ if (registration.state === "conflict")
2092
+ return { status: "unavailable" };
2093
+ if (registration.state !== "absent") {
2094
+ const env = asRecord(asRecord(top?.[registration.key])?.env);
2095
+ const repo = env?.BAPI_REPO_NAME;
2096
+ if (typeof repo === "string" && repo.trim() && !repo.includes("<"))
2097
+ candidates.push({ repo: repo.trim(), source: target.relPath });
2098
+ }
2099
+ }
2100
+ const names = new Set(candidates.map(c => c.repo));
2101
+ if (!names.size)
2102
+ return { status: "absent" };
2103
+ if (names.size > 1)
2104
+ return { status: "conflicting", candidates };
2105
+ return { status: "resolved", repo: candidates[0].repo, sources: candidates.map(c => c.source) };
2106
+ }
2054
2107
  export async function resolveApiKey(options, deps) {
2055
2108
  if (typeof options.apiKey === "string" && options.apiKey.trim().length > 0) {
2056
2109
  return { ok: true, value: options.apiKey.trim(), source: "flag" };
@@ -2066,6 +2119,14 @@ export async function resolveApiKey(options, deps) {
2066
2119
  : "env";
2067
2120
  return { ok: true, value: fromEnv.trim(), source };
2068
2121
  }
2122
+ const repo = resolveConfiguredRepoName(options, deps.env);
2123
+ if (repo) {
2124
+ const stored = await resolveBapiCredentials(repo, installerCredentialReadDeps(deps));
2125
+ if (stored.ok)
2126
+ return { ok: true, value: stored.credentials.apiKey, source: stored.credentials.source === "env" ? "env" : "store" };
2127
+ if (stored.kind !== "not-found" && stored.kind !== "missing-key")
2128
+ return { ok: false, error: stored.error };
2129
+ }
2069
2130
  if (deps.isTTY && deps.promptSecret) {
2070
2131
  // BAPI-708 (A-3): the prompt no longer asks the user to pre-classify their own
2071
2132
  // credential ("Bridge API key or invite"). Classification is done from SHAPE
@@ -3144,37 +3205,24 @@ function asRecord(value) {
3144
3205
  ? value
3145
3206
  : undefined;
3146
3207
  }
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
3208
  async function detectExistingRealKey(deps, targets) {
3209
+ const observations = [];
3155
3210
  for (const target of targets) {
3156
3211
  const result = await readHostConfig(deps, path.join(deps.cwd, target.relPath));
3157
- if (result.state === "invalid")
3158
- return true;
3159
- if (result.state === "absent")
3212
+ if (result.state !== "parsed")
3160
3213
  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")
3214
+ const top = asRecord(result.config[target.topLevelKey]);
3215
+ const registration = resolveRegistrationKey(top);
3216
+ if (registration.state === "absent" || registration.state === "conflict")
3170
3217
  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;
3218
+ const env = asRecord(asRecord(top?.[registration.key])?.env);
3219
+ if (env && typeof env.BAPI_API_KEY === "string" && !isPlaceholderApiKey(env.BAPI_API_KEY)) {
3220
+ observations.push({ source: target.relPath, key: env.BAPI_API_KEY,
3221
+ repo: typeof env.BAPI_REPO_NAME === "string" ? env.BAPI_REPO_NAME : undefined,
3222
+ baseUrl: typeof env.BAPI_BASE_URL === "string" ? env.BAPI_BASE_URL : undefined });
3175
3223
  }
3176
3224
  }
3177
- return false;
3225
+ return observations;
3178
3226
  }
3179
3227
  /** The fixed, secret-free hard warning shown for a git-tracked project config (BAPI-666). */
3180
3228
  function trackedConfigWarning(relPath) {
@@ -3346,6 +3394,7 @@ async function writeHostConfigs(deps, targets, entries, trackedState, ctx) {
3346
3394
  // for `absent` — decided AFTER the safety branches above so an absent file is
3347
3395
  // never initialized before its tracked-state consent is resolved.
3348
3396
  const config = read.state === "parsed" ? read.config : {};
3397
+ const originalConfig = JSON.stringify(config);
3349
3398
  const topLevel = asRecord(config[target.topLevelKey]) ?? {};
3350
3399
  // BAPI-807: resolve WHICH key this config's registration lives under before
3351
3400
  // writing. A legacy-only entry is replaced under `bridge-api`, a canonical-only
@@ -3379,6 +3428,8 @@ async function writeHostConfigs(deps, targets, entries, trackedState, ctx) {
3379
3428
  preserveProjectRoot: tracked,
3380
3429
  });
3381
3430
  config[target.topLevelKey] = topLevel;
3431
+ if (read.state === "parsed" && JSON.stringify(config) === originalConfig)
3432
+ continue;
3382
3433
  await deps.mkdir(path.dirname(fullPath), { recursive: true });
3383
3434
  await deps.writeFile(fullPath, JSON.stringify(config, null, 2) + "\n", {
3384
3435
  encoding: "utf-8",
@@ -3643,6 +3694,8 @@ const CONNECTIVITY_KEY_SOURCE_ATTRIBUTION = {
3643
3694
  "different one)",
3644
3695
  flag: " (this key came from the --api-key flag — omit it to be prompted for a different one)",
3645
3696
  prompt: "",
3697
+ store: " (this key came from the saved credential store; repair or explicitly replace that entry)",
3698
+ host: " (this key came from an existing host binding)",
3646
3699
  };
3647
3700
  /**
3648
3701
  * Verify connectivity. Distinguishes a rejected/expired credential (401) from a
@@ -3706,10 +3759,9 @@ export async function verifyConnectivity(deps, baseUrl, repoName, apiKey, apiKey
3706
3759
  catch {
3707
3760
  return { ok: false, message: CONNECTIVITY_ACCESS_DENIED_FALLBACK };
3708
3761
  }
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 };
3762
+ const safeDetail = typeof detail === "string" ? detail.trim() : "";
3763
+ return { ok: false, message: /^repository '[a-zA-Z0-9_.-]+' is not registered; verify the repo_name$/.test(safeDetail) && !safeDetail.includes(apiKey)
3764
+ ? safeDetail : CONNECTIVITY_ACCESS_DENIED_FALLBACK };
3713
3765
  }
3714
3766
  if (resp.status === 404) {
3715
3767
  return {
@@ -5339,7 +5391,7 @@ export function resolveInstallBridgeBaseUrl(env) {
5339
5391
  catch {
5340
5392
  return { ok: false, error: buildInstallBridgeBaseUrlError(candidate) };
5341
5393
  }
5342
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
5394
+ if ((parsed.protocol !== "http:" && parsed.protocol !== "https:") || parsed.username || parsed.password || parsed.search || parsed.hash) {
5343
5395
  return { ok: false, error: buildInstallBridgeBaseUrlError(candidate) };
5344
5396
  }
5345
5397
  // The TRIMMED candidate is returned, not `parsed.toString()`: the latter would
@@ -5464,8 +5516,51 @@ export function isMinttyNonInteractiveInstall(platform, env, isTTY) {
5464
5516
  const msystem = env.MSYSTEM;
5465
5517
  return (typeof msystem === "string" && msystem.trim().length > 0) || env.TERM_PROGRAM === "mintty";
5466
5518
  }
5519
+ /** Preserve project/host identity while still delivering independent generated assets. */
5520
+ async function refreshIndependentInstallAssets(deps, reason) {
5521
+ deps.errorLog(reason);
5522
+ try {
5523
+ await deps.runInit(deps.cwd, { assetsOnly: true, env: { ...deps.env, BAPI_API_KEY: undefined },
5524
+ stdout: deps.log, stderr: deps.errorLog });
5525
+ deps.log("Independent Bridge assets refreshed. Existing identity, host bindings and preferences preserved; requested identity-dependent capabilities remain unavailable.");
5526
+ }
5527
+ catch {
5528
+ deps.errorLog("Independent asset refresh failed; completed work was retained.");
5529
+ }
5530
+ return 1;
5531
+ }
5532
+ async function selectInstalledProject(options, deps) {
5533
+ const installed = await observeInstalledIdentity(deps);
5534
+ const explicit = resolveConfiguredRepoName(options, deps.env);
5535
+ const terminal = { write: deps.log, read: deps.isTTY ? deps.promptLine : undefined };
5536
+ if (installed.status === "unavailable")
5537
+ return false;
5538
+ if (installed.status === "conflicting" && !explicit) {
5539
+ const names = [...new Set(installed.candidates.map(c => c.repo))];
5540
+ const choice = await askSetupQuestion({ purpose: "Select the installed Bridge project",
5541
+ evidence: installed.candidates.map(c => `${c.source}: ${c.repo}`),
5542
+ options: names.map((repo, i) => ({ id: String(i + 1), label: repo })),
5543
+ consequences: ["Selected host bindings and future requests use the chosen project after credential validation."],
5544
+ deferred: "Conflicting bindings remain unchanged; independent assets can still be refreshed.",
5545
+ recovery: "Inspect the bindings and rerun with the intended --repo." }, terminal);
5546
+ if (choice.status !== "selected")
5547
+ return false;
5548
+ options.repo = names[Number(choice.id) - 1];
5549
+ }
5550
+ else if (explicit && ((installed.status === "resolved" && installed.repo !== explicit) || installed.status === "conflicting")) {
5551
+ const accepted = await authorizeMaintenanceEffect({ category: "credential", state: { status: "present", identity: explicit },
5552
+ 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."]);
5553
+ if (!accepted)
5554
+ return false;
5555
+ }
5556
+ else if (!explicit && installed.status === "resolved")
5557
+ options.repo = installed.repo;
5558
+ return true;
5559
+ }
5467
5560
  export async function runInstallBridgeCli(argv, overrides = {}) {
5468
5561
  const deps = { ...createDefaultInstallBridgeDeps(), ...overrides };
5562
+ const originalEnvironment = { ...deps.env };
5563
+ deps.env = { ...deps.env };
5469
5564
  // When the caller overrode only `fetch` (the common test seam), bind the
5470
5565
  // default resolver to the FINAL merged fetch so server resolution still routes
5471
5566
  // through the override. An explicit `resolveRepoViaServer` override is honored.
@@ -5503,20 +5598,20 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
5503
5598
  // A rejected value cannot be interpolated into guidance, so usage falls back to
5504
5599
  // the documented default — the run is about to fail on it anyway.
5505
5600
  const usageBaseUrl = baseUrlResult.ok ? baseUrlResult.value : DEFAULT_BAPI_BASE_URL;
5506
- // ---- BAPI-679: nested `install-bridge conductor` -----------------------
5601
+ // ---- BAPI-679: nested `install epic-implementer` -----------------------
5507
5602
  // Intercepted HERE, before `parseInstallBridgeArgs`, because that parser
5508
5603
  // rejects ALL positional arguments — a bare `conductor` token would otherwise
5509
5604
  // be an argument error. Deliberately after the deps merge and the base-URL
5510
5605
  // resolution above, so the nested command inherits the same final merged deps
5511
5606
  // (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
5607
+ // Note this is `install epic-implementer`; it is UNRELATED to the top-level
5513
5608
  // `conductor`/`epic-implementer` CLI split (S4/BAPI-1080) — the bare
5514
5609
  // top-level `conductor` token is now a fixed migration stub and the real
5515
5610
  // event-ledger CLI routes through `runEpicImplementerCli` under the
5516
- // `epic-implementer` name. This nested `install-bridge conductor` surface is
5611
+ // `epic-implementer` name. This nested `install epic-implementer` surface is
5517
5612
  // untouched by that rename.
5518
- if (argv[0] === "conductor") {
5519
- // ---- BAPI-1136: `install-bridge conductor --merge-workflow` ----------
5613
+ if (argv[0] === "conductor" || argv[0] === "epic-implementer") {
5614
+ // ---- BAPI-1136: `install epic-implementer --merge-workflow` ----------
5520
5615
  //
5521
5616
  // Intercepted ahead of `parseInstallBridgeConductorArgs` on purpose. That
5522
5617
  // parser REQUIRES at least one `--required-check` because an empty done gate
@@ -5537,6 +5632,23 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
5537
5632
  return 1;
5538
5633
  }
5539
5634
  try {
5635
+ if (!mergeWorkflowArgs.options.dryRun) {
5636
+ const setup = deps.conductorSetup ?? buildConductorSetupDeps(deps, log, errorLog);
5637
+ log("Epic Implementer merge-workflow setup requires github.com, GitHub CLI sign-in, and Claude Code sign-in.");
5638
+ const remote = await setup.readLocalGithubRemote();
5639
+ const signedIn = await setup.checkGithubSignIn();
5640
+ const claude = await setup.detectClaudeLogin();
5641
+ if (!remote || signedIn !== "signed_in" || !claude.detected) {
5642
+ 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.");
5643
+ return refreshIndependentInstallAssets(deps, "Epic Implementer prerequisites blocked; independent Bridge maintenance continues.");
5644
+ }
5645
+ const lookup = deps.lookupExecutable ?? defaultExecutablePresenceProbe;
5646
+ for (const tool of ["git", "gh", "claude"])
5647
+ if (!await lookup(tool)) {
5648
+ errorLog(`Epic Implementer requires ${tool} on PATH.`);
5649
+ return refreshIndependentInstallAssets(deps, "Epic Implementer tooling unavailable.");
5650
+ }
5651
+ }
5540
5652
  return await runMergeWorkflowInstall(deps.cwd, mergeWorkflowArgs.options, buildMergeWorkflowInstallDeps(deps, log, errorLog));
5541
5653
  }
5542
5654
  catch {
@@ -5556,14 +5668,73 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
5556
5668
  }
5557
5669
  const conductorBaseUrl = baseUrlResult.value;
5558
5670
  const conductorDeps = {
5671
+ prerequisites: async (executorRequested) => {
5672
+ const lookup = deps.lookupExecutable ?? defaultExecutablePresenceProbe;
5673
+ const tooling = await Promise.all(["git", "gh", "claude", ...(executorRequested ? ["wt"] : [])].map(async (name) => { try {
5674
+ return await lookup(name);
5675
+ }
5676
+ catch {
5677
+ return false;
5678
+ } }));
5679
+ return { claudeLoggedIn: null, githubSignIn: "unavailable", localRemote: null,
5680
+ toolsAvailable: tooling.every(Boolean), platformSupported: !executorRequested || deps.platform === "darwin" || deps.platform === "linux" };
5681
+ },
5682
+ isTTY: deps.isTTY,
5559
5683
  env: deps.env,
5560
5684
  cwd: deps.cwd,
5561
5685
  log: deps.log,
5562
5686
  errorLog: deps.errorLog,
5563
5687
  promptLine: deps.promptLine,
5564
5688
  resolveBaseUrl: () => ({ ok: true, value: conductorBaseUrl }),
5565
- resolveAccess: (repoName, resolvedBaseUrl) => (deps.conductorResolveAccess ??
5566
- (async () => ({ ok: false, error: "conductor access seam unavailable" })))(repoName, resolvedBaseUrl, deps),
5689
+ resolveAccess: async (repoName, resolvedBaseUrl) => {
5690
+ if (argv.includes("--dry-run")) {
5691
+ // Injected access providers own their already-settled identity. The production
5692
+ // preview uses the shared read-only endpoint resolver, with the original env.
5693
+ if (overrides.conductorResolveAccess)
5694
+ return overrides.conductorResolveAccess(repoName, resolvedBaseUrl, deps);
5695
+ const installed = await observeInstalledIdentity(deps);
5696
+ const project = repoName ?? originalEnvironment.BAPI_REPO_NAME ?? (installed.status === "resolved" ? installed.repo : undefined);
5697
+ if (!project || installed.status === "unavailable" || installed.status === "conflicting")
5698
+ return { ok: false, error: "Project identity deferred during preview." };
5699
+ const credential = await resolveEpicLaunchCredential(project, resolvedBaseUrl, { ...installerCredentialReadDeps(deps), env: originalEnvironment }, { productionBaseUrl: DEFAULT_BAPI_BASE_URL });
5700
+ return credential.ok ? { ok: true, access: { repoName: project, baseUrl: resolvedBaseUrl, apiKey: credential.apiKey } }
5701
+ : { ok: false, error: "Credential validation and endpoint authorization deferred during dry run." };
5702
+ }
5703
+ const parsedIdentity = parseInstallBridgeArgs(repoName ? ["--repo", repoName] : []);
5704
+ if (parsedIdentity.status !== "ok")
5705
+ return { ok: false, error: "Project selector unavailable." };
5706
+ if (!await selectInstalledProject(parsedIdentity.options, deps)) {
5707
+ return { ok: false, error: "Project identity remains unresolved." };
5708
+ }
5709
+ const access = await (deps.conductorResolveAccess ?? (async () => ({ ok: false, error: "access seam unavailable" })))(parsedIdentity.options.repo ?? repoName, resolvedBaseUrl, deps);
5710
+ if (!access.ok)
5711
+ return access;
5712
+ const settled = await settleMaintenanceCredential({ repoName: access.access.repoName, baseUrl: resolvedBaseUrl,
5713
+ productionBaseUrl: DEFAULT_BAPI_BASE_URL,
5714
+ hosts: await detectExistingRealKey(deps, hostConfigTargetsForPlatforms(["claude-code", "cursor", "copilot-vscode"])),
5715
+ candidate: { key: access.access.apiKey, source: originalEnvironment.BAPI_API_KEY ? "env" : "store" },
5716
+ originalEnvironment, store: installerCredentialReadDeps(deps), report: log,
5717
+ terminal: { write: log, read: deps.isTTY ? deps.promptLine : undefined },
5718
+ validate: async (key) => (await verifyConnectivity(deps, resolvedBaseUrl, access.access.repoName, key)).ok });
5719
+ if (!settled.ok) {
5720
+ return { ok: false, error: settled.reason };
5721
+ }
5722
+ const identity = settled.identity;
5723
+ if (identity.persist) {
5724
+ const written = await deps.upsertCredential(identity.repoName, identity.apiKey, modernWriteDeps(deps), { observedKey: identity.observedKey });
5725
+ if (!written.ok)
5726
+ return { ok: false, error: "Saved identity changed; rerun setup before dependent work." };
5727
+ }
5728
+ if (identity.bindEndpoint) {
5729
+ const bound = await (deps.bindCredential ?? bindEpicLaunchCredential)(identity.repoName, resolvedBaseUrl, modernWriteDeps(deps), { observedKey: identity.apiKey });
5730
+ if (!bound.ok)
5731
+ return { ok: false, error: "Endpoint approval could not be saved; rerun setup." };
5732
+ }
5733
+ deps.env = { ...deps.env, BAPI_API_KEY: identity.apiKey, BAPI_REPO_NAME: identity.repoName };
5734
+ conductorDeps.env = deps.env;
5735
+ deps.startTicketsDeps = { ...deps.startTicketsDeps, env: deps.env };
5736
+ return { ok: true, access: { ...access.access, apiKey: identity.apiKey, baseUrl: resolvedBaseUrl } };
5737
+ },
5567
5738
  fetchJson: deps.fetch,
5568
5739
  postJson: deps.fetch,
5569
5740
  runDoctor: (params) => (deps.conductorRunDoctor ??
@@ -5622,7 +5793,12 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
5622
5793
  }),
5623
5794
  },
5624
5795
  };
5625
- return runInstallBridgeConductorCli(argv.slice(1), conductorDeps);
5796
+ const result = await runInstallBridgeConductorCli(argv.slice(1), conductorDeps);
5797
+ const nested = parseInstallBridgeConductorArgs(argv.slice(1));
5798
+ if (result === 1 && nested.status === "ok" && !nested.options.dryRun) {
5799
+ return refreshIndependentInstallAssets(nested.options.json ? { ...deps, log: errorLog } : deps, "Epic Implementer setup remains incomplete; refreshing independent Bridge assets.");
5800
+ }
5801
+ return result;
5626
5802
  }
5627
5803
  const parsed = parseInstallBridgeArgs(argv);
5628
5804
  if (parsed.status === "help") {
@@ -5700,6 +5876,7 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
5700
5876
  // returns before `resolveInviteToken`/`resolveSignupEmail` even run.
5701
5877
  if (options.dryRun) {
5702
5878
  log(`${INSTALL_BRIDGE_CWD_BANNER_PREFIX}${deps.cwd}`);
5879
+ log(`Bridge destination: ${baseUrl} (${deps.env.BAPI_BASE_URL === undefined ? "production default" : "BAPI_BASE_URL"}).`);
5703
5880
  const repo = typeof options.repo === "string" && options.repo.trim().length > 0
5704
5881
  ? { kind: "explicit", value: options.repo.trim() }
5705
5882
  : typeof deps.env.BAPI_REPO_NAME === "string" && deps.env.BAPI_REPO_NAME.trim().length > 0
@@ -5782,12 +5959,14 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
5782
5959
  })) {
5783
5960
  log(line);
5784
5961
  }
5962
+ log("Credential validation and consequential authorization are deferred until a live run.");
5785
5963
  return 0;
5786
5964
  }
5787
5965
  // ---- BAPI-669 (U2): working-directory banner + project-root gate ----
5788
5966
  // See the section comment on `hasProjectRootMarker`: read-only, and positioned
5789
5967
  // ahead of ALL credential and configuration work so a decline costs nothing.
5790
5968
  log(`${INSTALL_BRIDGE_CWD_BANNER_PREFIX}${deps.cwd}`);
5969
+ log(`Bridge destination: ${baseUrl} (${deps.env.BAPI_BASE_URL === undefined ? "production default" : "BAPI_BASE_URL"}).`);
5791
5970
  if (!(await hasProjectRootMarker(deps))) {
5792
5971
  if (deps.isTTY && deps.promptLine) {
5793
5972
  let answer = "";
@@ -5819,6 +5998,26 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
5819
5998
  // The selection is pure and deterministic for every explicit, env-driven, and
5820
5999
  // non-TTY invocation; only a BARE interactive run is asked which branch it wants
5821
6000
  // (BAPI-626 — otherwise a first-time user can never reach self-serve).
6001
+ if (!await selectInstalledProject(options, deps))
6002
+ return refreshIndependentInstallAssets(deps, "Installed project identity is unresolved or unreadable; existing bindings preserved.");
6003
+ const establishedRepo = resolveConfiguredRepoName(options, deps.env);
6004
+ const storedObservation = establishedRepo ? await resolveBapiCredentials(establishedRepo, {
6005
+ ...installerCredentialReadDeps(deps), env: { ...deps.env, BAPI_API_KEY: undefined },
6006
+ }) : undefined;
6007
+ if (storedObservation && !storedObservation.ok && !["not-found", "missing-key"].includes(storedObservation.kind)) {
6008
+ return refreshIndependentInstallAssets(deps, `Saved credential ${storedObservation.kind}. Repair the credential store; signup was not selected.`);
6009
+ }
6010
+ const hostObservations = await detectExistingRealKey(deps, hostConfigTargetsForPlatforms(["claude-code", "cursor", "copilot-vscode"]));
6011
+ if (hostObservations.some(host => !host.repo))
6012
+ return refreshIndependentInstallAssets(deps, "An installed host credential has no project identity. Repair its BAPI_REPO_NAME binding before reconnecting; existing bindings preserved.");
6013
+ const establishedHost = hostObservations.find(host => host.repo === establishedRepo);
6014
+ const storedInputSource = storedObservation?.ok ? "store" : establishedHost ? "host" : undefined;
6015
+ const explicitRoute = options.inviteMode || options.email || deps.env.BAPI_INVITE?.trim() || deps.env.BAPI_SIGNUP_EMAIL?.trim();
6016
+ const usingInstalledInput = !!(storedInputSource && !explicitRoute && !options.apiKey && !deps.env.BAPI_API_KEY?.trim());
6017
+ if (usingInstalledInput) {
6018
+ options.apiKey = storedObservation?.ok ? storedObservation.credentials.apiKey : establishedHost.key;
6019
+ log("Resuming installed project with its saved credential.");
6020
+ }
5822
6021
  const branchResult = await resolveInstallBridgeOnboardingBranchForRun(options, deps, argv, baseUrl);
5823
6022
  if (!branchResult.ok) {
5824
6023
  errorLog(`Error: ${branchResult.error}`);
@@ -6001,6 +6200,25 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
6001
6200
  // 404 is the BAPI-616 feature-detect for an older or self-hosted server, and
6002
6201
  // `error` covers a transient network failure or a 401. Collapsing these into
6003
6202
  // the hard stop would make a blip unrecoverable.
6203
+ let acceptedIdentity;
6204
+ const oldKey = storedObservation?.ok ? storedObservation.credentials.apiKey : establishedHost?.key;
6205
+ let acceptedReplacement = false;
6206
+ if (!bootstrapInviteMode && establishedRepo) {
6207
+ const settled = await settleMaintenanceCredential({ repoName: establishedRepo, baseUrl,
6208
+ productionBaseUrl: DEFAULT_BAPI_BASE_URL, hosts: hostObservations,
6209
+ candidate: { key: apiKey, source: usingInstalledInput ? storedInputSource : apiKeySource ?? "prompt" },
6210
+ originalEnvironment, store: installerCredentialReadDeps(deps),
6211
+ terminal: { write: log, read: deps.isTTY ? deps.promptLine : undefined }, report: log,
6212
+ validate: async (key) => (await verifyConnectivity(deps, baseUrl, establishedRepo, key)).ok });
6213
+ if (!settled.ok)
6214
+ return refreshIndependentInstallAssets(deps, settled.reason);
6215
+ acceptedIdentity = settled.identity;
6216
+ apiKey = acceptedIdentity.apiKey;
6217
+ apiKeySource = acceptedIdentity.source;
6218
+ acceptedReplacement = acceptedIdentity.replacementAccepted;
6219
+ }
6220
+ if (!bootstrapInviteMode)
6221
+ deps.env = { ...deps.env, BAPI_API_KEY: apiKey };
6004
6222
  if (!bootstrapInviteMode && options.displayName !== undefined) {
6005
6223
  errorLog("Error: --display-name applies only to creation; existing-key registration uses canonical selection.");
6006
6224
  return 1;
@@ -6106,6 +6324,22 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
6106
6324
  }
6107
6325
  }
6108
6326
  }
6327
+ // A server-resolved project may already have a saved identity from another
6328
+ // clone. Observe and settle it before any project-dependent writes.
6329
+ if (!bootstrapInviteMode && !modernAttempt && !acceptedIdentity) {
6330
+ const settled = await settleMaintenanceCredential({ repoName, baseUrl,
6331
+ productionBaseUrl: DEFAULT_BAPI_BASE_URL, hosts: hostObservations,
6332
+ candidate: { key: apiKey, source: apiKeySource ?? "prompt" }, originalEnvironment,
6333
+ store: installerCredentialReadDeps(deps), terminal: { write: log, read: deps.isTTY ? deps.promptLine : undefined },
6334
+ report: log, validate: async (key) => (await verifyConnectivity(deps, baseUrl, repoName, key)).ok });
6335
+ if (!settled.ok)
6336
+ return refreshIndependentInstallAssets(deps, settled.reason);
6337
+ acceptedIdentity = settled.identity;
6338
+ apiKey = acceptedIdentity.apiKey;
6339
+ apiKeySource = acceptedIdentity.source;
6340
+ acceptedReplacement = acceptedIdentity.replacementAccepted;
6341
+ deps.env = { ...deps.env, BAPI_API_KEY: apiKey };
6342
+ }
6109
6343
  const credentialStorePath = getPrimaryCredentialStorePath({
6110
6344
  env: deps.env,
6111
6345
  homedir: deps.homedir,
@@ -6116,19 +6350,64 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
6116
6350
  // set. The selected project JSON targets drive the read-merge-write path; a selected
6117
6351
  // global (Codex) or manual (Windsurf) target is provisioned by the
6118
6352
  // registry-driven emitter after the connectivity check.
6119
- const selectedPlatforms = await resolveSelectedHostPlatforms(deps, options);
6353
+ const savedPreferences = await readMcpInstallState(deps.cwd, { readFile: deps.readFile });
6354
+ const toolPreferenceState = options.tools !== undefined ? "explicit"
6355
+ : savedPreferences.status === "valid" ? "preserved" : savedPreferences.status === "missing" ? "missing" : "invalid";
6356
+ if (toolPreferenceState === "invalid") {
6357
+ const repair = await askSetupQuestion({ purpose: "Repair invalid saved tool preferences",
6358
+ evidence: [`Preference status: ${savedPreferences.status}`],
6359
+ options: [{ id: "yes", label: "Choose replacement tool preferences" }, { id: "no", label: "Preserve the saved file" }],
6360
+ consequences: ["A new tool selection replaces the invalid installer preferences and determines which host configurations are maintained."],
6361
+ deferred: "Host configuration and preference writes are deferred; generated assets can still be refreshed.",
6362
+ recovery: "Repair .bridge/install-state.json or rerun with an explicit --tools selection." }, { write: log, read: deps.isTTY ? deps.promptLine : undefined });
6363
+ if (repair.status !== "accept")
6364
+ return refreshIndependentInstallAssets(deps, "Saved tool preferences require repair; existing preferences preserved.");
6365
+ }
6366
+ const selectedPlatforms = options.tools === undefined && savedPreferences.status === "valid"
6367
+ ? savedPreferences.state.selectedPlatforms
6368
+ : await resolveSelectedHostPlatforms(deps, options);
6369
+ if (options.tools === undefined && savedPreferences.status === "valid")
6370
+ log("Preserved saved tool selections; unavailable tools remain selected.");
6120
6371
  // ---- 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
6372
+ // Read established posture before offering a selection for missing or invalid
6373
+ // values. Valid preferences and indeterminate reads remain preserved. `--dry-run` already
6124
6374
  // returns long before this point (see the NOTE below), so this gate is
6125
6375
  // belt-and-suspenders, not the sole guard. The primary platform is
6126
6376
  // `selectedPlatforms[0]` exclusively, relying on the resolver's own
6127
6377
  // `HOST_PLATFORM_ORDER` normalization even when several tools were chosen.
6128
6378
  const optimizationPostureEligible = deps.isTTY && Boolean(deps.promptLine) && !options.dryRun;
6129
- const optimizationPostureSelection = optimizationPostureEligible
6130
- ? await promptOptimizationPosture(deps, selectedPlatforms[0])
6131
- : null;
6379
+ let savedPosture;
6380
+ let postureState = "missing";
6381
+ if (oldKey && !bootstrapInviteMode) {
6382
+ try {
6383
+ const response = await deps.fetch(`${buildOptimizationPostureUrl(baseUrl)}?repo_name=${encodeURIComponent(repoName)}`, {
6384
+ headers: { "X-API-Key": apiKey }, signal: AbortSignal.timeout(10_000)
6385
+ });
6386
+ if (response.ok) {
6387
+ const body = await response.json();
6388
+ if (body.value === "quality" || body.value === "speed" || body.value === "maximize_subscription") {
6389
+ savedPosture = body.value;
6390
+ postureState = "preserved";
6391
+ }
6392
+ else
6393
+ postureState = body.value == null ? "missing" : "invalid";
6394
+ }
6395
+ else
6396
+ postureState = response.status === 404 ? "missing" : "unavailable";
6397
+ }
6398
+ catch {
6399
+ postureState = "unavailable";
6400
+ }
6401
+ }
6402
+ let optimizationPostureSelection = null;
6403
+ if (optimizationPostureEligible && (postureState === "missing" || postureState === "invalid")) {
6404
+ const repairApproved = !oldKey || await authorizeMaintenanceEffect({ category: "bookkeeping",
6405
+ 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."]);
6406
+ if (repairApproved)
6407
+ optimizationPostureSelection = await promptOptimizationPosture(deps, selectedPlatforms[0]);
6408
+ }
6409
+ if (oldKey)
6410
+ 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
6411
  if (options.codexProfile && !selectedPlatforms.includes("codex")) {
6133
6412
  errorLog("Error: --codex-profile requires Codex in --tools or the interactive selection.");
6134
6413
  return 1;
@@ -6286,24 +6565,8 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
6286
6565
  unlink: deps.unlink,
6287
6566
  open: deps.open,
6288
6567
  };
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
- }
6568
+ // Only the explained replacement decision grants overwrite authority.
6569
+ let overwriteConsent = acceptedReplacement;
6307
6570
  // ---- BAPI-668 (R5-1): the guarded Step 1–5 execution region ----
6308
6571
  // Everything ABOVE this point — argument parsing, base-URL validation, input
6309
6572
  // resolution, the dry-run preview, and every deliberate pre-execution validation
@@ -6603,15 +6866,8 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
6603
6866
  }, credentialWriteDeps);
6604
6867
  // An existing bapi:<repo> credential is never clobbered without consent —
6605
6868
  // 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
- });
6869
+ // Creating replay proof does not authorize replacing the canonical credential.
6870
+ const prep = await prepareSelfServePending(true);
6615
6871
  if (prep === null)
6616
6872
  return false;
6617
6873
  if (!prep.ok) {
@@ -6681,15 +6937,8 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
6681
6937
  // An existing bapi:<repo> credential is never clobbered without consent. The
6682
6938
  // gate mirrors the host-config gate above: --force, else an interactive prompt,
6683
6939
  // 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
- });
6940
+ // Preserve replay proof independently of the later validated replacement decision.
6941
+ const prepared = await prepareInvitePending(true);
6693
6942
  if (prepared === null)
6694
6943
  return 1;
6695
6944
  // A pending record left by a DIFFERENT invite is that redemption's only replay
@@ -6893,21 +7142,62 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
6893
7142
  if (!reconciled.ok || reconciled.manifest.repoName !== repoName)
6894
7143
  return fatal("Installation incomplete: canonical configuration read-back failed. Preserve proof and resume from this folder.");
6895
7144
  }
7145
+ if (modernAttempt || bootstrapExchangeSucceeded) {
7146
+ const settled = await settleMaintenanceCredential({ repoName, baseUrl, productionBaseUrl: DEFAULT_BAPI_BASE_URL,
7147
+ candidate: { key: apiKey, source: "prompt" }, originalEnvironment,
7148
+ hosts: hostObservations, store: installerCredentialReadDeps(deps),
7149
+ terminal: { write: log, read: deps.isTTY ? deps.promptLine : undefined }, report: log,
7150
+ validate: async (key) => (await verifyConnectivity(deps, baseUrl, repoName, key)).ok });
7151
+ if (!settled.ok || settled.identity.apiKey !== apiKey) {
7152
+ return refreshIndependentInstallAssets(deps, "Bootstrap replacement deferred. Existing identity and durable replay proof were preserved; resume interactively from this folder.");
7153
+ }
7154
+ acceptedIdentity = settled.identity;
7155
+ overwriteConsent = acceptedIdentity.replacementAccepted;
7156
+ // Promote before writing host bindings; guarded failure preserves replay proof.
7157
+ currentStep = INSTALL_BRIDGE_STEP_LABELS.persistCredential;
7158
+ log(currentStep);
7159
+ if (modernAttempt) {
7160
+ const promoted = await promoteModernBootstrapCredential(modernAttempt.scope, modernAttempt.record, credentialWriteDeps, overwriteConsent, acceptedIdentity.observedKey);
7161
+ if (!promoted.ok)
7162
+ return fatal("Credential promotion changed or failed. Existing host bindings and replay proof preserved; rerun to re-evaluate.");
7163
+ }
7164
+ else {
7165
+ const promoted = await deps.promoteBootstrapPending({ repoName, inviteFingerprint,
7166
+ allowOverwriteExistingCredential: overwriteConsent, observedKey: acceptedIdentity.observedKey }, credentialWriteDeps);
7167
+ if (!promoted.ok)
7168
+ return fatal("Credential promotion changed or failed. Existing host bindings and replay proof preserved; rerun to re-evaluate.");
7169
+ }
7170
+ }
6896
7171
  // ---- 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.
7172
+ // is validated and `repoName`/`apiKey` are final. Only an intentional
7173
+ // selection is persisted. Failed requested writes report incomplete; no
7174
+ // answer leaves the existing preference unchanged.
7175
+ let maintenanceFailed = false;
6901
7176
  let persistedPosture;
6902
7177
  if (optimizationPostureSelection) {
6903
7178
  const postureResult = await persistOptimizationPosture(deps, baseUrl, apiKey, repoName, optimizationPostureSelection);
6904
7179
  reportOptimizationPostureOutcome(log, postureResult, optimizationPostureSelection, selectedPlatforms[0]);
6905
7180
  if (postureResult.kind === "success")
6906
7181
  persistedPosture = optimizationPostureSelection;
7182
+ else
7183
+ maintenanceFailed = true;
6907
7184
  }
6908
7185
  else if (optimizationPostureEligible) {
6909
7186
  log(OPTIMIZATION_POSTURE_UNCHANGED_MESSAGE);
6910
7187
  }
7188
+ let maintenancePersistence;
7189
+ if (!modernAttempt && !bootstrapExchangeSucceeded && (acceptedIdentity?.persist ?? (!storedObservation?.ok || storedObservation.credentials.apiKey !== apiKey))) {
7190
+ maintenancePersistence = await deps.upsertCredential(repoName, apiKey, credentialWriteDeps, { observedKey: acceptedIdentity?.observedKey ?? (storedObservation?.ok ? storedObservation.credentials.apiKey : null) });
7191
+ if (!maintenancePersistence.ok)
7192
+ return fatal("Credential persistence failed or identity changed since authorization. Host bindings and launches were deferred; rerun to re-evaluate.");
7193
+ }
7194
+ if (acceptedIdentity?.bindEndpoint) {
7195
+ const bound = await (deps.bindCredential ?? bindEpicLaunchCredential)(repoName, baseUrl, credentialWriteDeps, { observedKey: apiKey });
7196
+ if (!bound.ok)
7197
+ return fatal("Endpoint approval changed or could not be saved. Host bindings and launches deferred; rerun to re-evaluate.");
7198
+ }
7199
+ deps.env = { ...deps.env, BAPI_API_KEY: apiKey, BAPI_REPO_NAME: repoName };
7200
+ deps.startTicketsDeps = { ...deps.startTicketsDeps, env: deps.env };
6911
7201
  const entry = buildInstallBridgeServerEntry(deps.cwd, repoName, apiKey, baseUrl, docsDir);
6912
7202
  // BAPI-666: the secret-free variant (no BAPI_API_KEY) is written instead of the
6913
7203
  // real entry into any git-tracked project config the user did not explicitly
@@ -7061,8 +7351,30 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
7061
7351
  // writeMcpInstallState catches its own I/O errors and returns { ok: false }
7062
7352
  // (it does NOT throw), so the failure warning must inspect the return value —
7063
7353
  // a try/catch alone would silently swallow a real persistence failure.
7354
+ let stateReadFile = deps.readFile;
7355
+ if (savedPreferences.status !== "valid" && savedPreferences.status !== "missing") {
7356
+ // An intentional selection may repair only the tool roster in a readable
7357
+ // schema-v1 document. Preserve and validate every other owned preference.
7358
+ const statePath = path.join(deps.cwd, INSTALL_BRIDGE_INSTALL_STATE_PATH);
7359
+ const observed = await deps.readFile(statePath);
7360
+ const prior = JSON.parse(observed);
7361
+ if (!prior || Array.isArray(prior) || prior.version !== 1)
7362
+ throw new Error("Preference repair requires a supported document");
7363
+ const repaired = JSON.stringify({ ...prior, selectedPlatforms });
7364
+ const check = await readMcpInstallState(deps.cwd, { readFile: async () => repaired });
7365
+ if (check.status !== "valid" || check.state.packagedAssetsStatus)
7366
+ throw new Error("Other preferences require repair");
7367
+ stateReadFile = async (p) => {
7368
+ const current = await deps.readFile(p);
7369
+ if (p !== statePath)
7370
+ return current;
7371
+ if (current !== observed)
7372
+ throw new Error("Preferences changed since selection");
7373
+ return repaired;
7374
+ };
7375
+ }
7064
7376
  const stateResult = await writeMcpInstallState(deps.cwd, { selectedPlatforms, projectConfigPaths: targets.map((t) => t.relPath) }, {
7065
- readFile: deps.readFile,
7377
+ readFile: stateReadFile,
7066
7378
  writeFile: (p, data) => deps.writeFile(p, data, { encoding: "utf-8" }),
7067
7379
  rename: deps.rename,
7068
7380
  mkdir: async (p, o) => {
@@ -7071,13 +7383,13 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
7071
7383
  unlink: deps.unlink,
7072
7384
  });
7073
7385
  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).");
7386
+ maintenanceFailed = true;
7387
+ errorLog("Installation incomplete: could not persist tool preferences; existing state preserved.");
7076
7388
  }
7077
7389
  }
7078
7390
  catch {
7079
- // ensureGitignored for the state file can still throw — also advisory.
7080
- errorLog("Warning: could not persist the install-state file (non-fatal).");
7391
+ maintenanceFailed = true;
7392
+ errorLog("Installation incomplete: could not persist tool preferences; existing state preserved.");
7081
7393
  }
7082
7394
  // ---- Step 4 — persist the credential ----
7083
7395
  // Gated on the post-exchange transition rather than the mode flag (BAPI-668):
@@ -7085,16 +7397,6 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
7085
7397
  // two are equivalent — but keying promotion to the same state that justifies the
7086
7398
  // catch block's resume guidance makes that invariant explicit and un-driftable.
7087
7399
  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
7400
  log(formatProjectCredentialStoreLine(repoName, credentialStorePath));
7099
7401
  log(`Project '${modernAttempt.displayName}' installed successfully.`);
7100
7402
  }
@@ -7108,24 +7410,14 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
7108
7410
  // successful run prints exactly one Step 4 line and never narrates promotion
7109
7411
  // as a step of its own. Still assigned before the log, preserving the
7110
7412
  // 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));
7413
+ log(formatProjectCredentialStoreLine(repoName, credentialStorePath));
7122
7414
  }
7123
7415
  else {
7124
7416
  // ---- persist routing credential (non-blocking / fail-open) ----
7125
7417
  currentStep = INSTALL_BRIDGE_STEP_LABELS.persistCredential;
7126
7418
  log(currentStep);
7127
7419
  try {
7128
- const result = await deps.upsertCredential(repoName, apiKey, credentialWriteDeps);
7420
+ const result = maintenancePersistence ?? { ok: true, path: credentialStorePath, target: `bapi:${repoName}`, action: "unchanged", migratedFallback: false };
7129
7421
  if (result.ok) {
7130
7422
  log(formatProjectCredentialStoreLine(repoName, result.path));
7131
7423
  }
@@ -7195,6 +7487,7 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
7195
7487
  notesResult = await writeAgentNotes({
7196
7488
  cwd: deps.cwd,
7197
7489
  selectedPlatforms,
7490
+ fs: deps.notesFs,
7198
7491
  guidance: AGENT_GUIDANCE,
7199
7492
  readFile: deps.readFile,
7200
7493
  writeFile: deps.writeFile,
@@ -7202,6 +7495,7 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
7202
7495
  });
7203
7496
  for (const file of notesResult.files) {
7204
7497
  if (file.status === "failed") {
7498
+ maintenanceFailed = true;
7205
7499
  errorLog(` warning: could not update ${file.target} with agent notes (${file.reason}).`);
7206
7500
  errorLog(` Resolve the reported issue in ${file.target}, then rerun an interactive install to retry guidance.`);
7207
7501
  }
@@ -7211,6 +7505,7 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
7211
7505
  // Fail-open, mirroring the routing-credential persistence above: the
7212
7506
  // install itself is already complete and durable.
7213
7507
  notesWriteFailed = true;
7508
+ maintenanceFailed = true;
7214
7509
  errorLog(" warning: could not write agent notes (unexpected error).");
7215
7510
  }
7216
7511
  }
@@ -7330,7 +7625,7 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
7330
7625
  if (deps.platform === "darwin")
7331
7626
  errorLog(macosTerminalPermissionGuidance());
7332
7627
  log(buildManualInstallBridgeContinuation("configured", labelsForPlatforms(selectedPlatforms)));
7333
- return 0;
7628
+ return maintenanceFailed ? 1 : 0;
7334
7629
  }
7335
7630
  // BAPI-669 (U3): the handoff speaks the HOST TOOL'S display label, never the
7336
7631
  // raw agent binary name — computed once so all three sentences agree.
@@ -7351,18 +7646,18 @@ export async function runInstallBridgeCli(argv, overrides = {}) {
7351
7646
  "once the repository reaches full parse readiness — there is no indexing question to answer. " +
7352
7647
  `Verify afterwards at ${setupUrl} (Get Started page — install status panel) or via the ` +
7353
7648
  "session's 'Applied N of M' summary.");
7354
- return 0;
7649
+ return maintenanceFailed ? 1 : 0;
7355
7650
  }
7356
7651
  // Declined (or non-TTY suppression): the deterministic setup is complete and durable.
7357
7652
  log(buildManualInstallBridgeContinuation("configured", labelsForPlatforms(selectedPlatforms)));
7358
- return 0;
7653
+ return maintenanceFailed ? 1 : 0;
7359
7654
  }
7360
7655
  // No launchable session (a no-launchable selection, or a non-TTY / declined chooser):
7361
7656
  // finalAgentName is null, so nothing was materialized. The configured hosts are
7362
7657
  // durable — print the shared continuation + limited-tools note (never the
7363
7658
  // empty-selection variant, which already returned above).
7364
7659
  log(buildManualInstallBridgeContinuation("configured", labelsForPlatforms(selectedPlatforms)));
7365
- return 0;
7660
+ return maintenanceFailed ? 1 : 0;
7366
7661
  }
7367
7662
  catch (error) {
7368
7663
  // BAPI-807: a launcher-config PREFLIGHT refusal is actionable, and the