@bridge_gpt/mcp-server 0.2.72 → 0.2.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +15 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-config.js +7 -1
  5. package/build/bridge-permissions.js +30 -0
  6. package/build/ci-system-detection.js +50 -0
  7. package/build/ci-trigger-adapters.js +631 -0
  8. package/build/ci-trigger-install.js +106 -0
  9. package/build/codex-launcher-pin.js +33 -2
  10. package/build/codex-skill-adapter.js +3 -1
  11. package/build/command-host.js +33 -0
  12. package/build/command-provisioning.js +4 -3
  13. package/build/commands.generated.js +7 -6
  14. package/build/conductor/bridge-api-client.js +867 -35
  15. package/build/conductor/bring-up-facts.js +18 -5
  16. package/build/conductor/command-drift-production.js +42 -17
  17. package/build/conductor/command-drift.js +48 -1
  18. package/build/conductor/declare-blocked.js +554 -0
  19. package/build/conductor/declared-extras.js +335 -0
  20. package/build/conductor/doctor.js +108 -21
  21. package/build/conductor/driver-commands.js +141 -0
  22. package/build/conductor/driver-guard.js +277 -0
  23. package/build/conductor/driver-lapse.js +321 -0
  24. package/build/conductor/driver-pass-output.js +104 -0
  25. package/build/conductor/driver-pass.js +571 -0
  26. package/build/conductor/driver-register.js +176 -0
  27. package/build/conductor/driver-release.js +174 -0
  28. package/build/conductor/driver-session-state.js +315 -0
  29. package/build/conductor/epic-branch-ci-inspection.js +281 -43
  30. package/build/conductor/epic-implementer-cli.js +199 -15
  31. package/build/conductor/epic-server-database.js +162 -0
  32. package/build/conductor/epic-server-guidance.js +278 -0
  33. package/build/conductor/epic-server-journal.js +239 -0
  34. package/build/conductor/epic-server-processes.js +324 -0
  35. package/build/conductor/epic-server-recipe.js +397 -0
  36. package/build/conductor/epic-server-runtime.js +1207 -0
  37. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  38. package/build/conductor/epic-server-sfcc.js +85 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +647 -0
  41. package/build/conductor/gate-discovery.js +196 -11
  42. package/build/conductor/gate-settings-review.js +261 -4
  43. package/build/conductor/launch-need-probes.js +6 -53
  44. package/build/conductor/launch-plan.js +313 -156
  45. package/build/conductor/prerequisite-inputs.js +879 -45
  46. package/build/conductor/readiness-assessment.js +16 -1
  47. package/build/conductor/readiness-cli.js +20 -9
  48. package/build/conductor/readiness-prerequisites.js +28 -9
  49. package/build/conductor/readiness-sections.js +133 -126
  50. package/build/conductor/readiness.js +1 -1
  51. package/build/conductor/recovery-cli.js +13 -2
  52. package/build/conductor/tools.js +6 -5
  53. package/build/conductor/wait-run-attention.js +2 -2
  54. package/build/conductor/wait-run-cli.js +208 -22
  55. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  56. package/build/conductor/worker-setup-tally.js +27 -0
  57. package/build/credential-delivery.js +280 -0
  58. package/build/credential-launch-safety.js +142 -0
  59. package/build/credential-materialization.js +91 -16
  60. package/build/credential-references-node-deps.js +29 -0
  61. package/build/credential-references.js +1394 -0
  62. package/build/credential-references.test-fixtures.js +211 -0
  63. package/build/credential-scan-conventions.js +145 -0
  64. package/build/credential-scan.js +517 -0
  65. package/build/credential-store.js +121 -1
  66. package/build/credentials-cli.js +252 -3
  67. package/build/dependency-install-declarations.js +102 -1
  68. package/build/docs.generated.js +10 -3
  69. package/build/doctor.js +95 -3
  70. package/build/drive-epic-help.js +21 -2
  71. package/build/drive-epic.js +2095 -375
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +157 -0
  74. package/build/epic-capability-statement.js +175 -0
  75. package/build/epic-ci-workflow-drift.js +77 -23
  76. package/build/epic-ci-workflow-install.js +137 -44
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow-v3.js +273 -0
  79. package/build/epic-ci-workflow.js +165 -18
  80. package/build/epic-implementer-bin.js +2204 -56
  81. package/build/epic-launch-context.js +702 -0
  82. package/build/epic-server-record.js +288 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/completion-contract.js +8 -1
  87. package/build/executor/credential-delivery-step.js +168 -0
  88. package/build/executor/deps.js +3 -1
  89. package/build/executor/env.js +98 -23
  90. package/build/executor/epic-server-context.js +157 -0
  91. package/build/executor/gate-qualification-job.js +127 -26
  92. package/build/executor/guarded-fast-forward-push.js +13 -8
  93. package/build/executor/http-client.js +52 -5
  94. package/build/executor/job-runner.js +577 -81
  95. package/build/executor/observation.js +8 -0
  96. package/build/executor/permissions.js +85 -3
  97. package/build/executor/pre-pr-checks.js +363 -0
  98. package/build/executor/prompt-spec.js +149 -3
  99. package/build/executor/reconcile-overlap-job.js +5 -3
  100. package/build/executor/required-work-diagnostics.js +4 -2
  101. package/build/executor/required-work-ledger.js +936 -38
  102. package/build/executor/results.js +58 -0
  103. package/build/executor/terminal-mutation.js +8 -0
  104. package/build/executor/worker-command.js +72 -3
  105. package/build/executor/worker-database-config.js +281 -0
  106. package/build/executor/worker-database-target.js +16 -12
  107. package/build/executor/worker-database.js +320 -101
  108. package/build/executor/worker-finalization.js +7 -1
  109. package/build/executor/worker-resources.js +25 -3
  110. package/build/executor/worker-verification-guidance.js +18 -3
  111. package/build/executor/worktree.js +20 -1
  112. package/build/executor-launch.js +58 -4
  113. package/build/generated-assets-catalog.js +2 -2
  114. package/build/git-exclude-lock.js +187 -0
  115. package/build/index.js +824 -366
  116. package/build/init.js +26 -11
  117. package/build/install-bridge-conductor-answers.js +528 -0
  118. package/build/install-bridge-conductor-apply.js +288 -0
  119. package/build/install-bridge-conductor-assessment.js +1222 -0
  120. package/build/install-bridge-conductor-compact.js +186 -0
  121. package/build/install-bridge-conductor-contracts.js +72 -0
  122. package/build/install-bridge-conductor-gate.js +1312 -198
  123. package/build/install-bridge-conductor-setup.js +577 -83
  124. package/build/install-bridge-conductor.js +3381 -544
  125. package/build/install-bridge.js +280 -25
  126. package/build/install-doctor.js +38 -8
  127. package/build/install-maintenance.js +26 -3
  128. package/build/install-sfcc-detection.js +120 -0
  129. package/build/install-sfcc-setup.js +185 -0
  130. package/build/launcher-config-inspection.js +162 -1
  131. package/build/mcp-grant-candidates.js +779 -0
  132. package/build/mcp-grant-doctor.js +63 -0
  133. package/build/mcp-grant.js +288 -0
  134. package/build/mcp-host-targets.js +8 -0
  135. package/build/mcp-identity.js +23 -0
  136. package/build/mcp-invoke.js +292 -15
  137. package/build/mcp-presets.js +107 -0
  138. package/build/mcp-provisioning.js +155 -6
  139. package/build/mcp-registration-doctor.js +31 -2
  140. package/build/mcp-server-invocation.js +19 -1
  141. package/build/merge-workflow-install.js +243 -110
  142. package/build/pipelines.generated.js +7 -6
  143. package/build/plan-discovery.js +97 -4
  144. package/build/plan-execution-ledger.js +100 -7
  145. package/build/plan-generation-io.js +262 -0
  146. package/build/plan-generation.js +424 -0
  147. package/build/plane/build-freshness.js +6 -1
  148. package/build/plane/cli.js +75 -9
  149. package/build/plane/plane-freshness.js +17 -0
  150. package/build/plane/preflight.js +50 -10
  151. package/build/plane/shutdown.js +19 -0
  152. package/build/plane/status.js +8 -2
  153. package/build/plane/terminal-run-cleanup.js +18 -4
  154. package/build/printed-remedy-commands.js +211 -12
  155. package/build/project-root.js +40 -0
  156. package/build/readiness-check.js +77 -0
  157. package/build/readiness-prerequisites.generated.js +122 -14
  158. package/build/readme.generated.js +1 -1
  159. package/build/repository-state-paths.js +41 -0
  160. package/build/repository-toolchains.js +6 -3
  161. package/build/run-unit-tests-launcher.js +8 -1
  162. package/build/setup-epic.js +1305 -210
  163. package/build/setup-progress.js +44 -0
  164. package/build/setup-question.js +122 -4
  165. package/build/sfcc/credentials.js +3 -2
  166. package/build/sfcc/hostname.js +98 -2
  167. package/build/sfcc/tool-wrapper.js +6 -95
  168. package/build/start-tickets.js +193 -29
  169. package/build/test-support/executor-source-files.js +200 -0
  170. package/build/testing-config-client.js +25 -2
  171. package/build/third-party-mcp-targets.js +63 -2
  172. package/build/ticket-delivery-enrollment.js +9 -0
  173. package/build/upgrade-cli.js +85 -2
  174. package/build/v2-readiness-requirements.js +28 -1
  175. package/build/version.generated.js +3 -3
  176. package/build/with-credentials.js +208 -0
  177. package/build/worktree-credential-delivery.js +340 -0
  178. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  179. package/docs/epic-implementer/getting-started.md +3 -1
  180. package/docs/epic-implementer/self-hosting.md +14 -1
  181. package/package.json +2 -2
@@ -1,3 +1,5 @@
1
+ import { MCP_PACKAGE_NAME } from "./mcp-identity.js";
2
+ import { createSetupProgressTimer, withSetupProgress } from "./setup-progress.js";
1
3
  import { askSetupQuestion, setupConsentQuestion } from "./setup-question.js";
2
4
  /**
3
5
  * `install epic-implementer` — the owner-confirmed repository gate (BAPI-1391).
@@ -12,19 +14,24 @@ import { askSetupQuestion, setupConsentQuestion } from "./setup-question.js";
12
14
  *
13
15
  * Five properties are load-bearing:
14
16
  *
15
- * 1. **Discovery never confirms.** The deterministic collector
17
+ * 1. **Discovery never confirms on its own.** The deterministic collector
16
18
  * (`conductor/gate-discovery.ts`) reads the working tree and the provider's
17
- * real check history and PROPOSES a typed gate. A proposal is stored only
18
- * after the owner confirms it at a prompt, or supplies explicit gate flags,
19
- * 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.
20
26
  * 2. **The capability probe precedes every gate write.** A server that does not
21
27
  * advertise `gate_profile.v1` gets "Bridge API update required" and nothing
22
28
  * is written — including the qualification enqueue, and the short-lived
23
29
  * executor whose claim carries `job_types` (an older server answers that key
24
30
  * with 422). The probe is a read and runs after the base-URL consent.
25
31
  * 3. **Removals are visible.** The stored and proposed gates are shown side by
26
- * side before any write; a confirm that removes a member says so, and a
27
- * 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.
28
35
  * 4. **A refused write changes nothing.** BAPI-1390's PUT is admin-only and
29
36
  * compare-and-swaps the revision; on a refusal the installer shows the PRIOR
30
37
  * gate, never the proposal, as what is in force.
@@ -40,10 +47,12 @@ import { askSetupQuestion, setupConsentQuestion } from "./setup-question.js";
40
47
  * It never confirms a gate, authorizes a merge, or changes an approval rule
41
48
  * without an explicit typed "yes".
42
49
  */
43
- 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";
44
52
  import { applyApprovalExemption, assessApprovalExemptionScope, buildEpicBranchCiEvidence, exemptionManualSteps, inspectEpicBranchWorkflowCoverage, readEpicBranchRulesViaGh, } from "./conductor/epic-branch-ci-inspection.js";
45
- import { describeEvidence, discoverDeclarations, discoverGate, LOCAL_COMMAND_TIMEOUT_SECONDS, } from "./conductor/gate-discovery.js";
46
- import { dependencyInstallEqual, describeSettingsEdit, hasSettingsToReview, hasUnstoredDeclarationProposal, hintEqual, renderDeclarationsOnly, renderSettingsReview, reviewDeclarations, reviewDiscoveredSettings, settingsMatchStored, storedCiDatabase, 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, mergeDependencyProposal, 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";
47
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";
48
57
  export function emptyConductorGateFlags() {
49
58
  return {
@@ -152,17 +161,12 @@ export function validateConductorGateFlags(flags, context) {
152
161
  if (flags.gateNone && flags.migrationGuard !== undefined) {
153
162
  return "--gate-none has no members, so it cannot take a --migration-guard.";
154
163
  }
155
- if (flags.clearGate && (hasExplicitGateInput(flags) || flags.confirmGate || flags.qualifyGate)) {
156
- 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.";
157
166
  }
158
167
  if (flags.clearGate && context.replaceDoneGate) {
159
168
  return "--clear-gate cannot be combined with --replace-done-gate.";
160
169
  }
161
- if (flags.confirmGate && !hasExplicitGateInput(flags)) {
162
- return ("--confirm-gate confirms explicit gate flags. Supply --provider-check, --local-command, " +
163
- "--gate-none, --migration-guard, or --customized-command, or run without it to confirm " +
164
- "the discovered proposal at a prompt.");
165
- }
166
170
  if (flags.migrationGuard?.kind === "provider" && flags.providerChecks.length > 0 &&
167
171
  !flags.providerChecks.includes(flags.migrationGuard.ref)) {
168
172
  return "--migration-guard provider:<check> must name one of the supplied provider checks exactly.";
@@ -199,6 +203,26 @@ export function createQualificationExecutorRunner(seams) {
199
203
  return { started, exitCode };
200
204
  };
201
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
+ }
202
226
  const YES = new Set(["y", "yes"]);
203
227
  async function ask(io, promptText) {
204
228
  const decision = await askSetupQuestion(setupConsentQuestion(promptText), { read: io.promptLine, write: io.log });
@@ -245,6 +269,7 @@ export function desiredFromStored(profile) {
245
269
  return {
246
270
  kind: profile.kind,
247
271
  providerChecks: [...profile.provider_checks],
272
+ ...(profile.watched_checks !== undefined ? { watchedChecks: [...profile.watched_checks] } : {}),
248
273
  localCommands: profile.local_commands.map((c) => ({
249
274
  name: c.name,
250
275
  argv: [...c.argv],
@@ -271,9 +296,13 @@ export function gateMatchesStored(desired, stored, storedProfile) {
271
296
  (stored.customizedCommands !== undefined &&
272
297
  desired.customizedCommands.length === stored.customizedCommands.length &&
273
298
  desired.customizedCommands.every((c, i) => c === stored.customizedCommands?.[i]));
299
+ const desiredWatched = desired.watchedChecks ?? [];
300
+ const storedWatched = stored.watchedChecks ?? [];
274
301
  return (desired.kind === stored.kind &&
275
302
  desired.providerChecks.length === stored.providerChecks.length &&
276
303
  desired.providerChecks.every((c, i) => c === stored.providerChecks[i]) &&
304
+ desiredWatched.length === storedWatched.length &&
305
+ desiredWatched.every((c, i) => c === storedWatched[i]) &&
277
306
  desired.localCommands.length === stored.localCommands.length &&
278
307
  desired.localCommands.every((c, i) => sameCommand(c, stored.localCommands[i])) &&
279
308
  sameGuard &&
@@ -288,8 +317,82 @@ function settingsOf(desired) {
288
317
  ...(desired.reproduce !== undefined ? { reproduce: desired.reproduce } : {}),
289
318
  ...(desired.dependencyInstall !== undefined ? { dependencyInstall: desired.dependencyInstall } : {}),
290
319
  ...(desired.ciDatabase !== undefined ? { ciDatabase: desired.ciDatabase } : {}),
320
+ ...(desired.mustOrderPaths !== undefined ? { mustOrderPaths: desired.mustOrderPaths } : {}),
321
+ ...(desired.workerDatabase !== undefined ? { workerDatabase: desired.workerDatabase } : {}),
291
322
  };
292
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
+ }
293
396
  /** Human descriptions of every member `next` removes from `prior`. */
294
397
  export function gateRemovals(prior, next) {
295
398
  if (prior === null)
@@ -299,6 +402,10 @@ export function gateRemovals(prior, next) {
299
402
  if (!next.providerChecks.includes(check))
300
403
  removed.push(`provider check "${check}"`);
301
404
  }
405
+ for (const check of prior.watchedChecks ?? []) {
406
+ if (!(next.watchedChecks ?? []).includes(check))
407
+ removed.push(`watched check "${check}"`);
408
+ }
302
409
  for (const command of prior.localCommands) {
303
410
  if (!next.localCommands.some((c) => sameCommand(c, command))) {
304
411
  removed.push(`local command ${command.name}`);
@@ -315,22 +422,40 @@ export function confirmRequestFor(desired, expectedRevision, stored) {
315
422
  // BAPI-1520: a setting is sent only when it effectively changes what is stored.
316
423
  // An unchanged hint is omitted (the server keeps it); `reproduce: null` is sent
317
424
  // only to remove a hint that is actually stored.
318
- 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 } : {};
319
432
  const edit = desired.reproduce?.get(name);
320
433
  if (edit === undefined)
321
- return { name };
434
+ return { name, ...membership };
322
435
  const current = stored?.reproduction_hints?.get(name) ?? null;
323
436
  if (edit === null)
324
- return current !== null ? { name, reproduce: null } : { name };
437
+ return current !== null ? { name, reproduce: null, ...membership } : { name, ...membership };
325
438
  if (current !== null && hintEqual(edit, current))
326
- return { name };
327
- return { name, reproduce: { argv: [...edit.argv], timeout_seconds: edit.timeout_seconds } };
328
- });
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
+ ];
329
449
  const sendWorkerEnv = desired.workerEnv !== undefined && !workerEnvEqual(desired.workerEnv, stored?.worker_env);
330
450
  // BAPI-1551: each declaration is sent only when it differs from what is stored;
331
451
  // a clear sends `[]`, and a reset of the CI-database value sends `null`.
332
452
  const sendDependencyInstall = desired.dependencyInstall !== undefined && !dependencyInstallEqual(desired.dependencyInstall, stored?.dependency_install);
333
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);
334
459
  return {
335
460
  action: "confirm",
336
461
  confirm: true,
@@ -359,6 +484,10 @@ export function confirmRequestFor(desired, expectedRevision, stored) {
359
484
  ...(sendCiDatabase && desired.ciDatabase !== undefined
360
485
  ? { ci_database: desired.ciDatabase === "unknown" ? null : desired.ciDatabase }
361
486
  : {}),
487
+ ...(sendMustOrderPaths && mustOrderPaths !== undefined ? { must_order_paths: mustOrderPaths } : {}),
488
+ ...(sendWorkerDatabase && desired.workerDatabase !== undefined
489
+ ? { worker_database: structuredClone(desired.workerDatabase) }
490
+ : {}),
362
491
  };
363
492
  }
364
493
  function resolveLocalCommand(flag, proposal) {
@@ -380,8 +509,11 @@ function resolveLocalCommand(flag, proposal) {
380
509
  */
381
510
  export function desiredFromFlags(flags, current, proposal) {
382
511
  let providerChecks;
512
+ let watchedChecks = [];
383
513
  let localCommands;
384
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.
385
517
  providerChecks = [...flags.providerChecks];
386
518
  localCommands = [];
387
519
  for (const flag of flags.localCommands) {
@@ -401,6 +533,7 @@ export function desiredFromFlags(flags, current, proposal) {
401
533
  }
402
534
  else if (current !== null) {
403
535
  providerChecks = [...current.providerChecks];
536
+ watchedChecks = [...(current.watchedChecks ?? [])];
404
537
  localCommands = current.localCommands.map((c) => ({ ...c, argv: [...c.argv] }));
405
538
  }
406
539
  else {
@@ -439,6 +572,7 @@ export function desiredFromFlags(flags, current, proposal) {
439
572
  desired: {
440
573
  kind: kindForMembers(providerChecks, localCommands),
441
574
  providerChecks,
575
+ ...(watchedChecks.length > 0 ? { watchedChecks } : {}),
442
576
  localCommands,
443
577
  migrationGuard,
444
578
  customizedCommands: flags.customizedCommands,
@@ -448,28 +582,33 @@ export function desiredFromFlags(flags, current, proposal) {
448
582
  // ---------------------------------------------------------------------------
449
583
  // Rendering
450
584
  // ---------------------------------------------------------------------------
451
- const KIND_CONSEQUENCE = Object.freeze({
452
- provider: "every check must have actually reported on this repository before an unattended run is admitted",
453
- local: "the executor runs these commands before each auto-merge; they must pass once under the executor " +
454
- "(qualification) before an unattended run is admitted",
455
- mixed: "BOTH legs gate every merge: each provider check must report green AND each local command must pass",
456
- none: "no gate: an unattended run is admitted, but every child merge waits for your approval",
457
- });
458
585
  function quoted(names) {
459
586
  return names.map((n) => `"${n}"`).join(", ");
460
587
  }
461
- /** One-gate description lines (members, conjunction, guard, customized). */
462
- 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) {
463
599
  const lines = [];
464
600
  const members = [];
601
+ const watched = gate.watchedChecks ?? [];
465
602
  if (gate.providerChecks.length > 0)
466
603
  members.push(`provider checks ${quoted(gate.providerChecks)}`);
604
+ if (watched.length > 0)
605
+ members.push(`watched checks ${quoted(watched)}`);
467
606
  if (gate.localCommands.length > 0) {
468
607
  members.push(`local commands ${gate.localCommands.map((c) => `${c.name} (${c.argv.join(" ")})`).join(", ")}`);
469
608
  }
470
609
  lines.push(`${indent}${gate.kind}` +
471
610
  (members.length > 0 ? ` — ${members.join(gate.kind === "mixed" ? " AND " : "; ")}` : ""));
472
- lines.push(`${indent} ${KIND_CONSEQUENCE[gate.kind]}`);
611
+ lines.push(`${indent} ${describeGateConsequence(consequenceGate(gate), ciFacts)}`);
473
612
  if (gate.migrationGuard !== null) {
474
613
  lines.push(`${indent} migration guard: ${gate.migrationGuard.kind} ${gate.migrationGuard.name}`);
475
614
  }
@@ -478,6 +617,221 @@ export function describeGate(gate, indent = " ") {
478
617
  }
479
618
  return lines;
480
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
+ }
481
835
  function describeHistory(proposal) {
482
836
  switch (proposal.history.status) {
483
837
  case "available":
@@ -632,7 +986,19 @@ export async function runGateDiscovery(io, access, gateDeps) {
632
986
  const fs = gateDeps?.discoveryFs;
633
987
  if (!fs)
634
988
  return emptyProposal();
635
- return discoverGate({ fs, lookupHistory: historyLookupFor(io, access) });
989
+ const learned = await learnedInstructionsFor(gateDeps);
990
+ return discoverGate({ fs, lookupHistory: historyLookupFor(io, access), ...(learned !== undefined ? { learned } : {}) });
991
+ }
992
+ /** The learned snapshot, `undefined` when no reader was given. A failing reader is a limitation, never a throw. */
993
+ async function learnedInstructionsFor(gateDeps) {
994
+ if (gateDeps?.learnedInstructions === undefined)
995
+ return undefined;
996
+ try {
997
+ return await gateDeps.learnedInstructions();
998
+ }
999
+ catch {
1000
+ return null;
1001
+ }
636
1002
  }
637
1003
  /** A fresh explicit empty proposal: nothing discovered, nothing proposed. */
638
1004
  function emptyProposal() {
@@ -746,15 +1112,28 @@ async function reviewSettingsInto(io, proposal, current, desired) {
746
1112
  if (!prompt || !hasSettingsToReview(proposal, current.profile, desired.providerChecks)) {
747
1113
  return { desired, changed: false };
748
1114
  }
1115
+ if (usesSafeSettingDefaults(io)) {
1116
+ const selection = recommendedSettingsSelection(proposal, current.profile, desired.providerChecks);
1117
+ logSafeSettingReceipts(io, selection, current.profile, false);
1118
+ return {
1119
+ desired: { ...desired, ...settingsFieldsOf(selection.edit) },
1120
+ changed: !settingsMatchStored(selection.edit, current.profile),
1121
+ };
1122
+ }
749
1123
  const edit = await reviewDiscoveredSettings({ log: io.log, promptLine: prompt }, proposal, current.profile, desired.providerChecks);
750
- const merged = {
751
- ...desired,
1124
+ const merged = { ...desired, ...settingsFieldsOf(edit) };
1125
+ return { desired: merged, changed: !settingsMatchStored(edit, current.profile) };
1126
+ }
1127
+ /** The desired-gate fields an edit sets; untouched settings stay omitted from the write. */
1128
+ function settingsFieldsOf(edit) {
1129
+ return {
752
1130
  ...(edit.workerEnv !== undefined ? { workerEnv: edit.workerEnv } : {}),
753
1131
  ...(edit.reproduce !== undefined ? { reproduce: edit.reproduce } : {}),
754
1132
  ...(edit.dependencyInstall !== undefined ? { dependencyInstall: edit.dependencyInstall } : {}),
755
1133
  ...(edit.ciDatabase !== undefined ? { ciDatabase: edit.ciDatabase } : {}),
1134
+ ...(edit.mustOrderPaths !== undefined ? { mustOrderPaths: edit.mustOrderPaths } : {}),
1135
+ ...(edit.workerDatabase !== undefined ? { workerDatabase: edit.workerDatabase } : {}),
756
1136
  };
757
- return { desired: merged, changed: !settingsMatchStored(edit, current.profile) };
758
1137
  }
759
1138
  /**
760
1139
  * BAPI-1551 — keep the confirmed gate, and offer any unstored declaration
@@ -770,7 +1149,7 @@ async function keptGateWithDeclarations(io, current, currentDesired, gateDeps, o
770
1149
  if (!offered.changed)
771
1150
  return unchanged;
772
1151
  renderGateComparison(io, current, offered.desired, []);
773
- if (!options.planningOnly && !(await ask(io, "Store these worker setup declarations with the gate? [y/N]: "))) {
1152
+ if (!options.planningOnly && !usesSafeSettingDefaults(io) && !(await ask(io, "Store these worker setup declarations with the gate? [y/N]: "))) {
774
1153
  io.log(" Declarations not stored; the stored gate and its settings are unchanged.");
775
1154
  for (const key of offered.offeredKeys)
776
1155
  options.declinedDeclarations?.add(key);
@@ -797,28 +1176,23 @@ async function keptGateWithDeclarations(io, current, currentDesired, gateDeps, o
797
1176
  async function offerDeclarationChanges(io, current, desired, gateDeps, options) {
798
1177
  const none = { desired, changed: false, offeredKeys: [] };
799
1178
  const prompt = io.promptLine;
800
- const fs = gateDeps?.discoveryFs;
801
- if (!prompt || !fs || options.dryRun || current.profile === null)
1179
+ if (!gateDeps?.discoveryFs || current.profile === null)
802
1180
  return none;
803
- let declarations;
804
- try {
805
- declarations = await discoverDeclarations({ fs, providerChecks: desired.providerChecks });
806
- }
807
- catch {
1181
+ const safeDefaults = usesSafeSettingDefaults(io);
1182
+ // A dry run previews the safe selection but never reviews; a real run needs a reader or safe defaults.
1183
+ if (options.dryRun ? !safeDefaults : !prompt)
1184
+ return none;
1185
+ const proposal = await discoverDeclarationProposal(current, desired, gateDeps, options.declinedDeclarations);
1186
+ if (proposal === null)
808
1187
  return none;
809
- }
810
- // Never re-offer what the owner already ignored or declined in this invocation.
811
1188
  const declined = options.declinedDeclarations;
812
- const candidates = (declarations.dependencyInstallCandidates ?? []).filter((c) => !declined?.has(dependencyProposalKey(c)));
813
- const ci = declarations.ciDatabaseProposal;
814
- const proposal = {
815
- ...emptyProposal(),
816
- ...(candidates.length > 0 ? { dependencyInstallCandidates: candidates } : {}),
817
- ...(declarations.dependencyInstallNotes ? { dependencyInstallNotes: declarations.dependencyInstallNotes } : {}),
818
- ...(ci !== undefined && !declined?.has(ciDatabaseProposalKey(ci.value)) ? { ciDatabaseProposal: ci } : {}),
819
- };
820
- if (!hasUnstoredDeclarationProposal(proposal, current.profile))
1189
+ if (!hasUnstoredDeclarationProposal(proposal, current.profile)) {
1190
+ // BAPI-1580: discoveries the bound keeps from being offered are still named.
1191
+ const warning = mustOrderShortfallWarning(proposal, current.profile);
1192
+ if (warning !== null)
1193
+ io.log(warning);
821
1194
  return none;
1195
+ }
822
1196
  const offeredKeys = [
823
1197
  ...(proposal.dependencyInstallCandidates ?? [])
824
1198
  .filter((c) => !(current.profile?.dependency_install ?? []).some((e) => dependencyInstallEqual([e], [c])))
@@ -827,7 +1201,29 @@ async function offerDeclarationChanges(io, current, desired, gateDeps, options)
827
1201
  proposal.ciDatabaseProposal.value !== storedCiDatabase(current.profile)
828
1202
  ? [ciDatabaseProposalKey(proposal.ciDatabaseProposal.value)]
829
1203
  : []),
1204
+ ...mustOrderOffer(proposal, current.profile).offered.map(mustOrderProposalKey),
1205
+ ...(proposal.workerDatabaseProposal !== undefined && current.profile.worker_database === undefined
1206
+ ? [WORKER_DATABASE_PROPOSAL_KEY]
1207
+ : []),
830
1208
  ];
1209
+ if (safeDefaults) {
1210
+ const { edit: selected } = recommendedSettingsSelection(proposal, current.profile, desired.providerChecks);
1211
+ const edit = {
1212
+ ...(selected.dependencyInstall !== undefined ? { dependencyInstall: selected.dependencyInstall } : {}),
1213
+ ...(selected.ciDatabase !== undefined ? { ciDatabase: selected.ciDatabase } : {}),
1214
+ ...(selected.mustOrderPaths !== undefined ? { mustOrderPaths: selected.mustOrderPaths } : {}),
1215
+ ...(selected.workerDatabase !== undefined ? { workerDatabase: selected.workerDatabase } : {}),
1216
+ };
1217
+ io.log("");
1218
+ logSafeSettingReceipts(io, { edit, skipped: [] }, current.profile, options.dryRun);
1219
+ if (options.dryRun)
1220
+ return none;
1221
+ return {
1222
+ desired: { ...desired, ...settingsFieldsOf(edit) },
1223
+ changed: !settingsMatchStored(edit, current.profile),
1224
+ offeredKeys,
1225
+ };
1226
+ }
831
1227
  io.log("");
832
1228
  io.log(" Discovery proposes worker setup declarations this gate does not store yet (optional):");
833
1229
  renderDeclarationsOnly(io, proposal, current.profile, true);
@@ -836,7 +1232,12 @@ async function offerDeclarationChanges(io, current, desired, gateDeps, options)
836
1232
  ...desired,
837
1233
  ...(edit.dependencyInstall !== undefined ? { dependencyInstall: edit.dependencyInstall } : {}),
838
1234
  ...(edit.ciDatabase !== undefined ? { ciDatabase: edit.ciDatabase } : {}),
1235
+ ...(edit.mustOrderPaths !== undefined ? { mustOrderPaths: edit.mustOrderPaths } : {}),
1236
+ ...(edit.workerDatabase !== undefined ? { workerDatabase: edit.workerDatabase } : {}),
839
1237
  };
1238
+ if (proposal.workerDatabaseProposal !== undefined && edit.workerDatabase === undefined) {
1239
+ declined?.add(WORKER_DATABASE_PROPOSAL_KEY);
1240
+ }
840
1241
  // A proposal the owner did not take is remembered as declined for this invocation.
841
1242
  const resultingList = edit.dependencyInstall ?? current.profile.dependency_install ?? [];
842
1243
  const resultingCi = edit.ciDatabase ?? storedCiDatabase(current.profile);
@@ -848,8 +1249,155 @@ async function offerDeclarationChanges(io, current, desired, gateDeps, options)
848
1249
  if (proposal.ciDatabaseProposal !== undefined && proposal.ciDatabaseProposal.value !== resultingCi) {
849
1250
  declined?.add(ciDatabaseProposalKey(proposal.ciDatabaseProposal.value));
850
1251
  }
1252
+ const resultingMustOrder = edit.mustOrderPaths ?? current.profile.must_order_paths;
1253
+ for (const entry of mustOrderOffer(proposal, current.profile).offered) {
1254
+ if (!resultingMustOrder.includes(entry))
1255
+ declined?.add(mustOrderProposalKey(entry));
1256
+ }
851
1257
  return { desired: merged, changed: !settingsMatchStored(edit, current.profile), offeredKeys };
852
1258
  }
1259
+ /**
1260
+ * BAPI-1638 — the declaration discovery shared by the terminal offer and the
1261
+ * read-only planner. Reads repository files only: no prompt, no write. `null`
1262
+ * means there is nothing to discover from (no seam, no stored profile, or a
1263
+ * failed read). Discovery PROPOSES settings; it never authorizes the gate or a
1264
+ * declaration.
1265
+ */
1266
+ async function discoverDeclarationProposal(current, desired, gateDeps, declined,
1267
+ /** The read-only planner also proposes declarations for a gate that is not stored yet. */
1268
+ allowUnstored = false) {
1269
+ const fs = gateDeps?.discoveryFs;
1270
+ if (!fs || (current.profile === null && !allowUnstored))
1271
+ return null;
1272
+ let declarations;
1273
+ try {
1274
+ const learned = await learnedInstructionsFor(gateDeps);
1275
+ declarations = await discoverDeclarations({ fs, providerChecks: desired.providerChecks, ...(learned !== undefined ? { learned } : {}) });
1276
+ }
1277
+ catch {
1278
+ return null;
1279
+ }
1280
+ // BAPI-1677: when extras could not be worked out, what is stored stands. An unknown
1281
+ // read never proposes a change to a stored list, so it cannot strip a stored extra.
1282
+ const unknownAgainstStored = declarations.dependencyInstallUnknown === true && (current.profile?.dependency_install?.length ?? 0) > 0;
1283
+ // Never re-offer what the owner already ignored or declined in this invocation.
1284
+ const candidates = unknownAgainstStored
1285
+ ? []
1286
+ : (declarations.dependencyInstallCandidates ?? []).filter((c) => !declined?.has(dependencyProposalKey(c)));
1287
+ const ci = declarations.ciDatabaseProposal;
1288
+ const mustOrder = (declarations.mustOrderPathCandidates ?? []).filter((p) => !declined?.has(mustOrderProposalKey(p)));
1289
+ const workerDatabase = declarations.workerDatabaseProposal;
1290
+ return {
1291
+ ...emptyProposal(),
1292
+ ...(workerDatabase !== undefined && !declined?.has(WORKER_DATABASE_PROPOSAL_KEY)
1293
+ ? { workerDatabaseProposal: workerDatabase }
1294
+ : {}),
1295
+ ...(candidates.length > 0 ? { dependencyInstallCandidates: candidates } : {}),
1296
+ ...(declarations.dependencyInstallNotes ? { dependencyInstallNotes: declarations.dependencyInstallNotes } : {}),
1297
+ ...(declarations.dependencyInstallLimitations ? { dependencyInstallLimitations: declarations.dependencyInstallLimitations } : {}),
1298
+ ...(declarations.dependencyInstallUnknown === true ? { dependencyInstallUnknown: true } : {}),
1299
+ ...(ci !== undefined && !declined?.has(ciDatabaseProposalKey(ci.value)) ? { ciDatabaseProposal: ci } : {}),
1300
+ ...(mustOrder.length > 0 ? { mustOrderPathCandidates: mustOrder } : {}),
1301
+ ...(declarations.mustOrderPathOverflow !== undefined
1302
+ ? { mustOrderPathOverflow: declarations.mustOrderPathOverflow }
1303
+ : {}),
1304
+ };
1305
+ }
1306
+ /**
1307
+ * BAPI-1638 — plan the worker-setup declarations without a terminal.
1308
+ *
1309
+ * Read-only: the same discovery and the same safe recommended selection the
1310
+ * terminal path uses, split into one entry per answer key. It asks nothing,
1311
+ * writes nothing, and never decides. An entry is a proposal the owner approves
1312
+ * or declines by its key; discovery alone authorizes nothing.
1313
+ */
1314
+ export async function planDeclarationSelections(current, desired, gateDeps) {
1315
+ return (await planDeclarations(current, desired, gateDeps)).entries;
1316
+ }
1317
+ export async function planDeclarations(current, desired, gateDeps) {
1318
+ // A first install has no stored profile: its declarations are proposed with the
1319
+ // gate, so the first apply stores them before the learned check starts.
1320
+ const proposal = await discoverDeclarationProposal(current, desired, gateDeps, undefined, true);
1321
+ if (proposal === null)
1322
+ return { entries: [], dependencyInstall: null };
1323
+ const storedDeps = current.profile?.dependency_install ?? [];
1324
+ const candidates = proposal.dependencyInstallCandidates ?? [];
1325
+ const limitations = [...(proposal.dependencyInstallLimitations ?? [])];
1326
+ const merge = mergeDependencyProposal(storedDeps, candidates);
1327
+ if (!merge.withinBounds) {
1328
+ limitations.push("Adding what setup found would make too many install commands, so the stored ones stay. You can replace the whole list by correcting it.");
1329
+ }
1330
+ const facts = {
1331
+ planned: merge.withinBounds ? merge.merged : storedDeps.map((e) => ({ ...e })),
1332
+ stored: storedDeps,
1333
+ drift: merge.withinBounds ? merge.drift : "same",
1334
+ evidence: candidates.flatMap((c) => c.extraEvidence ?? []),
1335
+ limitations,
1336
+ };
1337
+ if (!hasUnstoredDeclarationProposal(proposal, current.profile))
1338
+ return { entries: [], dependencyInstall: facts };
1339
+ const { edit } = recommendedSettingsSelection(proposal, current.profile, desired.providerChecks);
1340
+ // Dependency drift is planned here, not by the safe selection: a replacing change is
1341
+ // still shown and offered, recommended decline, and only the owner can take it.
1342
+ if (facts.drift === "same")
1343
+ delete edit.dependencyInstall;
1344
+ else
1345
+ edit.dependencyInstall = facts.planned;
1346
+ const entries = [];
1347
+ const stored = current.profile;
1348
+ if (edit.dependencyInstall !== undefined) {
1349
+ entries.push({
1350
+ key: "dependency_install",
1351
+ proposalKeys: (proposal.dependencyInstallCandidates ?? []).map(dependencyProposalKey),
1352
+ fields: { dependencyInstall: edit.dependencyInstall },
1353
+ summary: describeSettingsEdit({ dependencyInstall: edit.dependencyInstall }, stored),
1354
+ });
1355
+ }
1356
+ if (edit.ciDatabase !== undefined) {
1357
+ entries.push({
1358
+ key: "ci_database",
1359
+ proposalKeys: [ciDatabaseProposalKey(edit.ciDatabase)],
1360
+ fields: { ciDatabase: edit.ciDatabase },
1361
+ summary: describeSettingsEdit({ ciDatabase: edit.ciDatabase }, stored),
1362
+ });
1363
+ }
1364
+ if (edit.mustOrderPaths !== undefined) {
1365
+ entries.push({
1366
+ key: "must_order_paths",
1367
+ proposalKeys: mustOrderOffer(proposal, stored).offered.map(mustOrderProposalKey),
1368
+ fields: { mustOrderPaths: edit.mustOrderPaths },
1369
+ summary: describeSettingsEdit({ mustOrderPaths: edit.mustOrderPaths }, stored),
1370
+ });
1371
+ }
1372
+ if (edit.workerDatabase !== undefined) {
1373
+ entries.push({
1374
+ key: "worker_database",
1375
+ proposalKeys: [WORKER_DATABASE_PROPOSAL_KEY],
1376
+ fields: { workerDatabase: edit.workerDatabase },
1377
+ summary: describeSettingsEdit({ workerDatabase: edit.workerDatabase }, stored),
1378
+ });
1379
+ }
1380
+ return { entries, dependencyInstall: facts };
1381
+ }
1382
+ /**
1383
+ * BAPI-1677 — the one list an answer leaves in force. A correction replaces the whole
1384
+ * list, approve takes the plan, keep and decline leave what is stored (nothing, on a
1385
+ * first install). Without an answer this is the recommendation: additive drift takes
1386
+ * the plan, and a replacing change does not.
1387
+ */
1388
+ export function resolveEffectiveDependencyInstall(facts, stored, answer) {
1389
+ const copy = (list) => list.map((e) => ({ cwd: e.cwd, argv: [...e.argv], lockfiles: [...e.lockfiles] }));
1390
+ if (typeof answer === "object" && answer !== null && Array.isArray(answer.entries)) {
1391
+ return copy(answer.entries);
1392
+ }
1393
+ if (answer === "keep" || answer === "decline")
1394
+ return copy(stored);
1395
+ if (facts === null)
1396
+ return copy(stored);
1397
+ if (answer === "approve")
1398
+ return copy(facts.planned);
1399
+ return copy(facts.drift === "replacing" ? stored : facts.planned);
1400
+ }
853
1401
  /** BAPI-1551 — a proposal's identity for the per-invocation declined set: the whole entry. */
854
1402
  export function dependencyProposalKey(entry) {
855
1403
  return `dependency_install:${JSON.stringify([entry.cwd, entry.argv, entry.lockfiles])}`;
@@ -858,6 +1406,12 @@ export function dependencyProposalKey(entry) {
858
1406
  export function ciDatabaseProposalKey(value) {
859
1407
  return `ci_database:${value}`;
860
1408
  }
1409
+ /** BAPI-1598 — the declined-set key of the worker-database proposal. */
1410
+ export const WORKER_DATABASE_PROPOSAL_KEY = "worker_database:proposed";
1411
+ /** BAPI-1580 — the declined-set key of one must-order proposal. */
1412
+ export function mustOrderProposalKey(entry) {
1413
+ return `must_order_paths:${entry}`;
1414
+ }
861
1415
  /**
862
1416
  * Decide the repository gate for this run (BEFORE any write).
863
1417
  *
@@ -915,21 +1469,13 @@ export async function resolveConductorGate(io, access, flags, gateDeps, options)
915
1469
  io.log(" The confirmed gate already matches — no gate write is needed.");
916
1470
  return { kind: "plan", plan: { current, desired: currentDesired, write: null, removals: [], origin: "stored" } };
917
1471
  }
918
- if (settingsChanged && !options.dryRun && !options.planningOnly) {
1472
+ if (settingsChanged && !options.dryRun && !options.planningOnly && !usesSafeSettingDefaults(io)) {
919
1473
  const ok = await ask(io, "Store these CI settings with the gate? [y/N]: ");
920
1474
  if (!ok) {
921
1475
  io.errorLog("CI settings not confirmed — nothing was written, and the stored gate is unchanged.");
922
1476
  return { kind: "exit", code: 1 };
923
1477
  }
924
1478
  }
925
- if (removals.length > 0 && !flags.confirmGate && !options.dryRun && !options.planningOnly) {
926
- const ok = await ask(io, "Confirm this gate, including the removals above? [y/N]: ");
927
- if (!ok) {
928
- io.errorLog("Gate change not confirmed — nothing was written, and the stored gate is unchanged.");
929
- io.errorLog("Pass --confirm-gate to confirm a removal from a script.");
930
- return { kind: "exit", code: 1 };
931
- }
932
- }
933
1479
  return {
934
1480
  kind: "plan",
935
1481
  plan: {
@@ -941,8 +1487,8 @@ export async function resolveConductorGate(io, access, flags, gateDeps, options)
941
1487
  },
942
1488
  };
943
1489
  }
944
- if (options.ensureProviderCheck !== undefined) {
945
- return ensureProviderCheckPlan(io, access, current, currentDesired, options.ensureProviderCheck, gateDeps, options);
1490
+ if (options.inferCi === true) {
1491
+ return inferredCiPlan(io, access, current, currentDesired, gateDeps, options);
946
1492
  }
947
1493
  if (currentDesired !== null) {
948
1494
  io.log(current.source === "legacy"
@@ -993,7 +1539,7 @@ export async function resolveConductorGate(io, access, flags, gateDeps, options)
993
1539
  },
994
1540
  };
995
1541
  }
996
- /** BAPI-1461 — `desired` with `check` added as a provider member (kept when present). */
1542
+ /** BAPI-1461 — `desired` with `check` added as a required provider member (kept when present). */
997
1543
  function withProviderCheck(desired, check) {
998
1544
  if (desired.providerChecks.includes(check))
999
1545
  return desired;
@@ -1001,92 +1547,143 @@ function withProviderCheck(desired, check) {
1001
1547
  return {
1002
1548
  ...desired,
1003
1549
  providerChecks,
1550
+ // A name is never both required and watched.
1551
+ ...(desired.watchedChecks !== undefined
1552
+ ? { watchedChecks: desired.watchedChecks.filter((name) => name !== check) }
1553
+ : {}),
1004
1554
  localCommands: desired.localCommands.map((c) => ({ ...c, argv: [...c.argv] })),
1005
1555
  kind: kindForMembers(providerChecks, desired.localCommands),
1006
1556
  };
1007
1557
  }
1008
1558
  /**
1009
- * BAPI-1461 — the converging setup's gate decision when no gate flag was given.
1559
+ * BAPI-1603 — the gate change that adds the managed workflow's check to the CURRENT
1560
+ * stored gate, for a caller that has just seen the setup pull request opened or
1561
+ * reused. Built from the profile read right now, so the server-promoted local
1562
+ * member and any watched checks are kept; the write names its expected revision.
1563
+ * `null` when the gate already requires the check, or there is no confirmed gate
1564
+ * to add it to.
1565
+ */
1566
+ export function planManagedProviderGate(current, check) {
1567
+ if (!current.confirmed || current.profile === null)
1568
+ return null;
1569
+ const stored = desiredFromStored(current.profile);
1570
+ if (stored.providerChecks.includes(check))
1571
+ return null;
1572
+ const desired = withProviderCheck(stored, check);
1573
+ return {
1574
+ current,
1575
+ desired,
1576
+ write: confirmRequestFor(desired, current.revision, current.profile),
1577
+ removals: [],
1578
+ origin: "stored",
1579
+ };
1580
+ }
1581
+ /** The command-free gate setup starts from: no members, nothing to qualify. */
1582
+ function emptyDesiredGate() {
1583
+ return { kind: "none", providerChecks: [], localCommands: [], migrationGuard: null, customizedCommands: undefined };
1584
+ }
1585
+ /**
1586
+ * BAPI-1603 — the converging setup's gate decision when no gate flag was given.
1587
+ *
1588
+ * - A confirmed stored gate (provider, local, mixed, none, watched, or the
1589
+ * legacy `--required-check` form) is kept exactly as it is. Discovery can
1590
+ * still offer worker setup declarations, but never changes its members.
1591
+ * - A stored value that could not be read is NOT replaced: it is unknown, not
1592
+ * absent, so nothing is inferred and nothing is written.
1593
+ * - Otherwise the plan comes from facts, with no question:
1594
+ * reported provider checks ⇒ stored as WATCHED members (when the server can
1595
+ * store them), never as required ones, and never adding the managed check;
1596
+ * nothing reported ⇒ a command-free `none` gate, so the server's promotion of
1597
+ * a proven local command later lands on a stored profile.
1010
1598
  *
1011
- * - A confirmed gate that already requires the check: used unchanged, no write.
1012
- * - A confirmed provider or mixed gate without it: the check is ADDED (every
1013
- * member kept), shown against the stored gate, and stored later under the
1014
- * combined gate-and-defaults consent.
1015
- * - A confirmed local-only or `none` gate: changing its kind is a policy change,
1016
- * so the comparison is shown and the owner is asked here. A decline keeps the
1017
- * stored gate and is reported as an outstanding blocking fix.
1018
- * - No confirmed gate: the discovery proposal plus the check, shown for the
1019
- * combined consent. Nothing is stored here.
1599
+ * The write is planned, not made: it goes through the combined policy preview.
1020
1600
  */
1021
- async function ensureProviderCheckPlan(io, access, current, currentDesired, check, gateDeps, options) {
1601
+ async function inferredCiPlan(io, access, current, currentDesired, gateDeps, options) {
1022
1602
  if (currentDesired !== null) {
1023
- if (currentDesired.providerChecks.includes(check)) {
1024
- io.log(current.source === "legacy"
1025
- ? " Using the confirmed gate from this repository's existing --required-check setup."
1026
- : ` Using the confirmed gate (revision ${current.revision}).`);
1027
- for (const line of describeGate(currentDesired))
1028
- io.log(line);
1029
- return keptGateWithDeclarations(io, current, currentDesired, gateDeps, options);
1030
- }
1031
- // BAPI-1551: unstored declaration proposals ride along with this gate change.
1032
- const offered = await offerDeclarationChanges(io, current, withProviderCheck(currentDesired, check), gateDeps, options);
1033
- const desired = offered.desired;
1603
+ io.log(current.source === "legacy"
1604
+ ? " Using the confirmed gate from this repository's existing --required-check setup."
1605
+ : ` Using the confirmed gate (revision ${current.revision}).`);
1606
+ for (const line of describeGate(currentDesired))
1607
+ io.log(line);
1608
+ return keptGateWithDeclarations(io, current, currentDesired, gateDeps, options);
1609
+ }
1610
+ const plan = (desired, write, inferred) => ({
1611
+ kind: "plan",
1612
+ plan: { current, desired, write, removals: [], origin: "inferred", inferred },
1613
+ });
1614
+ if (current.stored_malformed) {
1615
+ io.log(" The stored repository gate could not be read, so setup leaves it alone and plans nothing.");
1616
+ return plan(emptyDesiredGate(), null, {
1617
+ ciPlan: "none",
1618
+ reportedChecks: [],
1619
+ watchedWritable: false,
1620
+ watchedUnsupported: false,
1621
+ storedUnreadable: true,
1622
+ trialEligible: false,
1623
+ reasons: [],
1624
+ });
1625
+ }
1626
+ const proposal = await runGateDiscovery(io, access, gateDeps);
1627
+ const reported = reportedProviderChecks(proposal).slice(0, MAX_TYPED_CHECKS);
1628
+ if (reported.length === 0 && proposal.history.status === "unavailable") {
1629
+ // Unknown is not absent: a stored `none` would be kept on every rerun and
1630
+ // hide the repository's real CI for good. Store nothing and say why.
1631
+ io.log(" Bridge could not read this repository's CI history, so it cannot tell whether there is CI to watch. " +
1632
+ "It stores no gate now; run setup again when the history can be read.");
1633
+ return plan(emptyDesiredGate(), null, {
1634
+ ciPlan: "none",
1635
+ reportedChecks: [],
1636
+ watchedWritable: false,
1637
+ watchedUnsupported: false,
1638
+ storedUnreadable: false,
1639
+ trialEligible: false,
1640
+ reasons: [],
1641
+ });
1642
+ }
1643
+ if (reported.length === 0) {
1644
+ const desired = emptyDesiredGate();
1034
1645
  renderGateComparison(io, current, desired, []);
1035
- if (currentDesired.kind === "local" || currentDesired.kind === "none") {
1036
- if (options.dryRun) {
1037
- io.log(" Dry run — a real run asks before adding the CI check to this gate.");
1038
- }
1039
- else if (!options.planningOnly) {
1040
- const ok = await ask(io, "Add the CI workflow check to this repository gate? [y/N]: ");
1041
- if (!ok) {
1042
- io.log(" Kept the stored gate unchanged; the CI check is listed as a step left.");
1043
- // Declining the check never discards declarations the owner accepted.
1044
- const kept = {
1045
- ...currentDesired,
1046
- ...(desired.dependencyInstall !== undefined ? { dependencyInstall: desired.dependencyInstall } : {}),
1047
- ...(desired.ciDatabase !== undefined ? { ciDatabase: desired.ciDatabase } : {}),
1048
- };
1049
- return {
1050
- kind: "plan",
1051
- plan: {
1052
- current,
1053
- desired: kept,
1054
- write: offered.changed ? confirmRequestFor(kept, current.revision, current.profile) : null,
1055
- removals: [],
1056
- origin: "stored",
1057
- },
1058
- ensureDeclined: true,
1059
- };
1060
- }
1061
- }
1062
- }
1063
- return {
1064
- kind: "plan",
1065
- plan: {
1066
- current,
1067
- desired,
1068
- write: confirmRequestFor(desired, current.revision, current.profile),
1069
- removals: [],
1070
- origin: "stored",
1071
- },
1072
- };
1646
+ return plan(desired, confirmRequestFor(desired, current.revision, current.profile), {
1647
+ ciPlan: "none",
1648
+ reportedChecks: [],
1649
+ watchedWritable: false,
1650
+ watchedUnsupported: false,
1651
+ storedUnreadable: false,
1652
+ trialEligible: true,
1653
+ // BAPI-1654: missing reported checks, said as such. It is not proof the repository has no CI.
1654
+ reasons: ["No CI checks have reported on this repository yet."],
1655
+ });
1656
+ }
1657
+ // Reported checks exist. Whether the server can store them as watched is a
1658
+ // separate fact; an older one is never given a required-check or `none` stand-in.
1659
+ const watchedCapability = await probeConductorGateProfileWatchedCapability(access, io.fetchJson);
1660
+ if (!watchedCapability.supported) {
1661
+ io.log(` Bridge found ${reported.length} CI check(s) but this server cannot store watched checks, so it ` +
1662
+ "stores no CI checks for now. Nothing was replaced; update the Bridge API, then run setup again.");
1663
+ return plan(emptyDesiredGate(), null, {
1664
+ ciPlan: "watched",
1665
+ reportedChecks: reported,
1666
+ watchedWritable: false,
1667
+ watchedUnsupported: true,
1668
+ storedUnreadable: false,
1669
+ trialEligible: true,
1670
+ reasons: [],
1671
+ });
1073
1672
  }
1074
- const discovered = await runGateDiscovery(io, access, gateDeps);
1075
- const proposal = { ...discovered, proposed: { ...discovered.proposed,
1076
- providerChecks: [...new Set([...discovered.proposed.providerChecks, check])] } };
1077
- renderGateProposal(io, proposal);
1078
- const desired = desiredFromProposalSelection(proposal, proposal.proposed.providerChecks, proposal.proposed.localCommandIds);
1673
+ const desired = { ...emptyDesiredGate(), watchedChecks: reported };
1079
1674
  renderGateComparison(io, current, desired, []);
1080
- return {
1081
- kind: "plan",
1082
- plan: {
1083
- current,
1084
- desired,
1085
- write: confirmRequestFor(desired, current.revision, current.profile),
1086
- removals: [],
1087
- origin: "interactive",
1088
- },
1089
- };
1675
+ return plan(desired, confirmRequestFor(desired, current.revision, current.profile), {
1676
+ ciPlan: "watched",
1677
+ reportedChecks: reported,
1678
+ watchedWritable: true,
1679
+ watchedUnsupported: false,
1680
+ storedUnreadable: false,
1681
+ trialEligible: true,
1682
+ reasons: [
1683
+ "Bridge found CI checks that have already reported on this repository. It watches them: one that " +
1684
+ "finishes red stops a merge, and one that is missing only warns.",
1685
+ ],
1686
+ });
1090
1687
  }
1091
1688
  const GATE_WRITE_REFUSAL_TEXT = Object.freeze({
1092
1689
  "stale-revision": "the stored gate changed since it was read. Re-run to see the current gate.",
@@ -1100,7 +1697,7 @@ const GATE_WRITE_REFUSAL_TEXT = Object.freeze({
1100
1697
  server: "the Bridge API reported an internal error.",
1101
1698
  rejected: "the Bridge API rejected the request.",
1102
1699
  "extension-unsupported": "this server is older than the installer and cannot store worker variables, reproduction hints, " +
1103
- "dependency refresh declarations, or CI database behavior.",
1700
+ "dependency refresh declarations, CI database behavior, or must-order paths.",
1104
1701
  });
1105
1702
  /** Plain-language text for each closed `worker_env` refusal reason (BAPI-1520). */
1106
1703
  const WORKER_ENV_REASON_TEXT = Object.freeze({
@@ -1109,22 +1706,37 @@ const WORKER_ENV_REASON_TEXT = Object.freeze({
1109
1706
  worker_env_secret_name: "looks secret. Drop it, or confirm its committed-literal assertion individually, then confirm again.",
1110
1707
  worker_env_duplicate: "appears more than once. Keep one entry, then confirm again.",
1111
1708
  });
1112
- /** The request without the BAPI-1520 and BAPI-1551 extension fields, and what it dropped. */
1709
+ /** The request without the BAPI-1520, BAPI-1551, and BAPI-1580 extension fields, and what it dropped. */
1113
1710
  function withoutExtensions(request) {
1114
1711
  const workerEnvNames = (request.worker_env ?? []).map((e) => e.name);
1115
1712
  const hintChecks = (request.provider_checks ?? [])
1116
1713
  .filter((c) => c.reproduce !== undefined)
1117
1714
  .map((c) => c.name);
1118
- const { worker_env: _dropped, dependency_install: _install, ci_database: _database, ...rest } = request;
1715
+ const { worker_env: _dropped, dependency_install: _install, ci_database: _database, must_order_paths: _mustOrder, worker_database: _workerDatabase, verification_handoff_default: _handoff, ...rest } = request;
1119
1716
  void _dropped;
1120
1717
  void _install;
1121
1718
  void _database;
1719
+ void _mustOrder;
1720
+ void _workerDatabase;
1721
+ void _handoff;
1122
1722
  return {
1723
+ ...(request.worker_database !== undefined || request.verification_handoff_default !== undefined
1724
+ ? { workerDatabase: true }
1725
+ : {}),
1123
1726
  ...(request.dependency_install !== undefined ? { dependencyInstall: request.dependency_install } : {}),
1124
1727
  ...(request.ci_database !== undefined ? { ciDatabase: request.ci_database } : {}),
1728
+ ...(request.must_order_paths !== undefined ? { mustOrderPaths: request.must_order_paths } : {}),
1125
1729
  request: {
1126
1730
  ...rest,
1127
- ...(request.provider_checks ? { provider_checks: request.provider_checks.map((c) => ({ name: c.name })) } : {}),
1731
+ ...(request.provider_checks
1732
+ ? {
1733
+ provider_checks: request.provider_checks.map((c) => ({
1734
+ name: c.name,
1735
+ // Dropping a hint must never change a check's membership.
1736
+ ...(c.watched !== undefined ? { watched: c.watched } : {}),
1737
+ })),
1738
+ }
1739
+ : {}),
1128
1740
  },
1129
1741
  workerEnvNames,
1130
1742
  hintChecks,
@@ -1145,23 +1757,55 @@ export async function storeConductorGate(io, access, plan) {
1145
1757
  gateMatchesStored(plan.desired, desiredFromStored(plan.current.profile), plan.current.profile)) {
1146
1758
  return plan.current;
1147
1759
  }
1148
- let outcome = await putConductorGateProfile(access, plan.write, io.postJson);
1760
+ // BAPI-1598: the worker-database and hand-off settings are optional. A server
1761
+ // that does not advertise their capability gets the request without them, and the
1762
+ // owner is told they were not configured. Never a setup or launch stop.
1763
+ let write = plan.write;
1764
+ let workerSetupSkipped = false;
1765
+ if (write.worker_database !== undefined || write.verification_handoff_default !== undefined) {
1766
+ const probe = await probeConductorGateProfileWorkerSetupCapability(access, io.fetchJson);
1767
+ if (!probe.supported) {
1768
+ const { worker_database: _workerDatabase, verification_handoff_default: _handoff, ...rest } = write;
1769
+ void _workerDatabase;
1770
+ void _handoff;
1771
+ write = rest;
1772
+ workerSetupSkipped = true;
1773
+ if (plan.current.source === "stored" &&
1774
+ plan.current.profile !== null &&
1775
+ gateMatchesStored({ ...plan.desired, workerDatabase: undefined }, desiredFromStored(plan.current.profile), plan.current.profile)) {
1776
+ reportUnsavedSettings(io, { workerEnvNames: [], hintChecks: [], workerDatabase: true });
1777
+ io.log(" The gate itself already matched, so nothing was written.");
1778
+ return plan.current;
1779
+ }
1780
+ }
1781
+ }
1782
+ let outcome = await putConductorGateProfile(access, write, io.postJson);
1149
1783
  // BAPI-1520: an older server rejects exactly the extension fields it does not
1150
1784
  // know. Retry ONCE without them, keep everything else the owner approved, and
1151
1785
  // report what was not stored by name.
1152
1786
  let unsaved = null;
1153
1787
  if (!outcome.ok && outcome.refusal === "extension-unsupported") {
1154
- const stripped = withoutExtensions(plan.write);
1788
+ const stripped = withoutExtensions(write);
1155
1789
  unsaved = {
1156
1790
  workerEnvNames: stripped.workerEnvNames,
1157
1791
  hintChecks: stripped.hintChecks,
1158
1792
  ...(stripped.dependencyInstall !== undefined ? { dependencyInstall: stripped.dependencyInstall } : {}),
1159
1793
  ...(stripped.ciDatabase !== undefined ? { ciDatabase: stripped.ciDatabase } : {}),
1794
+ ...(stripped.mustOrderPaths !== undefined ? { mustOrderPaths: stripped.mustOrderPaths } : {}),
1795
+ ...(stripped.workerDatabase !== undefined ? { workerDatabase: true } : {}),
1160
1796
  };
1161
1797
  const storedDesired = plan.current.profile !== null ? desiredFromStored(plan.current.profile) : null;
1162
1798
  const membersUnchanged = plan.current.source === "stored" &&
1163
1799
  storedDesired !== null &&
1164
- gateMatchesStored({ ...plan.desired, workerEnv: undefined, reproduce: undefined, dependencyInstall: undefined, ciDatabase: undefined }, storedDesired);
1800
+ gateMatchesStored({
1801
+ ...plan.desired,
1802
+ workerEnv: undefined,
1803
+ reproduce: undefined,
1804
+ dependencyInstall: undefined,
1805
+ ciDatabase: undefined,
1806
+ mustOrderPaths: undefined,
1807
+ workerDatabase: undefined,
1808
+ }, storedDesired);
1165
1809
  if (membersUnchanged) {
1166
1810
  reportUnsavedSettings(io, unsaved);
1167
1811
  io.log(" The gate itself already matched, so nothing was written.");
@@ -1169,6 +1813,39 @@ export async function storeConductorGate(io, access, plan) {
1169
1813
  }
1170
1814
  outcome = await putConductorGateProfile(access, stripped.request, io.postJson);
1171
1815
  }
1816
+ if (!outcome.ok && (outcome.refusal === "network" || outcome.refusal === "timeout" || outcome.refusal === "server")) {
1817
+ // BAPI-1638 — an ambiguous answer may have stored the gate. Reconcile with one
1818
+ // authoritative read before saying anything was or was not written; never retry blindly.
1819
+ // Compare against what was actually SENT: a narrowed request leaves out the fields it stripped.
1820
+ const sentDesired = {
1821
+ ...plan.desired,
1822
+ ...(workerSetupSkipped || unsaved?.workerDatabase === true ? { workerDatabase: undefined } : {}),
1823
+ ...(unsaved !== null
1824
+ ? { workerEnv: undefined, reproduce: undefined, dependencyInstall: undefined, ciDatabase: undefined, mustOrderPaths: undefined }
1825
+ : {}),
1826
+ };
1827
+ let reread = null;
1828
+ try {
1829
+ reread = await fetchConductorGateProfile(access, io.fetchJson);
1830
+ }
1831
+ catch {
1832
+ reread = null;
1833
+ }
1834
+ if (reread !== null && reread.revision > plan.current.revision && reread.confirmed && reread.profile !== null
1835
+ && gateMatchesStored(sentDesired, desiredFromStored(reread.profile), reread.profile)) {
1836
+ io.log(` stored repository gate: ${reread.profile.kind ?? "none"} (revision ${reread.revision}; confirmed by reading it back)`);
1837
+ if (unsaved !== null)
1838
+ reportUnsavedSettings(io, unsaved);
1839
+ else if (workerSetupSkipped)
1840
+ reportUnsavedSettings(io, { workerEnvNames: [], hintChecks: [], workerDatabase: true });
1841
+ return reread;
1842
+ }
1843
+ if (reread === null) {
1844
+ io.errorLog(`Repository gate write uncertain (${outcome.refusal}): ${GATE_WRITE_REFUSAL_TEXT[outcome.refusal]}`);
1845
+ io.errorLog(" It may or may not have been stored, and it could not be read back. Read the gate before retrying.");
1846
+ return null;
1847
+ }
1848
+ }
1172
1849
  if (!outcome.ok) {
1173
1850
  io.errorLog(`Repository gate not stored (${outcome.refusal}): ${GATE_WRITE_REFUSAL_TEXT[outcome.refusal]}`);
1174
1851
  const reason = outcome.detail?.reason;
@@ -1196,6 +1873,8 @@ export async function storeConductorGate(io, access, plan) {
1196
1873
  io.log(` stored repository gate: ${outcome.profile.profile?.kind ?? "none"} (revision ${outcome.profile.revision})`);
1197
1874
  if (unsaved !== null)
1198
1875
  reportUnsavedSettings(io, unsaved);
1876
+ else if (workerSetupSkipped)
1877
+ reportUnsavedSettings(io, { workerEnvNames: [], hintChecks: [], workerDatabase: true });
1199
1878
  return outcome.profile;
1200
1879
  }
1201
1880
  /**
@@ -1221,6 +1900,16 @@ function describeUnsentDeclarations(write) {
1221
1900
  if (write.ci_database !== undefined) {
1222
1901
  lines.push(` Not stored — CI database behavior: ${write.ci_database ?? "unknown (reset)"}`);
1223
1902
  }
1903
+ if (write.worker_database !== undefined) {
1904
+ // Never the declaration itself: its identifiers and command stay in admin output.
1905
+ lines.push(" Not stored — worker database setup. Nothing else about setup or launch depends on it.");
1906
+ }
1907
+ if (write.must_order_paths !== undefined) {
1908
+ const paths = write.must_order_paths ?? [];
1909
+ lines.push(paths.length === 0
1910
+ ? " Not stored — must-order paths: clear every stored entry"
1911
+ : ` Not stored — must-order paths (re-enter them to keep them): ${paths.map(terminalSafe).join(", ")}`);
1912
+ }
1224
1913
  return lines;
1225
1914
  }
1226
1915
  /**
@@ -1231,7 +1920,9 @@ function reportUnsavedSettings(io, unsaved) {
1231
1920
  if (unsaved.workerEnvNames.length === 0 &&
1232
1921
  unsaved.hintChecks.length === 0 &&
1233
1922
  unsaved.dependencyInstall === undefined &&
1234
- unsaved.ciDatabase === undefined) {
1923
+ unsaved.ciDatabase === undefined &&
1924
+ unsaved.mustOrderPaths === undefined &&
1925
+ unsaved.workerDatabase === undefined) {
1235
1926
  return;
1236
1927
  }
1237
1928
  io.log(" ⚠ Partly stored: this server is older than the installer and cannot store these settings.");
@@ -1244,6 +1935,8 @@ function reportUnsavedSettings(io, unsaved) {
1244
1935
  for (const line of describeUnsentDeclarations({
1245
1936
  ...(unsaved.dependencyInstall !== undefined ? { dependency_install: unsaved.dependencyInstall } : {}),
1246
1937
  ...(unsaved.ciDatabase !== undefined ? { ci_database: unsaved.ciDatabase } : {}),
1938
+ ...(unsaved.mustOrderPaths !== undefined ? { must_order_paths: unsaved.mustOrderPaths } : {}),
1939
+ ...(unsaved.workerDatabase !== undefined ? { worker_database: { mode: "none" } } : {}),
1247
1940
  })) {
1248
1941
  io.log(line);
1249
1942
  }
@@ -1294,9 +1987,33 @@ function reportJob(io, job) {
1294
1987
  return "qualified";
1295
1988
  }
1296
1989
  if (job.job_status === "succeeded") {
1990
+ // BAPI-1637: the phase is the server's reading of the stored result. The gate
1991
+ // stays unqualified in every branch, and each says so.
1992
+ if (job.phase === "dependency_preparation_failed") {
1993
+ io.errorLog(` Failed — ${DEPENDENCY_INSTALL_FAILED_TEXT} The local gate stays unqualified, so unattended ` +
1994
+ "auto-merge stays closed.");
1995
+ io.errorLog(` ${DEPENDENCY_INSTALL_REPAIR_TEXT}`);
1996
+ io.errorLog(` Qualify again: ${PRINTED_QUALIFY_GATE_COMMAND}`);
1997
+ return "failed";
1998
+ }
1999
+ if (job.phase === "could_not_start") {
2000
+ io.errorLog(` Failed — ${COULD_NOT_START_TEXT} The local gate stays unqualified, so unattended auto-merge ` +
2001
+ "stays closed.");
2002
+ io.errorLog(` ${CHANGE_TEST_COMMAND_HINT} Then qualify again: ${PRINTED_QUALIFY_GATE_COMMAND}`);
2003
+ return "failed";
2004
+ }
2005
+ if (job.phase === null && job.dependency_install_declared === true) {
2006
+ io.errorLog(` Failed — ${PREPARATION_UNCERTAIN_TEXT} The local gate stays unqualified, so unattended ` +
2007
+ "auto-merge stays closed.");
2008
+ io.errorLog(` ${PREPARATION_UNCERTAIN_REPAIR_TEXT} Then qualify again: ${PRINTED_QUALIFY_GATE_COMMAND}`);
2009
+ return "failed";
2010
+ }
1297
2011
  io.errorLog(" Failed — a confirmed command did not pass under the executor. The installation itself " +
1298
2012
  "succeeded, but the local gate stays unqualified, so unattended auto-merge stays closed.");
1299
2013
  io.errorLog(` Fix the command, then qualify again: ${PRINTED_QUALIFY_GATE_COMMAND}`);
2014
+ if (job.phase === "ran_and_failed" && job.dependency_install_declared === false) {
2015
+ io.errorLog(` ${MISSING_INSTALL_TEXT}`);
2016
+ }
1300
2017
  return "failed";
1301
2018
  }
1302
2019
  io.errorLog(` Failed — the executor could not run job ${job.job_id} (no clean default-branch checkout, ` +
@@ -1387,6 +2104,268 @@ export async function runConductorGateQualification(io, access, gateDeps, input)
1387
2104
  return reportJob(io, latest);
1388
2105
  }
1389
2106
  // ---------------------------------------------------------------------------
2107
+ // BAPI-1603: the learned test command, proven by a server-owned trial
2108
+ // ---------------------------------------------------------------------------
2109
+ //
2110
+ // Setup never asks for a test command and never stores one itself. It asks the
2111
+ // server to find the command from the repository's learned prose (or to validate
2112
+ // the owner's `--test-command`), the server queues one TRIAL qualification, the
2113
+ // short-lived executor drains it, and the server promotes the local member only if
2114
+ // every command passes. Success is read from the validated job and a fresh read of
2115
+ // the gate profile, never from the executor's exit status, and the client writes no
2116
+ // local member. Anything uncertain is reconciled by re-reading authoritative state
2117
+ // before anything else happens, and the request is never repeated automatically.
2118
+ /** How often a running trial prints one plain progress line. */
2119
+ export const LEARNED_TRIAL_PROGRESS_INTERVAL_MS = 10_000;
2120
+ /** The commands a profile's local members run, by digest, in order. */
2121
+ function localDigests(profile) {
2122
+ return (profile?.local_commands ?? []).map((c) => c.digest).join(",");
2123
+ }
2124
+ /**
2125
+ * Whether `read` shows the trial's promotion: a confirmed profile with local
2126
+ * commands that differ from the ones the trial started with, qualified at its own
2127
+ * revision, past the revision the trial was bound to.
2128
+ */
2129
+ function promotionObserved(read, input) {
2130
+ if (read === null || !read.confirmed || read.profile === null)
2131
+ return false;
2132
+ if (read.profile.local_commands.length === 0)
2133
+ return false;
2134
+ if (read.qualification_state !== "qualified")
2135
+ return false;
2136
+ if (read.revision <= input.current.revision)
2137
+ return false;
2138
+ return localDigests(read.profile) !== localDigests(input.current.profile);
2139
+ }
2140
+ async function readGateProfileOrNull(io, access) {
2141
+ try {
2142
+ return await fetchConductorGateProfile(access, io.fetchJson);
2143
+ }
2144
+ catch {
2145
+ return null;
2146
+ }
2147
+ }
2148
+ /**
2149
+ * Ask the server for the learned (or owner-supplied) test command, drain the trial
2150
+ * it queues, and report only what the server and a fresh profile read confirm.
2151
+ * Never throws and never writes a gate: an unqualified, stale, or could-not-run
2152
+ * trial leaves the profile exactly as the server holds it.
2153
+ */
2154
+ export async function runLearnedTestCommandTrial(io, access, gateDeps, input) {
2155
+ const requestedSource = input.ownerCommand !== undefined ? "owner" : "learned";
2156
+ const posted = await requestConductorLearnedTestCommand(access, {
2157
+ expectedRevision: input.current.revision,
2158
+ ...(input.candidates !== undefined ? { candidates: input.candidates } : {}),
2159
+ ...(input.ownerCommand !== undefined ? { ownerCommand: input.ownerCommand } : {}),
2160
+ }, io.postJson);
2161
+ switch (posted.kind) {
2162
+ case "not_needed":
2163
+ case "stale_revision":
2164
+ case "unsupported":
2165
+ return { status: posted.kind };
2166
+ case "state_unavailable":
2167
+ return { status: "unavailable" };
2168
+ case "refused":
2169
+ return { status: "refused", reason: posted.reason };
2170
+ case "no_command":
2171
+ return { status: "no_command", source: posted.source, reason: posted.reason };
2172
+ case "uncertain":
2173
+ case "malformed": {
2174
+ // The request may have queued a trial and even finished it. Read the
2175
+ // authoritative profile before anything else.
2176
+ const read = await readGateProfileOrNull(io, access);
2177
+ if (promotionObserved(read, input)) {
2178
+ return { status: "promoted", source: requestedSource, commands: [], profile: read };
2179
+ }
2180
+ return { status: "uncertain", reason: "request_unclear", profile: read };
2181
+ }
2182
+ case "qualification_queued":
2183
+ break;
2184
+ }
2185
+ const { source, jobId, commands } = posted;
2186
+ const reconcile = async (reason) => {
2187
+ const read = await readGateProfileOrNull(io, access);
2188
+ if (promotionObserved(read, input))
2189
+ return { status: "promoted", source, commands, profile: read };
2190
+ return { status: "uncertain", reason, profile: read };
2191
+ };
2192
+ let job = await readJob(io, access, jobId);
2193
+ if (job === null)
2194
+ return reconcile("job_unreadable");
2195
+ if (!isTerminal(job)) {
2196
+ const runExecutor = gateDeps?.runQualificationExecutor;
2197
+ if (!runExecutor) {
2198
+ io.errorLog(" The trial is queued and needs a repository-wide executor to run it:");
2199
+ executorRemedy(io);
2200
+ return reconcile("executor_not_run");
2201
+ }
2202
+ io.log(" Running it once on this computer, in a clean checkout of your default branch…");
2203
+ // One progress notice covers the whole wait: the run itself and the polling that follows it.
2204
+ const progressTimer = gateDeps?.progressTimer ?? {
2205
+ ...createSetupProgressTimer(),
2206
+ intervalMs: gateDeps?.progressIntervalMs ?? LEARNED_TRIAL_PROGRESS_INTERVAL_MS,
2207
+ };
2208
+ const { run, latest } = await withSetupProgress("checking the test command", async () => {
2209
+ let ran;
2210
+ try {
2211
+ ran = await runExecutor({ repoName: access.repoName, baseUrl: input.baseUrl });
2212
+ }
2213
+ catch {
2214
+ ran = { started: false, exitCode: 1 };
2215
+ }
2216
+ // The exit code proves nothing: read the server.
2217
+ const now = gateDeps?.now ?? (() => Date.now());
2218
+ const sleep = gateDeps?.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
2219
+ const deadline = now() + QUALIFICATION_OBSERVATION_BUDGET_MS;
2220
+ let seen = null;
2221
+ while (true) {
2222
+ const read = await readJob(io, access, jobId);
2223
+ if (read !== null)
2224
+ seen = read;
2225
+ if (seen !== null && isTerminal(seen))
2226
+ break;
2227
+ // A queued job after the executor returned will not move on its own here.
2228
+ if (seen !== null && seen.job_status === "queued")
2229
+ break;
2230
+ const remaining = deadline - now();
2231
+ if (remaining <= 0)
2232
+ break;
2233
+ await sleep(Math.min(QUALIFICATION_OBSERVATION_INTERVAL_MS, remaining));
2234
+ }
2235
+ return { run: ran, latest: seen };
2236
+ }, { errorLog: io.errorLog, timer: progressTimer });
2237
+ if (latest === null)
2238
+ return reconcile(run.started ? "job_unreadable" : "executor_not_run");
2239
+ if (!isTerminal(latest)) {
2240
+ return reconcile(latest.job_status === "queued" ? (run.started ? "executor_failed" : "executor_not_run") : "still_running");
2241
+ }
2242
+ job = latest;
2243
+ }
2244
+ const read = await readGateProfileOrNull(io, access);
2245
+ // BAPI-1637: the server's own read of the finished job, carried as it came.
2246
+ const evidence = {
2247
+ phase: job.phase,
2248
+ dependencyInstallDeclared: job.dependency_install_declared,
2249
+ };
2250
+ if (job.qualification_state === "stale" || job.failure === "stale") {
2251
+ return { status: "stale", source, profile: read, evidence };
2252
+ }
2253
+ if (job.job_status === "succeeded" && job.qualification_state === "qualified") {
2254
+ if (promotionObserved(read, input))
2255
+ return { status: "promoted", source, commands, profile: read, evidence };
2256
+ return { status: "uncertain", reason: "result_unreadable", profile: read, evidence };
2257
+ }
2258
+ if (job.job_status === "succeeded" && job.qualification_state === "unqualified") {
2259
+ return { status: "unqualified", source, profile: read, evidence };
2260
+ }
2261
+ if (job.job_status === "succeeded") {
2262
+ // Finished without a verdict: only a promotion the profile shows can settle it.
2263
+ if (promotionObserved(read, input))
2264
+ return { status: "promoted", source, commands, profile: read, evidence };
2265
+ return { status: "uncertain", reason: "result_unreadable", profile: read, evidence };
2266
+ }
2267
+ return { status: "could_not_run", source, profile: read, evidence };
2268
+ }
2269
+ // BAPI-1637 — fixed wording for each completed phase. None of it names a command,
2270
+ // an install step, a path, or any output: the server's phase token selects the text.
2271
+ const DEPENDENCY_INSTALL_FAILED_TEXT = "The dependency install failed, so the tests did not run.";
2272
+ const DEPENDENCY_INSTALL_REPAIR_TEXT = "Correct the install step (for example, a lockfile that no longer matches the manifest), then run setup again.";
2273
+ const COULD_NOT_START_TEXT = "The test command could not be started (the program could not launch).";
2274
+ const MISSING_INSTALL_TEXT = "No install step was declared, so the dependencies may be missing. Run setup again and accept the proposed install step.";
2275
+ 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.";
2276
+ const PREPARATION_UNCERTAIN_REPAIR_TEXT = "Update the Bridge executor to the latest version, then run setup again.";
2277
+ /** The instruction every successful and failed trial line ends with. */
2278
+ const CHANGE_TEST_COMMAND_HINT = 'Change it with --test-command "<your command>".';
2279
+ /**
2280
+ * Print one trial outcome in plain words. The validated command is named ONLY on
2281
+ * the successful path, and only as the server returned it; no other outcome prints
2282
+ * a command, executor output, or a raw server response.
2283
+ */
2284
+ export function reportLearnedCommandTrial(io, result) {
2285
+ const learned = (source) => source === "owner" ? "you gave it with --test-command" : "it learned from your repository";
2286
+ switch (result.status) {
2287
+ case "promoted": {
2288
+ const named = result.commands.map((c) => `\`${c.command.replace(/[\u0000-\u001F\u007F]/g, "?")}\``).join(", ");
2289
+ io.log(named.length > 0
2290
+ ? ` Bridge will run ${named} before each merge. It is the command ${learned(result.source)}, and Bridge ` +
2291
+ `checked it by running it once. ${CHANGE_TEST_COMMAND_HINT}`
2292
+ : ` Bridge stored a test command ${learned(result.source)} and checked it by running it once. ` +
2293
+ CHANGE_TEST_COMMAND_HINT);
2294
+ return;
2295
+ }
2296
+ case "not_needed":
2297
+ io.log(" Bridge already has a test command for this repository, so it did not look for another.");
2298
+ return;
2299
+ case "no_command":
2300
+ io.log(` Bridge found no test command to try (${NO_COMMAND_TEXT[result.reason]}). It stored none. ` +
2301
+ "Give one with --test-command \"<your command>\" and Bridge will check it by running it once.");
2302
+ return;
2303
+ case "unqualified": {
2304
+ const { phase, dependencyInstallDeclared } = result.evidence ?? { phase: null, dependencyInstallDeclared: null };
2305
+ if (phase === "dependency_preparation_failed") {
2306
+ io.log(` ${DEPENDENCY_INSTALL_FAILED_TEXT} Bridge stored no learned command. ${DEPENDENCY_INSTALL_REPAIR_TEXT}`);
2307
+ return;
2308
+ }
2309
+ if (phase === "could_not_start") {
2310
+ io.log(` ${COULD_NOT_START_TEXT} Bridge stored none. ${CHANGE_TEST_COMMAND_HINT}`);
2311
+ return;
2312
+ }
2313
+ if (phase === null && dependencyInstallDeclared === true) {
2314
+ io.log(` ${PREPARATION_UNCERTAIN_TEXT} Bridge stored none. ${PREPARATION_UNCERTAIN_REPAIR_TEXT}`);
2315
+ return;
2316
+ }
2317
+ io.log(" The test command did not pass when Bridge ran it once, so Bridge stored none. " +
2318
+ "Fix the failing tests, or give another command with --test-command \"<your command>\".");
2319
+ if (phase === "ran_and_failed" && dependencyInstallDeclared === false)
2320
+ io.log(` ${MISSING_INSTALL_TEXT}`);
2321
+ return;
2322
+ }
2323
+ case "stale":
2324
+ io.log(" The gate changed while the test command was being checked, so Bridge stored none. Run setup again.");
2325
+ return;
2326
+ case "could_not_run":
2327
+ io.log(" Bridge could not run the test command (no clean checkout of your default branch, or the run was " +
2328
+ "interrupted), so it stored none. Run setup again.");
2329
+ return;
2330
+ case "stale_revision":
2331
+ io.log(" The gate changed before the test command could be checked, so nothing was started. Run setup again.");
2332
+ return;
2333
+ case "unsupported":
2334
+ io.log(" This Bridge server cannot learn a test command yet, so Bridge skipped it. Update the Bridge API to use it.");
2335
+ return;
2336
+ case "unavailable":
2337
+ io.log(" Bridge could not prepare the test command right now and started nothing. Run setup again shortly.");
2338
+ return;
2339
+ case "refused":
2340
+ io.log(result.reason === "unauthorized"
2341
+ ? " This key cannot ask Bridge to check a test command (an administrator key is needed), so Bridge skipped it."
2342
+ : " Bridge's server refused the test command request, so Bridge skipped it.");
2343
+ return;
2344
+ case "uncertain":
2345
+ io.log(` Bridge cannot tell whether the test command was stored (${UNCERTAIN_TEXT[result.reason]}). ` +
2346
+ "It will not try again on its own. Run setup again to read what the server holds.");
2347
+ return;
2348
+ }
2349
+ }
2350
+ const NO_COMMAND_TEXT = Object.freeze({
2351
+ no_testing_instructions: "the repository has no learned testing instructions",
2352
+ llm_unavailable: "the server could not read them just now",
2353
+ llm_output_invalid: "the server could not turn them into a command",
2354
+ no_candidates: "they name no command",
2355
+ working_directory_unsupported: "the command must run from a subdirectory, which a gate cannot do",
2356
+ not_plain_argv: "the command is not a plain program and arguments",
2357
+ command_not_allowed: "the command is not allowed",
2358
+ invalid_command: "the command is not valid",
2359
+ });
2360
+ const UNCERTAIN_TEXT = Object.freeze({
2361
+ request_unclear: "the request did not answer clearly",
2362
+ executor_not_run: "no executor ran the check",
2363
+ executor_failed: "the executor did not finish the check",
2364
+ job_unreadable: "the check's state could not be read",
2365
+ still_running: "the check was still running",
2366
+ result_unreadable: "the result could not be confirmed",
2367
+ });
2368
+ // ---------------------------------------------------------------------------
1390
2369
  // Standalone actions: --clear-gate and --qualify-gate
1391
2370
  // ---------------------------------------------------------------------------
1392
2371
  /** `--clear-gate`: BAPI-1390's clear action under the revision compare-and-swap. */
@@ -1535,6 +2514,31 @@ const COVERAGE_NEXT_STEP = Object.freeze({
1535
2514
  no_workflows: "add a workflow with a pull_request trigger whose branches list includes 'epic/**'.",
1536
2515
  });
1537
2516
  const GENERIC_COVERAGE_NEXT_STEP = "check by hand that a pull_request trigger includes 'epic/**'.";
2517
+ /** BAPI-1654 — each coverage state and reason in plain words, so no internal token reaches the owner. */
2518
+ const PLAIN_COVERAGE = Object.freeze({
2519
+ covers: "runs on epic-branch PRs",
2520
+ does_not_cover: "does not run on epic-branch PRs",
2521
+ could_not_tell: "could not be confirmed to run on epic-branch PRs",
2522
+ });
2523
+ const PLAIN_COVERAGE_REASON = Object.freeze({
2524
+ pr_trigger_covers: "its pull_request trigger includes epic branches",
2525
+ no_pr_trigger: "it has no pull_request trigger",
2526
+ branch_filter_excludes_epic: "its pull_request branch list leaves out epic branches",
2527
+ path_filter: "a paths filter decides whether it starts",
2528
+ branch_filter_uncertain: "its branch filter could not be matched to epic branches with certainty",
2529
+ types_filter: "its pull_request types leave out opened or synchronize",
2530
+ indirect_trigger: "another workflow starts it",
2531
+ reusable_workflow_job: "a job calls a reusable workflow",
2532
+ unparseable: "it could not be read as a workflow",
2533
+ unsupported_structure: "it uses YAML that Bridge does not read confidently",
2534
+ listing_failed: "the workflow folder could not be listed",
2535
+ file_limit_reached: "there are too many workflow files to read",
2536
+ read_failed: "it could not be read",
2537
+ no_workflows: "there are no workflow files",
2538
+ });
2539
+ function plainCoverageReason(reason) {
2540
+ return PLAIN_COVERAGE_REASON[reason] ?? "Bridge could not tell why";
2541
+ }
1538
2542
  function coverageNextStep(reason) {
1539
2543
  return COVERAGE_NEXT_STEP[reason] ?? GENERIC_COVERAGE_NEXT_STEP;
1540
2544
  }
@@ -1612,11 +2616,11 @@ export function renderEpicBranchCiFindings(io, coverage, rules) {
1612
2616
  if (coverage.coverage !== "covers" && unresolved.length > 0) {
1613
2617
  io.log(" Workflows that do not clearly cover epic-branch PRs:");
1614
2618
  for (const w of unresolved) {
1615
- io.log(` ${w.path}: ${w.coverage} (${w.reason}) — next step: ${coverageNextStep(w.reason)}`);
2619
+ io.log(` ${w.path}: ${PLAIN_COVERAGE[w.coverage]}, because ${plainCoverageReason(w.reason)} — next step: ${coverageNextStep(w.reason)}`);
1616
2620
  }
1617
2621
  }
1618
2622
  else if (coverage.coverage !== "covers") {
1619
- io.log(` (${coverage.reason}) — next step: ${coverageNextStep(coverage.reason)}`);
2623
+ io.log(` ${plainCoverageReason(coverage.reason)} — next step: ${coverageNextStep(coverage.reason)}`);
1620
2624
  }
1621
2625
  }
1622
2626
  /**
@@ -1631,7 +2635,29 @@ export function renderEpicBranchCiFindings(io, coverage, rules) {
1631
2635
  *
1632
2636
  * Returns the decision, or null when none was made.
1633
2637
  */
1634
- export async function resolveEpicBranchCiDecision(io, flag) {
2638
+ export async function resolveEpicBranchCiDecision(io, flag,
2639
+ /**
2640
+ * BAPI-1604 — when set, the decision is read from the inspected coverage instead of
2641
+ * asked: only a confirmed `covers` becomes an inferred `include`. Anything else records
2642
+ * nothing, asks nothing, and says how to record a choice. An explicit flag still wins.
2643
+ */
2644
+ inferFrom,
2645
+ /** BAPI-1679 — says where a decision came from when no owner passed it as a flag. */
2646
+ decisionNote) {
2647
+ if (inferFrom !== undefined) {
2648
+ if (flag !== null) {
2649
+ io.log(` ${decisionNote ?? `Using --epic-branch-ci-decision=${flag}.`}`);
2650
+ return flag;
2651
+ }
2652
+ if (inferFrom === "covers") {
2653
+ io.log(" Epic-branch CI: include (a workflow runs on epic-branch PRs).");
2654
+ return "include";
2655
+ }
2656
+ io.log(" No epic-branch CI decision was recorded: Bridge could not confirm that a workflow runs on epic-branch PRs. " +
2657
+ "To record one, pass --epic-branch-ci-decision=include or --epic-branch-ci-decision=decline. " +
2658
+ "Until one is recorded, runs behave as include.");
2659
+ return null;
2660
+ }
1635
2661
  io.log(" Include: each child waits for the checks that run on its epic-branch PR before it merges.");
1636
2662
  io.log(" Decline: children merge into the epic branch without waiting for checks that never run there. " +
1637
2663
  "Problems then surface only at the human-gated integration PR into the base branch.");
@@ -1663,12 +2689,59 @@ function printExemptionManualSteps(io, ownerRepo, branch) {
1663
2689
  for (const line of steps)
1664
2690
  io.log(` ${line}`);
1665
2691
  }
2692
+ /**
2693
+ * Map the exemption outcome to its setup write result. Exhaustive on purpose: a new
2694
+ * {@link ExemptionInstallOutcome} fails compilation here rather than defaulting.
2695
+ */
2696
+ export function mapExemptionOutcomeToWriteResult(outcome) {
2697
+ switch (outcome) {
2698
+ case "applied":
2699
+ return { key: "approval_exemption", status: "written", target: "github.rulesets" };
2700
+ case "declined":
2701
+ return { key: "approval_exemption", status: "declined", target: "github.rulesets" };
2702
+ case "not_needed":
2703
+ return { key: "approval_exemption", status: "unchanged", target: "github.rulesets" };
2704
+ case "unreadable":
2705
+ return {
2706
+ key: "approval_exemption",
2707
+ status: "unchanged",
2708
+ target: "github.rulesets",
2709
+ reason: "Bridge could not read the approval-rule settings. No approval-rule change was attempted.",
2710
+ };
2711
+ case "could_not_tell":
2712
+ return {
2713
+ key: "approval_exemption",
2714
+ status: "uncertain",
2715
+ target: "github.rulesets",
2716
+ reason: "the ruleset change could not be confirmed",
2717
+ fix: "Check the ruleset yourself; setup will not retry it blindly.",
2718
+ };
2719
+ case "printed_steps":
2720
+ return {
2721
+ key: "approval_exemption",
2722
+ status: "refused",
2723
+ target: "github.rulesets",
2724
+ reason: "the approval rule is not safe to change automatically",
2725
+ fix: "Follow the manual steps printed above.",
2726
+ };
2727
+ default: {
2728
+ const unreachable = outcome;
2729
+ return unreachable;
2730
+ }
2731
+ }
2732
+ }
1666
2733
  /**
1667
2734
  * The approval-rule exemption offer (requirement 6). Separate from the
1668
2735
  * include/decline choice and warning-toned. A ruleset is changed only after an
1669
2736
  * explicit typed "yes", a passed scope check, and a confirming re-read.
1670
2737
  */
1671
- export async function offerApprovalExemption(io, seams, run, ownerRepo, branch, rules) {
2738
+ export async function offerApprovalExemption(io, seams, run, ownerRepo, branch, rules,
2739
+ /**
2740
+ * BAPI-1638 — an explicit decision from the shared apply. `approve` stands in
2741
+ * for the typed `yes` (the answers path never prompts); `decline` changes
2742
+ * nothing. Absent keeps the interactive typed-`yes` question exactly as before.
2743
+ */
2744
+ decision) {
1672
2745
  const approvals = rules?.approvalsRequired ?? "could_not_tell";
1673
2746
  if (approvals === "no")
1674
2747
  return "not_needed";
@@ -1677,7 +2750,8 @@ export async function offerApprovalExemption(io, seams, run, ownerRepo, branch,
1677
2750
  io.log(" Could not tell whether an approval rule applies to epic-branch PRs, so no exemption was offered " +
1678
2751
  "and nothing was changed.");
1679
2752
  printExemptionManualSteps(io, ownerRepo, branch);
1680
- return "could_not_tell";
2753
+ // Nothing was read, so nothing was attempted: not an uncertain write.
2754
+ return "unreadable";
1681
2755
  }
1682
2756
  io.log("");
1683
2757
  io.log(" Warning: an approval rule applies to epic-branch PRs.");
@@ -1685,12 +2759,14 @@ export async function offerApprovalExemption(io, seams, run, ownerRepo, branch,
1685
2759
  "Whether it can is unknown: check the ruleset's bypass list.");
1686
2760
  io.log(" Bridge can exclude epic/** from this approval rule with your own gh login. It changes only the " +
1687
2761
  "ruleset's excluded branches, and only for a repository ruleset that holds nothing but the approval rule.");
1688
- if (!io.promptLine) {
2762
+ if (decision === undefined && !io.promptLine) {
1689
2763
  io.log(" This run cannot prompt, so nothing was changed. The --epic-branch-ci-decision flag never grants this.");
1690
2764
  printExemptionManualSteps(io, ownerRepo, branch);
1691
2765
  return "printed_steps";
1692
2766
  }
1693
- const consent = await ask(io, "Exclude epic/** from the approval rule now? Type yes to change it [y/N]: ");
2767
+ const consent = decision !== undefined
2768
+ ? decision === "approve"
2769
+ : await ask(io, "Exclude epic/** from the approval rule now? Type yes to change it [y/N]: ");
1694
2770
  if (!consent) {
1695
2771
  io.log(" Not changed.");
1696
2772
  printExemptionManualSteps(io, ownerRepo, branch);
@@ -1721,40 +2797,28 @@ export async function offerApprovalExemption(io, seams, run, ownerRepo, branch,
1721
2797
  io.log(" Excluded epic/** from the approval rule. A re-read confirmed no approval rule remains and required checks are unchanged.");
1722
2798
  return "applied";
1723
2799
  }
2800
+ // Only an explicit "nothing was written" signal with a recognized pre-write reason is
2801
+ // safe to report as unchanged. A missing signal, failed or partial PUT, or throw stays uncertain.
2802
+ if (applied.attempted === false && (applied.reason === "scope_not_eligible" || applied.reason === "ruleset_changed")) {
2803
+ io.log(` Not changed: the approval rule was not changed (${applied.reason}).`);
2804
+ printExemptionManualSteps(io, ownerRepo, branch);
2805
+ return "printed_steps";
2806
+ }
1724
2807
  io.log(` Could not confirm the change (${applied.reason}). Check the ruleset yourself; nothing else will be attempted.`);
1725
2808
  printExemptionManualSteps(io, ownerRepo, branch);
1726
2809
  return "could_not_tell";
1727
2810
  }
1728
2811
  /**
1729
- * Run the epic-branch CI step: detect the provider, inspect workflow triggers
1730
- * and epic-branch rules, print findings, resolve include/decline, offer the
1731
- * approval exemption, and record an explicit decision with its evidence.
1732
- *
1733
- * Never blocks the install: a failed read or write prints a warning and the
1734
- * step returns. It never writes `decline` unless the owner chose it.
2812
+ * BAPI-1638 — collect the epic-branch CI evidence: detect the provider, find an
2813
+ * example epic branch, inspect workflow coverage, and read the epic-branch rules.
2814
+ * Read-only. A failed read is recorded as `could_not_tell` (or `null` rules),
2815
+ * never guessed. The exemption's own scope check runs only after approval,
2816
+ * inside {@link offerApprovalExemption}.
1735
2817
  */
1736
- export async function runEpicBranchCiInspection(io, access, gateDeps, options) {
1737
- const result = {
1738
- status: "completed",
1739
- coverage: null,
1740
- rules: null,
1741
- exemptionOutcome: null,
1742
- decision: null,
1743
- evidence: null,
1744
- recorded: false,
1745
- manualAction: null,
1746
- };
1747
- io.log("");
1748
- io.log("Epic-branch CI — do checks run on pull requests into epic branches?");
2818
+ export async function collectEpicBranchCi(gateDeps) {
1749
2819
  const seams = gateDeps?.epicBranchCi;
1750
- if (!seams) {
1751
- io.log(" skipped — this caller supplied no epic-branch CI inspection seams. Nothing was recorded.");
1752
- return { ...result, status: "skipped_no_seams" };
1753
- }
1754
- if (options.dryRun) {
1755
- io.log(" Dry run — would inspect workflow triggers and epic-branch rules, then ask include or decline. Nothing was recorded.");
1756
- return { ...result, status: "skipped_dry_run" };
1757
- }
2820
+ if (!seams)
2821
+ return { status: "skipped_no_seams" };
1758
2822
  let provider;
1759
2823
  try {
1760
2824
  provider = await seams.detectProvider();
@@ -1762,12 +2826,8 @@ export async function runEpicBranchCiInspection(io, access, gateDeps, options) {
1762
2826
  catch {
1763
2827
  provider = { kind: "unknown" };
1764
2828
  }
1765
- if (provider.kind !== "github") {
1766
- io.log(" The epic-branch CI inspection is GitHub-only, and this repository's remote is not on github.com" +
1767
- (provider.kind === "unknown" ? " (or could not be read)" : "") +
1768
- ". No epic-branch CI decision was recorded.");
1769
- return { ...result, status: "skipped_not_github" };
1770
- }
2829
+ if (provider.kind !== "github")
2830
+ return { status: "skipped_not_github", provider: provider.kind };
1771
2831
  const ownerRepo = provider.ownerRepo;
1772
2832
  const run = safeGhRunner(seams.runGh);
1773
2833
  let branch = EPIC_BRANCH_CI_PROBE_BRANCH;
@@ -1793,11 +2853,63 @@ export async function runEpicBranchCiInspection(io, access, gateDeps, options) {
1793
2853
  catch {
1794
2854
  rules = null;
1795
2855
  }
2856
+ return { status: "collected", ownerRepo, branch, coverage, rules };
2857
+ }
2858
+ /**
2859
+ * BAPI-1638 — the decision write, alone: `putEpicBranchCiDecision` (or the test
2860
+ * override). Called only with an explicit or coverage-confirmed decision.
2861
+ */
2862
+ export async function applyEpicBranchCiDecision(io, access, seams, request) {
2863
+ const record = seams.recordDecision ??
2864
+ ((acc, body) => putEpicBranchCiDecision(acc, acc.repoName, body, io.postJson));
2865
+ try {
2866
+ await record(access, request);
2867
+ return { recorded: true };
2868
+ }
2869
+ catch (err) {
2870
+ return { recorded: false, kind: err instanceof ConductorBridgeApiError ? err.kind : "error" };
2871
+ }
2872
+ }
2873
+ export async function runEpicBranchCiInspection(io, access, gateDeps, options) {
2874
+ const result = {
2875
+ status: "completed",
2876
+ coverage: null,
2877
+ rules: null,
2878
+ exemptionOutcome: null,
2879
+ decision: null,
2880
+ evidence: null,
2881
+ recorded: false,
2882
+ manualAction: null,
2883
+ };
2884
+ io.log("");
2885
+ io.log("Epic-branch CI — do checks run on pull requests into epic branches?");
2886
+ const seams = gateDeps?.epicBranchCi;
2887
+ if (!seams) {
2888
+ io.log(" skipped — this caller supplied no epic-branch CI inspection seams. Nothing was recorded.");
2889
+ return { ...result, status: "skipped_no_seams" };
2890
+ }
2891
+ if (options.dryRun) {
2892
+ io.log(" Dry run — would inspect workflow triggers and epic-branch rules, then ask include or decline. Nothing was recorded.");
2893
+ return { ...result, status: "skipped_dry_run" };
2894
+ }
2895
+ const collected = options.collected ?? (await collectEpicBranchCi(gateDeps));
2896
+ if (collected.status === "skipped_no_seams") {
2897
+ io.log(" skipped — this caller supplied no epic-branch CI inspection seams. Nothing was recorded.");
2898
+ return { ...result, status: "skipped_no_seams" };
2899
+ }
2900
+ if (collected.status === "skipped_not_github") {
2901
+ io.log(" The epic-branch CI inspection is GitHub-only, and this repository's remote is not on github.com" +
2902
+ (collected.provider === "unknown" ? " (or could not be read)" : "") +
2903
+ ". No epic-branch CI decision was recorded.");
2904
+ return { ...result, status: "skipped_not_github" };
2905
+ }
2906
+ const { ownerRepo, branch, coverage, rules } = collected;
2907
+ const run = safeGhRunner(seams.runGh);
1796
2908
  result.coverage = coverage.coverage;
1797
2909
  result.rules = rules;
1798
2910
  renderEpicBranchCiFindings(io, coverage, rules);
1799
- const decision = await resolveEpicBranchCiDecision(io, options.decisionFlag);
1800
- const exemptionOutcome = await offerApprovalExemption(io, seams, run, ownerRepo, branch, rules);
2911
+ const decision = await resolveEpicBranchCiDecision(io, options.decisionFlag, options.inferFromCoverage === true ? coverage.coverage : undefined, options.decisionNote);
2912
+ const exemptionOutcome = await offerApprovalExemption(io, seams, run, ownerRepo, branch, rules, options.exemptionDecision);
1801
2913
  const evidence = buildEpicBranchCiEvidence(coverage.coverage, rules, exemptionOutcome);
1802
2914
  result.decision = decision;
1803
2915
  result.exemptionOutcome = exemptionOutcome;
@@ -1806,15 +2918,17 @@ export async function runEpicBranchCiInspection(io, access, gateDeps, options) {
1806
2918
  // the reason was already printed. It is not added to the manual steps.
1807
2919
  if (decision === null)
1808
2920
  return result;
1809
- const record = seams.recordDecision ??
1810
- ((acc, request) => putEpicBranchCiDecision(acc, acc.repoName, request, io.postJson));
1811
- try {
1812
- await record(access, { decision, evidence });
2921
+ if (options.recordedDecision !== undefined && options.recordedDecision === decision) {
2922
+ io.log(` epic-branch CI decision already recorded: ${decision}`);
2923
+ return { ...result, recorded: true, unchanged: true };
2924
+ }
2925
+ const written = await applyEpicBranchCiDecision(io, access, seams, { decision, evidence });
2926
+ if (written.recorded) {
1813
2927
  result.recorded = true;
1814
2928
  io.log(` recorded epic-branch CI decision: ${decision}`);
1815
2929
  }
1816
- catch (err) {
1817
- const kind = err instanceof ConductorBridgeApiError ? err.kind : "error";
2930
+ else {
2931
+ const kind = written.kind;
1818
2932
  io.errorLog(`Warning: the epic-branch CI decision could not be recorded (${kind}). The install continues; ` +
1819
2933
  "re-run it to record the decision.");
1820
2934
  result.manualAction =