@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 { MCP_PACKAGE_NAME } from "./mcp-identity.js";
2
+ import { createSetupProgressTimer, withSetupProgress } from "./setup-progress.js";
3
+ import { askSetupQuestion, setupConsentQuestion } from "./setup-question.js";
1
4
  /**
2
- * `install-bridge conductor` — the owner-confirmed repository gate (BAPI-1391).
5
+ * `install epic-implementer` — the owner-confirmed repository gate (BAPI-1391).
3
6
  *
4
7
  * Before this module, the conductor installer refused to run without at least
5
8
  * one `--required-check`, so a repository whose CI used other names, ran outside
@@ -11,19 +14,24 @@
11
14
  *
12
15
  * Five properties are load-bearing:
13
16
  *
14
- * 1. **Discovery never confirms.** The deterministic collector
17
+ * 1. **Discovery never confirms on its own.** The deterministic collector
15
18
  * (`conductor/gate-discovery.ts`) reads the working tree and the provider's
16
- * real check history and PROPOSES a typed gate. A proposal is stored only
17
- * after the owner confirms it at a prompt, or supplies explicit gate flags,
18
- * which are owner input. No LLM ever writes a gate.
19
+ * real check history and PROPOSES a typed gate. Nothing is stored until the
20
+ * owner authorizes the combined policy change the server previews, or
21
+ * supplies explicit gate flags, which are owner input. Setup no longer asks
22
+ * the owner to pick gate members: checks the repository's CI has really
23
+ * reported become WATCHED members (BAPI-1603), and a stored confirmed gate is
24
+ * never rewritten from discovery. No LLM ever writes a gate: a local command
25
+ * is stored only by the server, after it passes once under the executor.
19
26
  * 2. **The capability probe precedes every gate write.** A server that does not
20
27
  * advertise `gate_profile.v1` gets "Bridge API update required" and nothing
21
28
  * is written — including the qualification enqueue, and the short-lived
22
29
  * executor whose claim carries `job_types` (an older server answers that key
23
30
  * with 422). The probe is a read and runs after the base-URL consent.
24
31
  * 3. **Removals are visible.** The stored and proposed gates are shown side by
25
- * side before any write; a confirm that removes a member says so, and a
26
- * flag-driven removal needs `--confirm-gate` or an explicit yes.
32
+ * side before any write. Typed gate flags are the owner's consent, so a
33
+ * flag-driven removal applies without a removal question and the completed
34
+ * removal is reported plainly afterward.
27
35
  * 4. **A refused write changes nothing.** BAPI-1390's PUT is admin-only and
28
36
  * compare-and-swaps the revision; on a refusal the installer shows the PRIOR
29
37
  * gate, never the proposal, as what is in force.
@@ -39,10 +47,12 @@
39
47
  * It never confirms a gate, authorizes a merge, or changes an approval rule
40
48
  * without an explicit typed "yes".
41
49
  */
42
- import { ConductorBridgeApiError, GATE_PROFILE_CAPABILITY_TOKEN, enqueueConductorGateQualification, fetchConductorGateCheckHistory, fetchConductorGateProfile, fetchConductorGateQualificationJob, probeConductorGateProfileCapability, putConductorGateProfile, putEpicBranchCiDecision, } from "./conductor/bridge-api-client.js";
50
+ import { ConductorBridgeApiError, GATE_PROFILE_CAPABILITY_TOKEN, enqueueConductorGateQualification, fetchConductorGateCheckHistory, fetchConductorGateProfile, fetchConductorGateQualificationJob, fetchConductorReadiness, probeConductorGateProfileCapability, probeConductorGateProfileWatchedCapability, probeConductorGateProfileWorkerSetupCapability, putConductorGateProfile, requestConductorLearnedTestCommand, putEpicBranchCiDecision, } from "./conductor/bridge-api-client.js";
51
+ import { describeGateConsequence } from "./conductor/readiness-sections.js";
43
52
  import { applyApprovalExemption, assessApprovalExemptionScope, buildEpicBranchCiEvidence, exemptionManualSteps, inspectEpicBranchWorkflowCoverage, readEpicBranchRulesViaGh, } from "./conductor/epic-branch-ci-inspection.js";
44
- import { describeEvidence, discoverGate, LOCAL_COMMAND_TIMEOUT_SECONDS, } from "./conductor/gate-discovery.js";
45
- import { describeSettingsEdit, hasSettingsToReview, hintEqual, renderSettingsReview, reviewDiscoveredSettings, settingsMatchStored, terminalSafe, workerEnvEqual, } from "./conductor/gate-settings-review.js";
53
+ import { describeEvidence, discoverDeclarations, discoverGate, LOCAL_COMMAND_TIMEOUT_SECONDS, reportedProviderChecks, } from "./conductor/gate-discovery.js";
54
+ import { dependencyInstallEqual, describeSettingsEdit, hasSettingsToReview, hasUnstoredDeclarationProposal, hintEqual, mustOrderOffer, mustOrderShortfallWarning, recommendedSettingsSelection, renderDeclarationsOnly, renderSettingsReview, reviewDeclarations, reviewDiscoveredSettings, settingsMatchStored, storedCiDatabase, terminalSafe, workerDatabaseEqual, workerEnvEqual, } from "./conductor/gate-settings-review.js";
55
+ import { canonicalMustOrderPaths, sameMustOrderPaths, } from "./dependency-install-declarations.js";
46
56
  import { PRINTED_EXECUTOR_INSTALL_SERVICE_COMMAND, PRINTED_EXECUTOR_ID_INSTRUCTION, PRINTED_QUALIFY_GATE_COMMAND, PRINTED_REPO_WIDE_EXECUTOR_COMMAND, } from "./printed-remedy-commands.js";
47
57
  export function emptyConductorGateFlags() {
48
58
  return {
@@ -151,17 +161,12 @@ export function validateConductorGateFlags(flags, context) {
151
161
  if (flags.gateNone && flags.migrationGuard !== undefined) {
152
162
  return "--gate-none has no members, so it cannot take a --migration-guard.";
153
163
  }
154
- if (flags.clearGate && (hasExplicitGateInput(flags) || flags.confirmGate || flags.qualifyGate)) {
155
- return "--clear-gate runs on its own: it cannot be combined with gate flags, --confirm-gate, or --qualify-gate.";
164
+ if (flags.clearGate && (hasExplicitGateInput(flags) || flags.qualifyGate)) {
165
+ return "--clear-gate runs on its own: it cannot be combined with gate flags or --qualify-gate.";
156
166
  }
157
167
  if (flags.clearGate && context.replaceDoneGate) {
158
168
  return "--clear-gate cannot be combined with --replace-done-gate.";
159
169
  }
160
- if (flags.confirmGate && !hasExplicitGateInput(flags)) {
161
- return ("--confirm-gate confirms explicit gate flags. Supply --provider-check, --local-command, " +
162
- "--gate-none, --migration-guard, or --customized-command, or run without it to confirm " +
163
- "the discovered proposal at a prompt.");
164
- }
165
170
  if (flags.migrationGuard?.kind === "provider" && flags.providerChecks.length > 0 &&
166
171
  !flags.providerChecks.includes(flags.migrationGuard.ref)) {
167
172
  return "--migration-guard provider:<check> must name one of the supplied provider checks exactly.";
@@ -198,12 +203,30 @@ export function createQualificationExecutorRunner(seams) {
198
203
  return { started, exitCode };
199
204
  };
200
205
  }
206
+ /**
207
+ * BAPI-1604 — in an available terminal, discovered CI settings that need no
208
+ * individual confirmation are applied from the safe recommended selection and
209
+ * printed as receipts, instead of being asked one by one. `--review-ci-settings`
210
+ * restores the individual review.
211
+ */
212
+ function usesSafeSettingDefaults(io) {
213
+ return io.isTTY === true && io.reviewCiSettings !== true;
214
+ }
215
+ /** Name-only receipts for a safe selection; a skipped item is named, never valued. */
216
+ function logSafeSettingReceipts(io, selection, stored, dryRun) {
217
+ const lines = describeSettingsEdit(selection.edit, stored);
218
+ if (lines.length > 0) {
219
+ io.log(dryRun ? " Safe CI settings setup would apply (dry run):" : " Safe CI settings applied with the gate:");
220
+ for (const line of lines)
221
+ io.log(line);
222
+ }
223
+ for (const skipped of selection.skipped)
224
+ io.log(` ${skipped}`);
225
+ }
201
226
  const YES = new Set(["y", "yes"]);
202
227
  async function ask(io, promptText) {
203
- if (!io.promptLine)
204
- return false;
205
- const answer = await io.promptLine(promptText);
206
- return YES.has((answer ?? "").trim().toLowerCase());
228
+ const decision = await askSetupQuestion(setupConsentQuestion(promptText), { read: io.promptLine, write: io.log });
229
+ return decision.status === "accept";
207
230
  }
208
231
  /** The fixed update-required refusal (property 2). */
209
232
  export const GATE_UPDATE_REQUIRED_MESSAGE = `Bridge API update required: this server does not advertise ${GATE_PROFILE_CAPABILITY_TOKEN}, so ` +
@@ -246,6 +269,7 @@ export function desiredFromStored(profile) {
246
269
  return {
247
270
  kind: profile.kind,
248
271
  providerChecks: [...profile.provider_checks],
272
+ ...(profile.watched_checks !== undefined ? { watchedChecks: [...profile.watched_checks] } : {}),
249
273
  localCommands: profile.local_commands.map((c) => ({
250
274
  name: c.name,
251
275
  argv: [...c.argv],
@@ -272,9 +296,13 @@ export function gateMatchesStored(desired, stored, storedProfile) {
272
296
  (stored.customizedCommands !== undefined &&
273
297
  desired.customizedCommands.length === stored.customizedCommands.length &&
274
298
  desired.customizedCommands.every((c, i) => c === stored.customizedCommands?.[i]));
299
+ const desiredWatched = desired.watchedChecks ?? [];
300
+ const storedWatched = stored.watchedChecks ?? [];
275
301
  return (desired.kind === stored.kind &&
276
302
  desired.providerChecks.length === stored.providerChecks.length &&
277
303
  desired.providerChecks.every((c, i) => c === stored.providerChecks[i]) &&
304
+ desiredWatched.length === storedWatched.length &&
305
+ desiredWatched.every((c, i) => c === storedWatched[i]) &&
278
306
  desired.localCommands.length === stored.localCommands.length &&
279
307
  desired.localCommands.every((c, i) => sameCommand(c, stored.localCommands[i])) &&
280
308
  sameGuard &&
@@ -287,8 +315,84 @@ function settingsOf(desired) {
287
315
  return {
288
316
  ...(desired.workerEnv !== undefined ? { workerEnv: desired.workerEnv } : {}),
289
317
  ...(desired.reproduce !== undefined ? { reproduce: desired.reproduce } : {}),
318
+ ...(desired.dependencyInstall !== undefined ? { dependencyInstall: desired.dependencyInstall } : {}),
319
+ ...(desired.ciDatabase !== undefined ? { ciDatabase: desired.ciDatabase } : {}),
320
+ ...(desired.mustOrderPaths !== undefined ? { mustOrderPaths: desired.mustOrderPaths } : {}),
321
+ ...(desired.workerDatabase !== undefined ? { workerDatabase: desired.workerDatabase } : {}),
290
322
  };
291
323
  }
324
+ const UNSAFE_PROVIDER_NAME_RE = /["$`\\!]/;
325
+ const RESTORE_COMMAND_PREFIX = `To put them back, run: npx -y ${MCP_PACKAGE_NAME} install epic-implementer `;
326
+ /**
327
+ * Human-facing guidance for putting a prior gate back after a removal. It keeps
328
+ * the stored order (provider checks, local commands, then the migration guard)
329
+ * and names EVERY flag-restorable member, because member flags replace the whole
330
+ * gate. An executable command is emitted only when every such member is safely
331
+ * representable; one unsafe member suppresses the command rather than leaving a
332
+ * safe subset. Watched checks have no flag and are never rendered as one.
333
+ */
334
+ export function describeGateRestoration(prior) {
335
+ const flags = [];
336
+ const members = [];
337
+ const unsafe = [];
338
+ const providerSafe = (name) => isValidCheckName(name) && !UNSAFE_PROVIDER_NAME_RE.test(name);
339
+ for (const check of prior.providerChecks) {
340
+ members.push(`--provider-check ${terminalSafe(check)}`);
341
+ if (providerSafe(check))
342
+ flags.push(`--provider-check "${check}"`);
343
+ else
344
+ unsafe.push(`provider check ${terminalSafe(check)}`);
345
+ }
346
+ for (const command of prior.localCommands) {
347
+ members.push(`--local-command ${terminalSafe(command.name)}`);
348
+ const literal = `${command.name}=${command.argv.join(" ")}`;
349
+ const parsed = parseLocalCommandFlag(literal);
350
+ const safe = LITERAL_COMMAND_NAME_RE.test(command.name) &&
351
+ command.argv.every((w) => LITERAL_ARGV_WORD_RE.test(w)) &&
352
+ parsed.ok &&
353
+ parsed.value.form === "literal" &&
354
+ parsed.value.name === command.name &&
355
+ parsed.value.argv.length === command.argv.length &&
356
+ parsed.value.argv.every((w, i) => w === command.argv[i]);
357
+ if (safe)
358
+ flags.push(`--local-command "${literal}"`);
359
+ else
360
+ unsafe.push(`local command ${terminalSafe(command.name)}`);
361
+ }
362
+ if (prior.migrationGuard !== null) {
363
+ const guard = prior.migrationGuard;
364
+ members.push(`--migration-guard ${guard.kind}:${terminalSafe(guard.name)}`);
365
+ const safe = guard.kind === "provider" ? providerSafe(guard.name) : LITERAL_COMMAND_NAME_RE.test(guard.name);
366
+ if (safe)
367
+ flags.push(`--migration-guard "${guard.kind}:${guard.name}"`);
368
+ else
369
+ unsafe.push(`migration guard ${guard.kind}:${terminalSafe(guard.name)}`);
370
+ }
371
+ const lines = [];
372
+ if (members.length > 0) {
373
+ if (unsafe.length === 0) {
374
+ lines.push(RESTORE_COMMAND_PREFIX + flags.join(" "));
375
+ }
376
+ else {
377
+ lines.push(` The earlier gate had these flag-restorable members: ${members.join("; ")}.`);
378
+ lines.push(` These values cannot be safely written as a command: ${unsafe.join("; ")}.`);
379
+ lines.push(" Name all of the earlier members together in one install epic-implementer invocation: " +
380
+ "member flags replace the whole gate, so restoring them one at a time would not work.");
381
+ }
382
+ }
383
+ if ((prior.watchedChecks ?? []).length > 0) {
384
+ lines.push(" Watched checks have no flag. To have setup look for them again, run setup with --clear-gate, " +
385
+ "then run setup with no gate flags; it rediscovers watched checks from your CI, which may not " +
386
+ "match the earlier membership, and the earlier required and local members are not restored that way.");
387
+ }
388
+ for (const command of prior.localCommands) {
389
+ if (command.timeout_seconds !== LOCAL_COMMAND_TIMEOUT_SECONDS) {
390
+ lines.push(` Note: local command ${terminalSafe(command.name)} had a ${command.timeout_seconds}s timeout; ` +
391
+ `restoring it with --local-command uses the default ${LOCAL_COMMAND_TIMEOUT_SECONDS}s.`);
392
+ }
393
+ }
394
+ return lines;
395
+ }
292
396
  /** Human descriptions of every member `next` removes from `prior`. */
293
397
  export function gateRemovals(prior, next) {
294
398
  if (prior === null)
@@ -298,6 +402,10 @@ export function gateRemovals(prior, next) {
298
402
  if (!next.providerChecks.includes(check))
299
403
  removed.push(`provider check "${check}"`);
300
404
  }
405
+ for (const check of prior.watchedChecks ?? []) {
406
+ if (!(next.watchedChecks ?? []).includes(check))
407
+ removed.push(`watched check "${check}"`);
408
+ }
301
409
  for (const command of prior.localCommands) {
302
410
  if (!next.localCommands.some((c) => sameCommand(c, command))) {
303
411
  removed.push(`local command ${command.name}`);
@@ -314,18 +422,40 @@ export function confirmRequestFor(desired, expectedRevision, stored) {
314
422
  // BAPI-1520: a setting is sent only when it effectively changes what is stored.
315
423
  // An unchanged hint is omitted (the server keeps it); `reproduce: null` is sent
316
424
  // only to remove a hint that is actually stored.
317
- const providerChecks = desired.providerChecks.map((name) => {
425
+ const storedWatched = new Set(stored?.watched_checks ?? []);
426
+ // BAPI-1606: the server keeps a check's stored membership when `watched` is
427
+ // omitted. A check the gate now REQUIRES that is stored as watched must say
428
+ // `watched: false`, or it would stay watched; every other required check sends
429
+ // exactly the entry it always did.
430
+ const providerEntry = (name, watched) => {
431
+ const membership = watched ? { watched: true } : storedWatched.has(name) ? { watched: false } : {};
318
432
  const edit = desired.reproduce?.get(name);
319
433
  if (edit === undefined)
320
- return { name };
434
+ return { name, ...membership };
321
435
  const current = stored?.reproduction_hints?.get(name) ?? null;
322
436
  if (edit === null)
323
- return current !== null ? { name, reproduce: null } : { name };
437
+ return current !== null ? { name, reproduce: null, ...membership } : { name, ...membership };
324
438
  if (current !== null && hintEqual(edit, current))
325
- return { name };
326
- return { name, reproduce: { argv: [...edit.argv], timeout_seconds: edit.timeout_seconds } };
327
- });
439
+ return { name, ...membership };
440
+ return { name, reproduce: { argv: [...edit.argv], timeout_seconds: edit.timeout_seconds }, ...membership };
441
+ };
442
+ // Required entries first, then watched ones: the server's own order.
443
+ const providerChecks = [
444
+ ...desired.providerChecks.map((name) => providerEntry(name, false)),
445
+ ...(desired.watchedChecks ?? [])
446
+ .filter((name) => !desired.providerChecks.includes(name))
447
+ .map((name) => providerEntry(name, true)),
448
+ ];
328
449
  const sendWorkerEnv = desired.workerEnv !== undefined && !workerEnvEqual(desired.workerEnv, stored?.worker_env);
450
+ // BAPI-1551: each declaration is sent only when it differs from what is stored;
451
+ // a clear sends `[]`, and a reset of the CI-database value sends `null`.
452
+ const sendDependencyInstall = desired.dependencyInstall !== undefined && !dependencyInstallEqual(desired.dependencyInstall, stored?.dependency_install);
453
+ const sendCiDatabase = desired.ciDatabase !== undefined && desired.ciDatabase !== storedCiDatabase(stored);
454
+ // BAPI-1580: the canonical list is sent only when it differs from the stored one.
455
+ const mustOrderPaths = desired.mustOrderPaths !== undefined ? canonicalMustOrderPaths(desired.mustOrderPaths) : undefined;
456
+ const sendMustOrderPaths = mustOrderPaths !== undefined && !sameMustOrderPaths(mustOrderPaths, stored?.must_order_paths ?? []);
457
+ // BAPI-1598: sent only when it differs from what is stored; it replaces the stored object whole.
458
+ const sendWorkerDatabase = desired.workerDatabase !== undefined && !workerDatabaseEqual(desired.workerDatabase, stored?.worker_database);
329
459
  return {
330
460
  action: "confirm",
331
461
  confirm: true,
@@ -342,6 +472,22 @@ export function confirmRequestFor(desired, expectedRevision, stored) {
342
472
  ...(sendWorkerEnv && desired.workerEnv !== undefined
343
473
  ? { worker_env: desired.workerEnv.map((e) => ({ ...e })) }
344
474
  : {}),
475
+ ...(sendDependencyInstall && desired.dependencyInstall !== undefined
476
+ ? {
477
+ dependency_install: desired.dependencyInstall.map((e) => ({
478
+ cwd: e.cwd,
479
+ argv: [...e.argv],
480
+ lockfiles: [...e.lockfiles],
481
+ })),
482
+ }
483
+ : {}),
484
+ ...(sendCiDatabase && desired.ciDatabase !== undefined
485
+ ? { ci_database: desired.ciDatabase === "unknown" ? null : desired.ciDatabase }
486
+ : {}),
487
+ ...(sendMustOrderPaths && mustOrderPaths !== undefined ? { must_order_paths: mustOrderPaths } : {}),
488
+ ...(sendWorkerDatabase && desired.workerDatabase !== undefined
489
+ ? { worker_database: structuredClone(desired.workerDatabase) }
490
+ : {}),
345
491
  };
346
492
  }
347
493
  function resolveLocalCommand(flag, proposal) {
@@ -363,8 +509,11 @@ function resolveLocalCommand(flag, proposal) {
363
509
  */
364
510
  export function desiredFromFlags(flags, current, proposal) {
365
511
  let providerChecks;
512
+ let watchedChecks = [];
366
513
  let localCommands;
367
514
  if (hasExplicitGateMembers(flags)) {
515
+ // The member flags ARE the gate: stored watched checks are not carried over,
516
+ // and the comparison shows them as removals.
368
517
  providerChecks = [...flags.providerChecks];
369
518
  localCommands = [];
370
519
  for (const flag of flags.localCommands) {
@@ -384,6 +533,7 @@ export function desiredFromFlags(flags, current, proposal) {
384
533
  }
385
534
  else if (current !== null) {
386
535
  providerChecks = [...current.providerChecks];
536
+ watchedChecks = [...(current.watchedChecks ?? [])];
387
537
  localCommands = current.localCommands.map((c) => ({ ...c, argv: [...c.argv] }));
388
538
  }
389
539
  else {
@@ -422,6 +572,7 @@ export function desiredFromFlags(flags, current, proposal) {
422
572
  desired: {
423
573
  kind: kindForMembers(providerChecks, localCommands),
424
574
  providerChecks,
575
+ ...(watchedChecks.length > 0 ? { watchedChecks } : {}),
425
576
  localCommands,
426
577
  migrationGuard,
427
578
  customizedCommands: flags.customizedCommands,
@@ -431,28 +582,33 @@ export function desiredFromFlags(flags, current, proposal) {
431
582
  // ---------------------------------------------------------------------------
432
583
  // Rendering
433
584
  // ---------------------------------------------------------------------------
434
- const KIND_CONSEQUENCE = Object.freeze({
435
- provider: "every check must have actually reported on this repository before an unattended run is admitted",
436
- local: "the executor runs these commands before each auto-merge; they must pass once under the executor " +
437
- "(qualification) before an unattended run is admitted",
438
- mixed: "BOTH legs gate every merge: each provider check must report green AND each local command must pass",
439
- none: "no gate: an unattended run is admitted, but every child merge waits for your approval",
440
- });
441
585
  function quoted(names) {
442
586
  return names.map((n) => `"${n}"`).join(", ");
443
587
  }
444
- /** One-gate description lines (members, conjunction, guard, customized). */
445
- export function describeGate(gate, indent = " ") {
588
+ /** BAPI-1637 — the minimal shape the shared consequence wording needs, from a desired gate. */
589
+ function consequenceGate(gate) {
590
+ return { kind: gate.kind, hasWatchedChecks: (gate.watchedChecks ?? []).length > 0 };
591
+ }
592
+ /**
593
+ * One-gate description lines (members, conjunction, guard, customized). The
594
+ * consequence line is the shared {@link describeGateConsequence}, the same wording
595
+ * readiness renders; `ciFacts` is the server's `epic_branch_ci` block when the
596
+ * caller has one, and its absence leaves gate-only wording.
597
+ */
598
+ export function describeGate(gate, indent = " ", ciFacts) {
446
599
  const lines = [];
447
600
  const members = [];
601
+ const watched = gate.watchedChecks ?? [];
448
602
  if (gate.providerChecks.length > 0)
449
603
  members.push(`provider checks ${quoted(gate.providerChecks)}`);
604
+ if (watched.length > 0)
605
+ members.push(`watched checks ${quoted(watched)}`);
450
606
  if (gate.localCommands.length > 0) {
451
607
  members.push(`local commands ${gate.localCommands.map((c) => `${c.name} (${c.argv.join(" ")})`).join(", ")}`);
452
608
  }
453
609
  lines.push(`${indent}${gate.kind}` +
454
610
  (members.length > 0 ? ` — ${members.join(gate.kind === "mixed" ? " AND " : "; ")}` : ""));
455
- lines.push(`${indent} ${KIND_CONSEQUENCE[gate.kind]}`);
611
+ lines.push(`${indent} ${describeGateConsequence(consequenceGate(gate), ciFacts)}`);
456
612
  if (gate.migrationGuard !== null) {
457
613
  lines.push(`${indent} migration guard: ${gate.migrationGuard.kind} ${gate.migrationGuard.name}`);
458
614
  }
@@ -461,6 +617,221 @@ export function describeGate(gate, indent = " ") {
461
617
  }
462
618
  return lines;
463
619
  }
620
+ const asPolicyRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
621
+ const policySame = (a, b) => JSON.stringify(a) === JSON.stringify(b);
622
+ const SETTING_SOURCE_WORDS = { project_default: "project default", built_in: "built-in default" };
623
+ const GATE_LEAD_BY_KIND = {
624
+ provider: "required CI checks",
625
+ local: "required local commands",
626
+ mixed: "required CI checks and local commands",
627
+ none: "no required checks",
628
+ };
629
+ const workerEnvNames = (gate) => (Array.isArray(gate.worker_env) ? gate.worker_env : [])
630
+ .map((entry) => (typeof asPolicyRecord(entry).name === "string" ? String(asPolicyRecord(entry).name) : ""))
631
+ .filter((name) => name !== "");
632
+ const onOff = (value) => (value === true || value === "true" ? "on" : value === false || value === "false" ? "off" : "not set");
633
+ /**
634
+ * BAPI-1658 — owner-facing words for each review-policy source, taken from the
635
+ * readiness wording for the same four values. `none` means no review result is
636
+ * used to hold child merges; it is NOT permission to merge, and other merge
637
+ * checks still apply.
638
+ */
639
+ const REVIEW_POLICY_WORDS = {
640
+ repository_policy: "epic-branch merges need no review verdict, but a review asking for changes still sends the child back for fixes",
641
+ verdict_protocol: "child merges wait for the claude-review verdict",
642
+ native_review_decision: "child merges wait for GitHub's own review decision",
643
+ none: "no review result holds child merges; other merge checks still apply",
644
+ };
645
+ /**
646
+ * BAPI-1658 — owner-facing words for each gate qualification state. Qualification
647
+ * is only the proof run of the gate's local commands: `not_required` means there
648
+ * is nothing to prove, not that any other merge check is waived, and `qualified`
649
+ * does not promise overall readiness.
650
+ */
651
+ const QUALIFICATION_WORDS = {
652
+ qualified: "the local commands have passed their proof run; other merge checks still apply",
653
+ unqualified: "the local commands have not passed their proof run yet, so an unattended run is not admitted until they do",
654
+ stale: "the local commands must pass again before an unattended run is admitted",
655
+ not_required: "there are no local commands to prove; other merge checks still apply",
656
+ };
657
+ /** Gate projection keys described one line each, in a stable order. Values are never printed. */
658
+ const GATE_ANCILLARY_AREAS = [
659
+ ["customized_commands", "Customized commands"],
660
+ ["failure_formats", "Failure formats"],
661
+ ["dependency_install", "Dependency refresh"],
662
+ ["ci_database", "CI database setting"],
663
+ ["must_order_paths", "Must-order paths"],
664
+ ["worker_database", "Worker database setting"],
665
+ ["verification_handoff_default", "Verification handoff default"],
666
+ ];
667
+ /** Gate keys the formatter understands; `source` is provenance, never a change worth a line. */
668
+ const GATE_KNOWN_KEYS = new Set([
669
+ "kind", "provider_checks", "local_commands", "migration_guard", "worker_env", "source",
670
+ ...GATE_ANCILLARY_AREAS.map(([key]) => key),
671
+ ]);
672
+ const isAbsentPolicyValue = (value) => value === undefined || value === null || (Array.isArray(value) && value.length === 0);
673
+ /** Equal values, where a missing, null, or empty value counts as the same "nothing". */
674
+ const policySameOrBothAbsent = (a, b) => (isAbsentPolicyValue(a) && isAbsentPolicyValue(b)) || policySame(a, b);
675
+ /**
676
+ * Plain, one-line-per-change descriptions of a setup-policy difference.
677
+ *
678
+ * Presentation only: it accepts differences the server already established (the
679
+ * preview's `effects`, or the applied read-back as before/after pairs), decides
680
+ * no policy, and performs no I/O. Fields that did not change inside a broader
681
+ * `gate`, `setup`, `config`, or `sources` effect are omitted. Worker environment
682
+ * is described by name only. `ciFacts` is the readiness `epic_branch_ci` block
683
+ * when the caller already has it; the gate consequence is the shared wording.
684
+ */
685
+ export function describePolicyChanges(effects, ciFacts, options = {}) {
686
+ const lines = [];
687
+ for (const effect of effects) {
688
+ const before = asPolicyRecord(effect.before);
689
+ const after = asPolicyRecord(effect.after);
690
+ switch (effect.category) {
691
+ case "gate": {
692
+ const noGate = effect.after === null || effect.after === undefined;
693
+ if (noGate)
694
+ lines.push("Gate: no gate is stored.");
695
+ const kind = typeof after.kind === "string" && after.kind in GATE_LEAD_BY_KIND ? after.kind : null;
696
+ const beforeKind = before.kind;
697
+ const members = (Array.isArray(after.provider_checks) ? after.provider_checks : []);
698
+ const kindChanged = kind !== beforeKind;
699
+ const membersChanged = !policySame(after.provider_checks, before.provider_checks)
700
+ || !policySame(after.local_commands, before.local_commands)
701
+ || !policySame(after.migration_guard, before.migration_guard);
702
+ if (!noGate && (kindChanged || membersChanged)) {
703
+ // BAPI-1657: a consequence that already opens with its lead is printed once, without repeating the lead.
704
+ const lead = kind === null ? "changed" : GATE_LEAD_BY_KIND[kind];
705
+ if (options.brief === true)
706
+ lines.push(`Gate: ${lead}`);
707
+ else {
708
+ const consequence = kind === null ? "" : describeGateConsequence({ kind, hasWatchedChecks: members.some((c) => c.watched === true) }, ciFacts);
709
+ lines.push(consequence.startsWith(`${lead}:`) ? `Gate: ${consequence}` : `Gate: ${lead}.${consequence === "" ? "" : ` ${consequence}`}`);
710
+ }
711
+ // BAPI-1658: the summary names the kind, not what changed inside it. A member list that changed
712
+ // while the kind stayed the same, and a migration guard, each get their own line.
713
+ if (!kindChanged && !policySame(after.provider_checks, before.provider_checks))
714
+ lines.push("Provider checks: the list changed");
715
+ if (!kindChanged && !policySame(after.local_commands, before.local_commands))
716
+ lines.push("Local commands: the list changed");
717
+ if (!policySame(after.migration_guard, before.migration_guard)) {
718
+ lines.push(`Migration guard: ${isAbsentPolicyValue(after.migration_guard) ? "removed" : isAbsentPolicyValue(before.migration_guard) ? "added" : "changed"}`);
719
+ }
720
+ }
721
+ // BAPI-1658: compared on the whole value, so a value-only change is seen; only names are printed.
722
+ if (!policySameOrBothAbsent(after.worker_env, before.worker_env)) {
723
+ const names = workerEnvNames(after);
724
+ lines.push(`Worker environment: ${names.length === 0 ? "no variables are set" : `variables set by name: ${names.join(", ")}`}`);
725
+ }
726
+ for (const [key, area] of GATE_ANCILLARY_AREAS) {
727
+ if (policySameOrBothAbsent(after[key], before[key]))
728
+ continue;
729
+ lines.push(`${area}: ${isAbsentPolicyValue(after[key]) ? "removed" : isAbsentPolicyValue(before[key]) ? "added" : "changed"}`);
730
+ }
731
+ if (Object.keys({ ...before, ...after }).some((key) => !GATE_KNOWN_KEYS.has(key) && !policySame(before[key], after[key]))) {
732
+ lines.push("Gate: other gate details changed.");
733
+ }
734
+ break;
735
+ }
736
+ case "setup": {
737
+ if (!policySame(after.review_policy, before.review_policy)) {
738
+ const source = asPolicyRecord(after.review_policy).source;
739
+ lines.push(after.review_policy === null || after.review_policy === undefined
740
+ ? "Review policy: no project default is stored"
741
+ : typeof source === "string" && Object.hasOwn(REVIEW_POLICY_WORDS, source) ? `Review policy: ${REVIEW_POLICY_WORDS[source]}` : "Review policy: changed");
742
+ }
743
+ if (!policySame(after.review_source, before.review_source)) {
744
+ lines.push(`Review source: ${after.review_source === null || after.review_source === undefined ? "not set" : String(after.review_source)}`);
745
+ }
746
+ if (!policySame(after.min_approvals, before.min_approvals)) {
747
+ lines.push(`Required approvals: ${after.min_approvals === null || after.min_approvals === undefined ? "not set" : String(after.min_approvals)}`);
748
+ }
749
+ break;
750
+ }
751
+ case "config": {
752
+ for (const key of Object.keys({ ...before, ...after })) {
753
+ if (policySame(before[key], after[key]))
754
+ continue;
755
+ const v = after[key];
756
+ if (key === "merge_approval_required") {
757
+ lines.push(v === true || v === "true" ? "Child merges: each one waits for your approval"
758
+ : v === false || v === "false" ? "Child merges: no approval is asked for" : "Child merges: approval setting is not set");
759
+ }
760
+ else if (key === "auto_merge_enabled")
761
+ lines.push(`Auto-merge: ${onOff(v)}`);
762
+ else if (key === "teardown_enabled")
763
+ lines.push(`Teardown after merge: ${onOff(v)}`);
764
+ else if (key === "auto_rereview_enabled")
765
+ lines.push(`Automatic re-review: ${onOff(v)}`);
766
+ else if (key === "merge_execution")
767
+ lines.push(`Who runs merges: ${String(v)}`);
768
+ else
769
+ lines.push(`Setting changed: ${key.replace(/_/g, " ")}`);
770
+ }
771
+ break;
772
+ }
773
+ case "sources": {
774
+ for (const key of ["setup", "config"]) {
775
+ if (policySame(before[key], after[key]))
776
+ continue;
777
+ const word = typeof after[key] === "string" ? SETTING_SOURCE_WORDS[after[key]] ?? "unrecognized" : "unrecognized";
778
+ lines.push(`Settings source (${key}): ${word}`);
779
+ }
780
+ break;
781
+ }
782
+ case "qualification":
783
+ lines.push(`Gate qualification: ${typeof effect.after === "string" && Object.hasOwn(QUALIFICATION_WORDS, effect.after) ? QUALIFICATION_WORDS[effect.after] : "changed"}`);
784
+ break;
785
+ }
786
+ }
787
+ return lines;
788
+ }
789
+ /**
790
+ * BAPI-1637 — the post-epic-branch-CI summary: what the STORED gate means for
791
+ * merges, in the same words readiness uses. Reads readiness once and renders the
792
+ * shared consequence from that response's stored gate and `epic_branch_ci` facts,
793
+ * never from local flags or the profile the setup just built. Advisory: a failed
794
+ * readiness read falls back to the stored gate alone (gate-only wording, no
795
+ * invented CI fact); if that read fails too, nothing is printed. Never throws and
796
+ * never prints a transport error.
797
+ */
798
+ export async function runGateConsequenceSummary(io, access, gateDeps) {
799
+ let gate = null;
800
+ let ciFacts = null;
801
+ try {
802
+ const readiness = await (gateDeps?.fetchReadiness ?? fetchConductorReadiness)(access, io.fetchJson);
803
+ const profile = readiness.gate_profile;
804
+ if (profile !== undefined && profile !== null) {
805
+ gate = {
806
+ kind: profile.kind,
807
+ hasWatchedChecks: profile.provider_checks.some((check) => check.watched === true),
808
+ };
809
+ ciFacts = readiness.epic_branch_ci ?? null;
810
+ }
811
+ }
812
+ catch {
813
+ gate = null;
814
+ }
815
+ if (gate === null) {
816
+ try {
817
+ const stored = await fetchConductorGateProfile(access, io.fetchJson);
818
+ if (stored.confirmed && stored.profile !== null) {
819
+ gate = consequenceGate(desiredFromStored(stored.profile));
820
+ }
821
+ }
822
+ catch {
823
+ gate = null;
824
+ }
825
+ }
826
+ if (gate === null)
827
+ return;
828
+ const line = describeGateConsequence(gate, ciFacts);
829
+ if (line === "")
830
+ return;
831
+ io.log("");
832
+ io.log("What the stored gate means for merges:");
833
+ io.log(` ${line}`);
834
+ }
464
835
  function describeHistory(proposal) {
465
836
  switch (proposal.history.status) {
466
837
  case "available":
@@ -498,6 +869,8 @@ export function renderGateProposal(io, proposal) {
498
869
  numbered.push({ kind: "provider", name: candidate.name });
499
870
  io.log(` [${numbered.length}] provider check "${candidate.name}" — reported on this repository ` +
500
871
  `(confidence ${candidate.confidence})`);
872
+ if (candidate.checkEvidence)
873
+ io.log(` purpose: ${candidate.checkEvidence.purpose} (${candidate.checkEvidence.purposeProvenance}); source: ${candidate.checkEvidence.discoverySource}; outcome: ${candidate.checkEvidence.executionOutcome}`);
501
874
  for (const e of candidate.evidence)
502
875
  io.log(` evidence: ${describeEvidence(e)}`);
503
876
  }
@@ -611,25 +984,28 @@ function historyLookupFor(io, access) {
611
984
  /** Run discovery, or an explicit empty proposal when no discovery seam exists. */
612
985
  export async function runGateDiscovery(io, access, gateDeps) {
613
986
  const fs = gateDeps?.discoveryFs;
614
- if (!fs) {
615
- return {
616
- providerCandidates: [],
617
- unreportedProviderNames: [],
618
- localCandidates: [],
619
- evidence: [],
620
- history: { status: "not_queried" },
621
- proposed: { kind: "none", providerChecks: [], localCommandIds: [] },
622
- noCandidates: true,
623
- workerEnvCandidates: [],
624
- workerEnvConflicts: [],
625
- workerEnvSkipped: [],
626
- workerEnvOverflow: 0,
627
- reproductionHints: [],
628
- reproductionHintsSkipped: [],
629
- };
630
- }
987
+ if (!fs)
988
+ return emptyProposal();
631
989
  return discoverGate({ fs, lookupHistory: historyLookupFor(io, access) });
632
990
  }
991
+ /** A fresh explicit empty proposal: nothing discovered, nothing proposed. */
992
+ function emptyProposal() {
993
+ return {
994
+ providerCandidates: [],
995
+ unreportedProviderNames: [],
996
+ localCandidates: [],
997
+ evidence: [],
998
+ history: { status: "not_queried" },
999
+ proposed: { kind: "none", providerChecks: [], localCommandIds: [] },
1000
+ noCandidates: true,
1001
+ workerEnvCandidates: [],
1002
+ workerEnvConflicts: [],
1003
+ workerEnvSkipped: [],
1004
+ workerEnvOverflow: 0,
1005
+ reproductionHints: [],
1006
+ reproductionHintsSkipped: [],
1007
+ };
1008
+ }
633
1009
  const MAX_SELECTION_ATTEMPTS = 3;
634
1010
  const MAX_TYPED_CHECKS = 32;
635
1011
  /**
@@ -724,13 +1100,255 @@ async function reviewSettingsInto(io, proposal, current, desired) {
724
1100
  if (!prompt || !hasSettingsToReview(proposal, current.profile, desired.providerChecks)) {
725
1101
  return { desired, changed: false };
726
1102
  }
1103
+ if (usesSafeSettingDefaults(io)) {
1104
+ const selection = recommendedSettingsSelection(proposal, current.profile, desired.providerChecks);
1105
+ logSafeSettingReceipts(io, selection, current.profile, false);
1106
+ return {
1107
+ desired: { ...desired, ...settingsFieldsOf(selection.edit) },
1108
+ changed: !settingsMatchStored(selection.edit, current.profile),
1109
+ };
1110
+ }
727
1111
  const edit = await reviewDiscoveredSettings({ log: io.log, promptLine: prompt }, proposal, current.profile, desired.providerChecks);
728
- const merged = {
729
- ...desired,
1112
+ const merged = { ...desired, ...settingsFieldsOf(edit) };
1113
+ return { desired: merged, changed: !settingsMatchStored(edit, current.profile) };
1114
+ }
1115
+ /** The desired-gate fields an edit sets; untouched settings stay omitted from the write. */
1116
+ function settingsFieldsOf(edit) {
1117
+ return {
730
1118
  ...(edit.workerEnv !== undefined ? { workerEnv: edit.workerEnv } : {}),
731
1119
  ...(edit.reproduce !== undefined ? { reproduce: edit.reproduce } : {}),
1120
+ ...(edit.dependencyInstall !== undefined ? { dependencyInstall: edit.dependencyInstall } : {}),
1121
+ ...(edit.ciDatabase !== undefined ? { ciDatabase: edit.ciDatabase } : {}),
1122
+ ...(edit.mustOrderPaths !== undefined ? { mustOrderPaths: edit.mustOrderPaths } : {}),
1123
+ ...(edit.workerDatabase !== undefined ? { workerDatabase: edit.workerDatabase } : {}),
732
1124
  };
733
- return { desired: merged, changed: !settingsMatchStored(edit, current.profile) };
1125
+ }
1126
+ /**
1127
+ * BAPI-1551 — keep the confirmed gate, and offer any unstored declaration
1128
+ * proposal as an optional gate change. Declining it (or having none) keeps the
1129
+ * no-write plan exactly as before; it never becomes a blocking item.
1130
+ */
1131
+ async function keptGateWithDeclarations(io, current, currentDesired, gateDeps, options) {
1132
+ const unchanged = {
1133
+ kind: "plan",
1134
+ plan: { current, desired: currentDesired, write: null, removals: [], origin: "stored" },
1135
+ };
1136
+ const offered = await offerDeclarationChanges(io, current, currentDesired, gateDeps, options);
1137
+ if (!offered.changed)
1138
+ return unchanged;
1139
+ renderGateComparison(io, current, offered.desired, []);
1140
+ if (!options.planningOnly && !usesSafeSettingDefaults(io) && !(await ask(io, "Store these worker setup declarations with the gate? [y/N]: "))) {
1141
+ io.log(" Declarations not stored; the stored gate and its settings are unchanged.");
1142
+ for (const key of offered.offeredKeys)
1143
+ options.declinedDeclarations?.add(key);
1144
+ return unchanged;
1145
+ }
1146
+ return {
1147
+ kind: "plan",
1148
+ plan: {
1149
+ current,
1150
+ desired: offered.desired,
1151
+ write: confirmRequestFor(offered.desired, current.revision, current.profile),
1152
+ removals: [],
1153
+ origin: "stored",
1154
+ },
1155
+ };
1156
+ }
1157
+ /**
1158
+ * BAPI-1551 — with a confirmed gate kept as it is, offer the dependency-refresh
1159
+ * and CI-database proposals the stored profile does not hold yet. Advisory: the
1160
+ * offer only ever adds a gate change the owner accepts. It runs only in a
1161
+ * terminal, never under `--dry-run`, never without a discovery seam, and asks
1162
+ * nothing when there is no unstored proposal. Declining keeps the stored values.
1163
+ */
1164
+ async function offerDeclarationChanges(io, current, desired, gateDeps, options) {
1165
+ const none = { desired, changed: false, offeredKeys: [] };
1166
+ const prompt = io.promptLine;
1167
+ if (!gateDeps?.discoveryFs || current.profile === null)
1168
+ return none;
1169
+ const safeDefaults = usesSafeSettingDefaults(io);
1170
+ // A dry run previews the safe selection but never reviews; a real run needs a reader or safe defaults.
1171
+ if (options.dryRun ? !safeDefaults : !prompt)
1172
+ return none;
1173
+ const proposal = await discoverDeclarationProposal(current, desired, gateDeps, options.declinedDeclarations);
1174
+ if (proposal === null)
1175
+ return none;
1176
+ const declined = options.declinedDeclarations;
1177
+ if (!hasUnstoredDeclarationProposal(proposal, current.profile)) {
1178
+ // BAPI-1580: discoveries the bound keeps from being offered are still named.
1179
+ const warning = mustOrderShortfallWarning(proposal, current.profile);
1180
+ if (warning !== null)
1181
+ io.log(warning);
1182
+ return none;
1183
+ }
1184
+ const offeredKeys = [
1185
+ ...(proposal.dependencyInstallCandidates ?? [])
1186
+ .filter((c) => !(current.profile?.dependency_install ?? []).some((e) => dependencyInstallEqual([e], [c])))
1187
+ .map(dependencyProposalKey),
1188
+ ...(proposal.ciDatabaseProposal !== undefined &&
1189
+ proposal.ciDatabaseProposal.value !== storedCiDatabase(current.profile)
1190
+ ? [ciDatabaseProposalKey(proposal.ciDatabaseProposal.value)]
1191
+ : []),
1192
+ ...mustOrderOffer(proposal, current.profile).offered.map(mustOrderProposalKey),
1193
+ ...(proposal.workerDatabaseProposal !== undefined && current.profile.worker_database === undefined
1194
+ ? [WORKER_DATABASE_PROPOSAL_KEY]
1195
+ : []),
1196
+ ];
1197
+ if (safeDefaults) {
1198
+ const { edit: selected } = recommendedSettingsSelection(proposal, current.profile, desired.providerChecks);
1199
+ const edit = {
1200
+ ...(selected.dependencyInstall !== undefined ? { dependencyInstall: selected.dependencyInstall } : {}),
1201
+ ...(selected.ciDatabase !== undefined ? { ciDatabase: selected.ciDatabase } : {}),
1202
+ ...(selected.mustOrderPaths !== undefined ? { mustOrderPaths: selected.mustOrderPaths } : {}),
1203
+ ...(selected.workerDatabase !== undefined ? { workerDatabase: selected.workerDatabase } : {}),
1204
+ };
1205
+ io.log("");
1206
+ logSafeSettingReceipts(io, { edit, skipped: [] }, current.profile, options.dryRun);
1207
+ if (options.dryRun)
1208
+ return none;
1209
+ return {
1210
+ desired: { ...desired, ...settingsFieldsOf(edit) },
1211
+ changed: !settingsMatchStored(edit, current.profile),
1212
+ offeredKeys,
1213
+ };
1214
+ }
1215
+ io.log("");
1216
+ io.log(" Discovery proposes worker setup declarations this gate does not store yet (optional):");
1217
+ renderDeclarationsOnly(io, proposal, current.profile, true);
1218
+ const edit = await reviewDeclarations({ log: io.log, promptLine: prompt }, proposal, current.profile);
1219
+ const merged = {
1220
+ ...desired,
1221
+ ...(edit.dependencyInstall !== undefined ? { dependencyInstall: edit.dependencyInstall } : {}),
1222
+ ...(edit.ciDatabase !== undefined ? { ciDatabase: edit.ciDatabase } : {}),
1223
+ ...(edit.mustOrderPaths !== undefined ? { mustOrderPaths: edit.mustOrderPaths } : {}),
1224
+ ...(edit.workerDatabase !== undefined ? { workerDatabase: edit.workerDatabase } : {}),
1225
+ };
1226
+ if (proposal.workerDatabaseProposal !== undefined && edit.workerDatabase === undefined) {
1227
+ declined?.add(WORKER_DATABASE_PROPOSAL_KEY);
1228
+ }
1229
+ // A proposal the owner did not take is remembered as declined for this invocation.
1230
+ const resultingList = edit.dependencyInstall ?? current.profile.dependency_install ?? [];
1231
+ const resultingCi = edit.ciDatabase ?? storedCiDatabase(current.profile);
1232
+ for (const candidate of proposal.dependencyInstallCandidates ?? []) {
1233
+ if (!resultingList.some((e) => dependencyInstallEqual([e], [candidate]))) {
1234
+ declined?.add(dependencyProposalKey(candidate));
1235
+ }
1236
+ }
1237
+ if (proposal.ciDatabaseProposal !== undefined && proposal.ciDatabaseProposal.value !== resultingCi) {
1238
+ declined?.add(ciDatabaseProposalKey(proposal.ciDatabaseProposal.value));
1239
+ }
1240
+ const resultingMustOrder = edit.mustOrderPaths ?? current.profile.must_order_paths;
1241
+ for (const entry of mustOrderOffer(proposal, current.profile).offered) {
1242
+ if (!resultingMustOrder.includes(entry))
1243
+ declined?.add(mustOrderProposalKey(entry));
1244
+ }
1245
+ return { desired: merged, changed: !settingsMatchStored(edit, current.profile), offeredKeys };
1246
+ }
1247
+ /**
1248
+ * BAPI-1638 — the declaration discovery shared by the terminal offer and the
1249
+ * read-only planner. Reads repository files only: no prompt, no write. `null`
1250
+ * means there is nothing to discover from (no seam, no stored profile, or a
1251
+ * failed read). Discovery PROPOSES settings; it never authorizes the gate or a
1252
+ * declaration.
1253
+ */
1254
+ async function discoverDeclarationProposal(current, desired, gateDeps, declined,
1255
+ /** The read-only planner also proposes declarations for a gate that is not stored yet. */
1256
+ allowUnstored = false) {
1257
+ const fs = gateDeps?.discoveryFs;
1258
+ if (!fs || (current.profile === null && !allowUnstored))
1259
+ return null;
1260
+ let declarations;
1261
+ try {
1262
+ declarations = await discoverDeclarations({ fs, providerChecks: desired.providerChecks });
1263
+ }
1264
+ catch {
1265
+ return null;
1266
+ }
1267
+ // Never re-offer what the owner already ignored or declined in this invocation.
1268
+ const candidates = (declarations.dependencyInstallCandidates ?? []).filter((c) => !declined?.has(dependencyProposalKey(c)));
1269
+ const ci = declarations.ciDatabaseProposal;
1270
+ const mustOrder = (declarations.mustOrderPathCandidates ?? []).filter((p) => !declined?.has(mustOrderProposalKey(p)));
1271
+ const workerDatabase = declarations.workerDatabaseProposal;
1272
+ return {
1273
+ ...emptyProposal(),
1274
+ ...(workerDatabase !== undefined && !declined?.has(WORKER_DATABASE_PROPOSAL_KEY)
1275
+ ? { workerDatabaseProposal: workerDatabase }
1276
+ : {}),
1277
+ ...(candidates.length > 0 ? { dependencyInstallCandidates: candidates } : {}),
1278
+ ...(declarations.dependencyInstallNotes ? { dependencyInstallNotes: declarations.dependencyInstallNotes } : {}),
1279
+ ...(ci !== undefined && !declined?.has(ciDatabaseProposalKey(ci.value)) ? { ciDatabaseProposal: ci } : {}),
1280
+ ...(mustOrder.length > 0 ? { mustOrderPathCandidates: mustOrder } : {}),
1281
+ ...(declarations.mustOrderPathOverflow !== undefined
1282
+ ? { mustOrderPathOverflow: declarations.mustOrderPathOverflow }
1283
+ : {}),
1284
+ };
1285
+ }
1286
+ /**
1287
+ * BAPI-1638 — plan the worker-setup declarations without a terminal.
1288
+ *
1289
+ * Read-only: the same discovery and the same safe recommended selection the
1290
+ * terminal path uses, split into one entry per answer key. It asks nothing,
1291
+ * writes nothing, and never decides. An entry is a proposal the owner approves
1292
+ * or declines by its key; discovery alone authorizes nothing.
1293
+ */
1294
+ export async function planDeclarationSelections(current, desired, gateDeps) {
1295
+ // A first install has no stored profile: its declarations are proposed with the
1296
+ // gate, so the first apply stores them before the learned check starts.
1297
+ const proposal = await discoverDeclarationProposal(current, desired, gateDeps, undefined, true);
1298
+ if (proposal === null)
1299
+ return [];
1300
+ if (!hasUnstoredDeclarationProposal(proposal, current.profile))
1301
+ return [];
1302
+ const { edit } = recommendedSettingsSelection(proposal, current.profile, desired.providerChecks);
1303
+ const entries = [];
1304
+ const stored = current.profile;
1305
+ if (edit.dependencyInstall !== undefined) {
1306
+ entries.push({
1307
+ key: "dependency_install",
1308
+ proposalKeys: (proposal.dependencyInstallCandidates ?? []).map(dependencyProposalKey),
1309
+ fields: { dependencyInstall: edit.dependencyInstall },
1310
+ summary: describeSettingsEdit({ dependencyInstall: edit.dependencyInstall }, stored),
1311
+ });
1312
+ }
1313
+ if (edit.ciDatabase !== undefined) {
1314
+ entries.push({
1315
+ key: "ci_database",
1316
+ proposalKeys: [ciDatabaseProposalKey(edit.ciDatabase)],
1317
+ fields: { ciDatabase: edit.ciDatabase },
1318
+ summary: describeSettingsEdit({ ciDatabase: edit.ciDatabase }, stored),
1319
+ });
1320
+ }
1321
+ if (edit.mustOrderPaths !== undefined) {
1322
+ entries.push({
1323
+ key: "must_order_paths",
1324
+ proposalKeys: mustOrderOffer(proposal, stored).offered.map(mustOrderProposalKey),
1325
+ fields: { mustOrderPaths: edit.mustOrderPaths },
1326
+ summary: describeSettingsEdit({ mustOrderPaths: edit.mustOrderPaths }, stored),
1327
+ });
1328
+ }
1329
+ if (edit.workerDatabase !== undefined) {
1330
+ entries.push({
1331
+ key: "worker_database",
1332
+ proposalKeys: [WORKER_DATABASE_PROPOSAL_KEY],
1333
+ fields: { workerDatabase: edit.workerDatabase },
1334
+ summary: describeSettingsEdit({ workerDatabase: edit.workerDatabase }, stored),
1335
+ });
1336
+ }
1337
+ return entries;
1338
+ }
1339
+ /** BAPI-1551 — a proposal's identity for the per-invocation declined set: the whole entry. */
1340
+ export function dependencyProposalKey(entry) {
1341
+ return `dependency_install:${JSON.stringify([entry.cwd, entry.argv, entry.lockfiles])}`;
1342
+ }
1343
+ /** BAPI-1551 — the declined-set key of a CI-database proposal. */
1344
+ export function ciDatabaseProposalKey(value) {
1345
+ return `ci_database:${value}`;
1346
+ }
1347
+ /** BAPI-1598 — the declined-set key of the worker-database proposal. */
1348
+ export const WORKER_DATABASE_PROPOSAL_KEY = "worker_database:proposed";
1349
+ /** BAPI-1580 — the declined-set key of one must-order proposal. */
1350
+ export function mustOrderProposalKey(entry) {
1351
+ return `must_order_paths:${entry}`;
734
1352
  }
735
1353
  /**
736
1354
  * Decide the repository gate for this run (BEFORE any write).
@@ -789,21 +1407,13 @@ export async function resolveConductorGate(io, access, flags, gateDeps, options)
789
1407
  io.log(" The confirmed gate already matches — no gate write is needed.");
790
1408
  return { kind: "plan", plan: { current, desired: currentDesired, write: null, removals: [], origin: "stored" } };
791
1409
  }
792
- if (settingsChanged && !options.dryRun) {
1410
+ if (settingsChanged && !options.dryRun && !options.planningOnly && !usesSafeSettingDefaults(io)) {
793
1411
  const ok = await ask(io, "Store these CI settings with the gate? [y/N]: ");
794
1412
  if (!ok) {
795
1413
  io.errorLog("CI settings not confirmed — nothing was written, and the stored gate is unchanged.");
796
1414
  return { kind: "exit", code: 1 };
797
1415
  }
798
1416
  }
799
- if (removals.length > 0 && !flags.confirmGate && !options.dryRun) {
800
- const ok = await ask(io, "Confirm this gate, including the removals above? [y/N]: ");
801
- if (!ok) {
802
- io.errorLog("Gate change not confirmed — nothing was written, and the stored gate is unchanged.");
803
- io.errorLog("Pass --confirm-gate to confirm a removal from a script.");
804
- return { kind: "exit", code: 1 };
805
- }
806
- }
807
1417
  return {
808
1418
  kind: "plan",
809
1419
  plan: {
@@ -815,8 +1425,8 @@ export async function resolveConductorGate(io, access, flags, gateDeps, options)
815
1425
  },
816
1426
  };
817
1427
  }
818
- if (options.ensureProviderCheck !== undefined) {
819
- return ensureProviderCheckPlan(io, access, current, currentDesired, options.ensureProviderCheck, gateDeps, options);
1428
+ if (options.inferCi === true) {
1429
+ return inferredCiPlan(io, access, current, currentDesired, gateDeps, options);
820
1430
  }
821
1431
  if (currentDesired !== null) {
822
1432
  io.log(current.source === "legacy"
@@ -824,7 +1434,7 @@ export async function resolveConductorGate(io, access, flags, gateDeps, options)
824
1434
  : ` Using the confirmed gate (revision ${current.revision}).`);
825
1435
  for (const line of describeGate(currentDesired))
826
1436
  io.log(line);
827
- return { kind: "plan", plan: { current, desired: currentDesired, write: null, removals: [], origin: "stored" } };
1437
+ return keptGateWithDeclarations(io, current, currentDesired, gateDeps, options);
828
1438
  }
829
1439
  const proposal = await runGateDiscovery(io, access, gateDeps);
830
1440
  const numbered = renderGateProposal(io, proposal);
@@ -851,7 +1461,7 @@ export async function resolveConductorGate(io, access, flags, gateDeps, options)
851
1461
  // BAPI-1520: worker variables and reproduction hints, decided one at a time.
852
1462
  const { desired } = await reviewSettingsInto(io, proposal, current, chosen);
853
1463
  renderGateComparison(io, current, desired, []);
854
- const confirmed = await ask(io, "Store this repository gate? [y/N]: ");
1464
+ const confirmed = options.planningOnly || await ask(io, "Store this repository gate? [y/N]: ");
855
1465
  if (!confirmed) {
856
1466
  io.errorLog("Gate not confirmed — nothing was written. A confirmed gate is required to continue.");
857
1467
  return { kind: "exit", code: 1 };
@@ -867,7 +1477,7 @@ export async function resolveConductorGate(io, access, flags, gateDeps, options)
867
1477
  },
868
1478
  };
869
1479
  }
870
- /** BAPI-1461 — `desired` with `check` added as a provider member (kept when present). */
1480
+ /** BAPI-1461 — `desired` with `check` added as a required provider member (kept when present). */
871
1481
  function withProviderCheck(desired, check) {
872
1482
  if (desired.providerChecks.includes(check))
873
1483
  return desired;
@@ -875,76 +1485,143 @@ function withProviderCheck(desired, check) {
875
1485
  return {
876
1486
  ...desired,
877
1487
  providerChecks,
1488
+ // A name is never both required and watched.
1489
+ ...(desired.watchedChecks !== undefined
1490
+ ? { watchedChecks: desired.watchedChecks.filter((name) => name !== check) }
1491
+ : {}),
878
1492
  localCommands: desired.localCommands.map((c) => ({ ...c, argv: [...c.argv] })),
879
1493
  kind: kindForMembers(providerChecks, desired.localCommands),
880
1494
  };
881
1495
  }
882
1496
  /**
883
- * BAPI-1461 — the converging setup's gate decision when no gate flag was given.
1497
+ * BAPI-1603 — the gate change that adds the managed workflow's check to the CURRENT
1498
+ * stored gate, for a caller that has just seen the setup pull request opened or
1499
+ * reused. Built from the profile read right now, so the server-promoted local
1500
+ * member and any watched checks are kept; the write names its expected revision.
1501
+ * `null` when the gate already requires the check, or there is no confirmed gate
1502
+ * to add it to.
1503
+ */
1504
+ export function planManagedProviderGate(current, check) {
1505
+ if (!current.confirmed || current.profile === null)
1506
+ return null;
1507
+ const stored = desiredFromStored(current.profile);
1508
+ if (stored.providerChecks.includes(check))
1509
+ return null;
1510
+ const desired = withProviderCheck(stored, check);
1511
+ return {
1512
+ current,
1513
+ desired,
1514
+ write: confirmRequestFor(desired, current.revision, current.profile),
1515
+ removals: [],
1516
+ origin: "stored",
1517
+ };
1518
+ }
1519
+ /** The command-free gate setup starts from: no members, nothing to qualify. */
1520
+ function emptyDesiredGate() {
1521
+ return { kind: "none", providerChecks: [], localCommands: [], migrationGuard: null, customizedCommands: undefined };
1522
+ }
1523
+ /**
1524
+ * BAPI-1603 — the converging setup's gate decision when no gate flag was given.
1525
+ *
1526
+ * - A confirmed stored gate (provider, local, mixed, none, watched, or the
1527
+ * legacy `--required-check` form) is kept exactly as it is. Discovery can
1528
+ * still offer worker setup declarations, but never changes its members.
1529
+ * - A stored value that could not be read is NOT replaced: it is unknown, not
1530
+ * absent, so nothing is inferred and nothing is written.
1531
+ * - Otherwise the plan comes from facts, with no question:
1532
+ * reported provider checks ⇒ stored as WATCHED members (when the server can
1533
+ * store them), never as required ones, and never adding the managed check;
1534
+ * nothing reported ⇒ a command-free `none` gate, so the server's promotion of
1535
+ * a proven local command later lands on a stored profile.
884
1536
  *
885
- * - A confirmed gate that already requires the check: used unchanged, no write.
886
- * - A confirmed provider or mixed gate without it: the check is ADDED (every
887
- * member kept), shown against the stored gate, and stored later under the
888
- * combined gate-and-defaults consent.
889
- * - A confirmed local-only or `none` gate: changing its kind is a policy change,
890
- * so the comparison is shown and the owner is asked here. A decline keeps the
891
- * stored gate and is reported as an outstanding blocking fix.
892
- * - No confirmed gate: the discovery proposal plus the check, shown for the
893
- * combined consent. Nothing is stored here.
1537
+ * The write is planned, not made: it goes through the combined policy preview.
894
1538
  */
895
- async function ensureProviderCheckPlan(io, access, current, currentDesired, check, gateDeps, options) {
1539
+ async function inferredCiPlan(io, access, current, currentDesired, gateDeps, options) {
896
1540
  if (currentDesired !== null) {
897
- if (currentDesired.providerChecks.includes(check)) {
898
- io.log(current.source === "legacy"
899
- ? " Using the confirmed gate from this repository's existing --required-check setup."
900
- : ` Using the confirmed gate (revision ${current.revision}).`);
901
- for (const line of describeGate(currentDesired))
902
- io.log(line);
903
- return { kind: "plan", plan: { current, desired: currentDesired, write: null, removals: [], origin: "stored" } };
904
- }
905
- const desired = withProviderCheck(currentDesired, check);
906
- renderGateComparison(io, current, desired, []);
907
- if (currentDesired.kind === "local" || currentDesired.kind === "none") {
908
- if (options.dryRun) {
909
- io.log(" Dry run — a real run asks before adding the CI check to this gate.");
910
- }
911
- else {
912
- const ok = await ask(io, "Add the CI workflow check to this repository gate? [y/N]: ");
913
- if (!ok) {
914
- io.log(" Kept the stored gate unchanged; the CI check is listed as a step left.");
915
- return {
916
- kind: "plan",
917
- plan: { current, desired: currentDesired, write: null, removals: [], origin: "stored" },
918
- ensureDeclined: true,
919
- };
920
- }
921
- }
922
- }
923
- return {
924
- kind: "plan",
925
- plan: {
926
- current,
927
- desired,
928
- write: confirmRequestFor(desired, current.revision, current.profile),
929
- removals: [],
930
- origin: "stored",
931
- },
932
- };
1541
+ io.log(current.source === "legacy"
1542
+ ? " Using the confirmed gate from this repository's existing --required-check setup."
1543
+ : ` Using the confirmed gate (revision ${current.revision}).`);
1544
+ for (const line of describeGate(currentDesired))
1545
+ io.log(line);
1546
+ return keptGateWithDeclarations(io, current, currentDesired, gateDeps, options);
1547
+ }
1548
+ const plan = (desired, write, inferred) => ({
1549
+ kind: "plan",
1550
+ plan: { current, desired, write, removals: [], origin: "inferred", inferred },
1551
+ });
1552
+ if (current.stored_malformed) {
1553
+ io.log(" The stored repository gate could not be read, so setup leaves it alone and plans nothing.");
1554
+ return plan(emptyDesiredGate(), null, {
1555
+ ciPlan: "none",
1556
+ reportedChecks: [],
1557
+ watchedWritable: false,
1558
+ watchedUnsupported: false,
1559
+ storedUnreadable: true,
1560
+ trialEligible: false,
1561
+ reasons: [],
1562
+ });
933
1563
  }
934
1564
  const proposal = await runGateDiscovery(io, access, gateDeps);
935
- renderGateProposal(io, proposal);
936
- const desired = withProviderCheck(desiredFromProposalSelection(proposal, proposal.proposed.providerChecks, proposal.proposed.localCommandIds), check);
1565
+ const reported = reportedProviderChecks(proposal).slice(0, MAX_TYPED_CHECKS);
1566
+ if (reported.length === 0 && proposal.history.status === "unavailable") {
1567
+ // Unknown is not absent: a stored `none` would be kept on every rerun and
1568
+ // hide the repository's real CI for good. Store nothing and say why.
1569
+ io.log(" Bridge could not read this repository's CI history, so it cannot tell whether there is CI to watch. " +
1570
+ "It stores no gate now; run setup again when the history can be read.");
1571
+ return plan(emptyDesiredGate(), null, {
1572
+ ciPlan: "none",
1573
+ reportedChecks: [],
1574
+ watchedWritable: false,
1575
+ watchedUnsupported: false,
1576
+ storedUnreadable: false,
1577
+ trialEligible: false,
1578
+ reasons: [],
1579
+ });
1580
+ }
1581
+ if (reported.length === 0) {
1582
+ const desired = emptyDesiredGate();
1583
+ renderGateComparison(io, current, desired, []);
1584
+ return plan(desired, confirmRequestFor(desired, current.revision, current.profile), {
1585
+ ciPlan: "none",
1586
+ reportedChecks: [],
1587
+ watchedWritable: false,
1588
+ watchedUnsupported: false,
1589
+ storedUnreadable: false,
1590
+ trialEligible: true,
1591
+ // BAPI-1654: missing reported checks, said as such. It is not proof the repository has no CI.
1592
+ reasons: ["No CI checks have reported on this repository yet."],
1593
+ });
1594
+ }
1595
+ // Reported checks exist. Whether the server can store them as watched is a
1596
+ // separate fact; an older one is never given a required-check or `none` stand-in.
1597
+ const watchedCapability = await probeConductorGateProfileWatchedCapability(access, io.fetchJson);
1598
+ if (!watchedCapability.supported) {
1599
+ io.log(` Bridge found ${reported.length} CI check(s) but this server cannot store watched checks, so it ` +
1600
+ "stores no CI checks for now. Nothing was replaced; update the Bridge API, then run setup again.");
1601
+ return plan(emptyDesiredGate(), null, {
1602
+ ciPlan: "watched",
1603
+ reportedChecks: reported,
1604
+ watchedWritable: false,
1605
+ watchedUnsupported: true,
1606
+ storedUnreadable: false,
1607
+ trialEligible: true,
1608
+ reasons: [],
1609
+ });
1610
+ }
1611
+ const desired = { ...emptyDesiredGate(), watchedChecks: reported };
937
1612
  renderGateComparison(io, current, desired, []);
938
- return {
939
- kind: "plan",
940
- plan: {
941
- current,
942
- desired,
943
- write: confirmRequestFor(desired, current.revision, current.profile),
944
- removals: [],
945
- origin: "interactive",
946
- },
947
- };
1613
+ return plan(desired, confirmRequestFor(desired, current.revision, current.profile), {
1614
+ ciPlan: "watched",
1615
+ reportedChecks: reported,
1616
+ watchedWritable: true,
1617
+ watchedUnsupported: false,
1618
+ storedUnreadable: false,
1619
+ trialEligible: true,
1620
+ reasons: [
1621
+ "Bridge found CI checks that have already reported on this repository. It watches them: one that " +
1622
+ "finishes red stops a merge, and one that is missing only warns.",
1623
+ ],
1624
+ });
948
1625
  }
949
1626
  const GATE_WRITE_REFUSAL_TEXT = Object.freeze({
950
1627
  "stale-revision": "the stored gate changed since it was read. Re-run to see the current gate.",
@@ -957,7 +1634,8 @@ const GATE_WRITE_REFUSAL_TEXT = Object.freeze({
957
1634
  timeout: "the Bridge API did not answer in time.",
958
1635
  server: "the Bridge API reported an internal error.",
959
1636
  rejected: "the Bridge API rejected the request.",
960
- "extension-unsupported": "this server is older than the installer and cannot store worker variables or reproduction hints.",
1637
+ "extension-unsupported": "this server is older than the installer and cannot store worker variables, reproduction hints, " +
1638
+ "dependency refresh declarations, CI database behavior, or must-order paths.",
961
1639
  });
962
1640
  /** Plain-language text for each closed `worker_env` refusal reason (BAPI-1520). */
963
1641
  const WORKER_ENV_REASON_TEXT = Object.freeze({
@@ -966,18 +1644,37 @@ const WORKER_ENV_REASON_TEXT = Object.freeze({
966
1644
  worker_env_secret_name: "looks secret. Drop it, or confirm its committed-literal assertion individually, then confirm again.",
967
1645
  worker_env_duplicate: "appears more than once. Keep one entry, then confirm again.",
968
1646
  });
969
- /** The request without BAPI-1520's extension fields, and the NAMES it dropped. */
1647
+ /** The request without the BAPI-1520, BAPI-1551, and BAPI-1580 extension fields, and what it dropped. */
970
1648
  function withoutExtensions(request) {
971
1649
  const workerEnvNames = (request.worker_env ?? []).map((e) => e.name);
972
1650
  const hintChecks = (request.provider_checks ?? [])
973
1651
  .filter((c) => c.reproduce !== undefined)
974
1652
  .map((c) => c.name);
975
- const { worker_env: _dropped, ...rest } = request;
1653
+ const { worker_env: _dropped, dependency_install: _install, ci_database: _database, must_order_paths: _mustOrder, worker_database: _workerDatabase, verification_handoff_default: _handoff, ...rest } = request;
976
1654
  void _dropped;
1655
+ void _install;
1656
+ void _database;
1657
+ void _mustOrder;
1658
+ void _workerDatabase;
1659
+ void _handoff;
977
1660
  return {
1661
+ ...(request.worker_database !== undefined || request.verification_handoff_default !== undefined
1662
+ ? { workerDatabase: true }
1663
+ : {}),
1664
+ ...(request.dependency_install !== undefined ? { dependencyInstall: request.dependency_install } : {}),
1665
+ ...(request.ci_database !== undefined ? { ciDatabase: request.ci_database } : {}),
1666
+ ...(request.must_order_paths !== undefined ? { mustOrderPaths: request.must_order_paths } : {}),
978
1667
  request: {
979
1668
  ...rest,
980
- ...(request.provider_checks ? { provider_checks: request.provider_checks.map((c) => ({ name: c.name })) } : {}),
1669
+ ...(request.provider_checks
1670
+ ? {
1671
+ provider_checks: request.provider_checks.map((c) => ({
1672
+ name: c.name,
1673
+ // Dropping a hint must never change a check's membership.
1674
+ ...(c.watched !== undefined ? { watched: c.watched } : {}),
1675
+ })),
1676
+ }
1677
+ : {}),
981
1678
  },
982
1679
  workerEnvNames,
983
1680
  hintChecks,
@@ -998,18 +1695,55 @@ export async function storeConductorGate(io, access, plan) {
998
1695
  gateMatchesStored(plan.desired, desiredFromStored(plan.current.profile), plan.current.profile)) {
999
1696
  return plan.current;
1000
1697
  }
1001
- let outcome = await putConductorGateProfile(access, plan.write, io.postJson);
1698
+ // BAPI-1598: the worker-database and hand-off settings are optional. A server
1699
+ // that does not advertise their capability gets the request without them, and the
1700
+ // owner is told they were not configured. Never a setup or launch stop.
1701
+ let write = plan.write;
1702
+ let workerSetupSkipped = false;
1703
+ if (write.worker_database !== undefined || write.verification_handoff_default !== undefined) {
1704
+ const probe = await probeConductorGateProfileWorkerSetupCapability(access, io.fetchJson);
1705
+ if (!probe.supported) {
1706
+ const { worker_database: _workerDatabase, verification_handoff_default: _handoff, ...rest } = write;
1707
+ void _workerDatabase;
1708
+ void _handoff;
1709
+ write = rest;
1710
+ workerSetupSkipped = true;
1711
+ if (plan.current.source === "stored" &&
1712
+ plan.current.profile !== null &&
1713
+ gateMatchesStored({ ...plan.desired, workerDatabase: undefined }, desiredFromStored(plan.current.profile), plan.current.profile)) {
1714
+ reportUnsavedSettings(io, { workerEnvNames: [], hintChecks: [], workerDatabase: true });
1715
+ io.log(" The gate itself already matched, so nothing was written.");
1716
+ return plan.current;
1717
+ }
1718
+ }
1719
+ }
1720
+ let outcome = await putConductorGateProfile(access, write, io.postJson);
1002
1721
  // BAPI-1520: an older server rejects exactly the extension fields it does not
1003
1722
  // know. Retry ONCE without them, keep everything else the owner approved, and
1004
1723
  // report what was not stored by name.
1005
1724
  let unsaved = null;
1006
1725
  if (!outcome.ok && outcome.refusal === "extension-unsupported") {
1007
- const stripped = withoutExtensions(plan.write);
1008
- unsaved = { workerEnvNames: stripped.workerEnvNames, hintChecks: stripped.hintChecks };
1726
+ const stripped = withoutExtensions(write);
1727
+ unsaved = {
1728
+ workerEnvNames: stripped.workerEnvNames,
1729
+ hintChecks: stripped.hintChecks,
1730
+ ...(stripped.dependencyInstall !== undefined ? { dependencyInstall: stripped.dependencyInstall } : {}),
1731
+ ...(stripped.ciDatabase !== undefined ? { ciDatabase: stripped.ciDatabase } : {}),
1732
+ ...(stripped.mustOrderPaths !== undefined ? { mustOrderPaths: stripped.mustOrderPaths } : {}),
1733
+ ...(stripped.workerDatabase !== undefined ? { workerDatabase: true } : {}),
1734
+ };
1009
1735
  const storedDesired = plan.current.profile !== null ? desiredFromStored(plan.current.profile) : null;
1010
1736
  const membersUnchanged = plan.current.source === "stored" &&
1011
1737
  storedDesired !== null &&
1012
- gateMatchesStored({ ...plan.desired, workerEnv: undefined, reproduce: undefined }, storedDesired);
1738
+ gateMatchesStored({
1739
+ ...plan.desired,
1740
+ workerEnv: undefined,
1741
+ reproduce: undefined,
1742
+ dependencyInstall: undefined,
1743
+ ciDatabase: undefined,
1744
+ mustOrderPaths: undefined,
1745
+ workerDatabase: undefined,
1746
+ }, storedDesired);
1013
1747
  if (membersUnchanged) {
1014
1748
  reportUnsavedSettings(io, unsaved);
1015
1749
  io.log(" The gate itself already matched, so nothing was written.");
@@ -1017,6 +1751,39 @@ export async function storeConductorGate(io, access, plan) {
1017
1751
  }
1018
1752
  outcome = await putConductorGateProfile(access, stripped.request, io.postJson);
1019
1753
  }
1754
+ if (!outcome.ok && (outcome.refusal === "network" || outcome.refusal === "timeout" || outcome.refusal === "server")) {
1755
+ // BAPI-1638 — an ambiguous answer may have stored the gate. Reconcile with one
1756
+ // authoritative read before saying anything was or was not written; never retry blindly.
1757
+ // Compare against what was actually SENT: a narrowed request leaves out the fields it stripped.
1758
+ const sentDesired = {
1759
+ ...plan.desired,
1760
+ ...(workerSetupSkipped || unsaved?.workerDatabase === true ? { workerDatabase: undefined } : {}),
1761
+ ...(unsaved !== null
1762
+ ? { workerEnv: undefined, reproduce: undefined, dependencyInstall: undefined, ciDatabase: undefined, mustOrderPaths: undefined }
1763
+ : {}),
1764
+ };
1765
+ let reread = null;
1766
+ try {
1767
+ reread = await fetchConductorGateProfile(access, io.fetchJson);
1768
+ }
1769
+ catch {
1770
+ reread = null;
1771
+ }
1772
+ if (reread !== null && reread.revision > plan.current.revision && reread.confirmed && reread.profile !== null
1773
+ && gateMatchesStored(sentDesired, desiredFromStored(reread.profile), reread.profile)) {
1774
+ io.log(` stored repository gate: ${reread.profile.kind ?? "none"} (revision ${reread.revision}; confirmed by reading it back)`);
1775
+ if (unsaved !== null)
1776
+ reportUnsavedSettings(io, unsaved);
1777
+ else if (workerSetupSkipped)
1778
+ reportUnsavedSettings(io, { workerEnvNames: [], hintChecks: [], workerDatabase: true });
1779
+ return reread;
1780
+ }
1781
+ if (reread === null) {
1782
+ io.errorLog(`Repository gate write uncertain (${outcome.refusal}): ${GATE_WRITE_REFUSAL_TEXT[outcome.refusal]}`);
1783
+ io.errorLog(" It may or may not have been stored, and it could not be read back. Read the gate before retrying.");
1784
+ return null;
1785
+ }
1786
+ }
1020
1787
  if (!outcome.ok) {
1021
1788
  io.errorLog(`Repository gate not stored (${outcome.refusal}): ${GATE_WRITE_REFUSAL_TEXT[outcome.refusal]}`);
1022
1789
  const reason = outcome.detail?.reason;
@@ -1031,6 +1798,10 @@ export async function storeConductorGate(io, access, plan) {
1031
1798
  io.errorLog(" A worker variable was refused. Correct it, then confirm again; nothing was truncated or written.");
1032
1799
  }
1033
1800
  io.errorLog(` Nothing was written. ${describeStoredHeading(plan.current)}`);
1801
+ // BAPI-1551: what the owner typed for the declarations stays visible, so a
1802
+ // refused or failed write never silently loses it.
1803
+ for (const line of describeUnsentDeclarations(plan.write))
1804
+ io.errorLog(line);
1034
1805
  if (plan.current.confirmed && plan.current.profile !== null) {
1035
1806
  for (const line of describeGate(desiredFromStored(plan.current.profile)))
1036
1807
  io.errorLog(line);
@@ -1040,12 +1811,58 @@ export async function storeConductorGate(io, access, plan) {
1040
1811
  io.log(` stored repository gate: ${outcome.profile.profile?.kind ?? "none"} (revision ${outcome.profile.revision})`);
1041
1812
  if (unsaved !== null)
1042
1813
  reportUnsavedSettings(io, unsaved);
1814
+ else if (workerSetupSkipped)
1815
+ reportUnsavedSettings(io, { workerEnvNames: [], hintChecks: [], workerDatabase: true });
1043
1816
  return outcome.profile;
1044
1817
  }
1045
- /** BAPI-1520 — name the settings an older server could not store. Never a value. */
1818
+ /**
1819
+ * BAPI-1551 — the declaration edits a write carried, as the owner typed them, so
1820
+ * they can be re-entered after a refused or failed write. Printed only to the
1821
+ * owner's own installer output; the argv is the owner's own declaration.
1822
+ */
1823
+ function describeUnsentDeclarations(write) {
1824
+ const lines = [];
1825
+ if (write.dependency_install !== undefined) {
1826
+ const entries = write.dependency_install ?? [];
1827
+ if (entries.length === 0) {
1828
+ lines.push(" Not stored — dependency refresh: clear every stored entry");
1829
+ }
1830
+ else {
1831
+ lines.push(" Not stored — dependency refresh entries (re-enter them to keep them):");
1832
+ for (const e of entries) {
1833
+ lines.push(` ${terminalSafe(e.cwd)}, lockfiles ${e.lockfiles.map(terminalSafe).join(", ")}: ` +
1834
+ e.argv.map(terminalSafe).join(" "));
1835
+ }
1836
+ }
1837
+ }
1838
+ if (write.ci_database !== undefined) {
1839
+ lines.push(` Not stored — CI database behavior: ${write.ci_database ?? "unknown (reset)"}`);
1840
+ }
1841
+ if (write.worker_database !== undefined) {
1842
+ // Never the declaration itself: its identifiers and command stay in admin output.
1843
+ lines.push(" Not stored — worker database setup. Nothing else about setup or launch depends on it.");
1844
+ }
1845
+ if (write.must_order_paths !== undefined) {
1846
+ const paths = write.must_order_paths ?? [];
1847
+ lines.push(paths.length === 0
1848
+ ? " Not stored — must-order paths: clear every stored entry"
1849
+ : ` Not stored — must-order paths (re-enter them to keep them): ${paths.map(terminalSafe).join(", ")}`);
1850
+ }
1851
+ return lines;
1852
+ }
1853
+ /**
1854
+ * BAPI-1520 — name the settings an older server could not store. Worker-variable
1855
+ * values are never printed; BAPI-1551 declaration edits are, so they can be re-entered.
1856
+ */
1046
1857
  function reportUnsavedSettings(io, unsaved) {
1047
- if (unsaved.workerEnvNames.length === 0 && unsaved.hintChecks.length === 0)
1858
+ if (unsaved.workerEnvNames.length === 0 &&
1859
+ unsaved.hintChecks.length === 0 &&
1860
+ unsaved.dependencyInstall === undefined &&
1861
+ unsaved.ciDatabase === undefined &&
1862
+ unsaved.mustOrderPaths === undefined &&
1863
+ unsaved.workerDatabase === undefined) {
1048
1864
  return;
1865
+ }
1049
1866
  io.log(" ⚠ Partly stored: this server is older than the installer and cannot store these settings.");
1050
1867
  if (unsaved.workerEnvNames.length > 0) {
1051
1868
  io.log(` Not stored — worker variables: ${unsaved.workerEnvNames.map(terminalSafe).join(", ")}`);
@@ -1053,6 +1870,14 @@ function reportUnsavedSettings(io, unsaved) {
1053
1870
  if (unsaved.hintChecks.length > 0) {
1054
1871
  io.log(` Not stored — reproduction hints for: ${unsaved.hintChecks.map(terminalSafe).join(", ")}`);
1055
1872
  }
1873
+ for (const line of describeUnsentDeclarations({
1874
+ ...(unsaved.dependencyInstall !== undefined ? { dependency_install: unsaved.dependencyInstall } : {}),
1875
+ ...(unsaved.ciDatabase !== undefined ? { ci_database: unsaved.ciDatabase } : {}),
1876
+ ...(unsaved.mustOrderPaths !== undefined ? { must_order_paths: unsaved.mustOrderPaths } : {}),
1877
+ ...(unsaved.workerDatabase !== undefined ? { worker_database: { mode: "none" } } : {}),
1878
+ })) {
1879
+ io.log(line);
1880
+ }
1056
1881
  io.log(" Upgrade the Bridge API deployment, then re-run to store them.");
1057
1882
  }
1058
1883
  // ---------------------------------------------------------------------------
@@ -1100,9 +1925,33 @@ function reportJob(io, job) {
1100
1925
  return "qualified";
1101
1926
  }
1102
1927
  if (job.job_status === "succeeded") {
1928
+ // BAPI-1637: the phase is the server's reading of the stored result. The gate
1929
+ // stays unqualified in every branch, and each says so.
1930
+ if (job.phase === "dependency_preparation_failed") {
1931
+ io.errorLog(` Failed — ${DEPENDENCY_INSTALL_FAILED_TEXT} The local gate stays unqualified, so unattended ` +
1932
+ "auto-merge stays closed.");
1933
+ io.errorLog(` ${DEPENDENCY_INSTALL_REPAIR_TEXT}`);
1934
+ io.errorLog(` Qualify again: ${PRINTED_QUALIFY_GATE_COMMAND}`);
1935
+ return "failed";
1936
+ }
1937
+ if (job.phase === "could_not_start") {
1938
+ io.errorLog(` Failed — ${COULD_NOT_START_TEXT} The local gate stays unqualified, so unattended auto-merge ` +
1939
+ "stays closed.");
1940
+ io.errorLog(` ${CHANGE_TEST_COMMAND_HINT} Then qualify again: ${PRINTED_QUALIFY_GATE_COMMAND}`);
1941
+ return "failed";
1942
+ }
1943
+ if (job.phase === null && job.dependency_install_declared === true) {
1944
+ io.errorLog(` Failed — ${PREPARATION_UNCERTAIN_TEXT} The local gate stays unqualified, so unattended ` +
1945
+ "auto-merge stays closed.");
1946
+ io.errorLog(` ${PREPARATION_UNCERTAIN_REPAIR_TEXT} Then qualify again: ${PRINTED_QUALIFY_GATE_COMMAND}`);
1947
+ return "failed";
1948
+ }
1103
1949
  io.errorLog(" Failed — a confirmed command did not pass under the executor. The installation itself " +
1104
1950
  "succeeded, but the local gate stays unqualified, so unattended auto-merge stays closed.");
1105
1951
  io.errorLog(` Fix the command, then qualify again: ${PRINTED_QUALIFY_GATE_COMMAND}`);
1952
+ if (job.phase === "ran_and_failed" && job.dependency_install_declared === false) {
1953
+ io.errorLog(` ${MISSING_INSTALL_TEXT}`);
1954
+ }
1106
1955
  return "failed";
1107
1956
  }
1108
1957
  io.errorLog(` Failed — the executor could not run job ${job.job_id} (no clean default-branch checkout, ` +
@@ -1193,6 +2042,268 @@ export async function runConductorGateQualification(io, access, gateDeps, input)
1193
2042
  return reportJob(io, latest);
1194
2043
  }
1195
2044
  // ---------------------------------------------------------------------------
2045
+ // BAPI-1603: the learned test command, proven by a server-owned trial
2046
+ // ---------------------------------------------------------------------------
2047
+ //
2048
+ // Setup never asks for a test command and never stores one itself. It asks the
2049
+ // server to find the command from the repository's learned prose (or to validate
2050
+ // the owner's `--test-command`), the server queues one TRIAL qualification, the
2051
+ // short-lived executor drains it, and the server promotes the local member only if
2052
+ // every command passes. Success is read from the validated job and a fresh read of
2053
+ // the gate profile, never from the executor's exit status, and the client writes no
2054
+ // local member. Anything uncertain is reconciled by re-reading authoritative state
2055
+ // before anything else happens, and the request is never repeated automatically.
2056
+ /** How often a running trial prints one plain progress line. */
2057
+ export const LEARNED_TRIAL_PROGRESS_INTERVAL_MS = 10_000;
2058
+ /** The commands a profile's local members run, by digest, in order. */
2059
+ function localDigests(profile) {
2060
+ return (profile?.local_commands ?? []).map((c) => c.digest).join(",");
2061
+ }
2062
+ /**
2063
+ * Whether `read` shows the trial's promotion: a confirmed profile with local
2064
+ * commands that differ from the ones the trial started with, qualified at its own
2065
+ * revision, past the revision the trial was bound to.
2066
+ */
2067
+ function promotionObserved(read, input) {
2068
+ if (read === null || !read.confirmed || read.profile === null)
2069
+ return false;
2070
+ if (read.profile.local_commands.length === 0)
2071
+ return false;
2072
+ if (read.qualification_state !== "qualified")
2073
+ return false;
2074
+ if (read.revision <= input.current.revision)
2075
+ return false;
2076
+ return localDigests(read.profile) !== localDigests(input.current.profile);
2077
+ }
2078
+ async function readGateProfileOrNull(io, access) {
2079
+ try {
2080
+ return await fetchConductorGateProfile(access, io.fetchJson);
2081
+ }
2082
+ catch {
2083
+ return null;
2084
+ }
2085
+ }
2086
+ /**
2087
+ * Ask the server for the learned (or owner-supplied) test command, drain the trial
2088
+ * it queues, and report only what the server and a fresh profile read confirm.
2089
+ * Never throws and never writes a gate: an unqualified, stale, or could-not-run
2090
+ * trial leaves the profile exactly as the server holds it.
2091
+ */
2092
+ export async function runLearnedTestCommandTrial(io, access, gateDeps, input) {
2093
+ const requestedSource = input.ownerCommand !== undefined ? "owner" : "learned";
2094
+ const posted = await requestConductorLearnedTestCommand(access, {
2095
+ expectedRevision: input.current.revision,
2096
+ ...(input.candidates !== undefined ? { candidates: input.candidates } : {}),
2097
+ ...(input.ownerCommand !== undefined ? { ownerCommand: input.ownerCommand } : {}),
2098
+ }, io.postJson);
2099
+ switch (posted.kind) {
2100
+ case "not_needed":
2101
+ case "stale_revision":
2102
+ case "unsupported":
2103
+ return { status: posted.kind };
2104
+ case "state_unavailable":
2105
+ return { status: "unavailable" };
2106
+ case "refused":
2107
+ return { status: "refused", reason: posted.reason };
2108
+ case "no_command":
2109
+ return { status: "no_command", source: posted.source, reason: posted.reason };
2110
+ case "uncertain":
2111
+ case "malformed": {
2112
+ // The request may have queued a trial and even finished it. Read the
2113
+ // authoritative profile before anything else.
2114
+ const read = await readGateProfileOrNull(io, access);
2115
+ if (promotionObserved(read, input)) {
2116
+ return { status: "promoted", source: requestedSource, commands: [], profile: read };
2117
+ }
2118
+ return { status: "uncertain", reason: "request_unclear", profile: read };
2119
+ }
2120
+ case "qualification_queued":
2121
+ break;
2122
+ }
2123
+ const { source, jobId, commands } = posted;
2124
+ const reconcile = async (reason) => {
2125
+ const read = await readGateProfileOrNull(io, access);
2126
+ if (promotionObserved(read, input))
2127
+ return { status: "promoted", source, commands, profile: read };
2128
+ return { status: "uncertain", reason, profile: read };
2129
+ };
2130
+ let job = await readJob(io, access, jobId);
2131
+ if (job === null)
2132
+ return reconcile("job_unreadable");
2133
+ if (!isTerminal(job)) {
2134
+ const runExecutor = gateDeps?.runQualificationExecutor;
2135
+ if (!runExecutor) {
2136
+ io.errorLog(" The trial is queued and needs a repository-wide executor to run it:");
2137
+ executorRemedy(io);
2138
+ return reconcile("executor_not_run");
2139
+ }
2140
+ io.log(" Running it once on this computer, in a clean checkout of your default branch…");
2141
+ // One progress notice covers the whole wait: the run itself and the polling that follows it.
2142
+ const progressTimer = gateDeps?.progressTimer ?? {
2143
+ ...createSetupProgressTimer(),
2144
+ intervalMs: gateDeps?.progressIntervalMs ?? LEARNED_TRIAL_PROGRESS_INTERVAL_MS,
2145
+ };
2146
+ const { run, latest } = await withSetupProgress("checking the test command", async () => {
2147
+ let ran;
2148
+ try {
2149
+ ran = await runExecutor({ repoName: access.repoName, baseUrl: input.baseUrl });
2150
+ }
2151
+ catch {
2152
+ ran = { started: false, exitCode: 1 };
2153
+ }
2154
+ // The exit code proves nothing: read the server.
2155
+ const now = gateDeps?.now ?? (() => Date.now());
2156
+ const sleep = gateDeps?.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
2157
+ const deadline = now() + QUALIFICATION_OBSERVATION_BUDGET_MS;
2158
+ let seen = null;
2159
+ while (true) {
2160
+ const read = await readJob(io, access, jobId);
2161
+ if (read !== null)
2162
+ seen = read;
2163
+ if (seen !== null && isTerminal(seen))
2164
+ break;
2165
+ // A queued job after the executor returned will not move on its own here.
2166
+ if (seen !== null && seen.job_status === "queued")
2167
+ break;
2168
+ const remaining = deadline - now();
2169
+ if (remaining <= 0)
2170
+ break;
2171
+ await sleep(Math.min(QUALIFICATION_OBSERVATION_INTERVAL_MS, remaining));
2172
+ }
2173
+ return { run: ran, latest: seen };
2174
+ }, { errorLog: io.errorLog, timer: progressTimer });
2175
+ if (latest === null)
2176
+ return reconcile(run.started ? "job_unreadable" : "executor_not_run");
2177
+ if (!isTerminal(latest)) {
2178
+ return reconcile(latest.job_status === "queued" ? (run.started ? "executor_failed" : "executor_not_run") : "still_running");
2179
+ }
2180
+ job = latest;
2181
+ }
2182
+ const read = await readGateProfileOrNull(io, access);
2183
+ // BAPI-1637: the server's own read of the finished job, carried as it came.
2184
+ const evidence = {
2185
+ phase: job.phase,
2186
+ dependencyInstallDeclared: job.dependency_install_declared,
2187
+ };
2188
+ if (job.qualification_state === "stale" || job.failure === "stale") {
2189
+ return { status: "stale", source, profile: read, evidence };
2190
+ }
2191
+ if (job.job_status === "succeeded" && job.qualification_state === "qualified") {
2192
+ if (promotionObserved(read, input))
2193
+ return { status: "promoted", source, commands, profile: read, evidence };
2194
+ return { status: "uncertain", reason: "result_unreadable", profile: read, evidence };
2195
+ }
2196
+ if (job.job_status === "succeeded" && job.qualification_state === "unqualified") {
2197
+ return { status: "unqualified", source, profile: read, evidence };
2198
+ }
2199
+ if (job.job_status === "succeeded") {
2200
+ // Finished without a verdict: only a promotion the profile shows can settle it.
2201
+ if (promotionObserved(read, input))
2202
+ return { status: "promoted", source, commands, profile: read, evidence };
2203
+ return { status: "uncertain", reason: "result_unreadable", profile: read, evidence };
2204
+ }
2205
+ return { status: "could_not_run", source, profile: read, evidence };
2206
+ }
2207
+ // BAPI-1637 — fixed wording for each completed phase. None of it names a command,
2208
+ // an install step, a path, or any output: the server's phase token selects the text.
2209
+ const DEPENDENCY_INSTALL_FAILED_TEXT = "The dependency install failed, so the tests did not run.";
2210
+ const DEPENDENCY_INSTALL_REPAIR_TEXT = "Correct the install step (for example, a lockfile that no longer matches the manifest), then run setup again.";
2211
+ const COULD_NOT_START_TEXT = "The test command could not be started (the program could not launch).";
2212
+ const MISSING_INSTALL_TEXT = "No install step was declared, so the dependencies may be missing. Run setup again and accept the proposed install step.";
2213
+ const PREPARATION_UNCERTAIN_TEXT = "Bridge cannot tell whether the dependency install ran before the tests, so it cannot say why the check did not pass.";
2214
+ const PREPARATION_UNCERTAIN_REPAIR_TEXT = "Update the Bridge executor to the latest version, then run setup again.";
2215
+ /** The instruction every successful and failed trial line ends with. */
2216
+ const CHANGE_TEST_COMMAND_HINT = 'Change it with --test-command "<your command>".';
2217
+ /**
2218
+ * Print one trial outcome in plain words. The validated command is named ONLY on
2219
+ * the successful path, and only as the server returned it; no other outcome prints
2220
+ * a command, executor output, or a raw server response.
2221
+ */
2222
+ export function reportLearnedCommandTrial(io, result) {
2223
+ const learned = (source) => source === "owner" ? "you gave it with --test-command" : "it learned from your repository";
2224
+ switch (result.status) {
2225
+ case "promoted": {
2226
+ const named = result.commands.map((c) => `\`${c.command.replace(/[\u0000-\u001F\u007F]/g, "?")}\``).join(", ");
2227
+ io.log(named.length > 0
2228
+ ? ` Bridge will run ${named} before each merge. It is the command ${learned(result.source)}, and Bridge ` +
2229
+ `checked it by running it once. ${CHANGE_TEST_COMMAND_HINT}`
2230
+ : ` Bridge stored a test command ${learned(result.source)} and checked it by running it once. ` +
2231
+ CHANGE_TEST_COMMAND_HINT);
2232
+ return;
2233
+ }
2234
+ case "not_needed":
2235
+ io.log(" Bridge already has a test command for this repository, so it did not look for another.");
2236
+ return;
2237
+ case "no_command":
2238
+ io.log(` Bridge found no test command to try (${NO_COMMAND_TEXT[result.reason]}). It stored none. ` +
2239
+ "Give one with --test-command \"<your command>\" and Bridge will check it by running it once.");
2240
+ return;
2241
+ case "unqualified": {
2242
+ const { phase, dependencyInstallDeclared } = result.evidence ?? { phase: null, dependencyInstallDeclared: null };
2243
+ if (phase === "dependency_preparation_failed") {
2244
+ io.log(` ${DEPENDENCY_INSTALL_FAILED_TEXT} Bridge stored no learned command. ${DEPENDENCY_INSTALL_REPAIR_TEXT}`);
2245
+ return;
2246
+ }
2247
+ if (phase === "could_not_start") {
2248
+ io.log(` ${COULD_NOT_START_TEXT} Bridge stored none. ${CHANGE_TEST_COMMAND_HINT}`);
2249
+ return;
2250
+ }
2251
+ if (phase === null && dependencyInstallDeclared === true) {
2252
+ io.log(` ${PREPARATION_UNCERTAIN_TEXT} Bridge stored none. ${PREPARATION_UNCERTAIN_REPAIR_TEXT}`);
2253
+ return;
2254
+ }
2255
+ io.log(" The test command did not pass when Bridge ran it once, so Bridge stored none. " +
2256
+ "Fix the failing tests, or give another command with --test-command \"<your command>\".");
2257
+ if (phase === "ran_and_failed" && dependencyInstallDeclared === false)
2258
+ io.log(` ${MISSING_INSTALL_TEXT}`);
2259
+ return;
2260
+ }
2261
+ case "stale":
2262
+ io.log(" The gate changed while the test command was being checked, so Bridge stored none. Run setup again.");
2263
+ return;
2264
+ case "could_not_run":
2265
+ io.log(" Bridge could not run the test command (no clean checkout of your default branch, or the run was " +
2266
+ "interrupted), so it stored none. Run setup again.");
2267
+ return;
2268
+ case "stale_revision":
2269
+ io.log(" The gate changed before the test command could be checked, so nothing was started. Run setup again.");
2270
+ return;
2271
+ case "unsupported":
2272
+ io.log(" This Bridge server cannot learn a test command yet, so Bridge skipped it. Update the Bridge API to use it.");
2273
+ return;
2274
+ case "unavailable":
2275
+ io.log(" Bridge could not prepare the test command right now and started nothing. Run setup again shortly.");
2276
+ return;
2277
+ case "refused":
2278
+ io.log(result.reason === "unauthorized"
2279
+ ? " This key cannot ask Bridge to check a test command (an administrator key is needed), so Bridge skipped it."
2280
+ : " Bridge's server refused the test command request, so Bridge skipped it.");
2281
+ return;
2282
+ case "uncertain":
2283
+ io.log(` Bridge cannot tell whether the test command was stored (${UNCERTAIN_TEXT[result.reason]}). ` +
2284
+ "It will not try again on its own. Run setup again to read what the server holds.");
2285
+ return;
2286
+ }
2287
+ }
2288
+ const NO_COMMAND_TEXT = Object.freeze({
2289
+ no_testing_instructions: "the repository has no learned testing instructions",
2290
+ llm_unavailable: "the server could not read them just now",
2291
+ llm_output_invalid: "the server could not turn them into a command",
2292
+ no_candidates: "they name no command",
2293
+ working_directory_unsupported: "the command must run from a subdirectory, which a gate cannot do",
2294
+ not_plain_argv: "the command is not a plain program and arguments",
2295
+ command_not_allowed: "the command is not allowed",
2296
+ invalid_command: "the command is not valid",
2297
+ });
2298
+ const UNCERTAIN_TEXT = Object.freeze({
2299
+ request_unclear: "the request did not answer clearly",
2300
+ executor_not_run: "no executor ran the check",
2301
+ executor_failed: "the executor did not finish the check",
2302
+ job_unreadable: "the check's state could not be read",
2303
+ still_running: "the check was still running",
2304
+ result_unreadable: "the result could not be confirmed",
2305
+ });
2306
+ // ---------------------------------------------------------------------------
1196
2307
  // Standalone actions: --clear-gate and --qualify-gate
1197
2308
  // ---------------------------------------------------------------------------
1198
2309
  /** `--clear-gate`: BAPI-1390's clear action under the revision compare-and-swap. */
@@ -1249,7 +2360,7 @@ export async function runQualifyConductorGate(io, access, gateDeps, options) {
1249
2360
  }
1250
2361
  if (!current.confirmed || current.profile === null) {
1251
2362
  io.errorLog("No confirmed repository gate is stored, so there is nothing to qualify. Confirm one first " +
1252
- "with install-bridge conductor. Nothing was queued.");
2363
+ "with install epic-implementer. Nothing was queued.");
1253
2364
  return 1;
1254
2365
  }
1255
2366
  const profile = current.profile;
@@ -1341,6 +2452,31 @@ const COVERAGE_NEXT_STEP = Object.freeze({
1341
2452
  no_workflows: "add a workflow with a pull_request trigger whose branches list includes 'epic/**'.",
1342
2453
  });
1343
2454
  const GENERIC_COVERAGE_NEXT_STEP = "check by hand that a pull_request trigger includes 'epic/**'.";
2455
+ /** BAPI-1654 — each coverage state and reason in plain words, so no internal token reaches the owner. */
2456
+ const PLAIN_COVERAGE = Object.freeze({
2457
+ covers: "runs on epic-branch PRs",
2458
+ does_not_cover: "does not run on epic-branch PRs",
2459
+ could_not_tell: "could not be confirmed to run on epic-branch PRs",
2460
+ });
2461
+ const PLAIN_COVERAGE_REASON = Object.freeze({
2462
+ pr_trigger_covers: "its pull_request trigger includes epic branches",
2463
+ no_pr_trigger: "it has no pull_request trigger",
2464
+ branch_filter_excludes_epic: "its pull_request branch list leaves out epic branches",
2465
+ path_filter: "a paths filter decides whether it starts",
2466
+ branch_filter_uncertain: "its branch filter could not be matched to epic branches with certainty",
2467
+ types_filter: "its pull_request types leave out opened or synchronize",
2468
+ indirect_trigger: "another workflow starts it",
2469
+ reusable_workflow_job: "a job calls a reusable workflow",
2470
+ unparseable: "it could not be read as a workflow",
2471
+ unsupported_structure: "it uses YAML that Bridge does not read confidently",
2472
+ listing_failed: "the workflow folder could not be listed",
2473
+ file_limit_reached: "there are too many workflow files to read",
2474
+ read_failed: "it could not be read",
2475
+ no_workflows: "there are no workflow files",
2476
+ });
2477
+ function plainCoverageReason(reason) {
2478
+ return PLAIN_COVERAGE_REASON[reason] ?? "Bridge could not tell why";
2479
+ }
1344
2480
  function coverageNextStep(reason) {
1345
2481
  return COVERAGE_NEXT_STEP[reason] ?? GENERIC_COVERAGE_NEXT_STEP;
1346
2482
  }
@@ -1418,11 +2554,11 @@ export function renderEpicBranchCiFindings(io, coverage, rules) {
1418
2554
  if (coverage.coverage !== "covers" && unresolved.length > 0) {
1419
2555
  io.log(" Workflows that do not clearly cover epic-branch PRs:");
1420
2556
  for (const w of unresolved) {
1421
- io.log(` ${w.path}: ${w.coverage} (${w.reason}) — next step: ${coverageNextStep(w.reason)}`);
2557
+ io.log(` ${w.path}: ${PLAIN_COVERAGE[w.coverage]}, because ${plainCoverageReason(w.reason)} — next step: ${coverageNextStep(w.reason)}`);
1422
2558
  }
1423
2559
  }
1424
2560
  else if (coverage.coverage !== "covers") {
1425
- io.log(` (${coverage.reason}) — next step: ${coverageNextStep(coverage.reason)}`);
2561
+ io.log(` ${plainCoverageReason(coverage.reason)} — next step: ${coverageNextStep(coverage.reason)}`);
1426
2562
  }
1427
2563
  }
1428
2564
  /**
@@ -1437,7 +2573,27 @@ export function renderEpicBranchCiFindings(io, coverage, rules) {
1437
2573
  *
1438
2574
  * Returns the decision, or null when none was made.
1439
2575
  */
1440
- export async function resolveEpicBranchCiDecision(io, flag) {
2576
+ export async function resolveEpicBranchCiDecision(io, flag,
2577
+ /**
2578
+ * BAPI-1604 — when set, the decision is read from the inspected coverage instead of
2579
+ * asked: only a confirmed `covers` becomes an inferred `include`. Anything else records
2580
+ * nothing, asks nothing, and says how to record a choice. An explicit flag still wins.
2581
+ */
2582
+ inferFrom) {
2583
+ if (inferFrom !== undefined) {
2584
+ if (flag !== null) {
2585
+ io.log(` Using --epic-branch-ci-decision=${flag}.`);
2586
+ return flag;
2587
+ }
2588
+ if (inferFrom === "covers") {
2589
+ io.log(" Epic-branch CI: include (a workflow runs on epic-branch PRs).");
2590
+ return "include";
2591
+ }
2592
+ io.log(" No epic-branch CI decision was recorded: Bridge could not confirm that a workflow runs on epic-branch PRs. " +
2593
+ "To record one, pass --epic-branch-ci-decision=include or --epic-branch-ci-decision=decline. " +
2594
+ "Until one is recorded, runs behave as include.");
2595
+ return null;
2596
+ }
1441
2597
  io.log(" Include: each child waits for the checks that run on its epic-branch PR before it merges.");
1442
2598
  io.log(" Decline: children merge into the epic branch without waiting for checks that never run there. " +
1443
2599
  "Problems then surface only at the human-gated integration PR into the base branch.");
@@ -1474,7 +2630,13 @@ function printExemptionManualSteps(io, ownerRepo, branch) {
1474
2630
  * include/decline choice and warning-toned. A ruleset is changed only after an
1475
2631
  * explicit typed "yes", a passed scope check, and a confirming re-read.
1476
2632
  */
1477
- export async function offerApprovalExemption(io, seams, run, ownerRepo, branch, rules) {
2633
+ export async function offerApprovalExemption(io, seams, run, ownerRepo, branch, rules,
2634
+ /**
2635
+ * BAPI-1638 — an explicit decision from the shared apply. `approve` stands in
2636
+ * for the typed `yes` (the answers path never prompts); `decline` changes
2637
+ * nothing. Absent keeps the interactive typed-`yes` question exactly as before.
2638
+ */
2639
+ decision) {
1478
2640
  const approvals = rules?.approvalsRequired ?? "could_not_tell";
1479
2641
  if (approvals === "no")
1480
2642
  return "not_needed";
@@ -1491,12 +2653,14 @@ export async function offerApprovalExemption(io, seams, run, ownerRepo, branch,
1491
2653
  "Whether it can is unknown: check the ruleset's bypass list.");
1492
2654
  io.log(" Bridge can exclude epic/** from this approval rule with your own gh login. It changes only the " +
1493
2655
  "ruleset's excluded branches, and only for a repository ruleset that holds nothing but the approval rule.");
1494
- if (!io.promptLine) {
2656
+ if (decision === undefined && !io.promptLine) {
1495
2657
  io.log(" This run cannot prompt, so nothing was changed. The --epic-branch-ci-decision flag never grants this.");
1496
2658
  printExemptionManualSteps(io, ownerRepo, branch);
1497
2659
  return "printed_steps";
1498
2660
  }
1499
- const consent = await ask(io, "Exclude epic/** from the approval rule now? Type yes to change it [y/N]: ");
2661
+ const consent = decision !== undefined
2662
+ ? decision === "approve"
2663
+ : await ask(io, "Exclude epic/** from the approval rule now? Type yes to change it [y/N]: ");
1500
2664
  if (!consent) {
1501
2665
  io.log(" Not changed.");
1502
2666
  printExemptionManualSteps(io, ownerRepo, branch);
@@ -1532,35 +2696,16 @@ export async function offerApprovalExemption(io, seams, run, ownerRepo, branch,
1532
2696
  return "could_not_tell";
1533
2697
  }
1534
2698
  /**
1535
- * Run the epic-branch CI step: detect the provider, inspect workflow triggers
1536
- * and epic-branch rules, print findings, resolve include/decline, offer the
1537
- * approval exemption, and record an explicit decision with its evidence.
1538
- *
1539
- * Never blocks the install: a failed read or write prints a warning and the
1540
- * step returns. It never writes `decline` unless the owner chose it.
2699
+ * BAPI-1638 — collect the epic-branch CI evidence: detect the provider, find an
2700
+ * example epic branch, inspect workflow coverage, and read the epic-branch rules.
2701
+ * Read-only. A failed read is recorded as `could_not_tell` (or `null` rules),
2702
+ * never guessed. The exemption's own scope check runs only after approval,
2703
+ * inside {@link offerApprovalExemption}.
1541
2704
  */
1542
- export async function runEpicBranchCiInspection(io, access, gateDeps, options) {
1543
- const result = {
1544
- status: "completed",
1545
- coverage: null,
1546
- rules: null,
1547
- exemptionOutcome: null,
1548
- decision: null,
1549
- evidence: null,
1550
- recorded: false,
1551
- manualAction: null,
1552
- };
1553
- io.log("");
1554
- io.log("Epic-branch CI — do checks run on pull requests into epic branches?");
2705
+ export async function collectEpicBranchCi(gateDeps) {
1555
2706
  const seams = gateDeps?.epicBranchCi;
1556
- if (!seams) {
1557
- io.log(" skipped — this caller supplied no epic-branch CI inspection seams. Nothing was recorded.");
1558
- return { ...result, status: "skipped_no_seams" };
1559
- }
1560
- if (options.dryRun) {
1561
- io.log(" Dry run — would inspect workflow triggers and epic-branch rules, then ask include or decline. Nothing was recorded.");
1562
- return { ...result, status: "skipped_dry_run" };
1563
- }
2707
+ if (!seams)
2708
+ return { status: "skipped_no_seams" };
1564
2709
  let provider;
1565
2710
  try {
1566
2711
  provider = await seams.detectProvider();
@@ -1568,12 +2713,8 @@ export async function runEpicBranchCiInspection(io, access, gateDeps, options) {
1568
2713
  catch {
1569
2714
  provider = { kind: "unknown" };
1570
2715
  }
1571
- if (provider.kind !== "github") {
1572
- io.log(" The epic-branch CI inspection is GitHub-only, and this repository's remote is not on github.com" +
1573
- (provider.kind === "unknown" ? " (or could not be read)" : "") +
1574
- ". No epic-branch CI decision was recorded.");
1575
- return { ...result, status: "skipped_not_github" };
1576
- }
2716
+ if (provider.kind !== "github")
2717
+ return { status: "skipped_not_github", provider: provider.kind };
1577
2718
  const ownerRepo = provider.ownerRepo;
1578
2719
  const run = safeGhRunner(seams.runGh);
1579
2720
  let branch = EPIC_BRANCH_CI_PROBE_BRANCH;
@@ -1599,11 +2740,63 @@ export async function runEpicBranchCiInspection(io, access, gateDeps, options) {
1599
2740
  catch {
1600
2741
  rules = null;
1601
2742
  }
2743
+ return { status: "collected", ownerRepo, branch, coverage, rules };
2744
+ }
2745
+ /**
2746
+ * BAPI-1638 — the decision write, alone: `putEpicBranchCiDecision` (or the test
2747
+ * override). Called only with an explicit or coverage-confirmed decision.
2748
+ */
2749
+ export async function applyEpicBranchCiDecision(io, access, seams, request) {
2750
+ const record = seams.recordDecision ??
2751
+ ((acc, body) => putEpicBranchCiDecision(acc, acc.repoName, body, io.postJson));
2752
+ try {
2753
+ await record(access, request);
2754
+ return { recorded: true };
2755
+ }
2756
+ catch (err) {
2757
+ return { recorded: false, kind: err instanceof ConductorBridgeApiError ? err.kind : "error" };
2758
+ }
2759
+ }
2760
+ export async function runEpicBranchCiInspection(io, access, gateDeps, options) {
2761
+ const result = {
2762
+ status: "completed",
2763
+ coverage: null,
2764
+ rules: null,
2765
+ exemptionOutcome: null,
2766
+ decision: null,
2767
+ evidence: null,
2768
+ recorded: false,
2769
+ manualAction: null,
2770
+ };
2771
+ io.log("");
2772
+ io.log("Epic-branch CI — do checks run on pull requests into epic branches?");
2773
+ const seams = gateDeps?.epicBranchCi;
2774
+ if (!seams) {
2775
+ io.log(" skipped — this caller supplied no epic-branch CI inspection seams. Nothing was recorded.");
2776
+ return { ...result, status: "skipped_no_seams" };
2777
+ }
2778
+ if (options.dryRun) {
2779
+ io.log(" Dry run — would inspect workflow triggers and epic-branch rules, then ask include or decline. Nothing was recorded.");
2780
+ return { ...result, status: "skipped_dry_run" };
2781
+ }
2782
+ const collected = options.collected ?? (await collectEpicBranchCi(gateDeps));
2783
+ if (collected.status === "skipped_no_seams") {
2784
+ io.log(" skipped — this caller supplied no epic-branch CI inspection seams. Nothing was recorded.");
2785
+ return { ...result, status: "skipped_no_seams" };
2786
+ }
2787
+ if (collected.status === "skipped_not_github") {
2788
+ io.log(" The epic-branch CI inspection is GitHub-only, and this repository's remote is not on github.com" +
2789
+ (collected.provider === "unknown" ? " (or could not be read)" : "") +
2790
+ ". No epic-branch CI decision was recorded.");
2791
+ return { ...result, status: "skipped_not_github" };
2792
+ }
2793
+ const { ownerRepo, branch, coverage, rules } = collected;
2794
+ const run = safeGhRunner(seams.runGh);
1602
2795
  result.coverage = coverage.coverage;
1603
2796
  result.rules = rules;
1604
2797
  renderEpicBranchCiFindings(io, coverage, rules);
1605
- const decision = await resolveEpicBranchCiDecision(io, options.decisionFlag);
1606
- const exemptionOutcome = await offerApprovalExemption(io, seams, run, ownerRepo, branch, rules);
2798
+ const decision = await resolveEpicBranchCiDecision(io, options.decisionFlag, options.inferFromCoverage === true ? coverage.coverage : undefined);
2799
+ const exemptionOutcome = await offerApprovalExemption(io, seams, run, ownerRepo, branch, rules, options.exemptionDecision);
1607
2800
  const evidence = buildEpicBranchCiEvidence(coverage.coverage, rules, exemptionOutcome);
1608
2801
  result.decision = decision;
1609
2802
  result.exemptionOutcome = exemptionOutcome;
@@ -1612,15 +2805,17 @@ export async function runEpicBranchCiInspection(io, access, gateDeps, options) {
1612
2805
  // the reason was already printed. It is not added to the manual steps.
1613
2806
  if (decision === null)
1614
2807
  return result;
1615
- const record = seams.recordDecision ??
1616
- ((acc, request) => putEpicBranchCiDecision(acc, acc.repoName, request, io.postJson));
1617
- try {
1618
- await record(access, { decision, evidence });
2808
+ if (options.recordedDecision !== undefined && options.recordedDecision === decision) {
2809
+ io.log(` epic-branch CI decision already recorded: ${decision}`);
2810
+ return { ...result, recorded: true, unchanged: true };
2811
+ }
2812
+ const written = await applyEpicBranchCiDecision(io, access, seams, { decision, evidence });
2813
+ if (written.recorded) {
1619
2814
  result.recorded = true;
1620
2815
  io.log(` recorded epic-branch CI decision: ${decision}`);
1621
2816
  }
1622
- catch (err) {
1623
- const kind = err instanceof ConductorBridgeApiError ? err.kind : "error";
2817
+ else {
2818
+ const kind = written.kind;
1624
2819
  io.errorLog(`Warning: the epic-branch CI decision could not be recorded (${kind}). The install continues; ` +
1625
2820
  "re-run it to record the decision.");
1626
2821
  result.manualAction =