@bridge_gpt/mcp-server 0.2.72 → 0.2.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +15 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-config.js +7 -1
  5. package/build/bridge-permissions.js +30 -0
  6. package/build/ci-system-detection.js +50 -0
  7. package/build/ci-trigger-adapters.js +631 -0
  8. package/build/ci-trigger-install.js +106 -0
  9. package/build/codex-launcher-pin.js +33 -2
  10. package/build/codex-skill-adapter.js +3 -1
  11. package/build/command-host.js +33 -0
  12. package/build/command-provisioning.js +4 -3
  13. package/build/commands.generated.js +7 -6
  14. package/build/conductor/bridge-api-client.js +867 -35
  15. package/build/conductor/bring-up-facts.js +18 -5
  16. package/build/conductor/command-drift-production.js +42 -17
  17. package/build/conductor/command-drift.js +48 -1
  18. package/build/conductor/declare-blocked.js +554 -0
  19. package/build/conductor/declared-extras.js +335 -0
  20. package/build/conductor/doctor.js +108 -21
  21. package/build/conductor/driver-commands.js +141 -0
  22. package/build/conductor/driver-guard.js +277 -0
  23. package/build/conductor/driver-lapse.js +321 -0
  24. package/build/conductor/driver-pass-output.js +104 -0
  25. package/build/conductor/driver-pass.js +571 -0
  26. package/build/conductor/driver-register.js +176 -0
  27. package/build/conductor/driver-release.js +174 -0
  28. package/build/conductor/driver-session-state.js +315 -0
  29. package/build/conductor/epic-branch-ci-inspection.js +281 -43
  30. package/build/conductor/epic-implementer-cli.js +199 -15
  31. package/build/conductor/epic-server-database.js +162 -0
  32. package/build/conductor/epic-server-guidance.js +278 -0
  33. package/build/conductor/epic-server-journal.js +239 -0
  34. package/build/conductor/epic-server-processes.js +324 -0
  35. package/build/conductor/epic-server-recipe.js +397 -0
  36. package/build/conductor/epic-server-runtime.js +1207 -0
  37. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  38. package/build/conductor/epic-server-sfcc.js +85 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +647 -0
  41. package/build/conductor/gate-discovery.js +196 -11
  42. package/build/conductor/gate-settings-review.js +261 -4
  43. package/build/conductor/launch-need-probes.js +6 -53
  44. package/build/conductor/launch-plan.js +313 -156
  45. package/build/conductor/prerequisite-inputs.js +879 -45
  46. package/build/conductor/readiness-assessment.js +16 -1
  47. package/build/conductor/readiness-cli.js +20 -9
  48. package/build/conductor/readiness-prerequisites.js +28 -9
  49. package/build/conductor/readiness-sections.js +133 -126
  50. package/build/conductor/readiness.js +1 -1
  51. package/build/conductor/recovery-cli.js +13 -2
  52. package/build/conductor/tools.js +6 -5
  53. package/build/conductor/wait-run-attention.js +2 -2
  54. package/build/conductor/wait-run-cli.js +208 -22
  55. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  56. package/build/conductor/worker-setup-tally.js +27 -0
  57. package/build/credential-delivery.js +280 -0
  58. package/build/credential-launch-safety.js +142 -0
  59. package/build/credential-materialization.js +91 -16
  60. package/build/credential-references-node-deps.js +29 -0
  61. package/build/credential-references.js +1394 -0
  62. package/build/credential-references.test-fixtures.js +211 -0
  63. package/build/credential-scan-conventions.js +145 -0
  64. package/build/credential-scan.js +517 -0
  65. package/build/credential-store.js +121 -1
  66. package/build/credentials-cli.js +252 -3
  67. package/build/dependency-install-declarations.js +102 -1
  68. package/build/docs.generated.js +10 -3
  69. package/build/doctor.js +95 -3
  70. package/build/drive-epic-help.js +21 -2
  71. package/build/drive-epic.js +2095 -375
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +157 -0
  74. package/build/epic-capability-statement.js +175 -0
  75. package/build/epic-ci-workflow-drift.js +77 -23
  76. package/build/epic-ci-workflow-install.js +137 -44
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow-v3.js +273 -0
  79. package/build/epic-ci-workflow.js +165 -18
  80. package/build/epic-implementer-bin.js +2204 -56
  81. package/build/epic-launch-context.js +702 -0
  82. package/build/epic-server-record.js +288 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/completion-contract.js +8 -1
  87. package/build/executor/credential-delivery-step.js +168 -0
  88. package/build/executor/deps.js +3 -1
  89. package/build/executor/env.js +98 -23
  90. package/build/executor/epic-server-context.js +157 -0
  91. package/build/executor/gate-qualification-job.js +127 -26
  92. package/build/executor/guarded-fast-forward-push.js +13 -8
  93. package/build/executor/http-client.js +52 -5
  94. package/build/executor/job-runner.js +577 -81
  95. package/build/executor/observation.js +8 -0
  96. package/build/executor/permissions.js +85 -3
  97. package/build/executor/pre-pr-checks.js +363 -0
  98. package/build/executor/prompt-spec.js +149 -3
  99. package/build/executor/reconcile-overlap-job.js +5 -3
  100. package/build/executor/required-work-diagnostics.js +4 -2
  101. package/build/executor/required-work-ledger.js +936 -38
  102. package/build/executor/results.js +58 -0
  103. package/build/executor/terminal-mutation.js +8 -0
  104. package/build/executor/worker-command.js +72 -3
  105. package/build/executor/worker-database-config.js +281 -0
  106. package/build/executor/worker-database-target.js +16 -12
  107. package/build/executor/worker-database.js +320 -101
  108. package/build/executor/worker-finalization.js +7 -1
  109. package/build/executor/worker-resources.js +25 -3
  110. package/build/executor/worker-verification-guidance.js +18 -3
  111. package/build/executor/worktree.js +20 -1
  112. package/build/executor-launch.js +58 -4
  113. package/build/generated-assets-catalog.js +2 -2
  114. package/build/git-exclude-lock.js +187 -0
  115. package/build/index.js +824 -366
  116. package/build/init.js +26 -11
  117. package/build/install-bridge-conductor-answers.js +528 -0
  118. package/build/install-bridge-conductor-apply.js +288 -0
  119. package/build/install-bridge-conductor-assessment.js +1222 -0
  120. package/build/install-bridge-conductor-compact.js +186 -0
  121. package/build/install-bridge-conductor-contracts.js +72 -0
  122. package/build/install-bridge-conductor-gate.js +1312 -198
  123. package/build/install-bridge-conductor-setup.js +577 -83
  124. package/build/install-bridge-conductor.js +3381 -544
  125. package/build/install-bridge.js +280 -25
  126. package/build/install-doctor.js +38 -8
  127. package/build/install-maintenance.js +26 -3
  128. package/build/install-sfcc-detection.js +120 -0
  129. package/build/install-sfcc-setup.js +185 -0
  130. package/build/launcher-config-inspection.js +162 -1
  131. package/build/mcp-grant-candidates.js +779 -0
  132. package/build/mcp-grant-doctor.js +63 -0
  133. package/build/mcp-grant.js +288 -0
  134. package/build/mcp-host-targets.js +8 -0
  135. package/build/mcp-identity.js +23 -0
  136. package/build/mcp-invoke.js +292 -15
  137. package/build/mcp-presets.js +107 -0
  138. package/build/mcp-provisioning.js +155 -6
  139. package/build/mcp-registration-doctor.js +31 -2
  140. package/build/mcp-server-invocation.js +19 -1
  141. package/build/merge-workflow-install.js +243 -110
  142. package/build/pipelines.generated.js +7 -6
  143. package/build/plan-discovery.js +97 -4
  144. package/build/plan-execution-ledger.js +100 -7
  145. package/build/plan-generation-io.js +262 -0
  146. package/build/plan-generation.js +424 -0
  147. package/build/plane/build-freshness.js +6 -1
  148. package/build/plane/cli.js +75 -9
  149. package/build/plane/plane-freshness.js +17 -0
  150. package/build/plane/preflight.js +50 -10
  151. package/build/plane/shutdown.js +19 -0
  152. package/build/plane/status.js +8 -2
  153. package/build/plane/terminal-run-cleanup.js +18 -4
  154. package/build/printed-remedy-commands.js +211 -12
  155. package/build/project-root.js +40 -0
  156. package/build/readiness-check.js +77 -0
  157. package/build/readiness-prerequisites.generated.js +122 -14
  158. package/build/readme.generated.js +1 -1
  159. package/build/repository-state-paths.js +41 -0
  160. package/build/repository-toolchains.js +6 -3
  161. package/build/run-unit-tests-launcher.js +8 -1
  162. package/build/setup-epic.js +1305 -210
  163. package/build/setup-progress.js +44 -0
  164. package/build/setup-question.js +122 -4
  165. package/build/sfcc/credentials.js +3 -2
  166. package/build/sfcc/hostname.js +98 -2
  167. package/build/sfcc/tool-wrapper.js +6 -95
  168. package/build/start-tickets.js +193 -29
  169. package/build/test-support/executor-source-files.js +200 -0
  170. package/build/testing-config-client.js +25 -2
  171. package/build/third-party-mcp-targets.js +63 -2
  172. package/build/ticket-delivery-enrollment.js +9 -0
  173. package/build/upgrade-cli.js +85 -2
  174. package/build/v2-readiness-requirements.js +28 -1
  175. package/build/version.generated.js +3 -3
  176. package/build/with-credentials.js +208 -0
  177. package/build/worktree-credential-delivery.js +340 -0
  178. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  179. package/docs/epic-implementer/getting-started.md +3 -1
  180. package/docs/epic-implementer/self-hosting.md +14 -1
  181. package/package.json +2 -2
@@ -21,11 +21,13 @@ import { formatReadinessAssessment } from './conductor/readiness-prerequisites.j
21
21
  * row for the same fact. An unmet blocking item is counted once.
22
22
  */
23
23
  import { READINESS_PREREQUISITE_BY_ID, READINESS_PREREQUISITE_CATALOG, } from "./readiness-prerequisites.generated.js";
24
- import { READINESS_PREREQUISITE_FIXES, assessmentRemedyQuestion } from "./printed-remedy-commands.js";
24
+ import { READINESS_PREREQUISITE_FIXES, assessmentRemedyQuestion, formatProfilePolicyRemedy, resolveReadinessRemedy, PRE_SETUP_READINESS_REMEDY, } from "./printed-remedy-commands.js";
25
+ import { COMMAND_DRIFT_DIVERGENT_REMEDIATION, COMMAND_DRIFT_UNASSESSABLE_REMEDIATION } from "./conductor/command-drift.js";
26
+ import { shellQuote } from "./epic-launch-profile.js";
25
27
  import { decodeCanonicalProvenance } from "./conductor/bridge-api-client.js";
26
28
  import { githubSignInRemedy } from "./github-sign-in.js";
27
29
  import { EPIC_CI_WORKFLOW_ALL_MANAGED_BRANCHES } from "./epic-ci-workflow-install.js";
28
- import { MCP_PACKAGE_NAME } from "./mcp-identity.js";
30
+ import { MCP_PACKAGE_NAME, isLocalBuildLauncher } from "./mcp-identity.js";
29
31
  /** The catalog ids setup reports, named once. */
30
32
  export const SETUP_ITEM_IDS = Object.freeze({
31
33
  claudeLogin: "conductor.claude-login",
@@ -39,7 +41,29 @@ export const SETUP_ITEM_IDS = Object.freeze({
39
41
  requiredChecks: "server.supervisor-required-checks",
40
42
  repositoryIdentity: "install.identity",
41
43
  serverConnectivity: "install.connectivity",
44
+ /**
45
+ * BAPI-1545: a LOCAL advisory item. Deliberately not in the server readiness
46
+ * catalog (that would regenerate the shared catalog and its Python twin), so
47
+ * it carries its own label.
48
+ */
49
+ mcpGrant: "local.mcp-grant",
50
+ /**
51
+ * BAPI-1546: the epic-server opt-in. A LOCAL advisory item beside the MCP
52
+ * grant, behind its own consent, for the same reason the grant stays out of
53
+ * the server catalog. It never changes the verdict.
54
+ */
55
+ epicServer: "local.epic-server",
56
+ /** BAPI-1635: a LOCAL advisory item for default-branch index lag. Never blocking. */
57
+ indexFreshness: "local.index-freshness",
58
+ /** BAPI-1635: the committed-asset drift advisory, a catalog row labeled "Command versions". */
59
+ commandDrift: "conductor.command-drift",
42
60
  });
61
+ /** BAPI-1635: the explicit label of the local index-freshness item. */
62
+ export const INDEX_FRESHNESS_ITEM_LABEL = "Repository index freshness";
63
+ /** BAPI-1545: the explicit label of the local MCP grant item. */
64
+ export const MCP_GRANT_ITEM_LABEL = "Worker MCP servers (owner approval)";
65
+ /** BAPI-1546: the explicit label of the local epic-server item. */
66
+ export const EPIC_SERVER_ITEM_LABEL = "Epic server for UI checks (owner opt-in)";
43
67
  /** The catalog label for an id, falling back to the id itself. */
44
68
  export function catalogLabel(id) {
45
69
  return READINESS_PREREQUISITE_BY_ID.get(id)?.label ?? id;
@@ -51,21 +75,73 @@ function catalogIndex(id) {
51
75
  }
52
76
  /** The printed setup command, used in fixes that point back at setup. */
53
77
  export const PRINTED_SETUP_COMMAND = `npx -y ${MCP_PACKAGE_NAME} install epic-implementer`;
78
+ /** The default launcher: the published package through `npx`. */
79
+ export const NPM_SETUP_LAUNCHER = Object.freeze({ shape: "npm", base: `npx -y ${MCP_PACKAGE_NAME}` });
54
80
  /**
55
- * The fix for the escalation channel. There is no verification route on the
56
- * server, so this is a step the person carries out — setup never asks for or
57
- * sends an email address.
81
+ * The local-build launcher for a validated entry path, or null. Callers pass a path
82
+ * only after confirming the destination is local; this checks the path's shape.
58
83
  */
59
- export const ESCALATION_EMAIL_REMEDY = "verify the escalation email: declare notify.webhook_url in your run policy, or ask your Bridge " +
60
- "account administrator to confirm that the account email address receives mail, then re-run setup";
84
+ export function localBuildSetupLauncher(entryPath) {
85
+ if (!isLocalBuildLauncher("node", [entryPath]))
86
+ return null;
87
+ return { shape: "local-build", base: `node ${shellQuote(entryPath)}` };
88
+ }
89
+ function launcherOf(evidence) {
90
+ return evidence.launcher ?? NPM_SETUP_LAUNCHER;
91
+ }
92
+ /** The setup command in the detected launcher form. */
93
+ export function setupCommandFor(evidence) {
94
+ return `${launcherOf(evidence).base} install epic-implementer`;
95
+ }
96
+ /** The supported asset-refresh invocation (`--init` rewrites the packaged assets) in the detected launcher form. */
97
+ export function assetRefreshCommandFor(evidence) {
98
+ return `${launcherOf(evidence).base} --init`;
99
+ }
100
+ /** The profile-policy remedy for a known unmet escalation route, in the detected launcher form. */
101
+ export function profilePolicyRemedyFor(evidence) {
102
+ return formatProfilePolicyRemedy(setupCommandFor(evidence));
103
+ }
104
+ /**
105
+ * The one notice for a setup PR that was closed without merging. Legacy output,
106
+ * assessment JSON, and the final summary all print this exact string.
107
+ */
108
+ export function closedSetupPullRequestNotice(pr) {
109
+ return `The setup pull request ${pr.url} was closed without being merged. Bridge's GitHub workflow is not on your default branch, so epic pull requests do not run it. Setup will not reopen it or open another one. To fix this, reopen and merge it, or delete the branch ${pr.branch} and re-run setup.`;
110
+ }
111
+ /** BAPI-1657: the owner-facing remedy when approving this setup stores a missing test gate. */
112
+ const GATE_STORED_ON_APPROVAL_REMEDY = "No test gate is stored yet; approving this setup stores it.";
113
+ /** The proposal questions for the two local choices, shared with the agent proposal's catalog. */
114
+ export const MCP_GRANT_QUESTION = "Which of your MCP servers should every worker also be able to use?";
115
+ export const EPIC_SERVER_QUESTION = "Should runs start a test server so workers can check the user interface?";
116
+ export const REINDEX_RETRY_QUESTION = "Should Bridge try once more to read your repository, now that the last attempt did not finish?";
117
+ /**
118
+ * Client-only wording for a default-branch revision Bridge could not read. A
119
+ * parse cannot bind it, so the action is restoring Bridge's access to GitHub.
120
+ * Deliberately not in the shared published remedy tables.
121
+ */
122
+ const DEFAULT_BRANCH_ACCESS_REMEDY = "Bridge could not read the default branch from GitHub. Check Bridge’s access to the repository, then re-run setup.";
123
+ /** Opening words of an agent-path remedy that points at a proposal question. */
124
+ const AGENT_CHOICE_REMEDY_PREFIX = "Re-run setup with your answer to";
125
+ /** Present only in a printed command wrapped for the agent path. */
126
+ const AGENT_ANSWERS_MARKER = "--answers <answers-file>";
127
+ /** Index states in which a parse is already running or queued. */
128
+ const ACTIVE_INDEX_STATES = ["in_progress", "queued_by_setup", "recovery_pending"];
61
129
  // ---------------------------------------------------------------------------
62
130
  // Projection
63
131
  // ---------------------------------------------------------------------------
64
- function fromServerPrerequisite(p, isProduction) {
132
+ /**
133
+ * BAPI-1678: an item that only reflects that supervisor setup has not been saved yet.
134
+ * Strictly `false`: a true, missing, or unreadable setup presence keeps today's remedy.
135
+ */
136
+ function needsSetupFirst(setupPresent, id, scope) {
137
+ return setupPresent === false && (scope === "self_host" || id === "server.service-availability");
138
+ }
139
+ export function fromServerPrerequisite(p, isProduction, setupPresent) {
65
140
  if (p.check_status === "met" || p.check_status === "not_applicable") {
66
141
  return { id: p.id, label: p.label, state: "met", blocking: p.impact === "blocking", remedy: null };
67
142
  }
68
143
  const blocking = p.impact === "blocking";
144
+ const preSetup = needsSetupFirst(setupPresent, p.id, p.scope);
69
145
  // On production, a Bridge-hosted (self_host) fact is never the customer's to
70
146
  // fix, so it reads as "could not verify — retry", never as server repair advice.
71
147
  if (p.scope === "self_host" && isProduction) {
@@ -74,7 +150,7 @@ function fromServerPrerequisite(p, isProduction) {
74
150
  label: p.label,
75
151
  state: "unknown",
76
152
  blocking,
77
- remedy: READINESS_PREREQUISITE_FIXES.retry,
153
+ remedy: preSetup ? PRE_SETUP_READINESS_REMEDY : READINESS_PREREQUISITE_FIXES.retry,
78
154
  };
79
155
  }
80
156
  return {
@@ -82,7 +158,7 @@ function fromServerPrerequisite(p, isProduction) {
82
158
  label: p.label,
83
159
  state: p.check_status === "unknown" ? "unknown" : "needs_action",
84
160
  blocking,
85
- remedy: p.fix.length > 0 ? p.fix : READINESS_PREREQUISITE_FIXES.retry,
161
+ remedy: preSetup ? PRE_SETUP_READINESS_REMEDY : p.fix.length > 0 ? p.fix : READINESS_PREREQUISITE_FIXES.retry,
86
162
  };
87
163
  }
88
164
  function upsert(items, item) {
@@ -99,9 +175,12 @@ function local(id, state, blocking, remedy) {
99
175
  * Project one assessment pass onto the readiness items, in catalog order.
100
176
  *
101
177
  * Pure. It never derives readiness from a local write or an exit code: a
102
- * stored command is met only when the read-back saw it, a workflow only when
103
- * the installer found it identical, and indexing only when the index reached
104
- * the merge commit.
178
+ * workflow is met only when the installer found it identical, and indexing only
179
+ * when the index reached the merge commit. There is no test-command item: the
180
+ * command is learned and proven by the server, or there is none, and neither is a
181
+ * client-side blocker. The managed workflow blocks only when it is wanted (a
182
+ * `managed` plan, or a gate that requires its check); a watched, none, or
183
+ * declined-local plan stays ready without it.
105
184
  */
106
185
  export function projectSetupItems(evidence) {
107
186
  if (evidence.readiness?.assessmentNegotiation)
@@ -114,7 +193,7 @@ export function projectSetupItems(evidence) {
114
193
  }
115
194
  else if (readiness.prerequisites !== undefined) {
116
195
  for (const p of readiness.prerequisites) {
117
- const item = fromServerPrerequisite(p, isProduction);
196
+ const item = fromServerPrerequisite(p, isProduction, readiness.supervisor?.setup_present);
118
197
  if (item !== null)
119
198
  items.push(item);
120
199
  }
@@ -131,50 +210,149 @@ export function projectSetupItems(evidence) {
131
210
  upsert(items, local(SETUP_ITEM_IDS.githubSignIn, evidence.githubSignIn === "signed_in" ? "met" : evidence.githubSignIn === "unavailable" ? "unknown" : "needs_action", true, githubSignInRemedy(evidence.githubSignIn)));
132
211
  // --- Repository identity ------------------------------------------------
133
212
  if (evidence.repositoryIdentity !== "resolved") {
134
- upsert(items, local(SETUP_ITEM_IDS.repositoryIdentity, "needs_action", true, evidence.repositoryIdentity === "conflict"
135
- ? "this checkout's github.com remote names a different repository than Bridge does; run setup from the matching checkout"
136
- : "run setup from a checkout whose `origin` remote is the github.com repository"));
137
- }
138
- // --- Test command (the stored value, read back) --------------------------
139
- if (evidence.testCommand.state !== "stored") {
140
- const existing = items.find((i) => i.id === SETUP_ITEM_IDS.testCommand);
141
- upsert(items, local(SETUP_ITEM_IDS.testCommand, evidence.testCommand.state === "missing" ? "needs_action" : "unknown", true, evidence.testCommand.state === "missing"
142
- ? "save a test command: re-run setup and give the command that runs your tests"
143
- : existing?.remedy ?? READINESS_PREREQUISITE_FIXES.retry));
144
- }
145
- else {
146
- const existing = items.find((i) => i.id === SETUP_ITEM_IDS.testCommand);
147
- if (existing === undefined)
148
- upsert(items, local(SETUP_ITEM_IDS.testCommand, "met", true, null));
213
+ upsert(items, local(SETUP_ITEM_IDS.repositoryIdentity, "needs_action", true, repositoryIdentityRemedy(evidence.repositoryIdentity)));
149
214
  }
150
215
  // --- Workflow, setup pull request, and indexing --------------------------
151
216
  const workflowItem = projectWorkflowItem(evidence, items.find((i) => i.id === SETUP_ITEM_IDS.workflows));
152
217
  if (workflowItem !== null)
153
218
  upsert(items, workflowItem);
154
- // --- The gate change the owner declined ---------------------------------
155
- if (evidence.gateChangeDeclined) {
156
- upsert(items, local(SETUP_ITEM_IDS.requiredChecks, "needs_action", true, "add the CI workflow check to the repository gate: re-run setup and accept the gate change"));
157
- }
158
219
  // --- Merge credential ----------------------------------------------------
159
220
  const merge = projectMergeCredential(evidence.mergeCredential);
160
221
  if (merge !== null)
161
222
  upsert(items, merge);
162
- // --- Escalation channel: a fix the person carries out --------------------
163
- const escalation = items.find((i) => i.id === SETUP_ITEM_IDS.escalation);
164
- if (escalation !== undefined && escalation.state === "needs_action") {
165
- upsert(items, { ...escalation, remedy: ESCALATION_EMAIL_REMEDY });
166
- }
223
+ // --- BAPI-1545: worker MCP grant (advisory, never the verdict) ----------
224
+ const grant = projectMcpGrantItem(evidence.mcpGrant, evidence.path);
225
+ if (grant !== null)
226
+ upsert(items, grant);
227
+ // --- BAPI-1546: epic-server opt-in (advisory, never the verdict) ---------
228
+ const epicServer = projectEpicServerItem(evidence.epicServer, evidence.path);
229
+ if (epicServer !== null)
230
+ upsert(items, epicServer);
231
+ // --- BAPI-1635: a known unmet row never keeps the generic retry -----------
232
+ // `fromServerPrerequisite` stays as it was; a blank wire fix is resolved here by ID.
233
+ for (const item of items)
234
+ normalizeKnownRemedy(item);
235
+ // --- Escalation channel: the selected launch profile's route, or its remedy -
236
+ applyNotificationEvidence(items, evidence);
237
+ // --- BAPI-1635: index lag and committed-asset drift (advisory, never the verdict) ---
238
+ const freshness = projectFreshnessItem(evidence.freshness);
239
+ if (freshness !== null)
240
+ upsert(items, freshness);
241
+ const drift = projectCommandDriftItem(evidence);
242
+ if (drift !== null)
243
+ upsert(items, drift);
167
244
  return items
168
245
  .map((item, arrival) => ({ item, arrival }))
169
246
  .sort((a, b) => catalogIndex(a.item.id) - catalogIndex(b.item.id) || a.arrival - b.arrival)
170
247
  .map(({ item }) => item);
171
248
  }
249
+ /**
250
+ * BAPI-1635: replace the generic retry on a KNOWN unmet catalog row with its
251
+ * per-ID remedy. An unknown row, a met row, and a row with its own remedy are untouched.
252
+ */
253
+ function normalizeKnownRemedy(item) {
254
+ if (item.state !== "needs_action" || item.remedy !== READINESS_PREREQUISITE_FIXES.retry)
255
+ return;
256
+ const descriptor = READINESS_PREREQUISITE_BY_ID.get(item.id);
257
+ if (descriptor === undefined)
258
+ return;
259
+ item.remedy = resolveReadinessRemedy({ id: item.id, state: "not_met", scope: descriptor.scope, impact: item.blocking ? "blocking" : "warning" });
260
+ }
261
+ /**
262
+ * BAPI-1635: apply the selected launch profile's notification evidence to the
263
+ * effective escalation item. A valid declaration is an effective route; an
264
+ * independently confirmed live-email route (the item already met) is kept; a
265
+ * confirmed absent or invalid declaration keeps the profile-policy remedy; an
266
+ * unreadable policy stays unknown. Reachability is never inferred.
267
+ */
268
+ function applyNotificationEvidence(items, evidence) {
269
+ const escalation = items.find((i) => i.id === SETUP_ITEM_IDS.escalation);
270
+ if (escalation === undefined || escalation.state === "met")
271
+ return;
272
+ const notification = evidence.notification;
273
+ if (notification?.state === "declared") {
274
+ upsert(items, { ...escalation, state: "met", remedy: null });
275
+ }
276
+ else if (notification?.state === "unreadable") {
277
+ upsert(items, { ...escalation, state: "unknown", remedy: READINESS_PREREQUISITE_FIXES.retry });
278
+ }
279
+ else if (escalation.state === "needs_action") {
280
+ upsert(items, { ...escalation, remedy: profilePolicyRemedyFor(evidence) });
281
+ }
282
+ }
283
+ const COMMIT_ID = /^[0-9a-f]{40}$/;
284
+ /** The one remedy for index lag; names both commits and the manual re-index. */
285
+ function freshnessRemedy(fresh) {
286
+ const indexed = fresh.indexedSha ?? "unknown";
287
+ const head = fresh.defaultBranchSha ?? "unknown";
288
+ const relation = fresh.relation === "diverged" ? "diverges from" : "is behind";
289
+ return `The index at ${indexed} ${relation} the default branch at ${head}. ${READINESS_PREREQUISITE_FIXES.reindex_manual}`;
290
+ }
291
+ /**
292
+ * BAPI-1635: the advisory index-freshness item. Lag is confirmed only when both
293
+ * commit IDs are valid and the ancestry relation says so; `unknown` and `diverged`
294
+ * stay distinct. Always non-blocking: a mandatory server blocker is the server row's.
295
+ */
296
+ export function projectFreshnessItem(fresh) {
297
+ if (fresh === undefined)
298
+ return null;
299
+ const item = (state, remedy) => ({
300
+ id: SETUP_ITEM_IDS.indexFreshness,
301
+ label: INDEX_FRESHNESS_ITEM_LABEL,
302
+ state,
303
+ blocking: false,
304
+ remedy: state === "met" ? null : remedy,
305
+ });
306
+ const valid = fresh.indexedSha !== null && fresh.defaultBranchSha !== null
307
+ && COMMIT_ID.test(fresh.indexedSha) && COMMIT_ID.test(fresh.defaultBranchSha);
308
+ if (!valid)
309
+ return item("unknown", "the index could not be compared with the default branch; re-run setup later");
310
+ switch (fresh.relation) {
311
+ case "equal":
312
+ case "contains_target":
313
+ return item("met", null);
314
+ case "behind":
315
+ case "diverged":
316
+ if (fresh.requestState === "queued" || fresh.requestState === "in_progress") {
317
+ return item("pending", "indexing is running; re-run setup when it finishes");
318
+ }
319
+ return item("needs_action", freshnessRemedy(fresh));
320
+ case "unknown":
321
+ return item("unknown", "the index could not be compared with the default branch; re-run setup later");
322
+ }
323
+ }
324
+ /**
325
+ * BAPI-1635: the non-blocking "Command versions" advisory. Divergent stays
326
+ * divergent until refreshed bytes are committed at HEAD; setup never refreshes
327
+ * or commits on its own.
328
+ */
329
+ export function projectCommandDriftItem(evidence) {
330
+ const drift = evidence.drift;
331
+ if (drift === undefined)
332
+ return null;
333
+ const item = (state, remedy) => ({
334
+ id: SETUP_ITEM_IDS.commandDrift,
335
+ label: catalogLabel(SETUP_ITEM_IDS.commandDrift),
336
+ state,
337
+ blocking: false,
338
+ remedy: state === "met" ? null : remedy,
339
+ });
340
+ if (drift.status === "pass")
341
+ return item("met", null);
342
+ if (drift.kind === "unassessable")
343
+ return item("unknown", COMMAND_DRIFT_UNASSESSABLE_REMEDIATION);
344
+ return item("needs_action", COMMAND_DRIFT_DIVERGENT_REMEDIATION);
345
+ }
172
346
  function projectWorkflowItem(evidence, server) {
173
347
  const id = SETUP_ITEM_IDS.workflows;
174
348
  const pr = evidence.setupPullRequest;
175
349
  if (evidence.index.state === "recovery_unresolved")
176
350
  return local(id, "needs_action", true, evidence.index.remedy);
177
351
  if (evidence.recovery && evidence.index.state !== "reached") {
352
+ if (!evidence.recovery.supported && (evidence.freshness?.relation === "behind" || evidence.freshness?.relation === "diverged")) {
353
+ // BAPI-1635: a proven lag and its manual recovery beat "upgrade the backend".
354
+ return local(id, "needs_action", true, freshnessRemedy(evidence.freshness));
355
+ }
178
356
  if (!evidence.recovery.supported)
179
357
  return local(id, "unknown", true, evidence.recovery.reason === "upgrade_required" ? "upgrade the Bridge backend for target-aware setup recovery, then re-run setup" : "setup recovery evidence is unavailable; inspect the configured branch with your Bridge administrator, then re-run setup");
180
358
  const r = evidence.recovery.evidence;
@@ -182,39 +360,45 @@ function projectWorkflowItem(evidence, server) {
182
360
  if (r.request && ["queued", "in_progress"].includes(r.request.status ?? ""))
183
361
  return local(id, "pending", true, `${target}: request ${r.request.id}, run ${r.request.parse_run_id ?? "retained"} is pending; re-run setup to inspect it without replacing healthy work`);
184
362
  if (r.retry_generation !== null)
185
- return local(id, "needs_action", true, `${target}: prior request ${r.request?.id ?? "unknown"} ${r.request?.status ?? "unknown"}; explicit retry ${r.retry_generation} needs review in interactive setup`);
363
+ return local(id, "needs_action", true, evidence.path === "agent"
364
+ ? `${target}: prior request ${r.request?.id ?? "unknown"} ${r.request?.status ?? "unknown"}; re-run setup with your answer to “${REINDEX_RETRY_QUESTION}”`
365
+ : `${target}: prior request ${r.request?.id ?? "unknown"} ${r.request?.status ?? "unknown"}; explicit retry ${r.retry_generation} needs review in interactive setup`);
186
366
  if (r.reason)
187
367
  return local(id, "unknown", true, `${target}: ${r.reason}; inspect the configuration and verified index with your Bridge administrator`);
188
368
  if (r.active_runs.some(run => run.requested_target_sha === null))
189
369
  return local(id, "pending", true, `${target}: legacy-target-unknown active work cannot prove a match; interactive setup can admit one tracked successor after reviewing the target`);
190
370
  return local(id, "needs_action", true, `${target}: canonical content ${r.canonical_relation}; review keep/correct/defer in interactive setup`);
191
371
  }
372
+ // The managed workflow is wanted only when the plan is `managed` or the gate
373
+ // already requires its check. Otherwise its absence, an available upgrade, and
374
+ // an assessment that could not run say nothing about readiness: the server's own
375
+ // fact decides, and with none the item is met.
376
+ const workflowWanted = evidence.ciPlan === "managed" || evidence.gateRequiresManagedCheck === true;
192
377
  switch (evidence.workflow.state) {
193
378
  case "pr_open":
194
379
  return local(id, "pending", true, `merge the setup PR: ${evidence.workflow.url}`);
380
+ case "absent":
381
+ if (!workflowWanted)
382
+ return server ?? local(id, "met", true, null);
383
+ return local(id, "needs_action", true, "open the setup PR: re-run setup and accept the setup pull request");
195
384
  case "needs_pr":
385
+ // An installed Bridge workflow that could be upgraded still does its job.
386
+ if (!workflowWanted)
387
+ return server ?? local(id, "met", true, null);
196
388
  return local(id, "needs_action", true, "open the setup PR: re-run setup and accept the setup pull request");
197
389
  case "blocked":
390
+ // A real conflict (a modified managed file, a different open setup PR, a
391
+ // checkout that is not the repository root) stays visible whatever the plan.
198
392
  return local(id, "needs_action", true, evidence.workflow.remedy);
199
- case "needs_command":
200
- return local(id, "needs_action", true, "save a test command first; setup builds the CI workflow from it");
201
393
  case "unknown":
394
+ if (!workflowWanted)
395
+ return server ?? local(id, "met", true, null);
202
396
  return server ?? local(id, "unknown", true, "the CI workflow could not be checked; re-run setup");
203
- case "precondition":
204
- // The local preflight could not run, but a merged setup PR still proves the
205
- // workflow reached the default branch; then only indexing remains.
206
- if (server?.state === "met")
207
- return server;
208
- if (pr.state !== "merged")
209
- return local(id, "needs_action", true, evidence.workflow.remedy);
210
- break;
211
397
  case "installed":
212
398
  break;
213
399
  }
214
400
  // The workflow is on the default branch. What remains is indexing.
215
- if (pr.state === "closed_unmerged") {
216
- return local(id, "needs_action", true, `the setup PR was closed without merging (${pr.url}); reopen and merge it, or delete the branch ${pr.branch} and re-run setup`);
217
- }
401
+ // A closed setup PR is moot once the workflow is on the default branch.
218
402
  switch (evidence.index.state) {
219
403
  case "recovery_pending":
220
404
  return local(id, "pending", true, `request ${evidence.index.requestId}, run ${evidence.index.runId ?? "retained"} is pending; re-run setup to inspect it without cancelling parsing`);
@@ -236,6 +420,69 @@ function projectWorkflowItem(evidence, server) {
236
420
  return server ?? local(id, "met", true, null);
237
421
  }
238
422
  }
423
+ /**
424
+ * BAPI-1545: the advisory MCP grant item. Non-blocking in every state, so it
425
+ * never changes the setup verdict.
426
+ */
427
+ export function projectMcpGrantItem(state, path = "terminal") {
428
+ if (state === undefined)
429
+ return null;
430
+ const item = (s, remedy) => ({
431
+ id: SETUP_ITEM_IDS.mcpGrant,
432
+ label: MCP_GRANT_ITEM_LABEL,
433
+ state: s,
434
+ blocking: false,
435
+ remedy: s === "met" ? null : remedy,
436
+ });
437
+ switch (state.state) {
438
+ case "met":
439
+ return item("met", null);
440
+ case "unknown":
441
+ return item("unknown", "the MCP grant could not be checked; re-run setup");
442
+ case "needs_action":
443
+ return item("needs_action", state.reason === "no_grant"
444
+ ? path === "agent"
445
+ ? `Re-run setup with your answer to “${MCP_GRANT_QUESTION}” Workers keep today's servers until then.`
446
+ : "approve which extra MCP servers workers get: re-run setup in an interactive terminal (workers keep today's servers until then)"
447
+ : state.reason === "changed"
448
+ ? "the MCP servers available to approve changed since the last approval; re-run setup to review them (the current grant stays in force)"
449
+ : "the MCP grant file is unusable, so workers get Bridge only; re-run setup to replace it");
450
+ }
451
+ }
452
+ /**
453
+ * BAPI-1546: the advisory epic-server item. Non-blocking in every state, so it
454
+ * never changes the setup verdict. A failed capability-statement write after a
455
+ * change is reported here only.
456
+ */
457
+ export function projectEpicServerItem(state, path = "terminal") {
458
+ if (state === undefined)
459
+ return null;
460
+ const item = (s, remedy) => ({
461
+ id: SETUP_ITEM_IDS.epicServer,
462
+ label: EPIC_SERVER_ITEM_LABEL,
463
+ state: s,
464
+ blocking: false,
465
+ remedy: s === "met" ? null : remedy,
466
+ });
467
+ switch (state.state) {
468
+ case "met":
469
+ if (state.statementError !== undefined) {
470
+ return {
471
+ ...item("met", null),
472
+ remedy: `the epic-server choice was saved, but ${state.statementError}; re-run setup to retry the capability statement`,
473
+ };
474
+ }
475
+ return item("met", null);
476
+ case "unknown":
477
+ return item("unknown", "the epic-server choice could not be checked; re-run setup");
478
+ case "needs_action":
479
+ return item("needs_action", state.reason === "no_record"
480
+ ? path === "agent"
481
+ ? `Re-run setup with your answer to “${EPIC_SERVER_QUESTION}” UI checks are handed off until then.`
482
+ : "choose whether Epic Implementer runs get an epic server for UI checks: re-run setup in an interactive terminal (UI checks are handed off until then)"
483
+ : "the epic-server record is unusable, so runs have no epic server; re-run setup to replace it");
484
+ }
485
+ }
239
486
  function projectMergeCredential(state) {
240
487
  const id = SETUP_ITEM_IDS.mergeCredential;
241
488
  switch (state.state) {
@@ -255,17 +502,17 @@ function projectMergeCredential(state) {
255
502
  return local(id, "unknown", true, "the merge token could not be checked right now; re-run setup later");
256
503
  }
257
504
  }
258
- /** The two fixes that write the stored test command. */
259
- export function isTestCommandFix(fix) {
260
- return fix === "save_test_command" || fix === "replace_test_command";
261
- }
262
505
  /**
263
506
  * Pick the permitted fixes for the unmet items, in the order they must run.
264
507
  *
265
508
  * Pure. Dependencies are explicit:
266
- * - a missing stored command blocks the workflow PR (it is built from it);
267
- * - an explicit replacement is planned first and, like a save, can make the
268
- * workflow PR possible or necessary once its read-back is confirmed;
509
+ * - there is no test-command fix: the command is learned and proven by the
510
+ * server through a trial that setup's orchestration runs in its own explicit
511
+ * order, after the gate is written and before any workflow is offered;
512
+ * - the setup PR is planned to UPGRADE a Bridge workflow that is already
513
+ * installed, or to install the one a stored or explicit gate already requires
514
+ * the check of. A first workflow for a plan that does not need it is offered
515
+ * once by the orchestration, only for a proven local plan, and is never planned here;
269
516
  * - a GitHub sign-in that is not ready blocks GitHub-dependent fixes (the
270
517
  * setup PR), never the Bridge or local ones;
271
518
  * - an unresolved repository identity blocks the stored merge token.
@@ -275,18 +522,8 @@ export function isTestCommandFix(fix) {
275
522
  export function planSetupFixes(evidence, context) {
276
523
  const fixes = [];
277
524
  const githubReady = evidence.githubSignIn === "signed_in";
278
- // An explicit request outranks the interactive one; the interactive save is
279
- // kept only for a command that is KNOWN to be missing.
280
- if (context.replaceTestCommandRequested === true)
281
- fixes.push("replace_test_command");
282
- else if (evidence.testCommand.state === "missing")
283
- fixes.push("save_test_command");
284
- // Either command fix is a potential dependency of the workflow fix; whether
285
- // the workflow is then installed depends on the read-back being confirmed.
286
- const commandAvailable = evidence.testCommand.state === "stored" || fixes.some(isTestCommandFix);
287
- if (githubReady &&
288
- commandAvailable &&
289
- (evidence.workflow.state === "needs_pr" || evidence.workflow.state === "needs_command")) {
525
+ const workflowWanted = evidence.ciPlan === "managed" || evidence.gateRequiresManagedCheck === true;
526
+ if (githubReady && (evidence.workflow.state === "needs_pr" || (evidence.workflow.state === "absent" && workflowWanted))) {
290
527
  fixes.push("setup_pr");
291
528
  }
292
529
  if (context.gateOrDefaultsNeedWrite || context.suppliedPolicyInput)
@@ -295,7 +532,7 @@ export function planSetupFixes(evidence, context) {
295
532
  (evidence.mergeCredential.state === "missing" || evidence.mergeCredential.state === "stored_rejected")) {
296
533
  fixes.push("merge_token");
297
534
  }
298
- const recovery = evidence.recovery;
535
+ const recovery = evidence.setupPullRequest.state === "merged" ? evidence.recovery : undefined;
299
536
  const knownUnverified = recovery?.supported && !recovery.evidence.canonical.verified
300
537
  && ["absent", "unverified"].includes(recovery.evidence.canonical_observation ?? "unknown");
301
538
  if (recovery?.supported && !recovery.evidence.reason && ((recovery.evidence.canonical.verified
@@ -303,6 +540,18 @@ export function planSetupFixes(evidence, context) {
303
540
  && recovery.evidence.configured_relation !== "unknown"
304
541
  && !["queued", "in_progress"].includes(recovery.evidence.request?.status ?? ""))
305
542
  fixes.push("reindex");
543
+ // BAPI-1545: one advisory approval, asked only when the grant is missing,
544
+ // unusable, or its candidates changed. A met grant asks nothing.
545
+ if (evidence.mcpGrant?.state === "needs_action")
546
+ fixes.push("mcp_grant");
547
+ // BAPI-1546: the epic-server choice, after the grant, behind its own consent.
548
+ // Asked only when the record is missing or unusable, or the owner asked to
549
+ // change it. A valid record of any mode (`none` included) asks nothing.
550
+ if (evidence.epicServer !== undefined &&
551
+ evidence.epicServer.state !== "unknown" &&
552
+ (evidence.epicServer.state === "needs_action" || context.epicServerChangeRequested === true)) {
553
+ fixes.push("epic_server");
554
+ }
306
555
  return fixes;
307
556
  }
308
557
  const SHA_RE = /^[0-9a-f]{40}$/;
@@ -415,6 +664,37 @@ export async function assessSetupIndex(pr, readParseStatus, compare) {
415
664
  return { state: "in_progress" };
416
665
  return { state: "unknown" };
417
666
  }
667
+ /**
668
+ * BAPI-1635: compare the verified canonical index with the default-branch head.
669
+ *
670
+ * Read-only, and independent of {@link assessSetupIndex}: a repository with no setup
671
+ * pull request can still lag. It reuses canonical provenance decoding and
672
+ * {@link compareIndexedToMerge} with the default-branch commit as the comparison
673
+ * target. Lag is `behind` only when both commit IDs and GitHub's ancestry answer
674
+ * establish it; every other shape stays `unknown` or `diverged`. Never queues anything.
675
+ */
676
+ export async function assessIndexFreshness(defaultBranchSha, readParseStatus, compare) {
677
+ const unknown = (indexedSha, requestState) => ({
678
+ indexedSha,
679
+ defaultBranchSha,
680
+ relation: "unknown",
681
+ ...(requestState !== undefined ? { requestState } : {}),
682
+ });
683
+ let status;
684
+ try {
685
+ status = await readParseStatus();
686
+ }
687
+ catch {
688
+ return unknown(null);
689
+ }
690
+ const requestState = status.status === "queued" ? "queued" : status.status === "in_progress" ? "in_progress" : "none";
691
+ const canonical = decodeCanonicalProvenance(status);
692
+ if (!canonical.verified || defaultBranchSha === null || !SHA_RE.test(defaultBranchSha)) {
693
+ return unknown(canonical.verified ? canonical.sourceCommitSha : null, requestState);
694
+ }
695
+ const relation = await compare(defaultBranchSha, canonical.sourceCommitSha);
696
+ return { indexedSha: canonical.sourceCommitSha, defaultBranchSha, relation, requestState };
697
+ }
418
698
  // ---------------------------------------------------------------------------
419
699
  // Rendering
420
700
  // ---------------------------------------------------------------------------
@@ -424,6 +704,28 @@ const STATE_WORD = Object.freeze({
424
704
  pending: "pending",
425
705
  unknown: "could not verify",
426
706
  });
707
+ /** The advisory findings setup adds beside the server's own rows. */
708
+ const ADVISORY_FINDING_IDS = new Set([SETUP_ITEM_IDS.indexFreshness, SETUP_ITEM_IDS.commandDrift]);
709
+ /**
710
+ * BAPI-1635: the lines for the advisory findings setup adds (index lag, command
711
+ * versions) in the compact summary and in read-only runs, where the full assessment
712
+ * is not printed. Empty when none is unmet. They never change the verdict.
713
+ */
714
+ export function advisoryFindingLines(items) {
715
+ // Only a finding (needs action, or indexing already running); an unreadable comparison is not advice.
716
+ const found = items.filter((i) => !i.blocking && (i.state === "needs_action" || i.state === "pending") && ADVISORY_FINDING_IDS.has(i.id) && i.remedy !== null);
717
+ return found.length === 0 ? [] : ["", "Also worth doing (advisory)", ...found.map((i) => ` - ${i.label}: ${i.remedy}`)];
718
+ }
719
+ /**
720
+ * BAPI-1635: the one remedy to print for an item. An item with its own remedy keeps
721
+ * it; with none, a known state resolves by catalog ID and only an unreadable or
722
+ * pending one falls back to retry.
723
+ */
724
+ export function setupItemRemedy(item) {
725
+ if (item.remedy !== null)
726
+ return item.remedy;
727
+ return resolveReadinessRemedy({ id: item.id, state: item.state === "needs_action" ? "not_met" : "unknown" });
728
+ }
427
729
  /** Blocking items that are not met, each counted once. */
428
730
  export function unmetBlockingItems(items) {
429
731
  const seen = new Set();
@@ -438,26 +740,70 @@ export function unmetBlockingItems(items) {
438
740
  export function setupVerdictLine(items) {
439
741
  const assessment = items.find(i => i.assessment)?.assessment;
440
742
  if (assessment) {
743
+ // BAPI-1635: the verdict reads the effective assessment; the raw one stays evidence.
744
+ const effective = items.find(i => i.effectiveAssessment)?.effectiveAssessment ?? assessment;
441
745
  const extras = additionalRequiredItems(items, assessment);
442
- const verdict = extras.some(i => i.state === 'needs_action') ? 'Not ready' : extras.length && deriveAdvisoryVerdict(assessment) === 'Ready' ? 'Readiness not confirmed' : deriveAdvisoryVerdict(assessment);
746
+ const verdict = extras.some(i => i.state === 'needs_action') ? 'Not ready' : extras.length && deriveAdvisoryVerdict(effective) === 'Ready' ? 'Readiness not confirmed' : deriveAdvisoryVerdict(effective);
443
747
  return `${verdict} — ${assessmentContextLabel(assessment)}; advisory only.`;
444
748
  }
445
749
  const left = unmetBlockingItems(items).length;
446
750
  return left === 0 ? "Ready for your first epic" : `Not ready: ${left} step${left === 1 ? "" : "s"} left`;
447
751
  }
752
+ /**
753
+ * BAPI-1678: whether a run can start, from the post-apply readiness evidence only.
754
+ * `undefined` means the evidence gave no answer. It follows the same precedence as
755
+ * `setupVerdictLine`, which stays as it is for human output. Write results are not an
756
+ * input, so a successful write cannot make this true and a failed one cannot make it false.
757
+ */
758
+ export function deriveCompactReadiness(input) {
759
+ if (!input.readinessObserved)
760
+ return undefined;
761
+ const { items } = input;
762
+ const assessment = items.find(i => i.assessment)?.assessment;
763
+ if (assessment) {
764
+ const effective = items.find(i => i.effectiveAssessment)?.effectiveAssessment ?? assessment;
765
+ const extras = additionalRequiredItems(items, assessment);
766
+ if (extras.some(i => i.state === 'needs_action'))
767
+ return false;
768
+ const verdict = deriveAdvisoryVerdict(effective);
769
+ if (verdict === 'Not ready')
770
+ return false;
771
+ return verdict === 'Ready' && extras.length === 0 ? true : undefined;
772
+ }
773
+ const unmet = unmetBlockingItems(items);
774
+ if (unmet.some(i => i.state === 'needs_action'))
775
+ return false;
776
+ return unmet.length === 0 ? true : undefined;
777
+ }
448
778
  /** Render the assessment: a status list, then one fix per unmet blocking item. */
449
779
  export function renderSetupAssessment(items, heading, phase = 'final') {
450
780
  const assessment = items.find(i => i.assessment)?.assessment;
451
781
  if (assessment) {
452
- const lines = formatReadinessAssessment(assessment, { initial: phase === 'initial' });
782
+ const effective = items.find(i => i.effectiveAssessment)?.effectiveAssessment;
783
+ const profile = items.find(i => i.escalationProfile !== undefined)?.escalationProfile;
784
+ // The projected remedy replaces the raw reference text where setup chose a more specific one:
785
+ // an unbound revision, or a command wrapped for the agent path. Other records render as before.
786
+ const projected = new Map(items.filter(i => i.remedy !== null).map(i => [i.id, i.remedy]));
787
+ const remedyTextForRecord = (r) => {
788
+ const text = projected.get(`${r.scope}:${r.id}`);
789
+ return text !== undefined && (r.reason === 'revision_unbound' || text.includes(AGENT_ANSWERS_MARKER) || text === PRE_SETUP_READINESS_REMEDY) ? text : undefined;
790
+ };
791
+ const lines = formatReadinessAssessment(phase === 'final' && effective ? effective : assessment, { initial: phase === 'initial', remedyTextForRecord });
453
792
  if (phase === 'final') {
454
793
  lines.pop();
794
+ // The raw repository observation stays visible; the run's effective route is named beside it.
795
+ if (profile !== undefined)
796
+ lines.push(`Escalation route: the repository observation is unchanged; launch profile '${profile}' declares a notification route.`);
455
797
  const extras = additionalRequiredItems(items, assessment);
456
798
  if (extras.length)
457
799
  lines.push('Additional required setup actions', ...extras.map(item => renderSetupQuestion({
458
800
  ...assessmentRemedyQuestion({ reference: 'setup', audience: 'repository_admin' }, [`${item.label}: ${item.state}`]),
459
- purpose: item.remedy ?? READINESS_PREREQUISITE_FIXES.retry,
801
+ purpose: item.remedy ?? resolveReadinessRemedy({ id: item.id, state: item.state === 'unknown' || item.state === 'pending' ? 'unknown' : 'not_met' }),
460
802
  })));
803
+ const advisories = items.filter(i => !i.blocking && i.state !== 'met' && i.remedy !== null
804
+ && (ADVISORY_FINDING_IDS.has(i.id) || ((i.id === SETUP_ITEM_IDS.mcpGrant || i.id === SETUP_ITEM_IDS.epicServer) && i.remedy.startsWith(AGENT_CHOICE_REMEDY_PREFIX))));
805
+ if (advisories.length)
806
+ lines.push('Advisory findings (not blocking)', ...advisories.map(i => ` ${i.label}: ${i.remedy}`));
461
807
  lines.push(setupVerdictLine(items));
462
808
  }
463
809
  return ['', heading, ...lines];
@@ -475,9 +821,10 @@ export function renderSetupAssessment(items, heading, phase = 'final') {
475
821
  const unmet = unmetBlockingItems(items);
476
822
  if (unmet.length > 0) {
477
823
  lines.push("", "Steps left");
478
- unmet.forEach((item, index) => lines.push(` ${index + 1}. ${item.label}: ${item.remedy ?? READINESS_PREREQUISITE_FIXES.retry}`));
824
+ unmet.forEach((item, index) => lines.push(` ${index + 1}. ${item.label}: ${setupItemRemedy(item)}`));
479
825
  }
480
- const advisories = items.filter((i) => !i.blocking && i.state !== "met" && i.remedy !== null);
826
+ // BAPI-1546: a met epic-server item may still carry its failed statement write.
827
+ const advisories = items.filter((i) => !i.blocking && i.remedy !== null && (i.state !== "met" || i.id === SETUP_ITEM_IDS.epicServer));
481
828
  if (advisories.length > 0) {
482
829
  lines.push("", "Also worth doing (advisory)");
483
830
  for (const item of advisories)
@@ -485,6 +832,23 @@ export function renderSetupAssessment(items, heading, phase = 'final') {
485
832
  }
486
833
  return lines;
487
834
  }
835
+ /** The advisory setup-PR fact. Only a known closed-unmerged PR is deficient and carries a remedy. */
836
+ function setupPullRequestFact(pr, workflowInstalled) {
837
+ switch (pr.state) {
838
+ case 'closed_unmerged':
839
+ // With the workflow already on the default branch the closed PR is moot.
840
+ if (workflowInstalled)
841
+ return { id: 'local.setup-pr', observed_state: 'unknown', impact: 'advisory' };
842
+ return { id: 'local.setup-pr', observed_state: 'deficient', impact: 'advisory', remedy: closedSetupPullRequestNotice(pr) };
843
+ case 'merged':
844
+ return { id: 'local.setup-pr', observed_state: 'confirmed', impact: 'advisory' };
845
+ case 'open':
846
+ return { id: 'local.setup-pr', observed_state: 'pending', impact: 'advisory' };
847
+ case 'none':
848
+ case 'unknown':
849
+ return { id: 'local.setup-pr', observed_state: 'unknown', impact: 'advisory' };
850
+ }
851
+ }
488
852
  /** Separate negotiated path: local setup never overlays server-owned facts. */
489
853
  function projectAssessmentSetupItems(evidence) {
490
854
  const state = (value) => value === null ? 'unknown' : value ? 'confirmed' : 'absent';
@@ -496,20 +860,150 @@ function projectAssessmentSetupItems(evidence) {
496
860
  if (evidence.mergeCredential.state !== 'not_applicable')
497
861
  localFacts.push({ id: 'local.merge-credential',
498
862
  observed_state: evidence.mergeCredential.state === 'configured' ? 'confirmed' : evidence.mergeCredential.state === 'unknown' ? 'unknown' : 'absent', impact: 'mandatory' });
499
- localFacts.push({ id: 'local.workflow', observed_state: evidence.workflow.state === 'installed' ? 'confirmed' : evidence.workflow.state === 'unknown' ? 'unknown' : 'pending', impact: 'advisory' }, { id: 'local.setup-pr', observed_state: evidence.setupPullRequest.state === 'merged' ? 'confirmed' : evidence.setupPullRequest.state === 'open' ? 'pending' : 'unknown', impact: 'advisory' }, { id: 'local.index-progress', observed_state: evidence.index.state === 'reached' ? 'confirmed' : ['in_progress', 'queued_by_setup', 'recovery_pending'].includes(evidence.index.state) ? 'pending' : 'unknown', impact: 'advisory' });
863
+ localFacts.push({ id: 'local.workflow', observed_state: evidence.workflow.state === 'installed' ? 'confirmed' : evidence.workflow.state === 'unknown' ? 'unknown' : 'pending', impact: 'advisory' }, setupPullRequestFact(evidence.setupPullRequest, evidence.workflow.state === 'installed'), { id: 'local.index-progress', observed_state: evidence.index.state === 'reached' ? 'confirmed' : ['in_progress', 'queued_by_setup', 'recovery_pending'].includes(evidence.index.state) ? 'pending' : 'unknown', impact: 'advisory' });
500
864
  const assessment = composeReadinessAssessment(evidence.readiness?.assessmentNegotiation ?? { status: 'unavailable' }, localFacts);
501
- const items = assessment.records.map(r => ({ id: `${r.scope}:${r.id}`, label: catalogLabel(r.id),
865
+ // BAPI-1635: a valid launch-profile route satisfies escalation for this run only. The
866
+ // composed assessment stays untouched; the effective copy feeds the items and the verdict.
867
+ const escalationRecord = assessment.records.find(r => r.id === SETUP_ITEM_IDS.escalation && r.blocking_effect !== 'none');
868
+ const profileSatisfies = evidence.notification?.state === 'declared' && escalationRecord !== undefined;
869
+ const effective = profileSatisfies
870
+ ? Object.freeze({ ...assessment, records: assessment.records.map(r => r === escalationRecord ? { ...r, blocking_effect: 'none' } : r) })
871
+ : assessment;
872
+ // The remedy decision matrix. Terminal results are the established ones; the agent path
873
+ // differs only where a printed command would prompt for input.
874
+ // no blocking effect ............... null
875
+ // unbound indexed revision, parse active ... pending-index remedy
876
+ // unbound indexed revision, no parse ....... re-index remedy
877
+ // unbound default-branch revision .......... GitHub-access remedy
878
+ // other unresolved, pending ................ wait for indexing
879
+ // other unresolved, unverified index ....... manual re-index
880
+ // other unresolved ......................... retry
881
+ // escalation ............................... notification-aware remedy
882
+ // direct supported reference ............... its table remedy
883
+ // resolver fallback ........................ resolver result; on the agent path a
884
+ // prompting setup command is wrapped
885
+ const recordRemedy = (r) => {
886
+ if (r.blocking_effect === 'none')
887
+ return null;
888
+ // BAPI-1657: only a known-missing gate with a readable basis and a planned write says approval stores it.
889
+ if (r.id === 'server.gate-profile' && r.observed_state === 'unknown' && r.basis !== undefined
890
+ && r.basis !== 'policy_unreadable' && evidence.plannedGateWrite === true) {
891
+ return GATE_STORED_ON_APPROVAL_REMEDY;
892
+ }
893
+ // BAPI-1678: before setup is saved, this item only means setup has not run. Chosen before the
894
+ // retry handling below; the record's state and blocking effect do not change.
895
+ if (needsSetupFirst(evidence.readiness?.supervisor?.setup_present, r.id, READINESS_PREREQUISITE_BY_ID.get(r.id)?.scope))
896
+ return PRE_SETUP_READINESS_REMEDY;
897
+ if (r.blocking_effect === 'unresolved') {
898
+ // An unbound revision is not cured by a retry: name the action that supplies it.
899
+ // Any scope other than these two keeps the generic handling below.
900
+ if (r.reason === 'revision_unbound') {
901
+ if (r.scope === 'indexed_commit') {
902
+ return ACTIVE_INDEX_STATES.includes(evidence.index.state)
903
+ ? READINESS_PREREQUISITE_FIXES.pending_index
904
+ : READINESS_PREREQUISITE_FIXES.reindex_manual;
905
+ }
906
+ if (r.scope === 'default_branch')
907
+ return DEFAULT_BRANCH_ACCESS_REMEDY;
908
+ }
909
+ // Only a KNOWN state with a server-named index remedy (an index never verified) gets a repair;
910
+ // unreadable or unknown evidence retries, and a running parse is waited on.
911
+ if (r.observed_state === 'pending')
912
+ return 'indexing is running; re-run setup when it finishes';
913
+ return r.observed_state === 'unverified' && r.remedy.reference === 'index'
914
+ ? READINESS_PREREQUISITE_FIXES.reindex_manual
915
+ : READINESS_PREREQUISITE_FIXES.retry;
916
+ }
917
+ if (r.id === SETUP_ITEM_IDS.escalation)
918
+ return evidence.notification?.state === 'unreadable' ? READINESS_PREREQUISITE_FIXES.retry : profilePolicyRemedyFor(evidence);
919
+ const reference = r.remedy.reference;
920
+ return ['github', 'escalation', 'self_host', 'consent', 'missing_review_workflow'].includes(reference)
921
+ ? READINESS_PREREQUISITE_FIXES[reference]
922
+ : agentRunnableRemedy(resolveReadinessRemedy({ id: r.id, state: 'not_met', scope: READINESS_PREREQUISITE_BY_ID.get(r.id)?.scope }), evidence);
923
+ };
924
+ const items = effective.records.map(r => ({ id: `${r.scope}:${r.id}`, label: ASSESSMENT_ONLY_LABELS[r.id] ?? catalogLabel(r.id),
502
925
  state: r.blocking_effect === 'blocker' ? 'needs_action' : r.blocking_effect === 'unresolved' ? r.observed_state === 'pending' ? 'pending' : 'unknown' : 'met',
503
- blocking: r.impact === 'mandatory' && r.applicability !== 'policy_inapplicable', remedy: null }));
504
- items.push(...localFacts.map(f => ({ id: f.id, label: f.id, state: (f.observed_state === 'confirmed' ? 'met' : f.observed_state === 'absent' ? 'needs_action' : 'unknown'),
505
- blocking: f.impact === 'mandatory', remedy: null })));
926
+ blocking: r.impact === 'mandatory' && r.applicability !== 'policy_inapplicable', remedy: recordRemedy(r) }));
927
+ const localRemedy = (f) => {
928
+ if (f.observed_state === 'confirmed')
929
+ return null;
930
+ if (f.id === 'local.github-login')
931
+ return githubSignInRemedy(evidence.githubSignIn);
932
+ if (f.id === 'local.repository-identity')
933
+ return repositoryIdentityRemedy(evidence.repositoryIdentity);
934
+ if (f.id === 'local.merge-credential')
935
+ return projectMergeCredential(evidence.mergeCredential)?.remedy ?? null;
936
+ return null;
937
+ };
938
+ items.push(...localFacts.map(f => ({ id: f.id, label: LOCAL_FACT_LABELS[f.id] ?? f.id, state: (f.observed_state === 'confirmed' ? 'met' : f.observed_state === 'absent' ? 'needs_action' : 'unknown'),
939
+ blocking: f.impact === 'mandatory', remedy: localRemedy(f) })));
940
+ const grantItem = projectMcpGrantItem(evidence.mcpGrant, evidence.path);
941
+ if (grantItem !== null)
942
+ items.push(grantItem);
943
+ const epicServerItem = projectEpicServerItem(evidence.epicServer, evidence.path);
944
+ if (epicServerItem !== null)
945
+ items.push(epicServerItem);
946
+ // BAPI-1635: advisory findings beside the server's records; neither changes the verdict.
947
+ const freshnessItem = projectFreshnessItem(evidence.freshness);
948
+ if (freshnessItem !== null)
949
+ items.push(freshnessItem);
950
+ const driftItem = projectCommandDriftItem(evidence);
951
+ if (driftItem !== null)
952
+ items.push(driftItem);
506
953
  if (assessment.negotiation !== 'available')
507
954
  items.unshift({ id: 'assessment.coverage', label: 'Server assessment coverage', state: 'unknown', blocking: true, remedy: 'Upgrade the Bridge backend or contact Bridge support, then retry readiness.' });
508
955
  // The attached composition is immutable and reused by both final renderers.
509
- if (items[0])
956
+ if (items[0]) {
510
957
  items[0].assessment = assessment;
958
+ if (profileSatisfies && evidence.notification?.state === 'declared') {
959
+ items[0].effectiveAssessment = effective;
960
+ items[0].escalationProfile = evidence.notification.profile;
961
+ }
962
+ }
511
963
  return items;
512
964
  }
965
+ /**
966
+ * BAPI-1657: plain owner-facing labels for the local setup rows. These are local
967
+ * presentation facts, so they stay out of the shared readiness catalog. Every
968
+ * local row the projection emits has an entry here.
969
+ */
970
+ const LOCAL_FACT_LABELS = {
971
+ 'local.claude-login': 'Claude sign-in',
972
+ 'local.github-login': 'GitHub sign-in',
973
+ 'local.repository-identity': 'Repository identity',
974
+ 'local.merge-credential': 'Merge credential',
975
+ 'local.executor-installation': 'Executor installation',
976
+ 'local.workflow': 'Workflow installation',
977
+ 'local.setup-pr': 'Setup pull request',
978
+ 'local.index-progress': 'Index progress',
979
+ };
980
+ /** Labels for assessment-only records, matching the assessment renderer's own. */
981
+ const ASSESSMENT_ONLY_LABELS = {
982
+ 'server.canonical-index': 'Canonical index validity',
983
+ 'server.parse-progress': 'Parse progress',
984
+ };
985
+ /** Only the plain-command remedies are wrapped; flag-driven ones (such as the executor fix) stay as printed. */
986
+ const AGENT_WRAPPED_REMEDIES = [
987
+ READINESS_PREREQUISITE_FIXES.install_setup,
988
+ READINESS_PREREQUISITE_FIXES.supervisor_gate,
989
+ ];
990
+ /**
991
+ * The printed setup command prompts for input, so an agent cannot run it as printed.
992
+ * On the agent path it is replaced by the existing proposal and approved-answers route,
993
+ * in the detected launcher form. The terminal result is returned untouched.
994
+ */
995
+ function agentRunnableRemedy(remedy, evidence) {
996
+ if (evidence.path !== "agent" || !AGENT_WRAPPED_REMEDIES.includes(remedy))
997
+ return remedy;
998
+ const command = setupCommandFor(evidence);
999
+ return `Run ${command} --json to see the setup proposal, then run ${command} --answers <answers-file> with the owner's approved answers, then retry readiness.`;
1000
+ }
1001
+ /** The identity remedy in one place, so both projection paths print the same text. */
1002
+ function repositoryIdentityRemedy(state) {
1003
+ return state === "conflict"
1004
+ ? "this checkout's github.com remote names a different repository than Bridge does; run setup from the matching checkout"
1005
+ : "run setup from a checkout whose `origin` remote is the github.com repository";
1006
+ }
513
1007
  function additionalRequiredItems(items, assessment) {
514
1008
  const represented = new Set([...assessment.records.map(r => `${r.scope}:${r.id}`), ...assessment.local.map(r => r.id), 'assessment.coverage']);
515
1009
  return items.filter(i => i.blocking && i.state !== 'met' && !represented.has(i.id));