@bridge_gpt/mcp-server 0.2.71 → 0.2.73

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