@bridge_gpt/mcp-server 0.2.76 → 0.2.77

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 (58) hide show
  1. package/README.md +8 -6
  2. package/build/agents.generated.js +3 -3
  3. package/build/cli-dispatch.js +333 -0
  4. package/build/commands.generated.js +5 -5
  5. package/build/conductor/bridge-api-client.js +52 -7
  6. package/build/conductor/declare-blocked.js +142 -7
  7. package/build/conductor/driver-register.js +8 -2
  8. package/build/conductor/epic-implementer-cli.js +11 -7
  9. package/build/conductor/epic-server-journal.js +39 -22
  10. package/build/conductor/launch-plan.js +28 -7
  11. package/build/conductor/local-merge.js +1 -1
  12. package/build/conductor/readiness-prerequisites.js +89 -2
  13. package/build/conductor/recovery-cli.js +2 -0
  14. package/build/docs.generated.js +67 -4
  15. package/build/doctor.js +97 -1
  16. package/build/drive-epic.js +223 -6
  17. package/build/engine-paths.js +10 -0
  18. package/build/epic-coherence-input-cli.js +105 -10
  19. package/build/epic-coherence-input.js +877 -4
  20. package/build/epic-coherence-input.test-fixtures.js +117 -0
  21. package/build/epic-implementer-bin.js +901 -94
  22. package/build/epic-implementer-env.js +2 -2
  23. package/build/executor/completion-contract.js +14 -1
  24. package/build/executor/guarded-fast-forward-push.js +25 -2
  25. package/build/executor/job-runner.js +83 -27
  26. package/build/executor/likely-tests.js +78 -6
  27. package/build/executor/provider-checks.js +73 -0
  28. package/build/executor/rebase-finalization.js +29 -27
  29. package/build/executor/rename-aside.js +265 -0
  30. package/build/executor/required-work-ledger.js +82 -4
  31. package/build/executor/types.js +121 -0
  32. package/build/executor/worktree.js +27 -1
  33. package/build/index.js +2449 -386
  34. package/build/install-bridge-conductor-assessment.js +13 -0
  35. package/build/install-bridge-conductor.js +60 -776
  36. package/build/install-bridge.js +4 -11
  37. package/build/language-catalog.generated.js +2649 -0
  38. package/build/pipelines.generated.js +45 -17
  39. package/build/plan-execution-ledger.js +8 -0
  40. package/build/plan-generation.js +34 -0
  41. package/build/plane/build-freshness.js +6 -0
  42. package/build/plane/cli.js +12 -5
  43. package/build/printed-remedy-commands.js +9 -0
  44. package/build/readiness-prerequisites.generated.js +28 -0
  45. package/build/readme.generated.js +1 -1
  46. package/build/run-unit-tests-launcher.js +3 -1
  47. package/build/server.js +7946 -0
  48. package/build/start-tickets-prereqs.js +3 -6
  49. package/build/test-support/console-guard.js +30 -0
  50. package/build/test-support/module-imports.js +155 -0
  51. package/build/test-support/server-client.js +96 -0
  52. package/build/test-support/stdio-server.js +146 -0
  53. package/build/v2-readiness-requirements.js +31 -2
  54. package/build/version.generated.js +3 -3
  55. package/docs/EPIC-IMPLEMENTER.md +71 -2
  56. package/docs/epic-implementer/getting-started.md +4 -0
  57. package/package.json +3 -3
  58. package/pipelines/learn-repository.json +19 -1
@@ -17,22 +17,21 @@ import { withSetupProgress } from "./setup-progress.js";
17
17
  /**
18
18
  * `install epic-implementer` — the nested conductor bootstrap phase (BAPI-679).
19
19
  *
20
- * BAPI-1461 — CONVERGING SETUP. With the production setup seams (always
21
- * supplied by `install-bridge.ts`), this command is a loop, not a script: it
20
+ * BAPI-1461 — CONVERGING SETUP, the only setup flow (BAPI-1721 retired the
21
+ * phased sequence it replaced). Every caller supplies the setup seams
22
+ * (`install-bridge.ts` builds them), and the command is a loop, not a script: it
22
23
  * reads the Claude login marker, confirms the base URL, checks `gh auth
23
24
  * status`, collects every readiness finding read-only, fixes only the missing
24
25
  * items in order (each write surface behind its own consent), checks again —
25
- * running the deny-enforcement probe once, there — and prints one verdict
26
- * beside the legacy completion line. The fixed eight-phase sequence below
27
- * remains only for a caller that supplies no setup seams. See
28
- * `install-bridge-conductor-setup.ts` for the item model and fix planner.
26
+ * running the deny-enforcement probe once, there — and prints one readiness
27
+ * verdict. See `install-bridge-conductor-setup.ts` for the item model and fix
28
+ * planner.
29
29
  *
30
30
  * Standing up Epic Conductor v2 on a fresh repository previously meant a manual
31
31
  * sequence of API calls and hand-written config, with five server-side
32
32
  * prerequisites that were invisible until an epic was already running and
33
- * failing. This command replaces that sequence with: diagnose → consent →
34
- * bootstrap the safe posture → optionally scaffold the review workflow → report
35
- * capabilities → verify → diagnose again.
33
+ * failing. This command replaces that sequence with one run: a read-only check,
34
+ * the approved missing fixes, a closing check, and one verdict.
36
35
  *
37
36
  * Four properties are load-bearing and are pinned by tests:
38
37
  *
@@ -53,19 +52,20 @@ import { withSetupProgress } from "./setup-progress.js";
53
52
  * otherwise. Local lifecycle success and server observation are reported as
54
53
  * two separate facts, and the second is never derived from the first.
55
54
  *
56
- * The two local out-of-the-box phases (BAPI-775) run between the workflow
57
- * scaffold and setup-epic verification, each behind its own consent:
55
+ * Local host configuration (BAPI-775, narrowed by BAPI-1721). One local
56
+ * operation remains in setup, behind its own consent:
58
57
  *
59
- * tool visibility — merge the `conductor` token into EXISTING supported host
60
- * MCP entries (`.mcp.json`, `.vscode/mcp.json`, `.cursor/mcp.json` only,
61
- * never Codex or Copilot), then print the restart advisory, because
62
- * `ACTIVE_GROUPS` is frozen at MCP server startup.
63
- * local observability — install the managed Git hooks, then report
64
- * native ledger loadability. The ledger probe is READ-ONLY, so it needs no
65
- * consent and runs whether hook consent was accepted or declined.
58
+ * tool visibility — merge the `epic_implementer` token into EXISTING
59
+ * supported host MCP entries (`.mcp.json`, `.vscode/mcp.json`,
60
+ * `.cursor/mcp.json` only, never Codex or Copilot), then print the restart
61
+ * guidance, because `ACTIVE_GROUPS` is frozen at MCP server startup.
66
62
  *
67
- * Neither can produce `complete`: they provision LOCAL capability, and the
68
- * terminal outcome still turns only on the live server-observed executor claim.
63
+ * Optional Git hooks are NOT part of setup. `epic-implementer install-git-hooks`
64
+ * installs them on its own, and the doctor reports hook-target and native-ledger
65
+ * state read-only; setup only recommends the standalone command.
66
+ *
67
+ * Local provisioning cannot produce `complete`: the terminal outcome still turns
68
+ * only on the live server-observed executor claim.
69
69
  *
70
70
  * DURABLE-HOST MODE (BAPI-1137). The executor phase below is the supported
71
71
  * bring-up for a *durable host*: an execution home that is not an interactive
@@ -137,8 +137,7 @@ import { collectEpicBranchCi, confirmRequestFor, planDeclarations, resolveEffect
137
137
  import { classifyEpicPullRequestTrigger, readDefaultBranchRequiredChecksViaGh, readPullRequestBranchFilters, } from "./conductor/epic-branch-ci-inspection.js";
138
138
  import { describeGateConsequence } from "./conductor/readiness-sections.js";
139
139
  import { fetchConductorReadiness, } from "./conductor/bridge-api-client.js";
140
- import { CONDUCTOR_OPERATOR_RUNBOOK_POINTER, EXECUTOR_PROVISIONING_GUIDANCE, conductorInstallDoctorExitCode, conductorInstallDoctorHasFatal, formatConductorInstallDoctorReport, } from "./conductor/install-doctor.js";
141
- import { describeNativeLedgerAvailability, } from "./conductor/doctor.js";
140
+ import { CONDUCTOR_OPERATOR_RUNBOOK_POINTER, conductorInstallDoctorExitCode, conductorInstallDoctorHasFatal, formatConductorInstallDoctorReport, } from "./conductor/install-doctor.js";
142
141
  import { resolveGithubMergeRepositoryIdentity, } from "./credential-store.js";
143
142
  import { isUsableMergeCredentialValue, resolveLocalMergeCredentialDetailed, } from "./conductor/merge-credential.js";
144
143
  import { readStoredTestCommand } from "./testing-config-client.js";
@@ -157,8 +156,8 @@ import { CANDIDATE_EXCLUSION_TEXT, CANDIDATE_ORIGIN_LABEL, describeInventoryExcl
157
156
  import { buildEpicCapabilityStatement } from "./epic-capability-statement.js";
158
157
  import { MCP_GRANT_MAX_SERVERS } from "./mcp-grant.js";
159
158
  import { advisoryFindingLines, assessIndexFreshness, assessSetupIndex, catalogLabel, NPM_SETUP_LAUNCHER, closedSetupPullRequestNotice, compareIndexedToMerge, planSetupFixes, projectSetupItems, readSetupPullRequest, renderSetupAssessment, deriveCompactReadiness, setupItemRemedy, setupVerdictLine, unmetBlockingItems, } from "./install-bridge-conductor-setup.js";
160
- import { CONDUCTOR_BIN_UNRESOLVED_ERROR, MANAGED_HOOK_NAMES, } from "./conductor/git-hooks.js";
161
159
  import { profileMergeNeededFrom } from "./mcp-host-config.js";
160
+ import { overlayReadinessPrerequisites, toolVisibilityStateFromInspection } from "./conductor/readiness-prerequisites.js";
162
161
  import { DuplicateRegistrationError } from "./init.js";
163
162
  import { DUPLICATE_REGISTRATION_GUIDANCE } from "./launcher-config-inspection.js";
164
163
  import os from "node:os";
@@ -168,7 +167,6 @@ import { bindEpicLaunchCredential, readStoredBinding, } from "./credential-store
168
167
  import { EPIC_LAUNCH_EXECUTION_MODES, EPIC_LAUNCH_PROFILE_NAME_PATTERN, EPIC_LAUNCH_PROFILE_VERSION, createNodeEpicLaunchStoreDeps, readEpicLaunchProfile, renderEpicLaunchCommand, resolveEpicLaunchTarget, shellQuote, writeEpicLaunchProfile, } from "./epic-launch-profile.js";
169
168
  import { DEFAULT_BAPI_BASE_URL } from "./executor/credentials.js";
170
169
  import { MCP_PACKAGE_NAME } from "./mcp-identity.js";
171
- import { LOCAL_MERGE_CREDENTIAL_ENV_KEYS } from "./conductor/merge-credential.js";
172
170
  import { CLAUDE_REVIEW_WORKFLOW_RELPATH, renderClaudeReviewWorkflow, } from "./claude-review-workflow.js";
173
171
  import { formatExecutorInstallPreflight, } from "./executor/install-preflight.js";
174
172
  import { buildExecutorServiceStartPlan, formatExecutorServiceStartFailure, } from "./executor/service-lifecycle.js";
@@ -386,18 +384,14 @@ export function getInstallBridgeConductorUsage() {
386
384
  "setup then applies the previewed bootstrap policy. Without a TTY it shows",
387
385
  "the preview and writes no policy.",
388
386
  "",
389
- "Tool visibility (its own consent): adds the `epic_implementer` token to the",
390
- "BRIDGE_MCP_PROFILE of the Bridge entry in host MCP configurations that",
391
- "ALREADY have one (.mcp.json, .vscode/mcp.json, and .cursor/mcp.json only). No",
392
- "file is ever created: when no supported config carries a Bridge entry, the run",
393
- "says so and points at the base `install` command. Restart your MCP client to",
394
- "see the Epic Implementer tools.",
387
+ "Tool visibility (its own consent): an approved, additive merge of the",
388
+ "`epic_implementer` token into the BRIDGE_MCP_PROFILE of the Bridge entry in",
389
+ "host MCP configurations that ALREADY have one (.mcp.json, .vscode/mcp.json, and",
390
+ ".cursor/mcp.json only). No file is ever created, and a missing entry is not a",
391
+ "blocker: the run says so and points at the base `install` command. After a",
392
+ "write, restart your MCP client to see the Epic Implementer tools.",
395
393
  "",
396
- "Local observability (a SEPARATE consent): installs or updates this repository's",
397
- "managed Git hooks (post-commit, reference-transaction) and reports each hook's",
398
- "action. It then probes native ledger loadability, which is READ-ONLY; a degraded",
399
- "ledger reports the module, NODE_MODULE_VERSION, and failure kind, and never",
400
- "triggers an install, rebuild, or migration.",
394
+ "Optional Git hooks are installed separately: run `epic-implementer install-git-hooks`.",
401
395
  "",
402
396
  `See ${CONDUCTOR_OPERATOR_RUNBOOK_POINTER}.`,
403
397
  ].join("\n");
@@ -1078,55 +1072,6 @@ async function confirm(deps, promptText) {
1078
1072
  const decision = await askSetupQuestion(setupConsentQuestion(promptText), { read: deps.promptLine, write: deps.log });
1079
1073
  return decision.status === "accept";
1080
1074
  }
1081
- /**
1082
- * BAPI-1452 — the merge-credential next step. Value-free configuration guidance
1083
- * only: it names the configuration keys and never reads, writes, migrates, or
1084
- * asks for a credential value. `GITHUB_MERGE_TOKEN` is the local merge
1085
- * credential; the machine-user credential is a distinct key, not an alias.
1086
- */
1087
- export const MERGE_CREDENTIAL_INSTALL_GUIDANCE = `set ${LOCAL_MERGE_CREDENTIAL_ENV_KEYS.local} (the local merge credential) in the environment the ` +
1088
- `executor is launched from, or ${LOCAL_MERGE_CREDENTIAL_ENV_KEYS.machine_token} for machine-user ` +
1089
- "mode; Bridge never stores either.";
1090
- function renderCapabilityMatrix(deps, readiness) {
1091
- const apiReady = readiness !== null;
1092
- // BAPI-1391 — a CONFIRMED local-only or `none` gate has no CI checks by
1093
- // design: its gate is the profile (executor-run commands, or approval for
1094
- // every merge), so an empty CI list is not "unconfigured" there. Read from
1095
- // the server's own confirmed-profile state; an older server reports no
1096
- // `gate_profile` block and keeps the original rule exactly.
1097
- const gateProfile = readiness?.gate_profile ?? null;
1098
- const confirmedCiFreeGate = gateProfile !== null &&
1099
- gateProfile.confirmed === true &&
1100
- (gateProfile.kind === "local" || gateProfile.kind === "none");
1101
- // Derived from READINESS, never from the bootstrap's HTTP status: a 200 proves
1102
- // the write was accepted, not that the resulting posture is safe.
1103
- const configurationReady = readiness !== null &&
1104
- readiness.supervisor.setup_present &&
1105
- readiness.supervisor.config_present &&
1106
- (!readiness.supervisor.required_checks_empty || confirmedCiFreeGate);
1107
- // `ready === null` (never provisioned) and `false` (stale) are both "not ready"
1108
- // here, but only a recent server-observed claim/heartbeat counts as ready — a
1109
- // configured command or a local process does not.
1110
- const executorReady = readiness?.executor.ready === true;
1111
- deps.log("");
1112
- deps.log("Capability matrix");
1113
- deps.log("─────────────────");
1114
- deps.log(` api_ready: ${apiReady}`);
1115
- deps.log(` configuration_ready: ${configurationReady}`);
1116
- deps.log(` executor_ready: ${executorReady}`);
1117
- if (gateProfile !== null) {
1118
- // Names nothing: the kind, provenance, revision, and qualification state only.
1119
- deps.log(` repository gate: ${gateProfile.confirmed ? (gateProfile.kind ?? "unknown") : "not confirmed"}` +
1120
- (gateProfile.confirmed ? ` (${gateProfile.source}, revision ${gateProfile.revision}` +
1121
- (gateProfile.qualification_state && gateProfile.qualification_state !== "not_required"
1122
- ? `, local gate ${gateProfile.qualification_state})`
1123
- : ")") : ""));
1124
- }
1125
- deps.log(` executor provisioning: ${EXECUTOR_PROVISIONING_GUIDANCE}`);
1126
- deps.log(` merge credential: ${MERGE_CREDENTIAL_INSTALL_GUIDANCE}`);
1127
- deps.log(` runbook: ${CONDUCTOR_OPERATOR_RUNBOOK_POINTER}`);
1128
- return { apiReady, configurationReady, executorReady };
1129
- }
1130
1075
  /**
1131
1076
  * Build both plans, or explain why the host cannot be provisioned.
1132
1077
  *
@@ -1339,7 +1284,7 @@ async function runExecutorProvisioningPhase(deps, executor, plans, access) {
1339
1284
  return null;
1340
1285
  }
1341
1286
  // ---------------------------------------------------------------------------
1342
- // Local out-of-the-box phases (BAPI-775)
1287
+ // Local host configuration: tool visibility (BAPI-775, narrowed by BAPI-1721)
1343
1288
  // ---------------------------------------------------------------------------
1344
1289
  /**
1345
1290
  * The exact restart advisory the SFCC profile merge prints (`index.ts`), reused
@@ -1362,16 +1307,6 @@ export function formatConductorRestartAdvisory(mergedProfile) {
1362
1307
  * Owned by `printed-remedy-commands.ts` since BAPI-1719; re-exported for compatibility.
1363
1308
  */
1364
1309
  export { CONDUCTOR_PROFILE_EMPTY_MERGE_REMEDIATION };
1365
- /** Remediation printed whenever the managed git hooks were not installed. */
1366
- export const CONDUCTOR_HOOKS_MANUAL_REMEDIATION = "re-run `install epic-implementer` and accept the local-observability consent, or run " +
1367
- "`epic-implementer install-git-hooks` directly.";
1368
- /**
1369
- * Remediation for a non-fatal hook refusal (BAPI-1290): the hooks need a
1370
- * persistent install to embed, and the repair is to create one and reinstall.
1371
- */
1372
- export const CONDUCTOR_HOOKS_DURABLE_REMEDIATION = `install the CLI persistently (\`npm i -g ${MCP_PACKAGE_NAME}\`), then run ` +
1373
- "`epic-implementer install-git-hooks` (or re-run `install epic-implementer` and accept the " +
1374
- "local-observability consent).";
1375
1310
  /**
1376
1311
  * The plain restart line the converging setup prints once after a confirmed write
1377
1312
  * (BAPI-1719), and the advisory its structured result carries.
@@ -1467,211 +1402,6 @@ export async function applyToolVisibility(deps, local, options = {}) {
1467
1402
  }
1468
1403
  return result;
1469
1404
  }
1470
- /**
1471
- * Phase: tool visibility.
1472
- *
1473
- * Adds the `epic_implementer` token to EXISTING supported host MCP entries behind its
1474
- * own consent, then prints the restart advisory. It never creates a host config
1475
- * — the merge helper's never-create rule is what keeps a declined or
1476
- * unconfigured repository from acquiring files it did not ask for.
1477
- *
1478
- * Production has not reached this phase since BAPI-1461; the converging setup applies the same operation.
1479
- */
1480
- async function runConductorToolVisibilityPhase(deps, local) {
1481
- const consented = await confirm(deps, "Update existing supported host MCP configurations (.mcp.json, .vscode/mcp.json, " +
1482
- ".cursor/mcp.json) to add the `epic_implementer` profile? [y/N]: ");
1483
- if (!consented) {
1484
- deps.log(" declined — no host MCP configuration and no install state were written.");
1485
- return {
1486
- manualActions: [
1487
- "tool visibility: re-run `install epic-implementer` and accept the profile consent to " +
1488
- "make the Epic Implementer MCP tools visible.",
1489
- ],
1490
- };
1491
- }
1492
- // The legacy phase merges unconditionally and reports every non-empty merge, so it skips the fresh pre-write inspection.
1493
- const result = await applyToolVisibility(deps, local, { freshInspection: false });
1494
- if (result.outcome === "failed") {
1495
- deps.errorLog(" the host MCP profile could not be updated.");
1496
- return { manualActions: [], fatal: true };
1497
- }
1498
- if (result.outcome === "no_entry") {
1499
- deps.log(" no supported host MCP configuration carries a Bridge entry, so nothing " +
1500
- "was written (this command never creates one).");
1501
- return {
1502
- manualActions: [
1503
- `tool visibility: ${CONDUCTOR_PROFILE_EMPTY_MERGE_REMEDIATION}`,
1504
- ],
1505
- };
1506
- }
1507
- deps.log(result.carryingPaths.length > 0
1508
- ? ` updated: ${result.carryingPaths.join(", ")}`
1509
- : " the Epic Implementer profile was merged into your supported host MCP config(s).");
1510
- // Coverage honesty: the merge path writes these three files and no others.
1511
- deps.log(" Codex and Copilot host configuration was NOT inspected or changed.");
1512
- deps.log(` ${formatConductorRestartAdvisory(result.mergedProfile)}`);
1513
- for (const note of result.notes)
1514
- deps.errorLog(` note: ${note}`);
1515
- return { manualActions: [] };
1516
- }
1517
- /**
1518
- * Phase: local observability.
1519
- *
1520
- * Installs the managed Git hooks behind its OWN consent — never
1521
- * inferred from the base-URL, bootstrap, workflow, profile-token, or executor
1522
- * consents — and then always reports native ledger loadability, which is
1523
- * read-only and therefore needs no consent at all.
1524
- */
1525
- async function runConductorLocalObservabilityPhase(deps, local) {
1526
- const manualActions = [];
1527
- let fatal = false;
1528
- const consented = await confirm(deps, "Install or update this repository's managed Git hooks " +
1529
- "(post-commit, reference-transaction)? [y/N]: ");
1530
- if (!consented) {
1531
- deps.log(" declined — no Git hook and no install state were written.");
1532
- manualActions.push(`local observability: ${CONDUCTOR_HOOKS_MANUAL_REMEDIATION}`);
1533
- }
1534
- else {
1535
- let result = null;
1536
- try {
1537
- result = await local.installGitHooks();
1538
- }
1539
- catch {
1540
- // Generic by design: the caught value can carry a hooks-directory path.
1541
- // The phase is marked fatal but does NOT return here — the read-only
1542
- // ledger report below still owes the operator its answer.
1543
- deps.errorLog(" the Epic Implementer Git hooks could not be installed.");
1544
- manualActions.push(`local observability: ${CONDUCTOR_HOOKS_MANUAL_REMEDIATION}`);
1545
- fatal = true;
1546
- }
1547
- if (result !== null && !result.ok) {
1548
- // BAPI-772's fail-loud case: nothing was created, merged, or chmodded, and
1549
- // `reason` is already a sanitized sentence. This one IS a command failure —
1550
- // a hook that cannot resolve its binary is a dead hook, and the whole point
1551
- // of that ticket is that it no longer gets written silently.
1552
- // BAPI-1290: the refusal names its fixed classification (e.g.
1553
- // `ephemeral-cache` for an npx-cache runtime) or its per-hook planning
1554
- // reasons. It is an OPTIONAL-hook installation refusal — distinct from a
1555
- // setup-permission stop and from engine admission, which it never gates.
1556
- deps.errorLog(result.error === CONDUCTOR_BIN_UNRESOLVED_ERROR
1557
- ? ` hook installation refused (${result.classification}) — ${result.reason}`
1558
- : ` hook installation refused — ${result.reason}`);
1559
- deps.errorLog(" existing hooks were left unchanged; optional local hook delivery is unavailable " +
1560
- "(engine admission is unaffected).");
1561
- // Only BAPI-772's broken-package case stays fatal: the executing artifact
1562
- // ships no hook binary at all. Every other refusal — an npx-cache runtime
1563
- // (the documented `npx … install epic-implementer` path), an unqualified or
1564
- // unloadable runtime, an unsafe existing hook — is a manual action, and
1565
- // the installer continues to setup-epic verification and executor
1566
- // provisioning. Optional hooks must never stop the phases that do gate
1567
- // a run.
1568
- // A refusal without a classification (an older or injected result shape)
1569
- // is read as `missing` — fail-closed to BAPI-772's fatal contract.
1570
- const brokenPackage = result.error === CONDUCTOR_BIN_UNRESOLVED_ERROR &&
1571
- (result.classification ?? "missing") === "missing";
1572
- if (brokenPackage) {
1573
- manualActions.push(`local observability: ${CONDUCTOR_HOOKS_MANUAL_REMEDIATION}`);
1574
- fatal = true;
1575
- }
1576
- else {
1577
- manualActions.push(`local observability: ${CONDUCTOR_HOOKS_DURABLE_REMEDIATION}`);
1578
- }
1579
- }
1580
- else if (result !== null && result.ok) {
1581
- if (!result.is_worktree) {
1582
- deps.log(" not a git worktree, so no managed hook was installed (degraded optional capability).");
1583
- manualActions.push("local observability: run `install epic-implementer` from a git worktree to install the " +
1584
- "managed git hooks.");
1585
- }
1586
- else {
1587
- for (const hook of result.installed) {
1588
- // The per-hook warning is rendered beside its action, not merely
1589
- // counted: a hook reported as `created` while carrying "could not
1590
- // chmod +x" reads as provisioned unless the warning is visible, and
1591
- // that warning is exactly what makes it unusable.
1592
- deps.log(hook.warning === undefined
1593
- ? ` ${hook.name}: ${hook.action}`
1594
- : ` ${hook.name}: ${hook.action} — warning: ${hook.warning}`);
1595
- }
1596
- if (result.partial) {
1597
- deps.log(" the hook update is PARTIAL — one managed hook was published and the other was not.");
1598
- }
1599
- // Sanitized: the installer's own warnings are secret-free sentences, and
1600
- // hook CONTENT, env, and caught errors are never rendered.
1601
- for (const warning of result.warnings)
1602
- deps.log(` warning: ${warning}`);
1603
- // Completeness is checked against the managed-hook ROSTER, not against
1604
- // "at least one hook was installed": a partial install that wrote only
1605
- // post-commit and warned about nothing would otherwise be recorded as
1606
- // provisioned observability, and the missing reference-transaction hook
1607
- // is precisely the one that stops half the events from ever being
1608
- // emitted.
1609
- //
1610
- // BAPI-1290: each hook's `usable` is the installer's shared verdict —
1611
- // published over a matching snapshot, executable, and backed by the
1612
- // qualified persistent runtime — and the installer's own `complete`
1613
- // flag must agree. Anything less is not recorded.
1614
- const usable = (name) => {
1615
- const hook = result.installed.find((h) => h.name === name);
1616
- return (hook !== undefined &&
1617
- hook.usable === true &&
1618
- hook.action !== "skipped" &&
1619
- hook.warning === undefined);
1620
- };
1621
- const complete = result.complete === true &&
1622
- MANAGED_HOOK_NAMES.every((name) => usable(name)) &&
1623
- result.warnings.length === 0;
1624
- if (complete) {
1625
- const recorded = await local.recordCapability("conductor_local_observability");
1626
- if (!recorded.ok) {
1627
- deps.errorLog(` note: install-state not updated (${recorded.error ?? "unknown"})`);
1628
- }
1629
- }
1630
- else {
1631
- // A skipped or warned hook is NOT provisioned local observability, and
1632
- // recording the capability here would make install state claim
1633
- // something a `epic-implementer doctor` run would immediately contradict.
1634
- deps.log(" the managed hooks are not fully usable, so local observability was not recorded.");
1635
- manualActions.push(`local observability: ${CONDUCTOR_HOOKS_MANUAL_REMEDIATION}`);
1636
- }
1637
- }
1638
- }
1639
- }
1640
- // The ledger probe runs whether hook consent was accepted or DECLINED: it is
1641
- // strictly read-only, so it needs no consent, and its result is exactly what
1642
- // an operator needs to know before a hook can produce an event. It also runs
1643
- // before any fail-loud return below, so a hook-binary refusal never costs the
1644
- // operator this diagnostic.
1645
- let inspection = null;
1646
- try {
1647
- inspection = await local.probeNativeLedger();
1648
- }
1649
- catch {
1650
- inspection = null;
1651
- }
1652
- if (inspection === null) {
1653
- deps.log(" ledger loadability could not be probed on this host.");
1654
- }
1655
- else {
1656
- const availability = describeNativeLedgerAvailability(inspection);
1657
- if (availability.status === "available") {
1658
- deps.log(" ledger available — the native binding loads.");
1659
- }
1660
- else {
1661
- // Never fatal, and never an install/rebuild/migration attempt: the module,
1662
- // ABI, and sanitized failure kind are what make an npm optional-dependency
1663
- // build skip diagnosable.
1664
- deps.log(` ledger degraded — ${availability.module} did not load ` +
1665
- `(NODE_MODULE_VERSION ${availability.nodeModulesAbi}, failure: ${availability.failureKind}).`);
1666
- manualActions.push(`local observability: reinstall ${availability.module} for this Node runtime to ` +
1667
- "restore the local Epic Implementer event ledger.");
1668
- }
1669
- }
1670
- return { manualActions, fatal };
1671
- }
1672
- /**
1673
- * Run the nested conductor installer. Returns the process exit code.
1674
- */
1675
1405
  // ---------------------------------------------------------------------------
1676
1406
  // Epic launch profile phase (BAPI-1260)
1677
1407
  // ---------------------------------------------------------------------------
@@ -2093,48 +1823,34 @@ async function runStandaloneGateAction(options, deps, gateIo, access, accessErro
2093
1823
  : runQualifyConductorGate(gateIo, access, deps.gate, { dryRun: options.dryRun, baseUrl });
2094
1824
  }
2095
1825
  /**
2096
- * Explain the review policy. With a decision (the converging setup) it says whether
2097
- * the source is explicit, preserved, or inferred from the remote default branch;
2098
- * without one (a caller with no setup seams) it keeps the original install text.
1826
+ * Explain the review policy the converging setup resolved: whether the source is
1827
+ * explicit, preserved, or inferred from the remote default branch.
2099
1828
  */
2100
1829
  function renderReviewPolicy(deps, options, decision) {
2101
1830
  deps.log("");
2102
- if (decision !== undefined) {
2103
- if (decision.kind === "preserve") {
2104
- deps.log(decision.basis === "stored"
2105
- ? `Review policy: kept as the project default already stored (${terminalSafeText(decision.stored ?? "unrecognized")}). ` +
2106
- "Pass --review-policy to change it."
2107
- : "Review policy: Bridge could not read the stored review settings, so it leaves them as they are this time.");
2108
- return;
2109
- }
2110
- deps.log(`Review policy: ${decision.source}`);
2111
- deps.log(decision.basis === "explicit"
2112
- ? " Explicitly selected with --review-policy, so it is ALSO persisted as the supervisor project " +
2113
- "default and stamped into a new run that sets no review policy of its own. An explicit per-run " +
2114
- "policy always wins, and changing this later never alters an already-approved run."
2115
- : decision.basis === "workflow_present"
2116
- ? ` Inferred: ${CLAUDE_REVIEW_WORKFLOW_RELPATH} exists on your default branch and emits both the run-id: and ` +
2117
- "Reviewed-SHA: markers. It is stored as the project default, and a stored default is never overwritten by a later run. " +
2118
- "Pass --review-policy to choose another."
2119
- : decision.basis === "workflow_without_markers"
2120
- ? ` Inferred: ${CLAUDE_REVIEW_WORKFLOW_RELPATH} exists on your default branch but does not emit both the run-id: ` +
2121
- "and Reviewed-SHA: markers that verdict_protocol needs, so repository_policy was stored as the project default. " +
2122
- "Pass --review-policy verdict_protocol to opt in; setup then offers to write the workflow."
2123
- : ` Inferred: no ${CLAUDE_REVIEW_WORKFLOW_RELPATH} was found on your default branch, so no Claude review ` +
2124
- "workflow is needed. It is stored as the project default, and a stored default is never overwritten by a " +
2125
- "later run. Pass --review-policy verdict_protocol to opt in to AI review.");
1831
+ if (decision.kind === "preserve") {
1832
+ deps.log(decision.basis === "stored"
1833
+ ? `Review policy: kept as the project default already stored (${terminalSafeText(decision.stored ?? "unrecognized")}). ` +
1834
+ "Pass --review-policy to change it."
1835
+ : "Review policy: Bridge could not read the stored review settings, so it leaves them as they are this time.");
2126
1836
  return;
2127
1837
  }
2128
- deps.log(`Review policy: ${options.reviewPolicy}`);
2129
- deps.log(options.reviewPolicyExplicit
2130
- ? " Explicitly selected, so it is ALSO persisted as the supervisor project " +
2131
- "default and stamped into a new run that sets no review policy of its own. " +
2132
- "An explicit per-run policy always wins, and changing this later never " +
2133
- "alters an already-approved run."
2134
- : " Install assumption only: no repository default is persisted and no " +
2135
- "Claude review workflow is scaffolded. A new feature-branch run receives " +
2136
- "repository_policy at first approval when nothing else sets one — pass " +
2137
- "--review-policy verdict_protocol to opt in to AI review.");
1838
+ deps.log(`Review policy: ${decision.source}`);
1839
+ deps.log(decision.basis === "explicit"
1840
+ ? " Explicitly selected with --review-policy, so it is ALSO persisted as the supervisor project " +
1841
+ "default and stamped into a new run that sets no review policy of its own. An explicit per-run " +
1842
+ "policy always wins, and changing this later never alters an already-approved run."
1843
+ : decision.basis === "workflow_present"
1844
+ ? ` Inferred: ${CLAUDE_REVIEW_WORKFLOW_RELPATH} exists on your default branch and emits both the run-id: and ` +
1845
+ "Reviewed-SHA: markers. It is stored as the project default, and a stored default is never overwritten by a later run. " +
1846
+ "Pass --review-policy to choose another."
1847
+ : decision.basis === "workflow_without_markers"
1848
+ ? ` Inferred: ${CLAUDE_REVIEW_WORKFLOW_RELPATH} exists on your default branch but does not emit both the run-id: ` +
1849
+ "and Reviewed-SHA: markers that verdict_protocol needs, so repository_policy was stored as the project default. " +
1850
+ "Pass --review-policy verdict_protocol to opt in; setup then offers to write the workflow."
1851
+ : ` Inferred: no ${CLAUDE_REVIEW_WORKFLOW_RELPATH} was found on your default branch, so no Claude review ` +
1852
+ "workflow is needed. It is stored as the project default, and a stored default is never overwritten by a " +
1853
+ "later run. Pass --review-policy verdict_protocol to opt in to AI review.");
2138
1854
  }
2139
1855
  /** A stored value printed on one line: control characters and over-long text never reach the terminal. */
2140
1856
  function terminalSafeText(value) {
@@ -2324,423 +2040,7 @@ async function runInstallBridgeConductorCore(argv, deps) {
2324
2040
  return 1;
2325
2041
  }
2326
2042
  const options = parsed.options;
2327
- // BAPI-1461: production supplies the setup seams, which select the converging
2328
- // check → fix → check → verdict runner. A caller without them keeps the
2329
- // original phase sequence below, unchanged.
2330
- if (deps.setup !== undefined) {
2331
- return runConvergingSetup(options, deps, deps.setup);
2332
- }
2333
- if (options.removeMergeToken === true) {
2334
- deps.errorLog("Error: --remove-merge-token is unavailable here: this caller supplied no credential-store seams.");
2335
- return 1;
2336
- }
2337
- if (options.testCommand !== undefined) {
2338
- // Accepting the flag and running an implementation that ignores it would
2339
- // report success for a command that was never saved.
2340
- deps.errorLog("Error: --test-command is unavailable here: this caller supplied no test-command seams.");
2341
- return 1;
2342
- }
2343
- const confirmed = await resolveAndConfirmBaseUrl(options, deps, "Bootstrap against this URL? [y/N]: ");
2344
- if (!confirmed.ok)
2345
- return confirmed.code;
2346
- const baseUrl = confirmed.baseUrl;
2347
- if (!options.dryRun && !(await assessEpicInstallerPrerequisites(deps, Boolean(options.executorId))).available)
2348
- return 1;
2349
- const accessResult = await deps.resolveAccess(options.repo, baseUrl);
2350
- const access = accessResult.ok ? accessResult.access : null;
2351
- const accessError = accessResult.ok ? undefined : accessResult.error;
2352
- const earlyPreflight = await runExecutorPreflightPhase(options, deps, baseUrl, access);
2353
- if (earlyPreflight.kind === "refused")
2354
- return 1;
2355
- const gateIo = gateIoFor(deps);
2356
- const standalone = await runStandaloneGateAction(options, deps, gateIo, access, accessError, baseUrl);
2357
- if (standalone !== null)
2358
- return standalone;
2359
- // ---- Phase 1: unified doctor, BEFORE every write -----------------------
2360
- deps.log("Phase 1/8 — running the unified epic-implementer doctor (read-only)…");
2361
- const firstReport = await deps.runDoctor({
2362
- access,
2363
- accessError,
2364
- reviewPolicySource: options.reviewPolicy,
2365
- assessmentVersion: 1,
2366
- epicRunId: options.assessmentEpicRunId,
2367
- });
2368
- deps.log(formatConductorInstallDoctorReport(firstReport));
2369
- if (conductorInstallDoctorHasFatal(firstReport)) {
2370
- deps.errorLog("");
2371
- deps.errorLog("Fatal prerequisite(s) above. Aborting before any write — no bootstrap, workflow, " +
2372
- "install-state, or verification step was attempted.");
2373
- return 1;
2374
- }
2375
- // ---- Review policy: per-run, and a repository default when explicit ----
2376
- renderReviewPolicy(deps, options);
2377
- // ---- Executor preflight: AFTER the URL consent, BEFORE any mutation ----
2378
- // Placed here so an unsupported host or a missing `wt`/`git`/`claude` refuses
2379
- // before the bootstrap POST, the workflow write, or a single filesystem
2380
- // effect — provisioning a service that cannot run is worse than refusing —
2381
- // and before the dry-run return, so `--dry-run` reports the same refusal.
2382
- const executor = deps.executorProvisioning;
2383
- const local = deps.localProvisioning;
2384
- const executorPlans = earlyPreflight.plans;
2385
- // ---- BAPI-1391: the repository gate, decided BEFORE any write ----------
2386
- // Capability probe first (a read, after the base-URL consent), then the stored
2387
- // gate, explicit gate flags, or a discovery proposal the owner confirms. Under
2388
- // --dry-run it only shows the decision: no PUT, no enqueue, no gate prompt.
2389
- if (!access) {
2390
- deps.errorLog("Bridge API access could not be resolved; aborting before any write.");
2391
- return 1;
2392
- }
2393
- const gatePhase = await resolveConductorGate(gateIo, access, options.gate, deps.gate, {
2394
- dryRun: options.dryRun, planningOnly: true,
2395
- });
2396
- if (gatePhase.kind === "exit")
2397
- return gatePhase.code;
2398
- const gatePlan = gatePhase.kind === "plan" ? gatePhase.plan : null;
2399
- // The bootstrap's CI list is the gate's provider leg. A local-only or `none`
2400
- // gate sends an empty list, which the server accepts only for a stored gate
2401
- // of that kind.
2402
- const bootstrapChecks = gatePlan?.desired.providerChecks ?? options.requiredChecks;
2403
- // ---- Dry run: preview and RETURN before every write/prompt -------------
2404
- if (options.dryRun) {
2405
- deps.log("");
2406
- deps.log("Dry run — no writes will be performed.");
2407
- if (gatePlan !== null)
2408
- await fixGateAndDefaults(deps, options, access, gatePlan, legacyReviewDefault(options));
2409
- if (gatePlan === null) {
2410
- deps.log(" Repository gate: none confirmed — a real run asks you to confirm one before any write.");
2411
- }
2412
- else if (gatePlan.write !== null) {
2413
- // Field NAMES and counts only, as below.
2414
- deps.log(` Would PUT /jira/epic-runs/supervisor-setup/gate-profile/ (confirm, expected revision ` +
2415
- `${gatePlan.write.expected_revision}) with field NAMES: kind, ` +
2416
- `provider_checks (${gatePlan.desired.providerChecks.length}), ` +
2417
- `local_commands (${gatePlan.desired.localCommands.length}), migration_guard` +
2418
- (gatePlan.write.customized_commands !== undefined ? ", customized_commands" : ""));
2419
- }
2420
- else {
2421
- deps.log(" Repository gate: already confirmed as shown — no gate write.");
2422
- }
2423
- if (gatePlan !== null && gatePlan.desired.localCommands.length > 0) {
2424
- deps.log(" Gate qualification: would be offered after the gate is stored — no job was queued.");
2425
- }
2426
- deps.log(" Epic-branch CI: a real run inspects workflow triggers and epic-branch rules (GitHub only), " +
2427
- "then asks include or decline — nothing was inspected or recorded.");
2428
- deps.log(" Would PREVIEW, then POST /jira/epic-runs/supervisor-bootstrap with field NAMES:");
2429
- // Field NAMES and a COUNT only — never the check values, which are
2430
- // configuration content, and never the API key.
2431
- deps.log(" - done_gate_config.required_checks " +
2432
- `(${bootstrapChecks.length} check(s))`);
2433
- if (options.reviewPolicyExplicit)
2434
- deps.log(" - defaults.review_policy");
2435
- if (options.replaceDoneGate)
2436
- deps.log(" - replace_done_gate");
2437
- deps.log(" - auto_merge_enabled");
2438
- deps.log(" - merge_approval_required");
2439
- deps.log(" Existing project defaults would be KEPT: missing checks are added, nothing is " +
2440
- "removed without a previewed, separately approved change.");
2441
- deps.log(` Would target base URL: ${baseUrl}`);
2442
- deps.log(options.skipWorkflow || options.reviewPolicy !== "verdict_protocol"
2443
- ? " Workflow scaffold: skipped (not applicable for this policy)"
2444
- : ` Workflow scaffold target: ${CLAUDE_REVIEW_WORKFLOW_RELPATH}`);
2445
- deps.log(options.epicKey && options.planFile
2446
- ? ` Would verify with: setup-epic --dry-run --epic-key ${options.epicKey}`
2447
- : " setup-epic verification: skipped (no --epic-key/--plan-file supplied)");
2448
- // The REAL planned path and the REAL start command — computed by the same
2449
- // pure planners the live run uses, so the preview cannot drift from what
2450
- // would actually happen. Still zero writes: no unit writer, no
2451
- // install-state recorder, no lifecycle runner, and no consent prompt has
2452
- // been reached on this branch.
2453
- // BAPI-775: named as SEPARATE consents so the preview cannot read as one
2454
- // blanket approval. Nothing below this line invokes the profile merger, the
2455
- // hook installer, the capability recorder, or the phase's ledger probe —
2456
- // this branch returns before every one of them.
2457
- deps.log(local
2458
- ? " Tool visibility: would ask its OWN consent before adding the `epic_implementer` " +
2459
- "profile to existing .mcp.json / .vscode/mcp.json / .cursor/mcp.json entries."
2460
- : " Tool visibility: skipped (this caller supplied no local-provisioning seams)");
2461
- deps.log(local
2462
- ? " Local observability: would ask a SEPARATE consent before installing the " +
2463
- "managed Git hooks; the ledger probe is read-only."
2464
- : " Local observability: skipped (this caller supplied no local-provisioning seams)");
2465
- if (executorPlans) {
2466
- deps.log(` Would write executor unit: ${executorPlans.install.unitPath}`);
2467
- deps.log(` Would start it with: ${executorPlans.start.manualCommand}`);
2468
- deps.log(" Executor provisioning: two separate consents (write, then start) — neither was asked.");
2469
- }
2470
- else if (executor) {
2471
- deps.log(" Executor provisioning: skipped (no --executor-id supplied)");
2472
- }
2473
- if (options.launchProfile !== undefined) {
2474
- deps.log(` Epic launch profile '${options.launchProfile}': would verify target access, credential ` +
2475
- "binding, consent, notification, and actor, and persist the profile only if all hold " +
2476
- "(each write behind its own consent) — nothing was read from or written to the profile store.");
2477
- }
2478
- renderCapabilityMatrix(deps, firstReport.readiness);
2479
- deps.log("");
2480
- deps.log("complete-with-manual-steps (dry run)");
2481
- return 0;
2482
- }
2483
- if (gatePlan === null) {
2484
- // Unreachable outside a dry run: the gate phase either decided a gate or
2485
- // returned. Narrowed here so the bootstrap below always has one.
2486
- deps.errorLog("No confirmed repository gate; aborting before any write.");
2487
- return 1;
2488
- }
2489
- // ---- Phase 2: bootstrap — preview, consent, exact approval, apply -------
2490
- // BAPI-1288. The server decides what this bootstrap would do to the stored
2491
- // project defaults; this command only shows that decision and asks. It never
2492
- // evaluates gate strength itself, and it never falls back to the old
2493
- // replacing bootstrap when the server cannot preview.
2494
- deps.log("");
2495
- deps.log("Phase 2/8 — bootstrapping supervisor project defaults…");
2496
- const combined = await fixGateAndDefaults(deps, options, access, gatePlan, legacyReviewDefault(options));
2497
- if (combined.status === "deferred" || combined.status === "unknown")
2498
- return 1;
2499
- const storedGate = combined.current
2500
- ? { revision: combined.current.state.revision, qualification_state: combined.current.policy.qualification }
2501
- : gatePlan.current;
2502
- const manualActions = [];
2503
- if (gatePlan.desired.localCommands.length > 0) {
2504
- const qualified = storedGate.qualification_state === "qualified";
2505
- let qualify = options.gate.qualifyGate;
2506
- if (!qualify && !qualified) {
2507
- deps.log("");
2508
- deps.log(" The local gate must pass once under the executor before an unattended run is admitted.");
2509
- qualify = await confirm(deps, "Qualify gate now? [y/N]: ");
2510
- }
2511
- if (qualify) {
2512
- // Non-fatal by design: a failed qualification warns and the install goes on.
2513
- await runConductorGateQualification(gateIo, access, deps.gate, {
2514
- revision: storedGate.revision,
2515
- baseUrl,
2516
- });
2517
- }
2518
- else if (!qualified) {
2519
- manualActions.push(`gate qualification: run ${PRINTED_QUALIFY_GATE_COMMAND} to qualify the local gate; ` +
2520
- "until then admission refuses it (local_command_unqualified).");
2521
- }
2522
- else {
2523
- deps.log(` local gate already qualified at revision ${storedGate.revision}.`);
2524
- }
2525
- }
2526
- // ---- BAPI-1405: epic-branch CI inspection and the explicit decision ----
2527
- // Runs after the gate is resolved and stored, inside the gate phase. It only
2528
- // reports and proposes; it never confirms a gate or authorizes a merge. A
2529
- // failed read or decision write warns and the install continues.
2530
- const epicBranchCi = await runEpicBranchCiInspection(gateIo, access, deps.gate, {
2531
- decisionFlag: options.epicBranchCiDecision ?? null,
2532
- dryRun: false,
2533
- });
2534
- if (epicBranchCi.manualAction !== null)
2535
- manualActions.push(epicBranchCi.manualAction);
2536
- // BAPI-1637: say what the STORED gate means for merges, from readiness's own facts.
2537
- await runGateConsequenceSummary(gateIo, access, deps.gate);
2538
- if (options.reviewPolicy === "verdict_protocol") {
2539
- // ---- Phase 3: optional workflow scaffold -------------------------------
2540
- deps.log("");
2541
- deps.log("Phase 3/8 — claude-review workflow…");
2542
- if (options.skipWorkflow) {
2543
- deps.log(` skipped — the '${options.reviewPolicy}' review policy does not consume the ` +
2544
- "sticky verdict this workflow emits.");
2545
- }
2546
- else if (!options.allowedBot || !options.secretName || !options.branches) {
2547
- deps.log(" skipped — --allowed-bot, --secret-name, and --branches are required to render " +
2548
- "the workflow template.");
2549
- }
2550
- else {
2551
- const wantWorkflow = await confirm(deps, `Write ${CLAUDE_REVIEW_WORKFLOW_RELPATH}? [y/N]: `);
2552
- if (!wantWorkflow) {
2553
- deps.log(" declined — no file was written.");
2554
- }
2555
- else {
2556
- let content;
2557
- try {
2558
- content = renderClaudeReviewWorkflow({
2559
- allowedBot: options.allowedBot,
2560
- secretName: options.secretName,
2561
- branches: options.branches,
2562
- });
2563
- }
2564
- catch (err) {
2565
- deps.errorLog(` workflow parameters rejected: ${err instanceof Error ? err.message : "invalid"}`);
2566
- return 1;
2567
- }
2568
- let result = await deps.writeWorkflow(deps.cwd, content, {});
2569
- if (result.ok && result.outcome === "skipped") {
2570
- // A DIFFERENT file already exists. Overwriting review automation needs
2571
- // its own decision — never inferred from the earlier consents.
2572
- const overwrite = await confirm(deps, `${CLAUDE_REVIEW_WORKFLOW_RELPATH} exists and differs. Overwrite? [y/N]: `);
2573
- if (!overwrite) {
2574
- deps.log(" existing workflow left untouched.");
2575
- }
2576
- else {
2577
- result = await deps.writeWorkflow(deps.cwd, content, { overwriteConsent: true });
2578
- }
2579
- }
2580
- if (!result.ok) {
2581
- deps.errorLog(` workflow write failed: ${result.error}`);
2582
- return 1;
2583
- }
2584
- if (result.outcome === "written") {
2585
- deps.log(` wrote ${CLAUDE_REVIEW_WORKFLOW_RELPATH}`);
2586
- const recorded = await deps.recordArtifact(deps.cwd, CLAUDE_REVIEW_WORKFLOW_RELPATH);
2587
- if (!recorded.ok) {
2588
- // Advisory: install-state is a diagnostic aid, not a correctness
2589
- // dependency, so a failure here warns rather than failing the run.
2590
- deps.errorLog(` note: install-state not updated (${recorded.error ?? "unknown"})`);
2591
- }
2592
- }
2593
- else if (result.outcome === "unchanged") {
2594
- deps.log(` ${CLAUDE_REVIEW_WORKFLOW_RELPATH} already matches — nothing written.`);
2595
- }
2596
- }
2597
- }
2598
- }
2599
- // ---- Phases 4 + 5: local out-of-the-box provisioning (BAPI-775) --------
2600
- // Placed after the workflow scaffold and BEFORE setup-epic verification,
2601
- // executor provisioning, and the capability report, so a run that stops at a
2602
- // later phase has still closed the local gap it consented to close.
2603
- deps.log("");
2604
- deps.log("Phase 4/8 — Epic Implementer tool visibility…");
2605
- if (local) {
2606
- const outcome = await runConductorToolVisibilityPhase(deps, local);
2607
- manualActions.push(...outcome.manualActions);
2608
- if (outcome.fatal)
2609
- return 1;
2610
- }
2611
- else {
2612
- deps.log(" skipped — this caller supplied no local-provisioning seams.");
2613
- manualActions.push("tool visibility: run the packaged `install epic-implementer` command to add the " +
2614
- "`epic_implementer` profile to your host MCP configuration.");
2615
- }
2616
- deps.log("");
2617
- deps.log("Phase 5/8 — local observability…");
2618
- let observabilityFatal = false;
2619
- if (local) {
2620
- const outcome = await runConductorLocalObservabilityPhase(deps, local);
2621
- manualActions.push(...outcome.manualActions);
2622
- observabilityFatal = outcome.fatal === true;
2623
- }
2624
- else {
2625
- deps.log(" skipped — this caller supplied no local-provisioning seams.");
2626
- manualActions.push("local observability: run the packaged `install epic-implementer` command, or " +
2627
- "`epic-implementer install-git-hooks`, to install the managed Git hooks.");
2628
- }
2629
- // The fail-loud hook-binary refusal (a package that ships no hook binary)
2630
- // exits 1 — but only AFTER the phase's read-only ledger report has been
2631
- // printed, which the phase guarantees. BAPI-1290: qualification refusals are
2632
- // manual actions, not fatal, so they reach the phases below.
2633
- if (observabilityFatal)
2634
- return 1;
2635
- // ---- Phase 6: setup-epic verification (conditional) --------------------
2636
- // `parseSetupEpicArgs` hard-requires --epic-key AND --plan-file before any
2637
- // dry-run branch, so this phase can only run when both are supplied. Fresh
2638
- // repositories skip it with an explicit message rather than hard-failing.
2639
- deps.log("");
2640
- deps.log("Phase 6/8 — setup-epic verification…");
2641
- if (options.epicKey && options.planFile) {
2642
- deps.log(" verifying with `setup-epic --dry-run`…");
2643
- const verification = await deps.runSetupEpicDryRun([
2644
- "--dry-run",
2645
- "--epic-key",
2646
- options.epicKey,
2647
- "--plan-file",
2648
- options.planFile,
2649
- // The SELECTED per-run policy is forwarded so the verification exercises
2650
- // the same policy a real run would use — including its conflict guard.
2651
- "--review-policy",
2652
- options.reviewPolicy,
2653
- ...(options.repo ? ["--repo", options.repo] : []),
2654
- ]);
2655
- if (verification.exitCode !== 0) {
2656
- deps.errorLog(" setup-epic verification failed.");
2657
- return 1;
2658
- }
2659
- deps.log(" setup-epic verification passed.");
2660
- }
2661
- else {
2662
- deps.log(" setup-epic verification skipped — pass --epic-key and --plan-file once a plan exists.");
2663
- }
2664
- // ---- Phase 5: consented executor provisioning (BAPI-779) ---------------
2665
- // Runs AFTER the pre-existing phases so a bootstrap failure never leaves a
2666
- // started daemon behind, and BEFORE the capability report so the matrix can
2667
- // use the readiness this phase actually observed.
2668
- deps.log("");
2669
- deps.log("Phase 7/8 — executor provisioning…");
2670
- let observedReadiness = null;
2671
- if (executor && executorPlans) {
2672
- observedReadiness = await runExecutorProvisioningPhase(deps, executor, executorPlans, access);
2673
- }
2674
- else {
2675
- deps.log(" skipped — " +
2676
- (executor
2677
- ? "no --executor-id was supplied."
2678
- : "this caller supplied no executor-provisioning seams."));
2679
- }
2680
- // ---- Phase 6: capability matrix + final doctor -------------------------
2681
- deps.log("");
2682
- deps.log("Phase 8/8 — capability report…");
2683
- // The observed payload WINS when the executor phase actually saw the server
2684
- // report readiness. Otherwise the matrix re-reads readiness itself — it is
2685
- // never handed a synthesized response, so `executor_ready` still originates
2686
- // from exactly one place: a live server observation.
2687
- let postReadiness = observedReadiness;
2688
- if (postReadiness === null) {
2689
- try {
2690
- postReadiness = await fetchConductorReadiness(access, deps.fetchJson, { assessmentVersion: 1, epicRunId: options.assessmentEpicRunId });
2691
- }
2692
- catch {
2693
- // Degraded, not fatal: the write already succeeded, and the matrix simply
2694
- // reports what it can observe.
2695
- deps.errorLog(" readiness could not be re-read; capability matrix is best-effort.");
2696
- }
2697
- }
2698
- const matrix = renderCapabilityMatrix(deps, postReadiness);
2699
- deps.log("");
2700
- deps.log(" re-running the unified epic-implementer doctor (read-only)…");
2701
- const finalReport = await deps.runDoctor({
2702
- access,
2703
- reviewPolicySource: options.reviewPolicy,
2704
- assessmentVersion: 1,
2705
- epicRunId: options.assessmentEpicRunId,
2706
- });
2707
- deps.log(formatConductorInstallDoctorReport(finalReport));
2708
- // Manual actions (BAPI-775): every declined, unavailable, empty, or incomplete
2709
- // local phase leaves a pointer here. Collected in one place because an
2710
- // operator who scrolled past a phase still needs to know what is outstanding.
2711
- if (manualActions.length > 0) {
2712
- deps.log("");
2713
- deps.log("Manual actions");
2714
- deps.log("──────────────");
2715
- for (const action of manualActions)
2716
- deps.log(` → ${action}`);
2717
- }
2718
- // ---- BAPI-1260: the reusable epic launch profile ------------------------
2719
- // Last, because it can only be approved on facts every earlier phase
2720
- // produced: server-observed readiness at THIS target, the executor handshake
2721
- // for a durable host, and the operator's consents.
2722
- if (options.launchProfile !== undefined) {
2723
- const launch = await runLaunchProfilePhase(deps, options, {
2724
- access,
2725
- baseUrl,
2726
- readiness: postReadiness,
2727
- actorObserved: observedReadiness !== null || postReadiness?.executor.ready === true,
2728
- runtime: resolveLaunchRuntime(executor, options.executionMode ?? "local"),
2729
- });
2730
- deps.log("");
2731
- if (!launch.complete) {
2732
- deps.log("incomplete-setup");
2733
- return 1;
2734
- }
2735
- }
2736
- deps.log("");
2737
- // The executor leg can only be true when the server observed a recent claim,
2738
- // so a bootstrap alone can never print `complete`. The two local phases above
2739
- // deliberately do NOT feed this predicate: local provisioning cannot
2740
- // manufacture `complete`, and the terminal outcome is unchanged by BAPI-775.
2741
- const allReady = matrix.apiReady && matrix.configurationReady && matrix.executorReady;
2742
- deps.log(allReady ? "complete" : "complete-with-manual-steps");
2743
- return conductorInstallDoctorExitCode(finalReport);
2043
+ return runConvergingSetup(options, deps, deps.setup);
2744
2044
  }
2745
2045
  // ---------------------------------------------------------------------------
2746
2046
  // The converging setup runner (BAPI-1461)
@@ -3084,15 +2384,6 @@ async function resolveReviewDefault(deps, options, access, reviewWorkflow) {
3084
2384
  stored: null,
3085
2385
  };
3086
2386
  }
3087
- /**
3088
- * The review default for a caller that supplies no setup seams: only an explicit
3089
- * `--review-policy` is sent, exactly as before BAPI-1603.
3090
- */
3091
- function legacyReviewDefault(options) {
3092
- return options.reviewPolicyExplicit
3093
- ? { kind: "send", source: options.reviewPolicy, basis: "explicit", stored: null }
3094
- : { kind: "preserve", basis: "stored", stored: null };
3095
- }
3096
2387
  /** The review source the readiness doctor should assume: the one this run sends or keeps. */
3097
2388
  function effectiveReviewPolicy(options, reviewDefault) {
3098
2389
  if (reviewDefault.kind === "send")
@@ -6068,7 +5359,7 @@ async function runConvergingSetup(options, deps, setup) {
6068
5359
  }
6069
5360
  }
6070
5361
  else {
6071
- // The terminal path: the phased y/N wording. Without a terminal this is "no", and nothing is asked.
5362
+ // The terminal path: a plain y/N question. Without a terminal this is "no", and nothing is asked.
6072
5363
  if (deps.promptLine === undefined)
6073
5364
  return { key: "tool_visibility", status: "declined", target, reason: "there is no interactive terminal, so no MCP configuration was changed" };
6074
5365
  deps.log("");
@@ -6436,6 +5727,9 @@ function confirmedPresentation(readiness, evidence, items, unmet, applyResult) {
6436
5727
  blockers: unmet.map((item) => ({ label: item.label, fix: setupItemRemedy(item) })),
6437
5728
  results: applyResult.results,
6438
5729
  protection,
5730
+ // BAPI-1747 — the same overlay the launch preview and doctor use, fed by the
5731
+ // tool-visibility state that backs `local.tool-visibility`.
5732
+ prerequisites: overlayReadinessPrerequisites([], readiness?.prerequisites ?? [], evidence.toolVisibility),
6439
5733
  }),
6440
5734
  ...(ready !== undefined ? { ready } : {}),
6441
5735
  ...(protection !== undefined ? { merge_test_protection: protection } : {}),
@@ -6679,18 +5973,8 @@ async function publishCapabilityStatement(deps, grantDeps, access, verbose) {
6679
5973
  * (`skipped-duplicate-registration`) leave such a config untouched.
6680
5974
  */
6681
5975
  export function toolVisibilityStateFrom(inspection) {
6682
- const duplicates = inspection.configs.filter((c) => c.duplicateRegistration === true).map((c) => c.path);
6683
- if (duplicates.length > 0)
6684
- return { state: "duplicate_registration", configPaths: duplicates };
6685
- if (profileMergeNeededFrom(inspection)) {
6686
- return {
6687
- state: "needs_merge",
6688
- configPaths: inspection.configs.filter((c) => c.state === "token-absent").map((c) => c.path),
6689
- };
6690
- }
6691
- if (inspection.configs.some((c) => c.state === "unreadable"))
6692
- return { state: "unknown", reason: "inspection" };
6693
- return inspection.bridgeEntryPresent ? { state: "met" } : { state: "no_entry" };
5976
+ // BAPI-1747 — one owner for this mapping, shared with the readiness overlay.
5977
+ return toolVisibilityStateFromInspection(inspection);
6694
5978
  }
6695
5979
  /** Read-only. Unwired dependencies or a throwing inspector are `unknown`, never satisfied. */
6696
5980
  async function collectToolVisibilityEvidence(local) {