@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
@@ -0,0 +1,1222 @@
1
+ /**
2
+ * BAPI-1638 — the schema version 2 assessment of `install epic-implementer`.
3
+ *
4
+ * Pure. It turns the evidence setup already collects (read-only) into one
5
+ * document: every setup item with its evidence and fix, every open choice with
6
+ * its options and consequences, and the read-only repository facts. It never
7
+ * prompts, writes, or reads anything itself.
8
+ *
9
+ * Every value is projected through an explicit serializer here. Nothing spreads
10
+ * a raw server response, a policy object, a candidate record, or a resolver
11
+ * result into the document, so no credential value can reach it.
12
+ */
13
+ import { INSTALL_ASSESSMENT_SCHEMA_VERSION, } from "./install-bridge-conductor-contracts.js";
14
+ import { EPIC_SERVER_QUESTION, MCP_GRANT_QUESTION, REINDEX_RETRY_QUESTION, SETUP_ITEM_IDS, setupItemRemedy } from "./install-bridge-conductor-setup.js";
15
+ import { describeDeclinedCiChange, describeEpicBranchCi, finalIntegrationSentence } from "./epic-branch-ci-summary.js";
16
+ import { EPIC_CI_WORKFLOW_PATH, EPIC_IMPLEMENTER_CI_CHECK_NAME } from "./epic-ci-workflow.js";
17
+ import { READINESS_PREREQUISITE_FIXES } from "./printed-remedy-commands.js";
18
+ import { plainDisplayText } from "./conductor/gate-settings-review.js";
19
+ import { describeSfccUpload, isSfccUploadCapable, WORKER_UPLOAD_ADVISORY } from "./install-sfcc-setup.js";
20
+ /**
21
+ * BAPI-1667 — recommend the mode by where browser checks run. A settled or
22
+ * unreadable choice keeps. For an open choice: `local` with guidance or a dev script
23
+ * (uploads still work there), then `sfcc_shared_active` when upload can work and
24
+ * nothing runs locally, then `none`.
25
+ */
26
+ export function recommendEpicServer(e) {
27
+ const current = e?.current ?? null;
28
+ if (e === null || !e.applicable || current !== null) {
29
+ return {
30
+ recommended: "keep",
31
+ why: current !== null ? "A valid choice is already stored, so nothing changes." : "The epic-server record could not be read here, so nothing is written.",
32
+ };
33
+ }
34
+ const sfccDetected = e.sfcc?.detected === true;
35
+ const check = sfccDetected ? e.sfcc?.uploadCheck ?? null : null;
36
+ const capable = isSfccUploadCapable(check);
37
+ const workerAdvisory = check?.state === "possible_with_advisory" ? ` ${WORKER_UPLOAD_ADVISORY}` : "";
38
+ if (e.guidancePresent === true || e.devScript === true) {
39
+ const base = e.guidancePresent === true
40
+ ? "This repository has epic-server guidance, so a local epic server can run the app for browser checks."
41
+ : "This repository has a dev script, so the app can likely run on this machine for browser checks. Add .bridge/epic-server.toml and run epic-server prove; until then UI checks are handed off, exactly as with none.";
42
+ const upload = capable ? ` With an approved sandbox, cartridge changes are uploaded to it before each turn, so the local app sees them.${workerAdvisory}` : "";
43
+ return { recommended: "local", why: `${base}${upload}` };
44
+ }
45
+ if (capable) {
46
+ return {
47
+ recommended: "sfcc_shared_active",
48
+ why: `This SFCC repository can upload cartridges and has no local dev server, so browser checks run on one approved sandbox.${workerAdvisory}`,
49
+ };
50
+ }
51
+ return { recommended: "none", why: RECOMMENDATION_POLICY.epic_server.lastResort.why };
52
+ }
53
+ /**
54
+ * BAPI-1667 — the option ids to recommend for an open grant. Empty unless an SFCC
55
+ * repository's candidates were flagged, so every other repository keeps `[]`.
56
+ */
57
+ export function recommendMcpGrant(g) {
58
+ return g.candidates.filter((c) => c.sfcc_recommended === true).map((c) => c.id).sort();
59
+ }
60
+ // ---------------------------------------------------------------------------
61
+ // Items
62
+ // ---------------------------------------------------------------------------
63
+ /**
64
+ * Projected ids that name the same obligation as a catalog id. The assessment
65
+ * path reports local facts as `local.*`, and server records as `<scope>:<id>`.
66
+ * Assessment-only obligations (canonical index, parse progress, setup PR,
67
+ * coverage) have no catalog twin and keep their own ids.
68
+ */
69
+ const PROJECTED_ID_TO_SETUP_ITEM_ID = Object.freeze({
70
+ "local.claude-login": SETUP_ITEM_IDS.claudeLogin,
71
+ "local.github-login": SETUP_ITEM_IDS.githubSignIn,
72
+ "local.repository-identity": SETUP_ITEM_IDS.repositoryIdentity,
73
+ "local.merge-credential": SETUP_ITEM_IDS.mergeCredential,
74
+ "local.workflow": SETUP_ITEM_IDS.workflows,
75
+ });
76
+ /** Map a projected item id to its catalog id; the original is kept in evidence. */
77
+ export function catalogItemId(projectedId) {
78
+ const mapped = PROJECTED_ID_TO_SETUP_ITEM_ID[projectedId];
79
+ if (mapped !== undefined)
80
+ return { id: mapped, scope: "local" };
81
+ const colon = projectedId.indexOf(":");
82
+ if (colon > 0 && projectedId.slice(colon + 1).includes(".")) {
83
+ return { id: projectedId.slice(colon + 1), scope: projectedId.slice(0, colon) };
84
+ }
85
+ return { id: projectedId, scope: null };
86
+ }
87
+ /** The first back-quoted command in a remedy, when it has one. */
88
+ function remedyCommand(text) {
89
+ const match = /`([^`\n]{1,300})`/.exec(text);
90
+ return match?.[1];
91
+ }
92
+ function projectItem(item) {
93
+ const { id, scope } = catalogItemId(item.id);
94
+ const evidence = { projected_id: item.id };
95
+ if (scope !== null)
96
+ evidence.scope = scope;
97
+ // A remedy-less item resolves its fix by its CATALOG id, so a local fact gets its own repair, not a retry.
98
+ const fixText = item.state === "met" ? null : setupItemRemedy(item.remedy === null ? { ...item, id } : item);
99
+ return {
100
+ id,
101
+ label: item.label,
102
+ state: item.state,
103
+ blocking: item.blocking,
104
+ evidence,
105
+ fix: fixText === null || fixText.length === 0
106
+ ? null
107
+ : { text: fixText, ...(remedyCommand(fixText) !== undefined ? { command: remedyCommand(fixText) } : {}) },
108
+ };
109
+ }
110
+ const KEEP_OPTION = (consequence) => ({ id: "keep", label: "Keep it as it is", consequence });
111
+ function approveDecline(approve, decline) {
112
+ return [
113
+ { id: "approve", label: "Approve", consequence: approve },
114
+ { id: "decline", label: "Decline", consequence: decline },
115
+ ];
116
+ }
117
+ function gateEffect(gate) {
118
+ return {
119
+ action: "store_gate_and_defaults",
120
+ target: "repository_gate",
121
+ params: {
122
+ kind: gate.kind,
123
+ provider_checks: [...gate.providerChecks].sort(),
124
+ watched_checks: [...gate.watchedChecks].sort(),
125
+ local_commands: [...gate.localCommands].sort(),
126
+ },
127
+ };
128
+ }
129
+ /*
130
+ * A settled choice still carries the effect an approval would name. A replayed
131
+ * answers file then hashes the same after its write is done, and apply reports
132
+ * that write `unchanged` instead of refusing the file.
133
+ */
134
+ function gateChoice(gate) {
135
+ if (gate === null || !gate.writeNeeded) {
136
+ return {
137
+ id: "gate",
138
+ family: "gate",
139
+ answer_key: "gate",
140
+ current: gate?.currentKind ?? null,
141
+ options: [KEEP_OPTION(gate?.consequence || "The stored gate and supervisor defaults stay as they are.")],
142
+ recommended: "keep",
143
+ why_recommended: "The stored gate already matches what setup would write, so nothing changes.",
144
+ consequential: true,
145
+ applicable: false,
146
+ selection: "single",
147
+ ...(gate !== null ? { effects: { approve: gateEffect(gate) } } : {}),
148
+ };
149
+ }
150
+ return {
151
+ id: "gate",
152
+ family: "gate",
153
+ answer_key: "gate",
154
+ current: gate.currentKind,
155
+ options: approveDecline(gate.consequence || "Stores the proposed gate and the safe supervisor defaults.", "Keeps the saved merge checks and run defaults as they are, and writes nothing. A run without a stored gate is not ready."),
156
+ recommended: "approve",
157
+ why_recommended: "A run cannot start until a gate is saved, because the gate sets what must pass before a child merges.",
158
+ consequential: true,
159
+ applicable: true,
160
+ selection: "single",
161
+ effects: { approve: gateEffect(gate) },
162
+ };
163
+ }
164
+ const DECLARATION_LABEL = Object.freeze({
165
+ dependency_install: "dependency refresh before each worker step",
166
+ ci_database: "whether CI runs with a database",
167
+ must_order_paths: "paths that must change in order",
168
+ worker_database: "the worker database",
169
+ });
170
+ /** BAPI-1678 — why each declaration is offered. Each one states its own purpose. */
171
+ const DECLARATION_REASON = Object.freeze({
172
+ dependency_install: "Workers need this to install what the gate's command uses before they run it.",
173
+ ci_database: "CI needs this to know which database to start for its checks.",
174
+ must_order_paths: "Two children adding migrations at once can create two migration heads, so these merge one at a time.",
175
+ worker_database: "Workers use this to prepare the database they need while running checks.",
176
+ });
177
+ /** BAPI-1678 — what declining keeps. Declining never clears a stored value. */
178
+ const DECLARATION_DECLINE = Object.freeze({
179
+ dependency_install: "Writes nothing. Any install commands already stored stay, and workers and the test trial keep using them. If none are stored, they run no declared install.",
180
+ ci_database: "Writes nothing. Any CI database setting already stored stays, and CI keeps using it. If none is stored, CI has no declared database.",
181
+ must_order_paths: "Writes nothing. Any ordered paths already stored stay. These paths are not added, so children that change them are not held to one merge at a time.",
182
+ worker_database: "Writes nothing. Any worker database setting already stored stays, and workers keep using it. If none is stored, workers have no declared database.",
183
+ });
184
+ function declarationEffect(key, value) {
185
+ return { action: "store_declaration", target: `repository_gate.${key}`, params: { value } };
186
+ }
187
+ function declarationChoice(key, found) {
188
+ if (found === undefined || found.applicable === false) {
189
+ return {
190
+ id: key,
191
+ family: "worker_declaration",
192
+ answer_key: key,
193
+ current: null,
194
+ options: [KEEP_OPTION(`The stored ${DECLARATION_LABEL[key]} stays as it is.`)],
195
+ recommended: "keep",
196
+ why_recommended: "Discovery found nothing new to declare, so nothing changes.",
197
+ consequential: true,
198
+ applicable: false,
199
+ selection: "single",
200
+ ...(found !== undefined && found.value !== null ? { effects: { approve: declarationEffect(key, found.value) } } : {}),
201
+ ...(found?.dependencyInstall !== undefined ? { dependency_install: found.dependencyInstall } : {}),
202
+ };
203
+ }
204
+ const detail = found.summary.map((line) => line.trim()).join("; ");
205
+ const replacing = found.recommendDecline === true;
206
+ return {
207
+ id: key,
208
+ family: "worker_declaration",
209
+ answer_key: key,
210
+ current: null,
211
+ options: approveDecline(key === "dependency_install" && found.dependencyInstall !== undefined
212
+ ? `Stores these install commands with the gate: ${commandList(found.dependencyInstall.commands)}. ${found.dependencyInstall.lifecycle}`
213
+ : `Stores ${DECLARATION_LABEL[key]} with the gate${detail ? ` (${detail})` : ""}. Workers prepare with it before qualification.`, DECLARATION_DECLINE[key]),
214
+ recommended: replacing ? "decline" : "approve",
215
+ why_recommended: replacing
216
+ ? "This would drop or rewrite a command you already stored, so keeping it is the safer default. Approve it only if the new commands are what you want."
217
+ : DECLARATION_REASON[key],
218
+ consequential: true,
219
+ applicable: true,
220
+ selection: "single",
221
+ effects: { approve: declarationEffect(key, found.value) },
222
+ ...(found.dependencyInstall !== undefined ? { dependency_install: found.dependencyInstall } : {}),
223
+ };
224
+ }
225
+ /** The exact commands in the plain form people read. The list itself stays an argument array. */
226
+ function commandList(rows) {
227
+ return rows
228
+ .map((row) => `${row.argv.map(displayArg).join(" ")} (in ${row.cwd === "." ? "the repository root" : displayArg(row.cwd)})`)
229
+ .join("; ");
230
+ }
231
+ function displayArg(value) {
232
+ return plainDisplayText(value);
233
+ }
234
+ /** BAPI-1677 — the owner-facing facts of the install plan, safe to show. */
235
+ export function dependencyInstallDetails(input) {
236
+ const row = (e) => ({
237
+ cwd: displayArg(e.cwd),
238
+ argv: e.argv.map(displayArg),
239
+ lockfiles: e.lockfiles.map(displayArg),
240
+ });
241
+ return {
242
+ commands: input.commands.map(row),
243
+ ...(input.differs ? { stored: input.stored.map(row) } : {}),
244
+ evidence: input.evidence.map((e) => ({ extra: displayArg(e.extra), field: e.field, span: displayArg(e.span) })),
245
+ lifecycle: "Each command runs in every fresh worker worktree, and again only when a file it names changes.",
246
+ limitations: input.limitations.map(displayArg),
247
+ correction: "To correct them, choose change something and give the whole list as entries, each with its folder, its command as a list of arguments, and the files it watches. The list replaces every install command, in the order you give. An empty list means workers and the test trial run no declared install, and managed CI uses its normal toolchain install.",
248
+ };
249
+ }
250
+ /** The bounded discovery-and-promotion trial: the server tries learned candidates and stores one only if it passes. */
251
+ export const LEARN_EFFECT = Object.freeze({
252
+ action: "discover_and_promote_test_command",
253
+ target: "repository_gate.local_commands",
254
+ params: Object.freeze({ bounded: true }),
255
+ condition: "only_if_check_passes",
256
+ });
257
+ function testCommandChoice(t) {
258
+ const options = [];
259
+ const candidate = t.candidate !== undefined && t.candidate !== null ? displayArg(t.candidate) : null;
260
+ if (t.trialEligible) {
261
+ options.push({
262
+ id: "learn",
263
+ label: candidate !== null ? `Let Bridge learn and prove the test command (it expects to try ${candidate})` : "Let Bridge learn and prove the test command",
264
+ consequence: (candidate !== null ? `Bridge expects to try ${candidate} first. ` : "") +
265
+ "Learning stores instructions, not a proven command, so they guide the attempt and the server may choose another command. " +
266
+ "It runs one bounded trial and stores a command only if the check passes.",
267
+ });
268
+ }
269
+ options.push(t.stored
270
+ ? KEEP_OPTION("The stored test command stays as it is.")
271
+ : { id: "skip", label: "Do not set a test command now", consequence: "No command is stored; the gate keeps no local check." });
272
+ return {
273
+ id: "test_command",
274
+ family: "test_command",
275
+ answer_key: "test_command",
276
+ current: t.stored ? "stored" : "missing",
277
+ options,
278
+ recommended: t.trialEligible ? "learn" : t.stored ? "keep" : "skip",
279
+ why_recommended: t.trialEligible
280
+ ? "A learned command is stored only after the server proves it passes, so it cannot weaken the gate."
281
+ : t.stored
282
+ ? "A command is already stored and proven, so nothing changes."
283
+ : "There is no test command Bridge can try right now, and setup can still finish without one.",
284
+ consequential: false,
285
+ applicable: t.trialEligible || t.ownerCommandSupplied,
286
+ selection: "single",
287
+ effects: { learn: LEARN_EFFECT },
288
+ };
289
+ }
290
+ const SETUP_PR_EFFECT = Object.freeze({
291
+ action: "open_setup_pull_request",
292
+ target: "github.default_branch",
293
+ condition: "only_if_check_passes",
294
+ });
295
+ function setupPrChoice(pr) {
296
+ if (!pr.applicable) {
297
+ return {
298
+ id: "setup_pr",
299
+ family: "setup_pr",
300
+ answer_key: "setup_pr",
301
+ current: pr.workflowState,
302
+ options: [KEEP_OPTION("No setup pull request opens.")],
303
+ recommended: "keep",
304
+ why_recommended: "Nothing on the default branch needs Bridge's workflow, so no pull request is needed.",
305
+ consequential: true,
306
+ applicable: false,
307
+ selection: "single",
308
+ effects: { approve: SETUP_PR_EFFECT },
309
+ };
310
+ }
311
+ const runs = pr.commandSource === "learned" ? "the learned test command" : "the stored test command";
312
+ return {
313
+ id: "setup_pr",
314
+ family: "setup_pr",
315
+ answer_key: "setup_pr",
316
+ current: pr.workflowState,
317
+ options: approveDecline(`Opens a setup pull request running ${runs}, only if the check passes. You review and merge it.`, "Opens no pull request. Bridge's workflow is not added."),
318
+ recommended: "approve",
319
+ why_recommended: `The workflow runs ${runs}, the pull request opens only if that check passes, and you review and merge it, so nothing reaches your default branch without you.`,
320
+ consequential: true,
321
+ applicable: true,
322
+ selection: "single",
323
+ effects: { approve: SETUP_PR_EFFECT },
324
+ };
325
+ }
326
+ function mergeTokenChoice(m) {
327
+ const applicable = m.state === "missing" || m.state === "stored_rejected";
328
+ if (!applicable) {
329
+ return {
330
+ id: "merge_token",
331
+ family: "merge_token",
332
+ answer_key: "merge_token",
333
+ current: m.state,
334
+ options: [KEEP_OPTION("The merge credential stays as it is.")],
335
+ recommended: "keep",
336
+ why_recommended: m.state === "configured" || m.state === "not_applicable"
337
+ ? "Merges already have the credential they need, so nothing changes."
338
+ : "Setup cannot store a token for this state; fix the item it reports first.",
339
+ consequential: true,
340
+ applicable: false,
341
+ selection: "reference",
342
+ ...(m.storeTarget !== null ? { effects: { reference: { action: "store_merge_token", target: m.storeTarget } } } : {}),
343
+ };
344
+ }
345
+ return {
346
+ id: "merge_token",
347
+ family: "merge_token",
348
+ answer_key: "merge_token",
349
+ current: m.state,
350
+ options: [
351
+ {
352
+ id: "reference",
353
+ label: "Store the token named by a reference",
354
+ consequence: "Reads the token from the environment variable or credential-store entry you name, at apply time, and stores it on this computer for this repository only. It is never printed or sent to Bridge.",
355
+ },
356
+ { id: "decline", label: "Decline", consequence: "Stores nothing. Merges need GITHUB_MERGE_TOKEN set instead." },
357
+ ],
358
+ recommended: null,
359
+ why_recommended: "Only you can supply this token, so setup recommends no option and never reads one without your reference.",
360
+ consequential: true,
361
+ applicable: true,
362
+ selection: "reference",
363
+ effects: {
364
+ reference: { action: "store_merge_token", target: m.storeTarget ?? "credential_store.merge_token" },
365
+ },
366
+ };
367
+ }
368
+ /**
369
+ * The re-index effects, fixed so a replayed answer hashes the same after the
370
+ * recovery evidence moved on. The branch names live in the consequence text and
371
+ * are re-checked against fresh evidence at apply time, never reused blindly.
372
+ */
373
+ export const REINDEX_EFFECT = Object.freeze({ action: "queue_tracked_parse", target: "repository_index" });
374
+ export const REINDEX_BRANCH_EFFECTS = Object.freeze({
375
+ correct: Object.freeze({ action: "correct_index_branch", target: "repository_config.branch" }),
376
+ keep: Object.freeze({ action: "keep_index_branch", target: "repository_config.branch" }),
377
+ });
378
+ export const REINDEX_RETRY_EFFECTS = Object.freeze({
379
+ retry: Object.freeze({ action: "retry_tracked_parse", target: "repository_index" }),
380
+ });
381
+ const INDEX_ITEM_IDS = new Set(["server.canonical-index", SETUP_ITEM_IDS.indexFreshness]);
382
+ /**
383
+ * Whether the index can honestly be called current. The index items and the
384
+ * setup-revision index state must agree; anything unknown or behind is
385
+ * `unconfirmed`, and indexing under way is `running`.
386
+ */
387
+ export function indexDisplayStatus(items, index) {
388
+ const states = items.filter((i) => INDEX_ITEM_IDS.has(catalogItemId(i.id).id)).map((i) => i.state);
389
+ if (states.some((s) => s !== "met" && s !== "pending"))
390
+ return "unconfirmed";
391
+ if (["unknown", "behind", "diverged", "recovery_unresolved"].includes(index.state))
392
+ return "unconfirmed";
393
+ if (states.includes("pending") || ["in_progress", "queued_by_setup", "recovery_pending"].includes(index.state))
394
+ return "running";
395
+ return "current";
396
+ }
397
+ /** The `current` value of a not-planned re-index choice, by what the index items say. */
398
+ const REINDEX_NOT_PLANNED_CURRENT = Object.freeze({
399
+ current: "current",
400
+ running: "indexing",
401
+ unconfirmed: "unknown",
402
+ });
403
+ /** The shown text of the not-planned re-index choice, by what the index items say. */
404
+ const REINDEX_NOT_PLANNED_TEXT = Object.freeze({
405
+ current: {
406
+ why: "The index is current, so nothing needs queuing.",
407
+ keep: "The index already covers the setup revision; nothing is queued.",
408
+ },
409
+ running: {
410
+ why: "Indexing is already under way, so nothing more needs queuing.",
411
+ keep: "Nothing more is queued; the indexing already under way continues.",
412
+ },
413
+ unconfirmed: {
414
+ why: "Setup could not confirm the index is up to date and has no re-index to offer here, so follow the fix on the index items instead.",
415
+ keep: "Nothing is queued now. Setup could not confirm the index covers the setup revision.",
416
+ },
417
+ });
418
+ function reindexChoices(r) {
419
+ const notPlanned = REINDEX_NOT_PLANNED_TEXT[r.indexStatus ?? "current"];
420
+ const choices = [
421
+ {
422
+ id: "reindex",
423
+ family: "reindex",
424
+ answer_key: "reindex",
425
+ // Shown state only (never hashed, never planned on): it agrees with the index items.
426
+ current: r.planned ? "stale" : REINDEX_NOT_PLANNED_CURRENT[r.indexStatus ?? "current"],
427
+ options: r.planned
428
+ ? [
429
+ {
430
+ id: "approve",
431
+ label: "Re-index the repository",
432
+ consequence: "Queues one tracked parse of the configured branch so the index reaches the setup revision.",
433
+ },
434
+ { id: "skip", label: "Not now", consequence: "Queues nothing; the index stays behind." },
435
+ ]
436
+ : [KEEP_OPTION(notPlanned.keep)],
437
+ recommended: r.planned ? "approve" : "keep",
438
+ why_recommended: r.planned
439
+ ? "Workers read the index, and it is behind the setup revision."
440
+ : notPlanned.why,
441
+ consequential: false,
442
+ applicable: r.planned,
443
+ selection: "single",
444
+ effects: { approve: REINDEX_EFFECT },
445
+ },
446
+ ];
447
+ if (r.branchQuestion !== undefined) {
448
+ const q = r.branchQuestion;
449
+ const configured = JSON.stringify(q.configured);
450
+ choices.push({
451
+ id: "reindex_branch",
452
+ family: "reindex",
453
+ answer_key: "reindex_branch",
454
+ current: q.configured,
455
+ options: [
456
+ {
457
+ id: "correct",
458
+ label: `Use the default branch (${q.destination})`,
459
+ consequence: `Using the default changes the shared branch from ${configured} to ${q.destination}, then queues one tracked first parse once the change reads back and the fresh evidence agrees.`,
460
+ },
461
+ {
462
+ id: "keep",
463
+ label: `Keep the current branch (${configured})`,
464
+ consequence: "Keeping your branch preserves it. Setup can index it only if fresh evidence shows it contains the setup revision; otherwise merge the setup changes there first.",
465
+ },
466
+ ],
467
+ recommended: "correct",
468
+ why_recommended: "The setup revision is on the default branch, so indexing it there reaches the revision workers need.",
469
+ consequential: true,
470
+ applicable: true,
471
+ selection: "single",
472
+ effects: {
473
+ correct: REINDEX_BRANCH_EFFECTS.correct,
474
+ keep: REINDEX_BRANCH_EFFECTS.keep,
475
+ },
476
+ });
477
+ }
478
+ if (r.retryQuestion !== undefined) {
479
+ const q = r.retryQuestion;
480
+ choices.push({
481
+ id: "reindex_retry",
482
+ family: "reindex",
483
+ answer_key: "reindex_retry",
484
+ current: "failed_attempt",
485
+ options: [
486
+ {
487
+ id: "retry",
488
+ label: "Retry once",
489
+ consequence: "Retrying queues one new tracked attempt that picks the configured branch when it runs. Asking again for the same retry cannot queue another.",
490
+ },
491
+ { id: "no_retry", label: "Do not retry", consequence: "Queues nothing; the earlier attempt stays as it ended." },
492
+ ],
493
+ recommended: "retry",
494
+ why_recommended: "The earlier attempt did not finish, and one tracked retry is the bounded way to finish it.",
495
+ consequential: true,
496
+ applicable: true,
497
+ selection: "single",
498
+ effects: { retry: REINDEX_RETRY_EFFECTS.retry },
499
+ });
500
+ }
501
+ return choices;
502
+ }
503
+ /** A fixed shape for a listed-but-not-selectable entry: name, origin, and reason only. */
504
+ function excludedEntry(e) {
505
+ return { name: String(e.name), ...(e.origin !== undefined ? { origin: String(e.origin) } : {}), reason: String(e.reason) };
506
+ }
507
+ function mcpGrantChoice(g) {
508
+ if (g === null) {
509
+ return {
510
+ id: "worker_mcp_grant",
511
+ family: "worker_mcp_grant",
512
+ answer_key: "worker_mcp_grant",
513
+ current: null,
514
+ options: [KEEP_OPTION("Workers keep exactly the MCP servers they have today.")],
515
+ recommended: "keep",
516
+ why_recommended: "The MCP servers could not be inspected here, so nothing changes.",
517
+ consequential: true,
518
+ applicable: false,
519
+ selection: "multiple",
520
+ };
521
+ }
522
+ const options = g.candidates.map((c) => ({
523
+ id: c.id,
524
+ label: `${c.name} (${c.origins.join(", ")})`,
525
+ consequence: `Every Epic Implementer worker in this repository also gets ${c.name}.`,
526
+ }));
527
+ options.push({
528
+ id: "decline",
529
+ label: "Decline",
530
+ consequence: "Changes nothing. Any earlier approval, including an entry listed as no longer valid, stays as it is.",
531
+ });
532
+ // A settled grant is kept when its key is left out; only an open grant recommends the empty selection.
533
+ if (!g.applicable)
534
+ options.unshift(KEEP_OPTION("Workers keep exactly the MCP servers already approved."));
535
+ const sfccGrant = g.applicable ? recommendMcpGrant(g) : [];
536
+ return {
537
+ id: "worker_mcp_grant",
538
+ family: "worker_mcp_grant",
539
+ answer_key: "worker_mcp_grant",
540
+ current: g.current,
541
+ options,
542
+ recommended: g.applicable ? sfccGrant : "keep",
543
+ why_recommended: sfccGrant.length > 0
544
+ ? "This is an SFCC repository, so setup recommends the Playwright preset for browser checks and b2c-dx-mcp, when offered, as an agent tool (logs, SCAPI, docs). Verification uploads go through epic-server sfcc-upload, not through this server."
545
+ : g.applicable
546
+ ? "Workers always get Bridge; each extra server is a deliberate grant, so setup recommends none and you add only what you need."
547
+ : "The approved servers still match what this repository offers, so nothing changes.",
548
+ consequential: true,
549
+ applicable: g.applicable,
550
+ selection: "multiple",
551
+ effects: {
552
+ select: { action: "write_mcp_grant", target: "mcp_grant", params: { fingerprint: g.fingerprint } },
553
+ },
554
+ excluded: g.excluded.map(excludedEntry),
555
+ invalid_existing: g.invalidExisting.map(excludedEntry),
556
+ };
557
+ }
558
+ /** BAPI-1667 — an SFCC repository whose check did not run says so, the same as one that could not. */
559
+ const UPLOAD_CHECK_NOT_RUN = Object.freeze({ state: "unknown", missing: [] });
560
+ function epicServerChoice(e) {
561
+ const current = e?.current ?? null;
562
+ // BAPI-1667: fixed additions only when SFCC or a recorded sandbox applies; otherwise the text is unchanged.
563
+ const uploadText = e?.sfcc?.detected === true ? describeSfccUpload(e.sfcc.uploadCheck ?? UPLOAD_CHECK_NOT_RUN) : "";
564
+ const keptSandbox = e?.sandboxRecorded === true ? " The approved sandbox stays recorded, so uploads stay on." : "";
565
+ const options = [
566
+ {
567
+ id: "none",
568
+ label: "No epic server",
569
+ consequence: `Runs start no epic server; UI checks are handed off to a person.${keptSandbox}`,
570
+ },
571
+ {
572
+ id: "local",
573
+ label: "A local epic server",
574
+ consequence: `The driver starts the epic's code with a throwaway test login, and workers borrow it in turns for UI checks.${keptSandbox}`,
575
+ },
576
+ {
577
+ id: "sfcc_shared_active",
578
+ label: "One approved SFCC sandbox",
579
+ consequence: `Workers use the approved sandbox. Its account secret stays in the credential store; only its reference is stored.${uploadText !== "" ? ` ${uploadText}` : ""}`,
580
+ },
581
+ ];
582
+ const applicable = e?.applicable ?? false;
583
+ // Keep is always offered: on an open choice it declines, writing nothing, exactly as declining
584
+ // the interactive question does.
585
+ if (current !== null)
586
+ options.unshift(KEEP_OPTION(`The stored choice (${current}) stays as it is.`));
587
+ else
588
+ options.unshift(KEEP_OPTION("Nothing is written; the epic-server record stays as it is."));
589
+ const recommendation = recommendEpicServer(e);
590
+ return {
591
+ id: "epic_server",
592
+ family: "epic_server",
593
+ answer_key: "epic_server",
594
+ current,
595
+ options,
596
+ recommended: recommendation.recommended,
597
+ why_recommended: recommendation.why,
598
+ consequential: true,
599
+ applicable,
600
+ selection: "single",
601
+ effects: {
602
+ none: { action: "write_epic_server_record", target: "epic_server_record", params: { mode: "none" } },
603
+ local: { action: "write_epic_server_record", target: "epic_server_record", params: { mode: "local" } },
604
+ sfcc_shared_active: { action: "write_epic_server_record", target: "epic_server_record", params: { mode: "sfcc_shared_active" } },
605
+ },
606
+ ...(e?.credentialReferences !== undefined
607
+ ? { credential_references: e.credentialReferences.map((r) => ({ name: String(r.name), level: r.level, reaches_worker_tools: r.reaches_worker_tools === true })) }
608
+ : {}),
609
+ };
610
+ }
611
+ /** The summary input for this evidence. */
612
+ function summaryInput(e) {
613
+ const offer = e.ciOffer !== null && e.ciOffer !== undefined && e.ciOffer.applicable
614
+ ? { actionClass: e.ciOffer.identity.action_class, path: e.ciOffer.identity.path, ...(e.ciOffer.branchesBefore !== undefined ? { branchesBefore: e.ciOffer.branchesBefore } : {}) }
615
+ : e.managedWorkflowViaSetupPr === true
616
+ // The setup pull request itself offers Bridge's workflow: say so, never "without checks".
617
+ ? { actionClass: "managed_workflow", path: EPIC_CI_WORKFLOW_PATH }
618
+ : null;
619
+ return {
620
+ coverage: e.coverage,
621
+ offer,
622
+ excluded: e.excludedWorkflows ?? [],
623
+ ciSystems: e.ciSystems ?? null,
624
+ integrationTarget: e.integrationTarget ?? null,
625
+ };
626
+ }
627
+ /** BAPI-1654 — the plain text for the epic-branch CI state, or null when nothing was collected. */
628
+ export function epicBranchCiStateText(e) {
629
+ return e === null ? null : describeEpicBranchCi(summaryInput(e));
630
+ }
631
+ const CI_CHANGE_ACTION = Object.freeze({
632
+ trigger_edit: "open_ci_trigger_pull_request",
633
+ managed_workflow: "open_managed_epic_workflow_pull_request",
634
+ });
635
+ /** The effect an approval of the CI change has. Its params are the approval's binding. */
636
+ export function ciChangeEffect(identity) {
637
+ return {
638
+ action: CI_CHANGE_ACTION[identity.action_class],
639
+ target: identity.path,
640
+ params: {
641
+ action_class: identity.action_class,
642
+ source_sha256: identity.source_sha256,
643
+ patch_sha256: identity.patch_sha256,
644
+ },
645
+ };
646
+ }
647
+ /**
648
+ * BAPI-1654 — the CI change, an ordinary choice. Present only when a change is
649
+ * on offer (or already in place, for a replay), so every proposal without one
650
+ * keeps its exact decisions, actions, and digest.
651
+ */
652
+ function epicCiChangeChoice(e) {
653
+ const offer = e?.ciOffer ?? null;
654
+ if (e === null || offer === null)
655
+ return null;
656
+ const id = offer.identity;
657
+ const effect = ciChangeEffect(id);
658
+ if (!offer.applicable) {
659
+ return {
660
+ id: "epic_ci_change",
661
+ family: "epic_ci_change",
662
+ answer_key: "epic_ci_change",
663
+ current: "in_place",
664
+ options: [KEEP_OPTION(`The CI change to ${id.path} is already in place, so nothing changes.`)],
665
+ // A replay names no recommendation: it adds no decision to a proposal that never had one.
666
+ recommended: null,
667
+ why_recommended: "The CI change is already in place, so nothing changes.",
668
+ consequential: true,
669
+ applicable: false,
670
+ selection: "single",
671
+ effects: { approve: effect },
672
+ };
673
+ }
674
+ const input = summaryInput(e);
675
+ const before = offer.branchesBefore !== undefined && offer.branchesBefore.length > 0
676
+ ? ` (today it lists ${offer.branchesBefore.map((b) => `'${b}'`).join(", ")})`
677
+ : "";
678
+ const approve = id.action_class === "trigger_edit"
679
+ ? `Opens a separate pull request that adds 'epic/**' to the pull_request branch list in ${id.path}${before}. Only that list changes. You review and merge it; until then, child pull requests merge into the epic branch without checks.`
680
+ : `Opens one pull request that adds Bridge's epic workflow as a new file, ${id.path}. It runs your test command on each child pull request once you merge it. No existing workflow changes.${e.managedWorkflowViaSetupPr === true ? " If you also approve the setup pull request, that one pull request serves both." : ""}`;
681
+ return {
682
+ id: "epic_ci_change",
683
+ family: "epic_ci_change",
684
+ answer_key: "epic_ci_change",
685
+ current: id.action_class,
686
+ options: approveDecline(approve, describeDeclinedCiChange(input)),
687
+ recommended: "approve",
688
+ why_recommended: id.action_class === "trigger_edit"
689
+ ? `This is a one-line, trigger-only change to ${id.path} that you review and merge, and it lets each child's checks run before it merges.`
690
+ : `No existing workflow can be changed safely, and Bridge's workflow is a new file you review and merge that runs your test command on each child pull request.`,
691
+ consequential: true,
692
+ applicable: true,
693
+ selection: "single",
694
+ effects: { approve: effect },
695
+ };
696
+ }
697
+ /**
698
+ * What choosing `include` means, by what is known. Never claims checks run or pass:
699
+ * confirmed coverage says a workflow is configured to start; otherwise it says plainly
700
+ * that none is confirmed, and whether an approved change would only propose one.
701
+ */
702
+ function includeConsequence(covers, delivered) {
703
+ if (covers)
704
+ return "Each child waits for the checks of a workflow configured to start on its epic-branch PR before it merges.";
705
+ return delivered
706
+ ? "Each child waits for the proposed checks only once you merge the approved change. Until then, no workflow is confirmed to run on epic-branch pull requests."
707
+ : "No workflow is confirmed to run on epic-branch pull requests, so there may be no checks for a child to wait for.";
708
+ }
709
+ function epicBranchCiChoices(e) {
710
+ const covers = e?.coverage === "covers";
711
+ const recorded = e?.recordedDecision ?? null;
712
+ // BAPI-1659: only confirmed coverage recommends `include` here. An offer's existence is not
713
+ // evidence, so a delivery action lifts the recommendation in `resolveEpicBranchCiRecommendation`,
714
+ // from the proposed (or answered) selection set. `offered` below is display only: it picks the
715
+ // sentence the decline option shows.
716
+ const offered = (e?.ciOffer !== null && e?.ciOffer !== undefined && e.ciOffer.applicable) || e?.managedWorkflowViaSetupPr === true;
717
+ const recommendedCi = e === null ? null : covers ? "include" : "decline";
718
+ const stateText = e === null ? null : describeEpicBranchCi(summaryInput(e));
719
+ const decision = {
720
+ id: "epic_branch_ci",
721
+ family: "epic_branch_ci",
722
+ answer_key: "epic_branch_ci",
723
+ current: e?.coverage ?? null,
724
+ options: [
725
+ {
726
+ id: "include",
727
+ label: "Include",
728
+ consequence: includeConsequence(covers, false),
729
+ },
730
+ {
731
+ id: "decline",
732
+ label: "Decline",
733
+ // The detailed state lives here, not only in `why_recommended`: the recommendation
734
+ // policy replaces that reason when decline is the last resort.
735
+ consequence: e === null || (e.integrationTarget === undefined && e.ciSystems === undefined)
736
+ ? "Children merge into the epic branch without waiting for checks that never run there. Problems then surface only at the human-gated integration PR into the base branch."
737
+ : covers || offered
738
+ ? `Children merge into the epic branch without waiting for checks. ${finalIntegrationSentence(e.integrationTarget)}`
739
+ : stateText ?? "",
740
+ },
741
+ ],
742
+ recommended: recommendedCi,
743
+ // A recorded decision is shown as the earlier answer. `recommended` stays as the coverage
744
+ // says, so the digest of any answers file is unchanged. The reason explains only the
745
+ // recommendation, never the earlier answer.
746
+ ...(recorded !== null ? { earlier_answer: recorded } : {}),
747
+ why_recommended: covers
748
+ ? "A workflow is configured to start on epic-branch PRs, so waiting for its checks catches problems before each merge."
749
+ : stateText ?? "Bridge could not confirm a workflow runs on epic-branch PRs, so it recommends neither option; runs behave as include unless you decline.",
750
+ consequential: false,
751
+ applicable: e !== null,
752
+ selection: "single",
753
+ effects: {
754
+ include: { action: "record_epic_branch_ci_decision", target: "epic_branch_ci", params: { decision: "include" } },
755
+ decline: { action: "record_epic_branch_ci_decision", target: "epic_branch_ci", params: { decision: "decline" } },
756
+ },
757
+ };
758
+ const approvals = e?.approvalsRequired ?? null;
759
+ const exemptionApplicable = approvals === "yes";
760
+ // Absent and unreadable are different facts, so they get different sentences. Neither
761
+ // changes an option, an effect, or a digest-bearing field.
762
+ const exemptionKeepSentence = approvals === "no"
763
+ ? "No approval rule applies to epic-branch pull requests."
764
+ : "The approval rule could not be read, so nothing will change; check it yourself.";
765
+ const exemption = {
766
+ id: "approval_exemption",
767
+ family: "approval_exemption",
768
+ answer_key: "approval_exemption",
769
+ current: approvals,
770
+ options: exemptionApplicable
771
+ ? approveDecline("Excludes epic/** from the approval rule with your own gh login. Only the ruleset's excluded branches change, and only for a ruleset that holds nothing but the approval rule.", "Changes nothing. Each child merge waits for a human approval unless the merging account can bypass the rule.")
772
+ : [KEEP_OPTION(exemptionKeepSentence)],
773
+ recommended: exemptionApplicable ? "decline" : "keep",
774
+ why_recommended: exemptionApplicable
775
+ ? "Changing a ruleset is consequential, so the safe default is to leave it and decide yourself."
776
+ : exemptionKeepSentence,
777
+ consequential: true,
778
+ applicable: exemptionApplicable,
779
+ selection: "single",
780
+ effects: e?.ownerRepo !== null && e?.ownerRepo !== undefined
781
+ ? { approve: { action: "exclude_epic_from_approval_rule", target: `github.rulesets:${e.ownerRepo}` } }
782
+ : undefined,
783
+ };
784
+ return [decision, exemption];
785
+ }
786
+ function launchProfileChoice(l) {
787
+ const options = [];
788
+ if (l.selected !== null) {
789
+ options.push({
790
+ id: "save",
791
+ label: `Save the launch profile '${l.selected}'`,
792
+ consequence: "Saves a reusable launch profile for this computer with its policy file reference and alert route; never a secret.",
793
+ });
794
+ }
795
+ options.push({ id: "skip", label: "Do not save a launch profile", consequence: "Nothing is saved; drive-epic asks for its options each time." });
796
+ return {
797
+ id: "launch_profile",
798
+ family: "launch_profile",
799
+ answer_key: "launch_profile",
800
+ current: l.notification,
801
+ options,
802
+ recommended: l.selected !== null ? "save" : "skip",
803
+ why_recommended: l.selected !== null
804
+ ? "You named this profile, and saving it lets drive-epic reuse its policy and escalation route."
805
+ : "No profile was named, so there is nothing to save.",
806
+ consequential: false,
807
+ applicable: l.selected !== null,
808
+ selection: "single",
809
+ effects: l.selected !== null
810
+ ? { save: { action: "write_launch_profile", target: "launch_profile", params: { name: l.selected } } }
811
+ : undefined,
812
+ };
813
+ }
814
+ export const RECOMMENDATION_POLICY = Object.freeze({
815
+ gate: Object.freeze({
816
+ never: Object.freeze(["decline"]),
817
+ replacement: Object.freeze({
818
+ option: "approve",
819
+ why: "A run cannot start until a gate is saved, because the gate sets what must pass before a child merges.",
820
+ }),
821
+ }),
822
+ approval_exemption: Object.freeze({
823
+ never: Object.freeze(["decline"]),
824
+ replacement: Object.freeze({
825
+ option: "approve",
826
+ why: "Using your own GitHub CLI sign-in, this changes only the branches the ruleset excludes, only for a ruleset that holds nothing but the approval rule, and it appears in the single proposal you approve, though child merges may still need a human approval if the rule cannot be changed or other approval requirements remain.",
827
+ }),
828
+ }),
829
+ merge_token: Object.freeze({ never: Object.freeze(["decline"]), unresolvedOk: true }),
830
+ test_command: Object.freeze({
831
+ lastResort: Object.freeze({
832
+ option: "skip",
833
+ why: "This is the last resort because there is no test command Bridge can try right now, and setup can still finish without one.",
834
+ }),
835
+ }),
836
+ epic_branch_ci: Object.freeze({ lastResort: Object.freeze({ option: "decline", why: "This is the last resort because it lets each child merge without waiting for checks, and Bridge recommends it only when no other option can be offered." }), unresolvedOk: true }),
837
+ epic_server: Object.freeze({
838
+ lastResort: Object.freeze({
839
+ option: "none",
840
+ why: "This is the last resort because setup has no evidence the application runs locally, so runs start no epic server and UI checks are handed to a person.",
841
+ }),
842
+ }),
843
+ });
844
+ /**
845
+ * Apply the recommendation policy to one choice. Changes only `recommended` and
846
+ * `why_recommended`; every option, effect, selection and earlier answer is untouched.
847
+ */
848
+ export function finalizeRecommendation(choice) {
849
+ const rule = RECOMMENDATION_POLICY[choice.answer_key];
850
+ if (rule === undefined)
851
+ return choice;
852
+ const offered = (id) => choice.options.some((o) => o.id === id);
853
+ const rec = choice.recommended;
854
+ if (choice.applicable && typeof rec === "string" && rule.never?.includes(rec)) {
855
+ if (rule.replacement !== undefined && offered(rule.replacement.option)) {
856
+ return { ...choice, recommended: rule.replacement.option, why_recommended: rule.replacement.why };
857
+ }
858
+ if (rule.unresolvedOk === true) {
859
+ return { ...choice, recommended: null, why_recommended: choice.why_recommended };
860
+ }
861
+ return choice;
862
+ }
863
+ if (typeof rec === "string" && rule.lastResort !== undefined && rec === rule.lastResort.option) {
864
+ return { ...choice, why_recommended: rule.lastResort.why };
865
+ }
866
+ if (choice.applicable && rule.replacement !== undefined && rec === rule.replacement.option && offered(rec)) {
867
+ return { ...choice, why_recommended: rule.replacement.why };
868
+ }
869
+ return choice;
870
+ }
871
+ /**
872
+ * The question each choice asks, in the owner's words. Keyed by answer key so
873
+ * every choice has one. Display only: none of it reaches the digest.
874
+ */
875
+ // ---------------------------------------------------------------------------
876
+ // BAPI-1678: merge-test protection, the proposal's wording, and the final verdict
877
+ // ---------------------------------------------------------------------------
878
+ /** The no-tests sentence. Exact wording: the skill and the lanes pin it. */
879
+ export const NO_TESTS_SENTENCE = "Bridge will not require a passing test run before a child merges.";
880
+ /** Named apart from the sentence when a trial that has not run yet is the only route to a test. */
881
+ export const TEST_TRIAL_CONDITION = "If the test-command trial does not pass:";
882
+ /** The next step when nothing is left to do. */
883
+ export const READY_NEXT_STEP = "Next step: Run /drive-epic-run for an epic.";
884
+ /**
885
+ * The one rule for merge-test protection, used for both the proposal's planned value
886
+ * and the verdict's confirmed value. Returns `undefined` when the evidence does not
887
+ * settle it, and the field is then left out.
888
+ *
889
+ * - `local`: the gate is `local` or `mixed` and a command is stored. This wins over
890
+ * every CI fact, so unreadable CI does not hide it.
891
+ * - `ci`: `epic-implementer-ci / gate` is a stored check that is required, not watched.
892
+ * The managed workflow is installed, epic-branch CI is not declined, and the server
893
+ * reports an empty `no_ci_reasons`. All of these must hold. A workflow file, a check
894
+ * name, or an `include` answer alone is not proof of tests. Customer workflow
895
+ * contents are never parsed.
896
+ * - `watched_only` or `none`: only after enforced protection is confirmed absent. No
897
+ * required check remains, the gate and CI facts are readable, and the watched list
898
+ * is non-empty (`watched_only`) or empty (`none`). A declined managed check counts
899
+ * as absent, because declined CI means child merges do not wait for it.
900
+ * - `undefined`: an unreadable gate, command, or CI fact the answer depends on; a
901
+ * customer-owned required check, whose tests Bridge cannot know; or a managed check
902
+ * that is required but not proven. A required check that is missing holds a merge,
903
+ * so it does not prove that no test guards the merge. The managed workflow's state
904
+ * matters only while a required check depends on it, so reading it as unknown does
905
+ * not hide a confirmed absence. That read is unknown whenever no command is stored.
906
+ */
907
+ export function classifyMergeTestProtection(evidence) {
908
+ const { gate, localCommandStored, managedWorkflowInstalled, epicBranchCi } = evidence;
909
+ if (gate === null)
910
+ return undefined;
911
+ if (gate.kind === "local" || gate.kind === "mixed") {
912
+ if (localCommandStored === true)
913
+ return "local";
914
+ if (localCommandStored === null)
915
+ return undefined;
916
+ }
917
+ if (gate.requiredChecks.includes(EPIC_IMPLEMENTER_CI_CHECK_NAME) && !gate.watchedChecks.includes(EPIC_IMPLEMENTER_CI_CHECK_NAME)) {
918
+ if (epicBranchCi === null)
919
+ return undefined;
920
+ if (epicBranchCi.decision !== "decline") {
921
+ return managedWorkflowInstalled === true && epicBranchCi.noCiReasons.length === 0 ? "ci" : undefined;
922
+ }
923
+ }
924
+ if (gate.requiredChecks.some((name) => name !== EPIC_IMPLEMENTER_CI_CHECK_NAME))
925
+ return undefined;
926
+ if (epicBranchCi === null)
927
+ return undefined;
928
+ return gate.watchedChecks.length > 0 ? "watched_only" : "none";
929
+ }
930
+ /** The shared consequence's own parts, unchanged. Joining them with "; " gives it back. */
931
+ export function gateEffectLines(consequence) {
932
+ return consequence === "" ? [] : consequence.split("; ");
933
+ }
934
+ /** The proposal's planned protection, its disclosure, and the gate's effect lines. Pure. */
935
+ export function buildProposalPresentation(input) {
936
+ const planned = classifyMergeTestProtection(input.evidence);
937
+ const disclosed = planned === "none" || planned === "watched_only";
938
+ return {
939
+ ...(planned !== undefined ? { merge_test_protection: planned } : {}),
940
+ ...(disclosed ? { disclosure: { text: NO_TESTS_SENTENCE, ...(input.trialPending ? { condition: TEST_TRIAL_CONDITION } : {}) } } : {}),
941
+ gate_effect_lines: gateEffectLines(input.consequence),
942
+ };
943
+ }
944
+ const SETTING_LABEL = Object.freeze({
945
+ gate: "Merge gate",
946
+ dependency_install: "Install commands",
947
+ ci_database: "CI database",
948
+ must_order_paths: "Ordered paths",
949
+ worker_database: "Worker database",
950
+ test_command: "Test command",
951
+ setup_pr: "Setup pull request",
952
+ merge_token: "Merge token",
953
+ reindex: "Repository index",
954
+ reindex_branch: "Index branch",
955
+ reindex_retry: "Index retry",
956
+ worker_mcp_grant: "Worker servers",
957
+ epic_server: "Epic server",
958
+ epic_branch_ci: "Epic-branch CI",
959
+ approval_exemption: "Approval rule",
960
+ launch_profile: "Launch profile",
961
+ epic_ci_change: "Epic-branch CI change",
962
+ setup_record: "Setup record",
963
+ });
964
+ const INCOMPLETE_STATUS = new Set(["failed", "refused", "uncertain", "unattempted"]);
965
+ const FALLBACK_REASON = Object.freeze({
966
+ failed: "the write failed",
967
+ refused: "the write was refused",
968
+ uncertain: "the write could not be confirmed",
969
+ unattempted: "the write was not attempted",
970
+ });
971
+ function oneLine(text) {
972
+ return text.replace(/\s+/g, " ").trim();
973
+ }
974
+ function asSentence(text) {
975
+ const line = oneLine(text);
976
+ return /[.!?]$/.test(line) ? line : `${line}.`;
977
+ }
978
+ function asNextStep(fix) {
979
+ const line = oneLine(fix);
980
+ return line.startsWith("Next step:") ? line : `Next step: ${line}`;
981
+ }
982
+ /**
983
+ * The final verdict, from post-apply evidence. Pure.
984
+ *
985
+ * `ready` says whether a run can start, and comes only from the readiness evidence.
986
+ * `settings_not_applied` says what the owner approved that did not take. The two stay
987
+ * apart, so a failed optional setting never turns a confirmed `Ready` into a failure.
988
+ * A missing fix uses the read-only doctor check, and with no fix at all an unconfirmed
989
+ * verdict names that check too instead of recommending a run.
990
+ */
991
+ export function buildInstallVerdict(input) {
992
+ const { ready, blockers, results, protection } = input;
993
+ const settings = results
994
+ .filter((r) => INCOMPLETE_STATUS.has(r.status))
995
+ .map((r) => ({
996
+ key: r.key,
997
+ status: r.status,
998
+ reason: r.reason ?? FALLBACK_REASON[r.status] ?? "the write did not finish",
999
+ fix: r.fix ?? READINESS_PREREQUISITE_FIXES.doctor,
1000
+ }));
1001
+ const rule = results.find((r) => r.key === "approval_exemption");
1002
+ const approvalRule = rule === undefined
1003
+ ? undefined
1004
+ : { status: rule.status, ...(rule.reason !== undefined ? { reason: rule.reason } : {}) };
1005
+ const ruleText = approvalRule === undefined
1006
+ ? null
1007
+ : approvalRule.reason !== undefined ? `${approvalRule.status} — ${approvalRule.reason}` : approvalRule.status;
1008
+ const parts = [];
1009
+ if (ready === true)
1010
+ parts.push("Ready.");
1011
+ else if (ready === false)
1012
+ parts.push(blockers.length > 0 ? `Not ready. Still blocking: ${blockers.map((b) => oneLine(b.label)).join(", ")}.` : "Not ready.");
1013
+ else
1014
+ parts.push("Readiness was not confirmed.");
1015
+ const others = settings.filter((s) => s.key !== "approval_exemption");
1016
+ if (others.length > 0) {
1017
+ parts.push("These settings did not take:");
1018
+ for (const s of others)
1019
+ parts.push(`${SETTING_LABEL[s.key]}: ${asSentence(s.reason)} Fix: ${asSentence(s.fix)}`);
1020
+ }
1021
+ if (ruleText !== null) {
1022
+ const ruleFix = settings.find((s) => s.key === "approval_exemption")?.fix;
1023
+ parts.push(`${SETTING_LABEL.approval_exemption}: ${asSentence(ruleText)}${ruleFix !== undefined ? ` Fix: ${asSentence(ruleFix)}` : ""}`);
1024
+ }
1025
+ if (protection === "none" || protection === "watched_only")
1026
+ parts.push(NO_TESTS_SENTENCE);
1027
+ const firstFix = settings[0]?.fix ?? blockers[0]?.fix;
1028
+ const nextStep = firstFix !== undefined
1029
+ ? asNextStep(firstFix)
1030
+ : ready === true ? READY_NEXT_STEP : asNextStep(READINESS_PREREQUISITE_FIXES.doctor);
1031
+ return {
1032
+ line: parts.join(" "),
1033
+ settings_not_applied: settings,
1034
+ ...(approvalRule !== undefined ? { approval_rule: approvalRule } : {}),
1035
+ next_step: nextStep,
1036
+ };
1037
+ }
1038
+ const CHOICE_QUESTION = Object.freeze({
1039
+ gate: "Should setup save the checks each piece of epic work must pass before it can merge?",
1040
+ dependency_install: "Should workers refresh the project's dependencies, using the steps setup found, before each piece of work?",
1041
+ ci_database: "Should setup save what it found about whether your tests need a database?",
1042
+ must_order_paths: "Should setup save the list of files that must change in a set order, such as database migrations?",
1043
+ worker_database: "Should setup save the database settings workers use when they run tests?",
1044
+ test_command: "How should setup choose the command that runs your tests?",
1045
+ setup_pr: "Should setup open a pull request that adds Bridge's setup workflow to your repository?",
1046
+ merge_token: "Where should setup find the GitHub token it uses to merge finished work?",
1047
+ reindex: "Should Bridge read your repository again now, so its copy is up to date?",
1048
+ reindex_branch: "Which branch should Bridge read your repository from?",
1049
+ reindex_retry: REINDEX_RETRY_QUESTION,
1050
+ worker_mcp_grant: MCP_GRANT_QUESTION,
1051
+ epic_server: EPIC_SERVER_QUESTION,
1052
+ epic_branch_ci: "Should each piece of epic work wait for your CI checks before it merges into the epic branch?",
1053
+ approval_exemption: "Should setup change your GitHub rule so epic work can merge into the epic branch without a person approving each merge?",
1054
+ launch_profile: "Should setup save these launch settings so later runs can reuse them?",
1055
+ epic_ci_change: "Should setup open a pull request so your checks also run on pull requests into epic branches?",
1056
+ });
1057
+ /** Place the choice's question right after its answer key. */
1058
+ function withQuestion(c) {
1059
+ const { id, family, answer_key, ...rest } = c;
1060
+ return { id, family, answer_key, question: CHOICE_QUESTION[answer_key], ...rest };
1061
+ }
1062
+ /** What the settled answers say will deliver checks on epic-branch pull requests. */
1063
+ function epicBranchCiDelivery(choices, settled, context) {
1064
+ const picked = (key) => {
1065
+ const c = choiceFor(choices, key);
1066
+ if (c === undefined || !c.applicable)
1067
+ return undefined;
1068
+ return settled(key) ?? (typeof c.recommended === "string" ? c.recommended : undefined);
1069
+ };
1070
+ return {
1071
+ covers: choiceFor(choices, "epic_branch_ci")?.current === "covers",
1072
+ ciApproved: picked("epic_ci_change") === "approve",
1073
+ setupApproved: context.setupSuppliesWorkflow && picked("setup_pr") === "approve",
1074
+ };
1075
+ }
1076
+ /**
1077
+ * BAPI-1679 — true when the setup pull request is the only thing behind a recommended `include`.
1078
+ * The setup pull request opens only if the test trial passes, so at apply time this credit still
1079
+ * has to be proven. Confirmed coverage and an approved CI change do not depend on it.
1080
+ */
1081
+ export function epicBranchCiIncludeRestsOnSetupPr(choices, settled, context) {
1082
+ const { covers, ciApproved, setupApproved } = epicBranchCiDelivery(choices, settled, context);
1083
+ return setupApproved && !covers && !ciApproved;
1084
+ }
1085
+ /**
1086
+ * BAPI-1659 — the one answer-aware place where `epic_branch_ci` is recommended.
1087
+ *
1088
+ * `include` is recommended only when checks are confirmed to run on epic-branch
1089
+ * pull requests, an approved CI change will add them, or an approved setup pull
1090
+ * request genuinely adds Bridge's workflow. A declined, kept, duplicate-only, or
1091
+ * unanswered-and-not-recommended delivery earns no credit. An unanswered
1092
+ * delivery choice counts as its own recommendation, so the draft proposal reads
1093
+ * as a proposal; a stated answer always wins. Only `recommended` and its reason
1094
+ * change, and only when the choice carries a recommendation at all.
1095
+ */
1096
+ export function resolveEpicBranchCiRecommendation(choices, settled, context = { setupSuppliesWorkflow: false }) {
1097
+ const ci = choiceFor(choices, "epic_branch_ci");
1098
+ if (ci === undefined || ci.recommended === null || typeof ci.recommended !== "string")
1099
+ return [...choices];
1100
+ const { covers, ciApproved, setupApproved } = epicBranchCiDelivery(choices, settled, context);
1101
+ const delivered = ciApproved || setupApproved;
1102
+ const target = covers || delivered ? "include" : "decline";
1103
+ // The include option always reads from the final answers; an explicit `include` is never
1104
+ // reworded into a claim that checks run.
1105
+ const options = ci.options.map((o) => (o.id === "include" ? { ...o, consequence: includeConsequence(covers, delivered) } : o));
1106
+ const withOptions = { ...ci, options };
1107
+ const replaceCi = (next) => choices.map((c) => (c.answer_key === "epic_branch_ci" ? next : c));
1108
+ if (target === ci.recommended)
1109
+ return replaceCi(withOptions);
1110
+ if (target === "include") {
1111
+ // Delivered but not yet merged: say the checks are proposed and not running. The offer-state
1112
+ // sentence ("would fix that") is not reused. Only the unsupported-CI-systems sentence is kept.
1113
+ const unsupported = /This repository (?:also )?uses [^.]*\. Bridge can't safely change [^.]*\./.exec(context.stateText ?? "")?.[0];
1114
+ const next = {
1115
+ ...withOptions,
1116
+ recommended: "include",
1117
+ why_recommended: [
1118
+ "Checks are proposed, not running yet: the pull request you approve adds them.",
1119
+ // A one-line trigger edit leaves the workflow as it is until merged, so say what children do meanwhile.
1120
+ // Bridge's own new workflow is described only as proposed.
1121
+ choiceFor(choices, "epic_ci_change")?.current === "trigger_edit"
1122
+ ? "Until you merge it, child pull requests merge into the epic branch without checks, and each child waits for them only once the change is merged."
1123
+ : "Each child waits for them only once you merge it.",
1124
+ ...(unsupported !== undefined ? [unsupported] : []),
1125
+ ].join(" "),
1126
+ };
1127
+ return replaceCi(finalizeRecommendation(next));
1128
+ }
1129
+ // Decline: the draft's reason described a delivery the final answers no longer approve. Finalize
1130
+ // first, then set the reason, so the generic last-resort sentence cannot replace it.
1131
+ const declined = finalizeRecommendation({ ...withOptions, recommended: "decline" });
1132
+ return replaceCi({
1133
+ ...declined,
1134
+ why_recommended: "No workflow is confirmed to run on pull requests into epic branches and no CI change is approved, so child pull requests merge into the epic branch without checks.",
1135
+ });
1136
+ }
1137
+ /** Build the full choice catalog. Every family appears, applicable or not. */
1138
+ export function buildInstallChoices(d) {
1139
+ const declarations = new Map(d.declarations.map((entry) => [entry.key, entry]));
1140
+ const choices = [
1141
+ gateChoice(d.gate),
1142
+ declarationChoice("dependency_install", declarations.get("dependency_install")),
1143
+ declarationChoice("ci_database", declarations.get("ci_database")),
1144
+ declarationChoice("must_order_paths", declarations.get("must_order_paths")),
1145
+ declarationChoice("worker_database", declarations.get("worker_database")),
1146
+ testCommandChoice(d.testCommand),
1147
+ setupPrChoice(d.setupPr),
1148
+ mergeTokenChoice(d.mergeToken),
1149
+ ...reindexChoices(d.reindex),
1150
+ mcpGrantChoice(d.mcpGrant),
1151
+ epicServerChoice(d.epicServer),
1152
+ ...epicBranchCiChoices(d.epicBranchCi),
1153
+ launchProfileChoice(d.launchProfile),
1154
+ ];
1155
+ // BAPI-1654: the CI change is conditional, appended last so every other choice keeps its place.
1156
+ const ciChange = epicCiChangeChoice(d.epicBranchCi);
1157
+ if (ciChange !== null)
1158
+ choices.push(ciChange);
1159
+ const built = choices.map((c) => finalizeRecommendation(withQuestion(c)));
1160
+ // The draft resolves against the complete proposed selection set (recommended approvals as proposals).
1161
+ return resolveEpicBranchCiRecommendation(built, () => undefined, {
1162
+ setupSuppliesWorkflow: d.epicBranchCi?.managedWorkflowViaSetupPr === true,
1163
+ stateText: epicBranchCiStateText(d.epicBranchCi ?? null),
1164
+ });
1165
+ }
1166
+ export const EMPTY_REPOSITORY_FACTS = Object.freeze({
1167
+ ci_workflows: null,
1168
+ package_manager: null,
1169
+ mcp_configs: null,
1170
+ });
1171
+ /** Copy repository facts through a fixed shape: names, origins, and filters only. */
1172
+ function projectFacts(facts) {
1173
+ return {
1174
+ ci_workflows: facts.ci_workflows?.map((w) => ({
1175
+ path: String(w.path),
1176
+ pull_request_branches: w.pull_request_branches === null ? null : w.pull_request_branches.map(String),
1177
+ })) ?? null,
1178
+ package_manager: facts.package_manager === null
1179
+ ? null
1180
+ : { name: String(facts.package_manager.name), lockfile: facts.package_manager.lockfile === null ? null : String(facts.package_manager.lockfile) },
1181
+ mcp_configs: facts.mcp_configs?.map((c) => ({ name: String(c.name), origin: String(c.origin) })) ?? null,
1182
+ // BAPI-1654: additive, and only when detection ran, so older inputs keep their exact facts.
1183
+ ...(facts.ci_systems !== undefined
1184
+ ? { ci_systems: facts.ci_systems === null ? null : facts.ci_systems.map((c) => ({ name: String(c.name), path: String(c.path) })) }
1185
+ : {}),
1186
+ // BAPI-1667: additive, and only when detection ran.
1187
+ ...(facts.sfcc !== undefined
1188
+ ? {
1189
+ sfcc: {
1190
+ detected: facts.sfcc.detected,
1191
+ signals: [...facts.sfcc.signals],
1192
+ dev_script: facts.sfcc.dev_script,
1193
+ upload_check: facts.sfcc.upload_check === null ? null : { state: facts.sfcc.upload_check.state, missing: [...facts.sfcc.upload_check.missing] },
1194
+ },
1195
+ }
1196
+ : {}),
1197
+ };
1198
+ }
1199
+ /** The choice for a key, or undefined. */
1200
+ export function choiceFor(choices, key) {
1201
+ return choices.find((c) => c.answer_key === key);
1202
+ }
1203
+ /**
1204
+ * Build the schema version 2 document. The version 1 fields are copied as they
1205
+ * were, with the same meaning and optionality: `assessment` and
1206
+ * `advisoryVerdict` appear only when the run produced them.
1207
+ */
1208
+ export function buildInstallAssessment(input) {
1209
+ const { legacy } = input;
1210
+ return {
1211
+ schemaVersion: INSTALL_ASSESSMENT_SCHEMA_VERSION,
1212
+ outcome: legacy.outcome,
1213
+ exitCode: legacy.exitCode,
1214
+ dryRun: legacy.dryRun,
1215
+ ...(legacy.namedOutcome !== undefined ? { namedOutcome: legacy.namedOutcome } : {}),
1216
+ ...(legacy.assessment !== undefined ? { assessment: legacy.assessment } : {}),
1217
+ ...(legacy.advisoryVerdict !== undefined ? { advisoryVerdict: legacy.advisoryVerdict } : {}),
1218
+ items: input.items.map(projectItem),
1219
+ choices: input.choices !== undefined ? [...input.choices] : input.decisions === null ? [] : buildInstallChoices(input.decisions),
1220
+ repository_facts: projectFacts(input.decisions?.repositoryFacts ?? EMPTY_REPOSITORY_FACTS),
1221
+ };
1222
+ }