@bridge_gpt/mcp-server 0.2.71 → 0.2.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +22 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +7 -7
  5. package/build/bridge-permissions.js +31 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/ci-system-detection.js +50 -0
  9. package/build/ci-trigger-adapters.js +631 -0
  10. package/build/ci-trigger-install.js +106 -0
  11. package/build/claude-review-workflow.js +1 -1
  12. package/build/cli-help.js +6 -0
  13. package/build/codex-auto-recovery.js +126 -0
  14. package/build/codex-launcher-pin.js +33 -2
  15. package/build/codex-skill-adapter.js +5 -1
  16. package/build/command-host.js +33 -0
  17. package/build/commands.generated.js +7 -6
  18. package/build/conductor/bridge-api-client.js +1352 -50
  19. package/build/conductor/bring-up-facts.js +18 -5
  20. package/build/conductor/command-drift-production.js +42 -17
  21. package/build/conductor/command-drift.js +47 -0
  22. package/build/conductor/declare-blocked.js +554 -0
  23. package/build/conductor/doctor.js +187 -28
  24. package/build/conductor/driver-commands.js +141 -0
  25. package/build/conductor/driver-guard.js +277 -0
  26. package/build/conductor/driver-lapse.js +321 -0
  27. package/build/conductor/driver-register.js +176 -0
  28. package/build/conductor/driver-release.js +174 -0
  29. package/build/conductor/driver-session-state.js +315 -0
  30. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  31. package/build/conductor/epic-implementer-cli.js +213 -13
  32. package/build/conductor/epic-server-database.js +162 -0
  33. package/build/conductor/epic-server-guidance.js +278 -0
  34. package/build/conductor/epic-server-journal.js +239 -0
  35. package/build/conductor/epic-server-processes.js +324 -0
  36. package/build/conductor/epic-server-recipe.js +397 -0
  37. package/build/conductor/epic-server-runtime.js +1207 -0
  38. package/build/conductor/epic-server-sfcc.js +107 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +594 -0
  41. package/build/conductor/gate-discovery.js +281 -10
  42. package/build/conductor/gate-settings-review.js +525 -5
  43. package/build/conductor/git-hooks-uninstall.js +112 -0
  44. package/build/conductor/git-hooks.js +81 -15
  45. package/build/conductor/guided-repair.js +10 -1
  46. package/build/conductor/install-doctor.js +2 -4
  47. package/build/conductor/launch-need-probes.js +6 -53
  48. package/build/conductor/launch-plan.js +318 -121
  49. package/build/conductor/local-merge.js +12 -1
  50. package/build/conductor/merge-execution-contract.js +1 -1
  51. package/build/conductor/merged-child-check.js +2 -1
  52. package/build/conductor/prerequisite-inputs.js +1213 -0
  53. package/build/conductor/readiness-assessment.js +93 -0
  54. package/build/conductor/readiness-cli.js +30 -9
  55. package/build/conductor/readiness-prerequisites.js +77 -5
  56. package/build/conductor/readiness-sections.js +146 -126
  57. package/build/conductor/readiness.js +21 -3
  58. package/build/conductor/recovery-cli.js +236 -15
  59. package/build/conductor/recovery-operations.js +34 -4
  60. package/build/conductor/repair-contract.js +33 -0
  61. package/build/conductor/tools.js +36 -4
  62. package/build/conductor/wait-run-attention.js +115 -0
  63. package/build/conductor/wait-run-cli.js +300 -21
  64. package/build/conductor/worker-database-doctor-inspector.js +34 -2
  65. package/build/conductor/worker-setup-tally.js +27 -0
  66. package/build/credential-store.js +96 -21
  67. package/build/dependency-install-declarations.js +212 -0
  68. package/build/docs.generated.js +4 -4
  69. package/build/doctor.js +91 -8
  70. package/build/drive-epic-help.js +23 -4
  71. package/build/drive-epic.js +1841 -340
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +140 -0
  74. package/build/epic-capability-statement.js +107 -0
  75. package/build/epic-ci-workflow-drift.js +30 -15
  76. package/build/epic-ci-workflow-install.js +110 -42
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow.js +38 -12
  79. package/build/epic-implementer-bin.js +2184 -52
  80. package/build/epic-launch-context.js +607 -0
  81. package/build/epic-launch-profile.js +1 -1
  82. package/build/epic-server-record.js +273 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/cli.js +2 -0
  87. package/build/executor/completion-contract.js +24 -1
  88. package/build/executor/credentials.js +1 -1
  89. package/build/executor/delivery-observations.js +113 -0
  90. package/build/executor/delivery-outcome.js +30 -0
  91. package/build/executor/dependency-refresh-runner.js +132 -0
  92. package/build/executor/dependency-refresh.js +530 -0
  93. package/build/executor/deps.js +4 -0
  94. package/build/executor/env.js +119 -17
  95. package/build/executor/epic-server-context.js +141 -0
  96. package/build/executor/gate-qualification-job.js +127 -26
  97. package/build/executor/harness-coverage.js +19 -0
  98. package/build/executor/http-client.js +87 -6
  99. package/build/executor/index.js +2 -1
  100. package/build/executor/install-preflight.js +1 -1
  101. package/build/executor/job-runner.js +659 -87
  102. package/build/executor/likely-tests.js +94 -97
  103. package/build/executor/observation.js +8 -0
  104. package/build/executor/pre-pr-checks.js +363 -0
  105. package/build/executor/prompt-spec.js +127 -5
  106. package/build/executor/reconcile-overlap-job.js +5 -3
  107. package/build/executor/required-verification.js +28 -0
  108. package/build/executor/required-work-diagnostics.js +32 -0
  109. package/build/executor/required-work-ledger.js +955 -39
  110. package/build/executor/results.js +100 -0
  111. package/build/executor/service-discovery.js +42 -0
  112. package/build/executor/service-lifecycle.js +109 -2
  113. package/build/executor/service-uninstall.js +205 -0
  114. package/build/executor/service-unit.js +5 -3
  115. package/build/executor/terminal-mutation.js +8 -0
  116. package/build/executor/test-clock.js +3 -0
  117. package/build/executor/verification-hints.js +179 -0
  118. package/build/executor/worker-command.js +126 -5
  119. package/build/executor/worker-database-config.js +281 -0
  120. package/build/executor/worker-database-target.js +16 -12
  121. package/build/executor/worker-database.js +575 -116
  122. package/build/executor/worker-finalization.js +71 -10
  123. package/build/executor/worker-guard-hook.js +10 -2
  124. package/build/executor/worker-resources.js +25 -3
  125. package/build/executor/worker-verification-guidance.js +55 -5
  126. package/build/executor/worktree-inspection.js +42 -0
  127. package/build/executor/worktree.js +20 -1
  128. package/build/executor-launch.js +54 -2
  129. package/build/generated-assets-catalog.js +2 -2
  130. package/build/github-sign-in.js +1 -1
  131. package/build/index.js +1111 -381
  132. package/build/init.js +29 -14
  133. package/build/install-bridge-conductor-answers.js +465 -0
  134. package/build/install-bridge-conductor-apply.js +259 -0
  135. package/build/install-bridge-conductor-assessment.js +895 -0
  136. package/build/install-bridge-conductor-compact.js +161 -0
  137. package/build/install-bridge-conductor-contracts.js +63 -0
  138. package/build/install-bridge-conductor-gate.js +1383 -188
  139. package/build/install-bridge-conductor-setup.js +637 -92
  140. package/build/install-bridge-conductor.js +3163 -740
  141. package/build/install-bridge.js +601 -128
  142. package/build/install-maintenance.js +127 -0
  143. package/build/install-reexec.js +1 -1
  144. package/build/launcher-config-inspection.js +162 -1
  145. package/build/local-cleanup.js +59 -0
  146. package/build/mcp-grant-candidates.js +767 -0
  147. package/build/mcp-grant-doctor.js +63 -0
  148. package/build/mcp-grant.js +288 -0
  149. package/build/mcp-host-targets.js +8 -0
  150. package/build/mcp-identity.js +23 -0
  151. package/build/mcp-install-state.js +68 -2
  152. package/build/mcp-invoke.js +126 -13
  153. package/build/mcp-presets.js +107 -0
  154. package/build/mcp-provisioning.js +134 -2
  155. package/build/mcp-registration-doctor.js +31 -2
  156. package/build/mcp-server-invocation.js +6 -1
  157. package/build/merge-workflow-install.js +236 -111
  158. package/build/package-script-semantics.js +10 -0
  159. package/build/pipeline-utils.js +1 -1
  160. package/build/pipelines.generated.js +6 -6
  161. package/build/plan-discovery.js +97 -4
  162. package/build/plan-execution-ledger.js +248 -9
  163. package/build/plan-generation-io.js +262 -0
  164. package/build/plan-generation.js +424 -0
  165. package/build/plane/build-freshness.js +6 -1
  166. package/build/plane/cli.js +75 -9
  167. package/build/plane/plane-freshness.js +23 -7
  168. package/build/plane/preflight.js +50 -10
  169. package/build/plane/shutdown.js +19 -0
  170. package/build/plane/terminal-run-cleanup.js +23 -5
  171. package/build/plane/terminal-run-status.js +4 -0
  172. package/build/printed-remedy-commands.js +229 -15
  173. package/build/readiness-check.js +1 -1
  174. package/build/readiness-prerequisites.generated.js +311 -4
  175. package/build/readme.generated.js +1 -1
  176. package/build/repository-state-paths.js +38 -0
  177. package/build/repository-toolchains.js +50 -8
  178. package/build/run-unit-tests-launcher.js +8 -1
  179. package/build/setup-change-policy.js +32 -0
  180. package/build/setup-epic.js +1192 -198
  181. package/build/setup-progress.js +44 -0
  182. package/build/setup-question.js +180 -0
  183. package/build/start-tickets.js +4 -0
  184. package/build/test-command-detection.js +32 -88
  185. package/build/test-support/notes-fs.js +40 -0
  186. package/build/third-party-mcp-targets.js +30 -0
  187. package/build/ticket-delivery-enrollment.js +30 -8
  188. package/build/ticket-delivery-run-scope.js +128 -0
  189. package/build/upgrade-cli.js +85 -2
  190. package/build/v2-readiness-requirements.js +28 -1
  191. package/build/version.generated.js +3 -3
  192. package/build/worker-guard-hook-bin.js +2 -2
  193. package/build/worktrees.js +105 -0
  194. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  195. package/docs/EPIC-IMPLEMENTER.md +5 -0
  196. package/docs/epic-implementer/getting-started.md +42 -15
  197. package/docs/epic-implementer/self-hosting.md +14 -1
  198. package/package.json +2 -2
@@ -1,5 +1,6 @@
1
+ import { parseAssessmentNegotiation } from './readiness-assessment.js';
1
2
  import { READINESS_PREREQUISITE_BY_ID } from "../readiness-prerequisites.generated.js";
2
- import { READINESS_PREREQUISITE_FIXES } from "../printed-remedy-commands.js";
3
+ import { PREVIOUS_SERVER_READINESS_FIXES, READINESS_PREREQUISITE_FIXES } from "../printed-remedy-commands.js";
3
4
  /**
4
5
  * TypeScript-side Bridge API access layer for the conductor producer (BAPI-395).
5
6
  *
@@ -20,6 +21,7 @@ import { normalizePrNumber, normalizeSha } from "./git-ci-types.js";
20
21
  import { ConductorValidationError } from "./errors.js";
21
22
  import { parseContinuationStatusResult, parseContinueParkedChildResult, } from "./epic-child-continuation.js";
22
23
  import { resolveDeclaredRunBaseBranch } from "./run-branch.js";
24
+ import { CI_DATABASE_DEFAULT, isCiDatabase, parseDependencyInstallStrict, parseMustOrderPathsStrict, } from "../dependency-install-declarations.js";
23
25
  import { safeEpicLaunchTargetUrl } from "../epic-launch-diagnostic.js";
24
26
  import { validateHttpBaseUrl } from "../base-url.js";
25
27
  import { RERUN_CI_CHECK_STATUSES, RERUN_CI_NOT_RUNNABLE_REASONS, RERUN_CI_OUTCOMES, isCiResumeRefusalCode, } from "./repair-contract.js";
@@ -27,6 +29,18 @@ import { RERUN_CI_CHECK_STATUSES, RERUN_CI_NOT_RUNNABLE_REASONS, RERUN_CI_OUTCOM
27
29
  export const CONDUCTOR_DEFAULT_BASE_URL = "https://bridgegpt-api.com";
28
30
  /** Default per-request timeout for conductor Bridge API calls. */
29
31
  export const CONDUCTOR_FETCH_TIMEOUT_MS = 30_000;
32
+ /**
33
+ * BAPI-1593 — the budget for one full readiness read (the GET report and the
34
+ * preview's read-only POST alike). A readiness report composes many server-side
35
+ * probes, and a read that ran a little past the 30 s default used to turn a
36
+ * healthy server into an unknown launch.
37
+ */
38
+ export const CONDUCTOR_READINESS_FETCH_TIMEOUT_MS = 60_000;
39
+ /**
40
+ * BAPI-1593 — the approve-plan budget. Approval seeds tickets and activates the
41
+ * run in one request, which can outlast the 30 s default even when it succeeds.
42
+ */
43
+ export const CONDUCTOR_APPROVE_FETCH_TIMEOUT_MS = 120_000;
30
44
  /** Keep an explicit readiness target from borrowing a key bound to another ambient endpoint. */
31
45
  export function readinessEndpointEnvironments(env, baseUrl) {
32
46
  if (baseUrl === undefined)
@@ -49,9 +63,33 @@ export function readinessEndpointEnvironments(env, baseUrl) {
49
63
  * Resolve `{ repoName, apiKey, baseUrl }` from the environment, the shared repo
50
64
  * resolver, and the shared credential store. Never throws and never embeds the
51
65
  * secret value in any failure text. No Postgres/DB module is imported here.
66
+ *
67
+ * Launch-specific access (profile target and its endpoint-bound credential) is
68
+ * opt-in through `followEpicLaunchProfile`: selected Epic Implementer verbs set
69
+ * it, while other callers keep general `BAPI_BASE_URL` resolution unchanged.
52
70
  */
53
71
  export async function resolveConductorBridgeApiAccess(deps = {}) {
54
72
  const env = deps.env ?? process.env;
73
+ if (deps.followEpicLaunchProfile === true && env.BAPI_EPIC_LAUNCH_PROFILE?.trim()) {
74
+ const launch = await resolveEpicLaunchBridgeApiAccess({}, deps);
75
+ if (launch.ok)
76
+ return { ok: true, access: launch.access };
77
+ if (launch.kind === "credential-unbound") {
78
+ // No fallback to ambient credentials: the profile named this endpoint.
79
+ return { ok: false, kind: "credentials-unavailable", error: launch.error };
80
+ }
81
+ if (launch.kind === "profile-unusable") {
82
+ // One fixed, secret-free line per resolution; the general path continues.
83
+ process.stderr.write("warning: the selected Epic launch profile is unusable; using general Bridge API resolution\n");
84
+ }
85
+ else {
86
+ return {
87
+ ok: false,
88
+ kind: launch.kind === "repo-missing" ? "repo-missing" : "credentials-unavailable",
89
+ error: launch.error,
90
+ };
91
+ }
92
+ }
55
93
  const cwd = deps.cwd ?? process.cwd();
56
94
  const homedir = deps.homedir ?? os.homedir;
57
95
  const platform = deps.platform ?? process.platform;
@@ -359,6 +397,11 @@ function formatValidationDetailItem(item) {
359
397
  const path = scoped.slice(0, CONDUCTOR_VALIDATION_LOC_MAX_PARTS).join(".");
360
398
  return path ? `${path}: ${msg}` : msg;
361
399
  }
400
+ /** BAPI-1550 — the shape of a closed executor-job-type token (e.g. `ci_fix`). */
401
+ const HOLDER_JOB_TYPE_RE = /^[a-z][a-z_]{0,39}$/;
402
+ /** BAPI-1585 — closed-token shapes for an approval refusal's code, predicate, and reason. */
403
+ const REFUSAL_ERROR_CODE_RE = /^[A-Z][A-Z0-9_]{0,63}$/;
404
+ const REFUSAL_TOKEN_RE = /^[a-z][a-z0-9_]{0,63}$/;
362
405
  /**
363
406
  * Extract sanitized diagnostics from a parsed backend error body. Recognizes the
364
407
  * FastAPI/backend shapes `{ detail: { error_code, message } }`,
@@ -407,6 +450,21 @@ export function extractSanitizedErrorDiagnostics(body) {
407
450
  diagnostics.errorCode = boundedErrorPreview(errorCode);
408
451
  if (message)
409
452
  diagnostics.bodyPreview = boundedErrorPreview(message);
453
+ diagnostics.detailKind =
454
+ typeof detail === "string"
455
+ ? "string"
456
+ : detail && typeof detail === "object" && !Array.isArray(detail)
457
+ ? "object"
458
+ : "other";
459
+ if (detail && typeof detail === "object" && !Array.isArray(detail)) {
460
+ const d = detail;
461
+ if (typeof d["predicate"] === "string" && REFUSAL_TOKEN_RE.test(d["predicate"])) {
462
+ diagnostics.predicate = d["predicate"];
463
+ }
464
+ if (typeof d["reason_code"] === "string" && REFUSAL_TOKEN_RE.test(d["reason_code"])) {
465
+ diagnostics.reasonCode = d["reason_code"];
466
+ }
467
+ }
410
468
  const gateEvidence = extractGateProfileEvidence(detail);
411
469
  if (gateEvidence)
412
470
  diagnostics.gateProfileEvidence = gateEvidence;
@@ -424,6 +482,21 @@ export function extractSanitizedErrorDiagnostics(body) {
424
482
  rawCurrentRowVersion >= 0) {
425
483
  diagnostics.currentRowVersion = rawCurrentRowVersion;
426
484
  }
485
+ // BAPI-1550: the allowlisted lane-holder pair. Accepted only together and only
486
+ // when well formed, so a half-pair or a free-form value is never forwarded.
487
+ const holderSource = detail && typeof detail === "object" && !Array.isArray(detail)
488
+ ? detail
489
+ : record;
490
+ const rawHolderId = holderSource["holder_job_id"];
491
+ const rawHolderType = holderSource["holder_job_type"];
492
+ if (typeof rawHolderId === "number" &&
493
+ Number.isSafeInteger(rawHolderId) &&
494
+ rawHolderId > 0 &&
495
+ typeof rawHolderType === "string" &&
496
+ HOLDER_JOB_TYPE_RE.test(rawHolderType)) {
497
+ diagnostics.holderJobId = rawHolderId;
498
+ diagnostics.holderJobType = rawHolderType;
499
+ }
427
500
  return diagnostics;
428
501
  }
429
502
  /** Redact exact secret substrings (e.g. the API key from the request headers). */
@@ -445,6 +518,18 @@ function redactDiagnosticValues(diagnostics, secrets) {
445
518
  if (typeof diagnostics.currentRowVersion === "number") {
446
519
  out.currentRowVersion = diagnostics.currentRowVersion;
447
520
  }
521
+ // BAPI-1550: validated at extraction (integer id, closed-token type).
522
+ if (diagnostics.holderJobId !== undefined && diagnostics.holderJobType !== undefined) {
523
+ out.holderJobId = diagnostics.holderJobId;
524
+ out.holderJobType = diagnostics.holderJobType;
525
+ }
526
+ // BAPI-1585: closed tokens, pattern-checked at extraction.
527
+ if (diagnostics.detailKind)
528
+ out.detailKind = diagnostics.detailKind;
529
+ if (diagnostics.predicate)
530
+ out.predicate = diagnostics.predicate;
531
+ if (diagnostics.reasonCode)
532
+ out.reasonCode = diagnostics.reasonCode;
448
533
  // BAPI-1520: pattern-checked at extraction, so there is nothing left to scrub.
449
534
  if (diagnostics.gateProfileEvidence)
450
535
  out.gateProfileEvidence = diagnostics.gateProfileEvidence;
@@ -510,8 +595,17 @@ export class ConductorBridgeApiError extends Error {
510
595
  * that need it read this field directly.
511
596
  */
512
597
  currentRowVersion;
598
+ /** BAPI-1550 — the queued job holding the serial lane (a complete pair, or absent). */
599
+ holderJobId;
600
+ holderJobType;
601
+ /** BAPI-1585 — the `detail` shape and closed refusal tokens, when the body carried them. */
602
+ detailKind;
603
+ predicate;
604
+ reasonCode;
513
605
  /** BAPI-1520 — sanitized structural evidence of a gate-profile refusal. */
514
606
  gateProfileEvidence;
607
+ /** BAPI-1593 — the server answered 2xx, but its body could not be read. */
608
+ unreadableSuccess;
515
609
  constructor(kindOrMessage, status, diagnostics) {
516
610
  const isKnownKind = CONDUCTOR_BRIDGE_API_ERROR_KINDS.includes(kindOrMessage);
517
611
  const errorCode = diagnostics?.errorCode;
@@ -541,8 +635,21 @@ export class ConductorBridgeApiError extends Error {
541
635
  if (typeof diagnostics?.currentRowVersion === "number") {
542
636
  this.currentRowVersion = diagnostics.currentRowVersion;
543
637
  }
638
+ if (typeof diagnostics?.holderJobId === "number" &&
639
+ typeof diagnostics?.holderJobType === "string") {
640
+ this.holderJobId = diagnostics.holderJobId;
641
+ this.holderJobType = diagnostics.holderJobType;
642
+ }
643
+ if (diagnostics?.detailKind)
644
+ this.detailKind = diagnostics.detailKind;
645
+ if (diagnostics?.predicate)
646
+ this.predicate = diagnostics.predicate;
647
+ if (diagnostics?.reasonCode)
648
+ this.reasonCode = diagnostics.reasonCode;
544
649
  if (diagnostics?.gateProfileEvidence)
545
650
  this.gateProfileEvidence = diagnostics.gateProfileEvidence;
651
+ if (diagnostics?.unreadableSuccess === true)
652
+ this.unreadableSuccess = true;
546
653
  }
547
654
  }
548
655
  /**
@@ -568,6 +675,141 @@ export function safeDiagnosticMessage(err, fallback) {
568
675
  }
569
676
  return fallback;
570
677
  }
678
+ /** Gateway statuses that, with no typed body, say nothing about whether the POST applied. */
679
+ const UNCERTAIN_GATEWAY_STATUSES = new Set([502, 503, 504]);
680
+ /**
681
+ * Classify a create/approve failure as uncertain, or `null` when it is a proven
682
+ * answer (a typed refusal, a 4xx, a 500, an auth failure). Pure.
683
+ */
684
+ export function classifyMutationUncertainty(err) {
685
+ if (!(err instanceof ConductorBridgeApiError))
686
+ return null;
687
+ if (err.errorCode !== undefined)
688
+ return null;
689
+ if (err.kind === "timeout")
690
+ return "timeout";
691
+ if (err.kind === "network")
692
+ return err.unreadableSuccess === true ? "unreadable_response" : "network";
693
+ if (err.kind === "server" && typeof err.status === "number" && UNCERTAIN_GATEWAY_STATUSES.has(err.status)) {
694
+ return "gateway_unavailable";
695
+ }
696
+ return null;
697
+ }
698
+ /**
699
+ * BAPI-1593 — a create or approve whose outcome is unknown. A subclass, so every
700
+ * existing `instanceof ConductorBridgeApiError` handler keeps its behavior; only a
701
+ * caller that reconciles reads `operation` and `uncertainty`. It carries no body,
702
+ * URL, or exception text: there was no readable answer to carry.
703
+ */
704
+ export class ConductorMutationOutcomeUnknownError extends ConductorBridgeApiError {
705
+ operation;
706
+ uncertainty;
707
+ constructor(operation, uncertainty, cause) {
708
+ super(cause.kind, cause.status, cause.unreadableSuccess === true ? { unreadableSuccess: true } : undefined);
709
+ this.name = "ConductorMutationOutcomeUnknownError";
710
+ this.operation = operation;
711
+ this.uncertainty = uncertainty;
712
+ }
713
+ }
714
+ /** Re-throw an uncertain create/approve failure as {@link ConductorMutationOutcomeUnknownError}. */
715
+ function rethrowMutationFailure(operation, err) {
716
+ const uncertainty = classifyMutationUncertainty(err);
717
+ if (uncertainty !== null) {
718
+ throw new ConductorMutationOutcomeUnknownError(operation, uncertainty, err);
719
+ }
720
+ throw err;
721
+ }
722
+ // ---------------------------------------------------------------------------
723
+ // BAPI-1593 — one readiness acquisition per launch operation
724
+ // ---------------------------------------------------------------------------
725
+ //
726
+ // "Retry once" means once per launch operation, not once per caller. A launch
727
+ // creates ONE acquisition and hands its result to every later consumer in the
728
+ // same operation (drive-epic hands it to setup-epic). Nothing is cached across
729
+ // operations or process-wide, and the preview's POST `/launch-readiness` and the
730
+ // launch's GET report are separate acquisitions: one never stands in for the
731
+ // other.
732
+ //
733
+ // The single-attempt callback makes exactly one request, parsing included, so
734
+ // there is no nested retry below this boundary.
735
+ /** The fixed pause before the one readiness retry. */
736
+ export const READINESS_RETRY_BACKOFF_MS = 1_500;
737
+ /** Two full reads at most: one attempt plus one retry. */
738
+ export const READINESS_MAX_ATTEMPTS = 2;
739
+ /** Map a failed readiness attempt to its closed unknown reason. */
740
+ export function readinessUnknownReason(err) {
741
+ if (!(err instanceof ConductorBridgeApiError))
742
+ return "invalid_response";
743
+ if (err.kind === "timeout")
744
+ return "timeout";
745
+ if (err.kind === "network")
746
+ return err.unreadableSuccess === true ? "unreadable_response" : "network";
747
+ if (err.kind === "server")
748
+ return "server_error";
749
+ if (err.kind === "unauthorized")
750
+ return "unauthorized";
751
+ if (err.kind === "invalid-input")
752
+ return "invalid_response";
753
+ return "http_error";
754
+ }
755
+ /**
756
+ * The unknown reasons a retry can change: a slow, dropped, or half-deployed
757
+ * server. A 4xx or an auth failure is the server's definite answer, so a second
758
+ * identical request would only repeat it.
759
+ */
760
+ const RETRYABLE_READINESS_REASONS = new Set([
761
+ "timeout",
762
+ "network",
763
+ "unreadable_response",
764
+ "server_error",
765
+ "invalid_response",
766
+ ]);
767
+ const defaultReadinessSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
768
+ /**
769
+ * Create one launch-scoped readiness acquisition over a single-attempt read.
770
+ *
771
+ * A success or a proven refusal settles it at once. A transient first failure
772
+ * (timeout, network, unreadable body, 5xx, invalid shape) is retried once after
773
+ * {@link READINESS_RETRY_BACKOFF_MS}; a second failure settles it as `unknown`.
774
+ * A 4xx or auth failure settles as `unknown` at once: retrying cannot change it.
775
+ */
776
+ export function createReadinessAcquisition(readOnce, options = {}) {
777
+ const sleep = options.sleep ?? defaultReadinessSleep;
778
+ let latest = null;
779
+ const attempt = async (n) => {
780
+ try {
781
+ latest = { kind: "ready", readiness: await readOnce(), attempts: n };
782
+ }
783
+ catch (err) {
784
+ latest = isSchemaIncompatibleError(err)
785
+ ? { kind: "refused", error: err, attempts: n }
786
+ : { kind: "unknown", reason: readinessUnknownReason(err), error: err, attempts: n };
787
+ }
788
+ return latest;
789
+ };
790
+ let first = null;
791
+ let settled = null;
792
+ const firstAttempt = () => {
793
+ first ??= attempt(1);
794
+ return first;
795
+ };
796
+ const result = () => {
797
+ settled ??= (async () => {
798
+ const one = await firstAttempt();
799
+ if (one.kind !== "unknown" || !RETRYABLE_READINESS_REASONS.has(one.reason))
800
+ return one;
801
+ options.onRetry?.(one.reason);
802
+ await sleep(READINESS_RETRY_BACKOFF_MS);
803
+ return attempt(READINESS_MAX_ATTEMPTS);
804
+ })();
805
+ return settled;
806
+ };
807
+ return { firstAttempt, result, peek: () => latest };
808
+ }
809
+ /** Acquire readiness once for a standalone operation: one attempt plus at most one retry. */
810
+ export function acquireConductorReadiness(readOnce, options = {}) {
811
+ return createReadinessAcquisition(readOnce, options).result();
812
+ }
571
813
  /**
572
814
  * GET auth headers. The API key travels ONLY in a header, never in the URL.
573
815
  *
@@ -611,7 +853,7 @@ export async function fetchConductorJsonWithTimeout(url, headers, timeoutMs, fet
611
853
  return await resp.json();
612
854
  }
613
855
  catch {
614
- throw new ConductorBridgeApiError("network");
856
+ throw new ConductorBridgeApiError("network", undefined, { unreadableSuccess: true });
615
857
  }
616
858
  }
617
859
  finally {
@@ -771,7 +1013,7 @@ async function fetchConductorJsonWithMethodStatusAndTimeout(method, url, headers
771
1013
  return { status: resp.status, body: await resp.json() };
772
1014
  }
773
1015
  catch {
774
- throw new ConductorBridgeApiError("network");
1016
+ throw new ConductorBridgeApiError("network", undefined, { unreadableSuccess: true });
775
1017
  }
776
1018
  }
777
1019
  finally {
@@ -1026,10 +1268,23 @@ export async function claimEpicSupervisionLease(access, request, fetchImpl = glo
1026
1268
  * Returns the server payload verbatim — no ready-set computation, plan-hash
1027
1269
  * assertion, or derived control-loop fields are added.
1028
1270
  */
1029
- export async function fetchEpicRunState(access, epicKey, fetchImpl = globalThis.fetch) {
1271
+ export async function fetchEpicRunState(access, epicKey, fetchImpl = globalThis.fetch, options, timeoutMs) {
1030
1272
  requireNonEmptyString(epicKey);
1031
- const url = buildConductorJiraUrl(access.baseUrl, `${epicRunApiPath(epicKey)}/state`, { repo_name: access.repoName });
1032
- const parsed = await fetchConductorJsonWithTimeout(url, conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
1273
+ // Defaulted in the body, not the signature: the source-boundary test brace-matches
1274
+ // from the first open brace after the function name, so a default object literal
1275
+ // in the signature would hide the real body from it.
1276
+ const readOptions = options ?? {};
1277
+ // Bounds are added only when the caller supplied them, so every existing
1278
+ // caller keeps requesting the exact URL it always did.
1279
+ const params = { repo_name: access.repoName };
1280
+ if (readOptions.job_limit !== undefined)
1281
+ params.job_limit = String(readOptions.job_limit);
1282
+ if (readOptions.ticket_key !== undefined)
1283
+ params.ticket_key = readOptions.ticket_key;
1284
+ const url = buildConductorJiraUrl(access.baseUrl, `${epicRunApiPath(epicKey)}/state`, params);
1285
+ // BAPI-1593 — a caller reconciling against one overall deadline caps this GET
1286
+ // to the time it has left; every other caller keeps the default budget.
1287
+ const parsed = await fetchConductorJsonWithTimeout(url, conductorGetHeaders(access), timeoutMs ?? CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
1033
1288
  return parsed;
1034
1289
  }
1035
1290
  /**
@@ -1045,7 +1300,7 @@ export async function fetchEpicRunState(access, epicKey, fetchImpl = globalThis.
1045
1300
  * through the shared timeout/sanitization helper as a `ConductorBridgeApiError`,
1046
1301
  * so no response body ever reaches a caller.
1047
1302
  */
1048
- export async function fetchExplainRun(access, epicRunId, ticketKey, fetchImpl = globalThis.fetch) {
1303
+ export async function fetchExplainRun(access, epicRunId, ticketKey, fetchImpl = globalThis.fetch, options = {}) {
1049
1304
  requireNonEmptyString(epicRunId);
1050
1305
  let apiPath = `${epicRunApiPath(epicRunId)}/explain`;
1051
1306
  if (ticketKey !== undefined) {
@@ -1055,11 +1310,110 @@ export async function fetchExplainRun(access, epicRunId, ticketKey, fetchImpl =
1055
1310
  requireNoSlashPathSegment(ticketKey);
1056
1311
  apiPath = `${epicRunApiPath(epicRunId)}/tickets/${encodeURIComponent(ticketKey)}/explain`;
1057
1312
  }
1058
- const url = buildConductorJiraUrl(access.baseUrl, apiPath, {
1059
- repo_name: access.repoName,
1060
- });
1313
+ const params = { repo_name: access.repoName };
1314
+ // BAPI-1557: forwarded only when supplied, so the default request is unchanged.
1315
+ if (options.include_run !== undefined)
1316
+ params.include_run = String(options.include_run);
1317
+ const url = buildConductorJiraUrl(access.baseUrl, apiPath, params);
1061
1318
  return fetchConductorJsonWithTimeout(url, conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
1062
1319
  }
1320
+ /**
1321
+ * GET `/jira/tickets/{ticket_number}` and return only the key and description.
1322
+ *
1323
+ * The returned key must equal the requested one and `description` must be a
1324
+ * string (empty is accepted; missing, null or non-string is rejected). Failures
1325
+ * are a sanitized {@link ConductorBridgeApiError}: upstream text is limited to
1326
+ * the bounded `detail.error` code, never a raw body or an exception message.
1327
+ */
1328
+ export async function fetchStoredTicket(access, ticketNumber, fetchImpl = globalThis.fetch) {
1329
+ requireNonEmptyString(ticketNumber);
1330
+ requireNoSlashPathSegment(ticketNumber);
1331
+ const url = buildConductorJiraUrl(access.baseUrl, `/tickets/${encodeURIComponent(ticketNumber)}`, { repo_name: access.repoName });
1332
+ const parsed = await fetchConductorJsonWithTimeout(url, conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl, { readErrorField: true });
1333
+ const record = parsed && typeof parsed === "object" && !Array.isArray(parsed)
1334
+ ? parsed
1335
+ : undefined;
1336
+ if (!record ||
1337
+ record["ticket_number"] !== ticketNumber ||
1338
+ typeof record["description"] !== "string") {
1339
+ // Shape failures carry no upstream content at all.
1340
+ throw new ConductorBridgeApiError("http", 200);
1341
+ }
1342
+ return { ticket_number: ticketNumber, description: record["description"] };
1343
+ }
1344
+ /**
1345
+ * BAPI-1621 — GET `/jira/tickets/{ticket_number}` for a description that may be
1346
+ * blank. The server returns `null` (or omits the field) for a ticket with no
1347
+ * body, and that is a successful read of absent text: it maps to `""`.
1348
+ * {@link fetchStoredTicket} stays strict for its own callers. A mismatched key or
1349
+ * any other non-string description is still a shape failure, and transport and
1350
+ * HTTP failures throw exactly as `fetchStoredTicket` does.
1351
+ */
1352
+ export async function fetchStoredTicketDescription(access, ticketNumber, fetchImpl = globalThis.fetch) {
1353
+ requireNonEmptyString(ticketNumber);
1354
+ requireNoSlashPathSegment(ticketNumber);
1355
+ const url = buildConductorJiraUrl(access.baseUrl, `/tickets/${encodeURIComponent(ticketNumber)}`, { repo_name: access.repoName });
1356
+ const parsed = await fetchConductorJsonWithTimeout(url, conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl, { readErrorField: true });
1357
+ const record = parsed && typeof parsed === "object" && !Array.isArray(parsed)
1358
+ ? parsed
1359
+ : undefined;
1360
+ if (!record || record["ticket_number"] !== ticketNumber) {
1361
+ throw new ConductorBridgeApiError("http", 200);
1362
+ }
1363
+ const description = record["description"];
1364
+ if (description === null || description === undefined)
1365
+ return "";
1366
+ if (typeof description !== "string")
1367
+ throw new ConductorBridgeApiError("http", 200);
1368
+ return description;
1369
+ }
1370
+ /** null for an absent value, the string for a string, undefined for anything else. */
1371
+ function epicChildField(value) {
1372
+ if (value === null || value === undefined)
1373
+ return null;
1374
+ return typeof value === "string" ? value : undefined;
1375
+ }
1376
+ /**
1377
+ * GET `/jira/tickets/{epic_key}/children` — the epic's direct children through
1378
+ * the server's ticket-store seam, for both ticket backends.
1379
+ *
1380
+ * Failed requests throw a sanitized {@link ConductorBridgeApiError}. A body that
1381
+ * does not match the strict shape also throws, as a protocol error, so a caller
1382
+ * can always tell "the read failed" from "the list is incomplete"
1383
+ * (`enumeration_complete: false`) from "the epic has no children" (an empty,
1384
+ * complete list).
1385
+ */
1386
+ export async function fetchEpicChildren(access, epicKey, fetchImpl = globalThis.fetch) {
1387
+ requireNonEmptyString(epicKey);
1388
+ requireNoSlashPathSegment(epicKey);
1389
+ const url = buildConductorJiraUrl(access.baseUrl, `/tickets/${encodeURIComponent(epicKey)}/children`, { repo_name: access.repoName });
1390
+ const parsed = await fetchConductorJsonWithTimeout(url, conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl, { readErrorField: true });
1391
+ const record = parsed && typeof parsed === "object" && !Array.isArray(parsed)
1392
+ ? parsed
1393
+ : undefined;
1394
+ if (!record ||
1395
+ record["epic_key"] !== epicKey ||
1396
+ typeof record["enumeration_complete"] !== "boolean" ||
1397
+ !Array.isArray(record["children"])) {
1398
+ throw new ConductorBridgeApiError("http", 200);
1399
+ }
1400
+ const children = [];
1401
+ for (const raw of record["children"]) {
1402
+ const child = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : undefined;
1403
+ const key = child?.["ticket_key"];
1404
+ if (!child || typeof key !== "string" || key.trim() === "") {
1405
+ throw new ConductorBridgeApiError("http", 200);
1406
+ }
1407
+ const status = epicChildField(child["status"]);
1408
+ const category = epicChildField(child["status_category"]);
1409
+ const issueType = epicChildField(child["issue_type"]);
1410
+ if (status === undefined || category === undefined || issueType === undefined) {
1411
+ throw new ConductorBridgeApiError("http", 200);
1412
+ }
1413
+ children.push({ ticket_key: key, status, status_category: category, issue_type: issueType });
1414
+ }
1415
+ return { epic_key: epicKey, children, enumeration_complete: record["enumeration_complete"] };
1416
+ }
1063
1417
  // ---------------------------------------------------------------------------
1064
1418
  // Executor wind-down: read-only completion-state projection (BAPI-1010)
1065
1419
  // ---------------------------------------------------------------------------
@@ -1137,6 +1491,56 @@ export async function readEpicRunCompletionState(access, epicRunId, fetchImpl =
1137
1491
  state: featureBranch !== undefined ? { status, featureBranch } : { status },
1138
1492
  };
1139
1493
  }
1494
+ // ---------------------------------------------------------------------------
1495
+ // BAPI-1545 — the advisory capability statement
1496
+ // ---------------------------------------------------------------------------
1497
+ /** Install's bound on the statement write; a failure only warns. */
1498
+ export const EPIC_CAPABILITY_STATEMENT_WRITE_TIMEOUT_MS = 15_000;
1499
+ /** The worker-spawn read is advisory and short. */
1500
+ export const EPIC_CAPABILITY_STATEMENT_READ_TIMEOUT_MS = 5_000;
1501
+ const EPIC_CAPABILITY_STATEMENT_PATH = `${EPIC_RUNS_API_PREFIX}/capability-statement`;
1502
+ /**
1503
+ * PUT `/jira/epic-runs/capability-statement` with `{repo_name, statement}`.
1504
+ * Throws a sanitized {@link ConductorBridgeApiError} on any failure; install
1505
+ * catches it and prints one warning. The statement is advisory: it is never an
1506
+ * authorization source.
1507
+ */
1508
+ export async function writeEpicCapabilityStatement(access, statement, fetchImpl, timeoutMs = EPIC_CAPABILITY_STATEMENT_WRITE_TIMEOUT_MS) {
1509
+ const url = buildConductorJiraUrl(access.baseUrl, EPIC_CAPABILITY_STATEMENT_PATH);
1510
+ await fetchConductorJsonPutWithTimeout(url, conductorPostHeaders(access), JSON.stringify({ repo_name: access.repoName, statement }), timeoutMs, fetchImpl);
1511
+ }
1512
+ /**
1513
+ * GET `/jira/epic-runs/capability-statement?repo_name=`. Never throws. Any
1514
+ * transport or shape failure is a reason the caller treats as "append nothing".
1515
+ */
1516
+ export async function readEpicCapabilityStatement(access, fetchImpl = globalThis.fetch, timeoutMs = EPIC_CAPABILITY_STATEMENT_READ_TIMEOUT_MS) {
1517
+ let parsed;
1518
+ try {
1519
+ const url = buildConductorJiraUrl(access.baseUrl, EPIC_CAPABILITY_STATEMENT_PATH, { repo_name: access.repoName });
1520
+ parsed = await fetchConductorJsonWithTimeout(url, conductorGetHeaders(access), timeoutMs, fetchImpl);
1521
+ }
1522
+ catch (err) {
1523
+ if (err instanceof ConductorBridgeApiError) {
1524
+ if (err.kind === "timeout")
1525
+ return { ok: false, reason: "timeout" };
1526
+ if (err.kind === "unauthorized")
1527
+ return { ok: false, reason: "unauthorized" };
1528
+ if (err.kind === "server")
1529
+ return { ok: false, reason: "server" };
1530
+ if (err.kind === "http")
1531
+ return { ok: false, reason: "http" };
1532
+ }
1533
+ return { ok: false, reason: "network" };
1534
+ }
1535
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1536
+ return { ok: false, reason: "malformed" };
1537
+ const doc = parsed;
1538
+ if (doc.state === "present")
1539
+ return { ok: true, state: "present", statement: doc.statement };
1540
+ if (doc.state === "absent" || doc.state === "unavailable")
1541
+ return { ok: true, state: doc.state };
1542
+ return { ok: false, reason: "malformed" };
1543
+ }
1140
1544
  /**
1141
1545
  * GET `/jira/epic-runs/runs?repo_name=<repo>&status=active` and return the
1142
1546
  * list of active epic runs. Caps at 20 results — enough for typical deployments
@@ -1254,8 +1658,16 @@ export async function createEpicRunWithDisposition(access, request, fetchImpl =
1254
1658
  body.budget_cost_cents = request.budgetCostCents;
1255
1659
  }
1256
1660
  const url = buildConductorJiraUrl(access.baseUrl, `${EPIC_RUNS_API_PREFIX}/runs`);
1257
- const { status, body: parsed } = await fetchConductorJsonWithMethodStatusAndTimeout("POST", url, conductorPostHeaders(access), JSON.stringify(body), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
1258
- return { run: parsed, created: status === 201 };
1661
+ // BAPI-1593 — sent exactly once. An uncertain outcome throws
1662
+ // `ConductorMutationOutcomeUnknownError`; the caller re-reads, never re-sends.
1663
+ let response;
1664
+ try {
1665
+ response = await fetchConductorJsonWithMethodStatusAndTimeout("POST", url, conductorPostHeaders(access), JSON.stringify(body), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
1666
+ }
1667
+ catch (err) {
1668
+ rethrowMutationFailure("create", err);
1669
+ }
1670
+ return { run: response.body, created: response.status === 201 };
1259
1671
  }
1260
1672
  /**
1261
1673
  * PATCH `/jira/epic-runs/runs/{identifier}` with a COMPLETE replacement of the
@@ -1405,10 +1817,14 @@ export async function advanceEpicTicketStatus(access, request, fetchImpl = globa
1405
1817
  */
1406
1818
  async function postUnparkLikeRequest(url, headers, body, fetchImpl) {
1407
1819
  try {
1408
- const parsed = await fetchConductorJsonPostWithTimeout(url, headers, body, CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
1820
+ // BAPI-1554: opt in to the server's bounded `detail.error` explanation so a
1821
+ // refused unpark-like request tells the operator why. Same POST, URL, body,
1822
+ // timeout, and headers as the shared POST wrapper; only the error read widens.
1823
+ const parsed = await fetchConductorJsonWithMethodAndTimeout("POST", url, headers, body, CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl, { readErrorField: true });
1409
1824
  return parseAdvanceEpicTicketStatusResult(parsed);
1410
1825
  }
1411
1826
  catch (err) {
1827
+ // The stale-CAS translation stays first, before any generic validation text.
1412
1828
  if (err instanceof ConductorBridgeApiError &&
1413
1829
  err.status === 400 &&
1414
1830
  typeof err.currentRowVersion === "number") {
@@ -1672,7 +2088,7 @@ function parseDispatchRemediationResult(parsed) {
1672
2088
  throw new ConductorBridgeApiError("server");
1673
2089
  }
1674
2090
  const jobId = p["job_id"];
1675
- return {
2091
+ const result = {
1676
2092
  epic_run_id: p["epic_run_id"],
1677
2093
  ticket_key: p["ticket_key"],
1678
2094
  before: parseRepairNullableString(p["before"]),
@@ -1682,8 +2098,18 @@ function parseDispatchRemediationResult(parsed) {
1682
2098
  job_type: typeof p["job_type"] === "string" ? p["job_type"] : "",
1683
2099
  job_id: typeof jobId === "number" && Number.isSafeInteger(jobId) ? jobId : null,
1684
2100
  };
2101
+ // BAPI-1550: optional and backward compatible — an older server omits them, and
2102
+ // a malformed value is dropped rather than failing a dispatch that succeeded.
2103
+ if (typeof p["driver_context_delivered"] === "boolean") {
2104
+ result.driver_context_delivered = p["driver_context_delivered"];
2105
+ }
2106
+ const queuedBehind = p["queued_behind"];
2107
+ if (typeof queuedBehind === "number" && Number.isSafeInteger(queuedBehind) && queuedBehind > 0) {
2108
+ result.queued_behind = queuedBehind;
2109
+ }
2110
+ return result;
1685
2111
  }
1686
- function parseMergeChildRouteResponse(parsed) {
2112
+ function parseMergeChildRouteResponse(parsed, options = {}) {
1687
2113
  const p = parseRepairBase(parsed);
1688
2114
  const prNumber = p["pr_number"];
1689
2115
  if (typeof prNumber !== "number" || !Number.isSafeInteger(prNumber) || prNumber <= 0) {
@@ -1702,6 +2128,18 @@ function parseMergeChildRouteResponse(parsed) {
1702
2128
  expected_head_sha: sha,
1703
2129
  merge_method: parseRepairNullableString(l["merge_method"]),
1704
2130
  };
2131
+ // BAPI-1564 — a carry-gaps approval must name the base it was admitted for;
2132
+ // an older or malformed response is refused here, never executed unguarded.
2133
+ const base = l["expected_base_branch"];
2134
+ if (base !== undefined && base !== null) {
2135
+ if (typeof base !== "string" || base.trim().length === 0 || base.length > 255) {
2136
+ throw new ConductorBridgeApiError("server");
2137
+ }
2138
+ localExecution.expected_base_branch = base;
2139
+ }
2140
+ else if (options.requireExpectedBase) {
2141
+ throw new ConductorBridgeApiError("server");
2142
+ }
1705
2143
  }
1706
2144
  return {
1707
2145
  epic_run_id: p["epic_run_id"],
@@ -1813,6 +2251,46 @@ export async function resolveHandoff(access, request, fetchImpl = globalThis.fet
1813
2251
  }, fetchImpl);
1814
2252
  return parseResolveHandoffResult(parsed);
1815
2253
  }
2254
+ const ACKNOWLEDGE_GAPS_DIGEST_RE = /^[0-9a-f]{64}$/;
2255
+ const ACKNOWLEDGE_GAPS_RESULT_KEYS = new Set([
2256
+ "epic_run_id",
2257
+ "digest",
2258
+ "entry_count",
2259
+ "committed",
2260
+ "event_recorded",
2261
+ ]);
2262
+ function parseAcknowledgeGapsResult(parsed) {
2263
+ const p = parseRepairBase(parsed);
2264
+ const count = p["entry_count"];
2265
+ if (Object.keys(p).some((key) => !ACKNOWLEDGE_GAPS_RESULT_KEYS.has(key)) ||
2266
+ typeof p["digest"] !== "string" ||
2267
+ !ACKNOWLEDGE_GAPS_DIGEST_RE.test(p["digest"]) ||
2268
+ typeof count !== "number" ||
2269
+ !Number.isSafeInteger(count) ||
2270
+ count < 0) {
2271
+ throw new ConductorBridgeApiError("server");
2272
+ }
2273
+ return {
2274
+ epic_run_id: p["epic_run_id"],
2275
+ digest: p["digest"],
2276
+ entry_count: count,
2277
+ committed: p["committed"],
2278
+ event_recorded: p["event_recorded"],
2279
+ };
2280
+ }
2281
+ /**
2282
+ * POST `/jira/epic-runs/runs/{epic_run_id}/acknowledge-gaps` (BAPI-1562) — body
2283
+ * `{repo_name, digest, reason}` and nothing else. There is no actor field: the
2284
+ * SERVER records the verified request actor, and it recomputes the list digest
2285
+ * itself, refusing `GAP_DIGEST_STALE` when the named digest is not current.
2286
+ */
2287
+ export async function acknowledgeGaps(access, request, fetchImpl = globalThis.fetch) {
2288
+ requireNonEmptyString(request.epicRunId);
2289
+ requireNonEmptyString(request.digest);
2290
+ requireNonEmptyString(request.reason);
2291
+ const parsed = await postRepairRequest(access, `${epicRunApiPath(request.epicRunId)}/acknowledge-gaps`, { digest: request.digest, reason: request.reason }, fetchImpl);
2292
+ return parseAcknowledgeGapsResult(parsed);
2293
+ }
1816
2294
  /** The synthetic code an old server's missing escalate route is reported under. */
1817
2295
  export const ESCALATE_ROUTE_UNAVAILABLE_CODE = "ESCALATE_ROUTE_UNAVAILABLE";
1818
2296
  /** The fixed operator text for a server that has no `escalate` route. */
@@ -1962,15 +2440,20 @@ export async function rerunCi(access, request, fetchImpl = globalThis.fetch) {
1962
2440
  }
1963
2441
  /**
1964
2442
  * POST `/jira/epic-runs/runs/{epic_run_id}/merge-child` — body EXACTLY
1965
- * `{repo_name, pr_number}`. The server composes the head, gate, and action key.
1966
- * When the repository merges locally the response carries a `local_execution`
1967
- * approval the caller completes with {@link completeMergeChild}.
2443
+ * `{repo_name, pr_number}`, plus `carry_gaps: true` only when `carryGaps` is set
2444
+ * (BAPI-1564). The server composes the head, gate, base, and action key. When the
2445
+ * repository merges locally the response carries a `local_execution` approval the
2446
+ * caller completes with {@link completeMergeChild}; a carry-gaps approval must
2447
+ * also name its `expected_base_branch`.
1968
2448
  */
1969
2449
  export async function mergeChild(access, request, fetchImpl = globalThis.fetch) {
1970
2450
  requireNonEmptyString(request.epicRunId);
1971
2451
  requirePositiveSafeInteger(request.prNumber);
1972
- const parsed = await postRepairRequest(access, `${epicRunApiPath(request.epicRunId)}/merge-child`, { pr_number: request.prNumber }, fetchImpl);
1973
- return parseMergeChildRouteResponse(parsed);
2452
+ const carryGaps = request.carryGaps === true;
2453
+ const parsed = await postRepairRequest(access, `${epicRunApiPath(request.epicRunId)}/merge-child`, carryGaps
2454
+ ? { pr_number: request.prNumber, carry_gaps: true }
2455
+ : { pr_number: request.prNumber }, fetchImpl);
2456
+ return parseMergeChildRouteResponse(parsed, { requireExpectedBase: carryGaps });
1974
2457
  }
1975
2458
  /**
1976
2459
  * POST `/jira/epic-runs/runs/{epic_run_id}/merge-child/complete` — body
@@ -2515,6 +2998,7 @@ export const CHILD_MERGE_EVIDENCE_SOURCES = ["delivery_binding", "feature_branch
2515
2998
  export const CHILD_MERGE_ANCESTRY_VALUES = ["covered", "behind", "unknown", "not_checked"];
2516
2999
  export const CHILD_MERGE_REASONS = [
2517
3000
  "merged_on_cut_commit",
3001
+ "merged_outside_run",
2518
3002
  "merged_without_delivery_record",
2519
3003
  "merged_after_index",
2520
3004
  "ancestry_unknown",
@@ -2654,6 +3138,8 @@ export function parseRecordSkippedChildrenResponse(parsed, expectedKeys) {
2654
3138
  function safeCount(value) {
2655
3139
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
2656
3140
  }
3141
+ const GATE_PROFILE_STAMP_REASON_RE = /^[a-z0-9_]+$/;
3142
+ const ESCALATION_WARNING_RE = /^[a-z][a-z0-9_]{0,63}$/;
2657
3143
  /**
2658
3144
  * POST the immutable plan blob to the durable-store endpoint. The blob is
2659
3145
  * written once per `(epic_run_id, plan_version)` and never mutated — a
@@ -2751,6 +3237,24 @@ function parseApproveEpicPlanSuccess(parsed) {
2751
3237
  };
2752
3238
  }
2753
3239
  }
3240
+ // BAPI-1602 — tolerant: only a bounded snake_case token is kept.
3241
+ const escalationWarning = record["escalation_warning"];
3242
+ if (typeof escalationWarning === "string" && ESCALATION_WARNING_RE.test(escalationWarning)) {
3243
+ result.escalationWarning = escalationWarning;
3244
+ }
3245
+ // BAPI-1601 — tolerant: only a non-null, non-array object yields a stamp, and
3246
+ // nothing about it can fail an approval that already succeeded.
3247
+ const stamp = record["gate_profile_stamp"];
3248
+ if (stamp && typeof stamp === "object" && !Array.isArray(stamp)) {
3249
+ const raw = stamp;
3250
+ const reasons = Array.isArray(raw["reasons"])
3251
+ ? raw["reasons"].filter((reason) => typeof reason === "string" && GATE_PROFILE_STAMP_REASON_RE.test(reason))
3252
+ : [];
3253
+ result.gateProfileStamp = {
3254
+ autoMerge: typeof raw["auto_merge"] === "boolean" ? raw["auto_merge"] : "unknown",
3255
+ reasons,
3256
+ };
3257
+ }
2754
3258
  return result;
2755
3259
  }
2756
3260
  export async function approveEpicPlan(access, request, fetchImpl = globalThis.fetch) {
@@ -2762,7 +3266,9 @@ export async function approveEpicPlan(access, request, fetchImpl = globalThis.fe
2762
3266
  plan_version: request.planVersion,
2763
3267
  });
2764
3268
  try {
2765
- const parsed = await fetchConductorJsonPostWithTimeout(url, conductorPostHeaders(access), body, CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
3269
+ // BAPI-1593 — sent exactly once, with the approval budget. An uncertain
3270
+ // outcome throws `ConductorMutationOutcomeUnknownError` (see the catch).
3271
+ const parsed = await fetchConductorJsonPostWithTimeout(url, conductorPostHeaders(access), body, CONDUCTOR_APPROVE_FETCH_TIMEOUT_MS, fetchImpl);
2766
3272
  return parseApproveEpicPlanSuccess(parsed);
2767
3273
  }
2768
3274
  catch (error) {
@@ -2777,9 +3283,23 @@ export async function approveEpicPlan(access, request, fetchImpl = globalThis.fe
2777
3283
  if (/multiple active runs/i.test(preview)) {
2778
3284
  return { ok: false, kind: "conflict", reason: "multiple_active_runs" };
2779
3285
  }
2780
- return { ok: false, kind: "conflict", reason: "superseded" };
3286
+ // BAPI-1585: "superseded" is only the server's bare-string message (both the
3287
+ // ordinary and the concurrent-CAS wording). Any other 409 — a structured
3288
+ // refusal such as UNATTENDED_POSTURE_REFUSED, or a shape we do not
3289
+ // recognize — is a refusal and is never reported as benign.
3290
+ if (error.detailKind === "string" && /superseded/i.test(preview)) {
3291
+ return { ok: false, kind: "conflict", reason: "superseded" };
3292
+ }
3293
+ const code = error.errorCode;
3294
+ return {
3295
+ ok: false,
3296
+ kind: "refused",
3297
+ error_code: typeof code === "string" && REFUSAL_ERROR_CODE_RE.test(code) ? code : "unknown",
3298
+ predicate: error.predicate ?? "unknown",
3299
+ reason_code: error.reasonCode ?? "unknown",
3300
+ };
2781
3301
  }
2782
- throw error;
3302
+ rethrowMutationFailure("approve", error);
2783
3303
  }
2784
3304
  }
2785
3305
  /**
@@ -2917,6 +3437,153 @@ export async function triggerRepositoryParse(access, fetchImpl = globalThis.fetc
2917
3437
  const body = JSON.stringify({ repo_name: access.repoName });
2918
3438
  return fetchConductorJsonPostWithTimeout(url, conductorPostHeaders(access), body, CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
2919
3439
  }
3440
+ export const SETUP_RECOVERY_VERSION = "bridge.setup-parse.v1";
3441
+ export const SETUP_CORRECTION_VERSION = "bridge.setup-branch-correction.v1";
3442
+ const setupRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
3443
+ const setupBranch = (v) => typeof v === "string" && v.length > 0 && v.length <= 255 && v === v.trim() && !v.startsWith("-") && !/[\x00-\x1f\x7f]/.test(v);
3444
+ const setupSha = (v) => typeof v === "string" && /^[0-9a-f]{40}$/.test(v);
3445
+ const setupId = (v) => typeof v === "string" && /^[0-9a-f-]{36}$/.test(v);
3446
+ const setupPositive = (v) => Number.isSafeInteger(v) && Number(v) > 0;
3447
+ const setupRelation = (v) => ["equal", "contains_target", "behind", "diverged", "unknown"].includes(String(v));
3448
+ /** Strict boundary decode; never render unknown server error text or metadata as content. */
3449
+ export function decodeSetupRecoveryEvidence(value) {
3450
+ if (!setupRecord(value) || value.version !== SETUP_RECOVERY_VERSION || !setupPositive(value.setup_pr_number)
3451
+ || !["read", "missing", "unavailable"].includes(value.configuration_outcome)
3452
+ || !setupRelation(value.configured_relation) || !setupRelation(value.canonical_relation))
3453
+ return null;
3454
+ for (const key of ["configured_branch", "provider_default", "resolved_branch", "destination_branch"]) {
3455
+ if (value[key] !== null && !setupBranch(value[key]))
3456
+ return null;
3457
+ }
3458
+ for (const key of ["required_commit_sha", "resolved_head_sha", "canonical_commit_sha"]) {
3459
+ if (value[key] !== null && !setupSha(value[key]))
3460
+ return null;
3461
+ }
3462
+ if (value.configuration_fingerprint !== null && !/^v1:[0-9a-f]{64}$/.test(value.configuration_fingerprint))
3463
+ return null;
3464
+ if (value.canonical_identity !== null && (typeof value.canonical_identity !== "string" || !/^[A-Za-z0-9_.:-]{1,128}$/.test(value.canonical_identity)))
3465
+ return null;
3466
+ const reasons = [null, "configuration_unavailable", "configuration_missing", "default_branch_unknown", "configured_branch_unknown",
3467
+ "canonical_evidence_unknown", "lifecycle_unavailable", "request_history_unavailable", "ancestry_unknown", "provider_evidence_unavailable", "observation_deadline"];
3468
+ if (!reasons.includes(value.reason))
3469
+ return null;
3470
+ if (value.setup_pr_url !== null && (typeof value.setup_pr_url !== "string" || !/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*$/.test(value.setup_pr_url)))
3471
+ return null;
3472
+ const run = (r) => {
3473
+ if (!setupRecord(r) || !setupPositive(r.id) || !["queued", "in_progress", "failed", "succeeded"].includes(r.status))
3474
+ return null;
3475
+ for (const k of ["requested_branch", "actual_fetched_branch"])
3476
+ if (r[k] !== null && !setupBranch(r[k]))
3477
+ return null;
3478
+ for (const k of ["requested_target_sha", "actual_fetched_sha"])
3479
+ if (r[k] !== null && !setupSha(r[k]))
3480
+ return null;
3481
+ if (r.configuration_fingerprint !== null && !/^v1:[0-9a-f]{64}$/.test(r.configuration_fingerprint))
3482
+ return null;
3483
+ if (r.setup_request_id !== null && !setupId(r.setup_request_id))
3484
+ return null;
3485
+ return { id: r.id, status: r.status, requested_branch: r.requested_branch, requested_target_sha: r.requested_target_sha,
3486
+ configuration_fingerprint: r.configuration_fingerprint, setup_request_id: r.setup_request_id,
3487
+ actual_fetched_branch: r.actual_fetched_branch, actual_fetched_sha: r.actual_fetched_sha };
3488
+ };
3489
+ if (!Array.isArray(value.active_runs) || value.active_runs.length > 20)
3490
+ return null;
3491
+ const active = value.active_runs.map(run);
3492
+ if (active.some(r => r === null))
3493
+ return null;
3494
+ const latest = value.latest_run === null ? null : run(value.latest_run);
3495
+ if (value.latest_run !== null && latest === null)
3496
+ return null;
3497
+ const q = value.request;
3498
+ if (q !== null && (!setupRecord(q) || !setupId(q.id) || !Number.isSafeInteger(q.generation) || q.generation < 0
3499
+ || (q.parse_run_id !== null && !setupPositive(q.parse_run_id)) || ![null, "queued", "in_progress", "succeeded", "failed"].includes(q.status)))
3500
+ return null;
3501
+ if (value.retry_generation !== null && !setupPositive(value.retry_generation))
3502
+ return null;
3503
+ const canonical = decodeCanonicalProvenance(value);
3504
+ const observation = value.canonical_observation ?? "unknown";
3505
+ if (!["unknown", "absent", "unverified", "verified"].includes(observation))
3506
+ return null;
3507
+ if (["absent", "unverified"].includes(observation)
3508
+ && (canonical.verified || value.canonical_validity_state !== "unverified" || value.canonical_validity_verified !== false))
3509
+ return null;
3510
+ if (value.canonical_relation !== "unknown" && (!canonical.verified || canonical.sourceCommitSha !== value.canonical_commit_sha || canonical.generation !== value.canonical_identity))
3511
+ return null;
3512
+ return { version: SETUP_RECOVERY_VERSION, setup_pr_number: value.setup_pr_number, setup_pr_url: value.setup_pr_url,
3513
+ required_commit_sha: value.required_commit_sha, destination_branch: value.destination_branch,
3514
+ configuration_outcome: value.configuration_outcome, configured_branch: value.configured_branch,
3515
+ configuration_fingerprint: value.configuration_fingerprint, provider_default: value.provider_default,
3516
+ resolved_branch: value.resolved_branch, resolved_head_sha: value.resolved_head_sha, configured_relation: value.configured_relation,
3517
+ canonical_relation: value.canonical_relation, canonical_commit_sha: value.canonical_commit_sha,
3518
+ canonical_identity: value.canonical_identity, canonical, canonical_observation: observation, reason: value.reason, active_runs: active, latest_run: latest,
3519
+ request: q === null ? null : { id: q.id, generation: q.generation, parse_run_id: q.parse_run_id, status: q.status }, retry_generation: value.retry_generation };
3520
+ }
3521
+ async function supportsSetupRecovery(access, fetchImpl) {
3522
+ const body = await fetchConductorJsonWithTimeout(buildConductorJiraUrl(access.baseUrl, "/ping", { repo_name: access.repoName }), conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
3523
+ if (!setupRecord(body) || !setupRecord(body.setup_recovery_contracts))
3524
+ return false;
3525
+ const c = body.setup_recovery_contracts;
3526
+ return c.nullable_correction === SETUP_CORRECTION_VERSION && c.setup_admission === SETUP_RECOVERY_VERSION && c.target_evidence === SETUP_RECOVERY_VERSION;
3527
+ }
3528
+ export async function fetchSetupRecoveryEvidence(access, prNumber, fetchImpl = globalThis.fetch) {
3529
+ if (!setupPositive(prNumber))
3530
+ return { supported: false, reason: "evidence_unavailable" };
3531
+ try {
3532
+ if (!await supportsSetupRecovery(access, fetchImpl))
3533
+ return { supported: false, reason: "upgrade_required" };
3534
+ const raw = await fetchConductorJsonWithTimeout(buildConductorJiraUrl(access.baseUrl, "/setup-parse-recovery", { repo_name: access.repoName, setup_pr_number: String(prNumber) }), conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
3535
+ const evidence = decodeSetupRecoveryEvidence(raw);
3536
+ return evidence && evidence.setup_pr_number === prNumber ? { supported: true, evidence } : { supported: false, reason: "evidence_unavailable" };
3537
+ }
3538
+ catch {
3539
+ return { supported: false, reason: "evidence_unavailable" };
3540
+ }
3541
+ }
3542
+ export async function correctSetupBranch(access, expected, destination, fetchImpl = globalThis.fetch) {
3543
+ if ((expected !== null && !setupBranch(expected)) || !setupBranch(destination))
3544
+ return "refused";
3545
+ try {
3546
+ if (!await supportsSetupRecovery(access, fetchImpl))
3547
+ return "unsupported";
3548
+ await fetchConductorJsonWithMethodAndTimeout("PUT", buildConductorJiraUrl(access.baseUrl, "/config-field/base_branch"), conductorPostHeaders(access), JSON.stringify({ repo_name: access.repoName, value: destination, expected_current_value: expected, setup_correction_version: SETUP_CORRECTION_VERSION }), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
3549
+ }
3550
+ catch (e) {
3551
+ if (e instanceof ConductorBridgeApiError && e.status === 409)
3552
+ return "conflict";
3553
+ if (e instanceof ConductorBridgeApiError && e.status !== undefined && e.status >= 400 && e.status < 500)
3554
+ return "refused";
3555
+ return "uncertain";
3556
+ }
3557
+ try {
3558
+ const body = await fetchConductorJsonWithTimeout(buildConductorJiraUrl(access.baseUrl, "/config-field/base_branch", { repo_name: access.repoName }), conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
3559
+ return setupRecord(body) && Object.hasOwn(body, "value") && body.value === destination ? "verified" : "readback_mismatch";
3560
+ }
3561
+ catch {
3562
+ return "readback_unavailable";
3563
+ }
3564
+ }
3565
+ export async function admitSetupRecovery(access, evidence, retryGeneration, fetchImpl = globalThis.fetch) {
3566
+ const unknown = { version: SETUP_RECOVERY_VERSION, outcome: "unknown", reason: "admission_response_unknown" };
3567
+ try {
3568
+ if (!await supportsSetupRecovery(access, fetchImpl))
3569
+ return { ...unknown, reason: "upgrade_required" };
3570
+ const body = await fetchConductorJsonPostWithTimeout(buildConductorJiraUrl(access.baseUrl, "/parse-repository"), conductorPostHeaders(access), JSON.stringify({ repo_name: access.repoName, setup_recovery: {
3571
+ version: SETUP_RECOVERY_VERSION, setup_pr_number: evidence.setup_pr_number, reviewed_branch: evidence.configured_branch,
3572
+ configuration_fingerprint: evidence.configuration_fingerprint, ...(retryGeneration === undefined ? {} : { retry_generation: retryGeneration }),
3573
+ } }), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
3574
+ if (!setupRecord(body) || body.version !== SETUP_RECOVERY_VERSION || !["created", "reused", "serialized_successor", "already_satisfied", "retry_required", "unknown"].includes(body.outcome))
3575
+ return unknown;
3576
+ if (body.request_id != null && !setupId(body.request_id))
3577
+ return unknown;
3578
+ if (body.parse_run_id != null && !setupPositive(body.parse_run_id))
3579
+ return unknown;
3580
+ return { version: SETUP_RECOVERY_VERSION, outcome: body.outcome, request_id: body.request_id, parse_run_id: body.parse_run_id,
3581
+ generation: Number.isSafeInteger(body.generation) ? body.generation : null, retry_generation: setupPositive(body.retry_generation) ? body.retry_generation : null };
3582
+ }
3583
+ catch (e) {
3584
+ return { ...unknown, reason: e instanceof ConductorBridgeApiError && e.status === 409 ? "configuration_changed" : "admission_response_unknown" };
3585
+ }
3586
+ }
2920
3587
  /**
2921
3588
  * Call the protected `DELETE /vcs/pull-requests/{pr_number}/branch` endpoint.
2922
3589
  * Treats 404-equivalent responses as idempotent success (already deleted).
@@ -3006,6 +3673,17 @@ export const REQUIRED_CHECKS_VERIFICATIONS = new Set([
3006
3673
  "unknown_name",
3007
3674
  "unverifiable",
3008
3675
  ]);
3676
+ /**
3677
+ * BAPI-1602 — prerequisite rows an OLDER server may still send after this build
3678
+ * stopped knowing them. A retired row is kept and rendered with the server's own
3679
+ * text, never dropped and never fatal, because dropping it would hide a blocker
3680
+ * the older server also enforces. Only rows named here get this treatment.
3681
+ */
3682
+ const RETIRED_READINESS_PREREQUISITE_IDS = new Set(['server.test-command']);
3683
+ const RETIRED_ROW_TEXT_MAX = 400;
3684
+ function isBoundedServerText(value) {
3685
+ return typeof value === 'string' && value.length <= RETIRED_ROW_TEXT_MAX && !/[\u0000-\u001f\u007f]/.test(value);
3686
+ }
3009
3687
  export function parseReadinessPrerequisites(raw) {
3010
3688
  if (!Array.isArray(raw))
3011
3689
  return undefined;
@@ -3015,10 +3693,20 @@ export function parseReadinessPrerequisites(raw) {
3015
3693
  if (typeof item !== 'object' || item === null || Array.isArray(item))
3016
3694
  return undefined;
3017
3695
  const r = item;
3696
+ if (typeof r.id === 'string' && RETIRED_READINESS_PREREQUISITE_IDS.has(r.id) && !READINESS_PREREQUISITE_BY_ID.has(r.id)) {
3697
+ if (seen.has(r.id) || Object.keys(r).sort().join(',') !== 'check_status,fix,id,impact,label,scope' ||
3698
+ !isBoundedServerText(r.label) || !isBoundedServerText(r.fix) || !['customer', 'self_host'].includes(String(r.scope)) ||
3699
+ !['met', 'not_met', 'unknown', 'not_applicable'].includes(String(r.check_status)) || !['blocking', 'warning', 'info'].includes(String(r.impact)) ||
3700
+ (r.check_status === 'unknown' && r.impact === 'blocking'))
3701
+ return undefined;
3702
+ seen.add(r.id);
3703
+ result.push(r);
3704
+ continue;
3705
+ }
3018
3706
  const d = typeof r.id === 'string' ? READINESS_PREREQUISITE_BY_ID.get(r.id) : undefined;
3019
3707
  if (!d || seen.has(d.id) || Object.keys(r).sort().join(',') !== 'check_status,fix,id,impact,label,scope' || r.label !== d.label || r.scope !== d.scope ||
3020
3708
  !['met', 'not_met', 'unknown', 'not_applicable'].includes(String(r.check_status)) || !['blocking', 'warning', 'info'].includes(String(r.impact)) ||
3021
- typeof r.fix !== 'string' || !Object.values(READINESS_PREREQUISITE_FIXES).includes(r.fix) ||
3709
+ typeof r.fix !== 'string' || !(Object.values(READINESS_PREREQUISITE_FIXES).includes(r.fix) || PREVIOUS_SERVER_READINESS_FIXES.includes(r.fix)) ||
3022
3710
  (r.check_status === 'unknown' && r.impact === 'blocking'))
3023
3711
  return undefined;
3024
3712
  seen.add(d.id);
@@ -3061,15 +3749,33 @@ export const GATE_PROFILE_ADMISSION_REASONS = [
3061
3749
  export const GATE_PROFILE_WARNING_CODES = [
3062
3750
  "provider_check_not_seen_on_epic_branches",
3063
3751
  "epic_branch_search_unavailable",
3752
+ // BAPI-1606: warn-only rows for WATCHED checks. They never hold a launch.
3753
+ "watched_check_not_seen",
3754
+ "watched_check_evidence_unavailable",
3755
+ ];
3756
+ /**
3757
+ * BAPI-1606 — the closed reasons a watched check can warn with at run time. The
3758
+ * `explain_run` tool returns the server's projection unparsed, so these are named
3759
+ * here only as the contract surface; no runtime warning parser exists.
3760
+ */
3761
+ export const WATCHED_CHECK_WARNING_REASONS = [
3762
+ "watched_check_missing",
3763
+ "watched_check_pending",
3764
+ "watched_check_did_not_run",
3765
+ "watched_check_unavailable",
3064
3766
  ];
3065
3767
  /**
3066
3768
  * True when the server's rules waive the CI lane file
3067
3769
  * (`.github/workflows/epic-implementer-ci.yml`): a repository with a STORED gate
3068
- * profile names its own checks, so the lane file is not required. Absent profile
3069
- * (older server) keeps the lane-file requirement exactly as before.
3770
+ * profile names its own checks, so the lane file is not required. BAPI-1602: so
3771
+ * does a repository whose readable configured checks are its own reporting CI,
3772
+ * which the server reports as one bounded fact (`supervisor.reporting_ci_configured`).
3773
+ * Nothing is inferred from recent CI runs. Absent profile or fact (older server, or
3774
+ * an unreadable configuration) keeps the lane-file requirement exactly as before.
3070
3775
  */
3071
3776
  export function gateProfileWaivesCiWorkflow(readiness) {
3072
- return readiness.gate_profile?.source === "stored";
3777
+ return readiness.gate_profile?.source === "stored" ||
3778
+ readiness.supervisor?.reporting_ci_configured === true;
3073
3779
  }
3074
3780
  /** BAPI-1405 — the review mode the server will actually apply to this repository. */
3075
3781
  export const EFFECTIVE_REVIEW_MODES = [
@@ -3317,6 +4023,7 @@ export function parseConductorReadinessResponse(body) {
3317
4023
  const thr = requireObject(root.thresholds);
3318
4024
  const requiredChecksCount = requireInt(sup, "required_checks_count");
3319
4025
  return {
4026
+ ...(Object.hasOwn(root, 'assessment') ? { assessmentNegotiation: parseAssessmentNegotiation(root), ...(parseAssessmentNegotiation(root).status === 'available' ? { assessment: parseAssessmentNegotiation(root).assessment } : {}) } : {}),
3320
4027
  ...(typeof root.is_production === 'boolean' ? { is_production: root.is_production } : {}),
3321
4028
  ...(root.is_production === undefined || typeof root.is_production === 'boolean'
3322
4029
  ? { prerequisites: parseReadinessPrerequisites(root.prerequisites) } : {}),
@@ -3341,6 +4048,7 @@ export function parseConductorReadinessResponse(body) {
3341
4048
  required_checks_retired_gate_configured: parseOptionalBool(sup, "required_checks_retired_gate_configured"),
3342
4049
  required_checks_ci_workflow_absent: parseOptionalBool(sup, "required_checks_ci_workflow_absent"),
3343
4050
  required_checks_review_workflow_absent: parseOptionalBool(sup, "required_checks_review_workflow_absent"),
4051
+ reporting_ci_configured: parseOptionalBool(sup, "reporting_ci_configured"),
3344
4052
  },
3345
4053
  github: {
3346
4054
  credentials_readable: requireBool(gh, "credentials_readable"),
@@ -3608,6 +4316,7 @@ function parseGateProfile(body) {
3608
4316
  revision,
3609
4317
  provider_checks: list(o.provider_checks).map((c) => ({
3610
4318
  name: requiredName(c.name),
4319
+ watched: c.watched === true,
3611
4320
  outcome: enumOrNull(c.outcome, ["reported", "unseen", "evidence_unavailable"]),
3612
4321
  epic_branch_seen: boolOrNull(c.epic_branch_seen),
3613
4322
  })),
@@ -3633,8 +4342,37 @@ function parseGateProfile(body) {
3633
4342
  code: tokenOrNull(w.code) ?? "unknown",
3634
4343
  name: safeSubject(w.name),
3635
4344
  })),
4345
+ ...optionalWorkerSetupFields(o),
3636
4346
  };
3637
4347
  }
4348
+ /**
4349
+ * BAPI-1598. The two additive readiness fields. LENIENT by design: an older
4350
+ * server omits them, and a value this client does not understand is omitted too,
4351
+ * never turned into confirmed evidence and never a shape error (a readiness body
4352
+ * that cannot be read would become "no readiness at all").
4353
+ */
4354
+ function optionalWorkerSetupFields(o) {
4355
+ const out = {};
4356
+ const handoff = o.verification_handoff_default;
4357
+ if (handoff === "proceed" || handoff === "block")
4358
+ out.verification_handoff_default = handoff;
4359
+ const raw = o.worker_database;
4360
+ if (typeof raw === "object" && raw !== null && !Array.isArray(raw)) {
4361
+ const w = raw;
4362
+ const names = w.protected_databases;
4363
+ if ((w.mode === "none" || w.mode === "disposable_postgres") &&
4364
+ (names === undefined || names === null ||
4365
+ (Array.isArray(names) && names.length <= 16 && names.every((n) => safeSubject(n) !== null)))) {
4366
+ const role = safeSubject(w.worker_role);
4367
+ out.worker_database = {
4368
+ mode: w.mode,
4369
+ protected_databases: Array.isArray(names) ? names : [],
4370
+ worker_role: role,
4371
+ };
4372
+ }
4373
+ }
4374
+ return out;
4375
+ }
3638
4376
  const EPIC_BRANCH_CI_DECISIONS = new Set(["include", "decline"]);
3639
4377
  const EPIC_BRANCH_CI_OBSERVATION_QUALITIES = new Set(["exact", "inferred", "could_not_tell"]);
3640
4378
  const EPIC_BRANCH_CI_EXEMPTION_OUTCOMES = new Set(["exempt", "not_exempt", "unknown"]);
@@ -3755,6 +4493,9 @@ function parseMergeExecution(body) {
3755
4493
  throw readinessShapeError();
3756
4494
  }
3757
4495
  return {
4496
+ ...(o.probe_skipped_reason === "merge_execution_mode_not_github_actions"
4497
+ ? { probe_skipped_reason: "merge_execution_mode_not_github_actions" }
4498
+ : {}),
3758
4499
  branch_scope: requireEnum(o, "branch_scope", MERGE_EXECUTION_BRANCH_SCOPES),
3759
4500
  branch_protection_probe_succeeded: requireBool(o, "branch_protection_probe_succeeded"),
3760
4501
  branch_protection_actions_bot_admitted: requireBool(o, "branch_protection_actions_bot_admitted"),
@@ -3856,16 +4597,35 @@ export async function fetchConductorReadiness(access, fetchImpl = globalThis.fet
3856
4597
  const url = buildConductorJiraUrl(access.baseUrl, `${EPIC_RUNS_API_PREFIX}/conductor-readiness`, {
3857
4598
  repo_name: access.repoName,
3858
4599
  ...(options.epicRunId ? { epic_run_id: options.epicRunId } : {}),
4600
+ ...(options.assessmentVersion === 1 ? { assessment_version: "1" } : {}),
3859
4601
  });
3860
4602
  // BAPI-1455 — a `SCHEMA_INCOMPATIBLE` refusal explains itself in
3861
4603
  // `detail.error` (the applied stamp, the missing objects, the repair route),
3862
4604
  // so that field is read, with room for the object names.
3863
- const body = await fetchConductorJsonWithTimeout(url, conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl, {
3864
- readErrorField: true,
3865
- errorFieldPreviewMax: SCHEMA_REFUSAL_PREVIEW_MAX,
3866
- readErrorFieldOnlyFor: [SCHEMA_INCOMPATIBLE_ERROR_CODE],
3867
- });
3868
- return parseConductorReadinessResponse(body);
4605
+ try {
4606
+ const body = await fetchConductorJsonWithTimeout(url, conductorGetHeaders(access), CONDUCTOR_READINESS_FETCH_TIMEOUT_MS, fetchImpl, { readErrorField: true, errorFieldPreviewMax: SCHEMA_REFUSAL_PREVIEW_MAX, readErrorFieldOnlyFor: [SCHEMA_INCOMPATIBLE_ERROR_CODE] });
4607
+ const parsed = parseConductorReadinessResponse(body);
4608
+ if (options.assessmentVersion === 1) {
4609
+ const negotiation = parseAssessmentNegotiation(requireObject(body));
4610
+ // Scope and identity must describe this exact request.
4611
+ if (negotiation.status === 'available' && (negotiation.assessment.context.repo_name !== access.repoName ||
4612
+ negotiation.assessment.context.epic_run_id !== (options.epicRunId ?? null))) {
4613
+ const { assessment: _ignored, ...legacy } = parsed;
4614
+ return { ...legacy, assessmentNegotiation: { status: 'unavailable' } };
4615
+ }
4616
+ return { ...parsed, assessmentNegotiation: negotiation };
4617
+ }
4618
+ return parsed;
4619
+ }
4620
+ catch (error) {
4621
+ const issues = error instanceof ConductorBridgeApiError ? error.gateProfileEvidence?.issues : undefined;
4622
+ if (options.assessmentVersion === 1 && error instanceof ConductorBridgeApiError && error.status === 422 &&
4623
+ issues?.length === 1 && issues[0]?.type === 'literal_error' && issues[0]?.loc.join('.') === 'query.assessment_version') {
4624
+ const legacy = await fetchConductorReadiness(access, fetchImpl, { epicRunId: options.epicRunId });
4625
+ return { ...legacy, assessmentNegotiation: { status: 'unsupported' } };
4626
+ }
4627
+ throw error;
4628
+ }
3869
4629
  }
3870
4630
  /** The answer for every failure: an older server, a non-200, a timeout, a bad body. */
3871
4631
  export const REPOSITORY_USAGE_ADVISORY_UNAVAILABLE = Object.freeze({
@@ -4144,7 +4904,7 @@ export function classifySupervisorBootstrapFailure(err) {
4144
4904
  return "server";
4145
4905
  return "rejected";
4146
4906
  }
4147
- const CI_STOP_REASONS = new Set(["wait_expired", "verdict_unavailable", "repair_exhausted"]);
4907
+ const CI_STOP_REASONS = new Set(["wait_expired", "verdict_unavailable", "repair_exhausted", "required_check_not_reporting"]);
4148
4908
  const RESUME_CI_AUDIT_WARNING_MAX = 200;
4149
4909
  function isPlainRecord(value) {
4150
4910
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -4446,6 +5206,21 @@ export async function regeneratePlanTicket(access, request, fetchImpl = globalTh
4446
5206
  // nothing here echoes a response body, the API key, or command output.
4447
5207
  /** The capability token the gate-profile server answers (BAPI-1390). */
4448
5208
  export const GATE_PROFILE_CAPABILITY_TOKEN = "gate_profile.v1";
5209
+ /**
5210
+ * The additive capability a server answers when it accepts and stores a provider
5211
+ * check as watched (BAPI-1606). It follows {@link GATE_PROFILE_CAPABILITY_TOKEN}
5212
+ * and never replaces it. Setup reads it through
5213
+ * {@link probeConductorGateProfileWatchedCapability}.
5214
+ */
5215
+ export const GATE_PROFILE_WATCHED_CAPABILITY_TOKEN = "gate_profile.watched.v1";
5216
+ /**
5217
+ * The additive capability a server answers when it accepts and stores the
5218
+ * optional `worker_database` and `verification_handoff_default` settings
5219
+ * (BAPI-1598). It follows {@link GATE_PROFILE_WATCHED_CAPABILITY_TOKEN} and never
5220
+ * replaces it. Its absence is informational: setup then skips only those two
5221
+ * fields, and nothing about creating, approving, or launching a run depends on it.
5222
+ */
5223
+ export const GATE_PROFILE_WORKER_SETUP_CAPABILITY_TOKEN = "gate_profile.worker_setup.v1";
4449
5224
  const GATE_PROFILE_KINDS = new Set(["provider", "local", "mixed", "none"]);
4450
5225
  const GATE_PROFILE_SOURCES = new Set(["stored", "legacy", "unconfirmed"]);
4451
5226
  const GATE_QUALIFICATION_STATES = new Set(["qualified", "unqualified", "stale", "not_required"]);
@@ -4469,6 +5244,8 @@ const GATE_MAX_LOCAL_COMMANDS = 16;
4469
5244
  const GATE_MAX_CUSTOMIZED = 64;
4470
5245
  /** The provider-history walk makes bounded provider calls; give it longer. */
4471
5246
  const GATE_CHECK_HISTORY_TIMEOUT_MS = 90_000;
5247
+ /** The learned-command request makes one model call on the server; give it longer. */
5248
+ const CONDUCTOR_LEARNED_TEST_COMMAND_TIMEOUT_MS = 90_000;
4472
5249
  const GATE_MAX_WORKER_ENV = 32;
4473
5250
  const GATE_WORKER_ENV_VALUE_MAX_BYTES = 1024;
4474
5251
  const GATE_WORKER_ENV_NAME_RE = /^[A-Z_][A-Z0-9_]{0,63}$/;
@@ -4522,6 +5299,106 @@ function parseWorkerEnvList(raw) {
4522
5299
  }
4523
5300
  return entries.length > 0 ? entries : undefined;
4524
5301
  }
5302
+ /**
5303
+ * BAPI-1551 — parse a returned `dependency_install` list, fail-closed. Absent or
5304
+ * `null` is no declaration; any invalid entry throws the field-free shape error,
5305
+ * never a partly trusted list.
5306
+ */
5307
+ function parseDependencyInstallField(raw) {
5308
+ if (raw === undefined || raw === null)
5309
+ return undefined;
5310
+ const entries = parseDependencyInstallStrict(raw);
5311
+ if (entries === null)
5312
+ throw readinessShapeError();
5313
+ return entries.length > 0 ? entries : undefined;
5314
+ }
5315
+ /**
5316
+ * BAPI-1580 — parse a returned `must_order_paths` list, fail-closed. Absent or
5317
+ * `null` is no declaration; any invalid entry, duplicate, or over-bound list
5318
+ * throws the field-free shape error, never a partly trusted or emptied list.
5319
+ * Returns the canonical sorted list.
5320
+ */
5321
+ function parseMustOrderPathsField(raw) {
5322
+ if (raw === undefined || raw === null)
5323
+ return [];
5324
+ const paths = parseMustOrderPathsStrict(raw);
5325
+ if (paths === null)
5326
+ throw readinessShapeError();
5327
+ return paths;
5328
+ }
5329
+ /** BAPI-1551 — absent or `null` is `unknown`; any other non-enum value throws. */
5330
+ function parseCiDatabaseField(raw) {
5331
+ if (raw === undefined || raw === null)
5332
+ return CI_DATABASE_DEFAULT;
5333
+ if (!isCiDatabase(raw))
5334
+ throw readinessShapeError();
5335
+ return raw;
5336
+ }
5337
+ /** BAPI-1598. Parse a returned worker-database declaration, fail-closed; absent and `null` read as unset. */
5338
+ function parseWorkerDatabaseField(raw) {
5339
+ if (raw === undefined || raw === null)
5340
+ return undefined;
5341
+ const o = requireObject(raw);
5342
+ for (const key of Object.keys(o)) {
5343
+ if (!["mode", "worker_role", "protected_databases", "env_names", "migrate_command"].includes(key)) {
5344
+ throw readinessShapeError();
5345
+ }
5346
+ }
5347
+ const mode = o.mode === undefined ? "none" : o.mode;
5348
+ if (mode !== "none" && mode !== "disposable_postgres")
5349
+ throw readinessShapeError();
5350
+ const names = (value) => {
5351
+ if (value === undefined || value === null)
5352
+ return undefined;
5353
+ if (!Array.isArray(value) || value.length > 16 || value.some((n) => typeof n !== "string" || n.length === 0 || n.length > 128)) {
5354
+ throw readinessShapeError();
5355
+ }
5356
+ return value;
5357
+ };
5358
+ const out = { mode };
5359
+ if (o.worker_role !== undefined && o.worker_role !== null) {
5360
+ if (typeof o.worker_role !== "string" || o.worker_role.length === 0 || o.worker_role.length > 128)
5361
+ throw readinessShapeError();
5362
+ out.worker_role = o.worker_role;
5363
+ }
5364
+ const protectedDatabases = names(o.protected_databases);
5365
+ if (protectedDatabases)
5366
+ out.protected_databases = protectedDatabases;
5367
+ const envNames = names(o.env_names);
5368
+ if (envNames)
5369
+ out.env_names = envNames;
5370
+ if (o.migrate_command !== undefined && o.migrate_command !== null) {
5371
+ const m = requireObject(o.migrate_command);
5372
+ for (const key of Object.keys(m)) {
5373
+ if (key !== "argv" && key !== "timeout_seconds" && key !== "head_check")
5374
+ throw readinessShapeError();
5375
+ }
5376
+ const argv = m.argv;
5377
+ if (!Array.isArray(argv) || argv.length === 0 || argv.length > GATE_MAX_ARGV_ENTRIES ||
5378
+ argv.some((a) => typeof a !== "string" || a.length === 0 || a.length > GATE_ARGV_ENTRY_MAX)) {
5379
+ throw readinessShapeError();
5380
+ }
5381
+ if (typeof m.timeout_seconds !== "number" || !Number.isInteger(m.timeout_seconds))
5382
+ throw readinessShapeError();
5383
+ if (m.head_check !== undefined && m.head_check !== null && m.head_check !== "alembic" && m.head_check !== "none") {
5384
+ throw readinessShapeError();
5385
+ }
5386
+ out.migrate_command = {
5387
+ argv: argv,
5388
+ timeout_seconds: m.timeout_seconds,
5389
+ ...(m.head_check ? { head_check: m.head_check } : {}),
5390
+ };
5391
+ }
5392
+ return out;
5393
+ }
5394
+ /** BAPI-1598. Parse the stored hand-off default; absent and `null` read as unset (effective `proceed`). */
5395
+ function parseHandoffDefaultField(raw) {
5396
+ if (raw === undefined || raw === null)
5397
+ return undefined;
5398
+ if (raw !== "proceed" && raw !== "block")
5399
+ throw readinessShapeError();
5400
+ return raw;
5401
+ }
4525
5402
  /** Parse a returned or proposed reproduction hint, fail-closed. */
4526
5403
  function parseReproductionHint(raw) {
4527
5404
  const o = requireObject(raw);
@@ -4559,15 +5436,28 @@ function parseGateProfileBody(raw) {
4559
5436
  const checksRaw = o.provider_checks;
4560
5437
  if (!Array.isArray(checksRaw) || checksRaw.length > GATE_MAX_PROVIDER_CHECKS)
4561
5438
  throw readinessShapeError();
4562
- const providerChecks = checksRaw.map((c) => gateName(requireObject(c).name, GATE_MEMBER_NAME_MAX));
5439
+ // BAPI-1606: the server lists required entries first, then watched ones flagged
5440
+ // `watched: true`. Split them here; the hints stay keyed by name for both groups.
5441
+ const providerChecks = [];
5442
+ const watchedChecks = [];
4563
5443
  const reproductionHints = new Map();
4564
- checksRaw.forEach((c, index) => {
4565
- const reproduce = requireObject(c).reproduce;
5444
+ checksRaw.forEach((c) => {
5445
+ const entry = requireObject(c);
5446
+ const name = gateName(entry.name, GATE_MEMBER_NAME_MAX);
5447
+ if (entry.watched !== undefined && typeof entry.watched !== "boolean")
5448
+ throw readinessShapeError();
5449
+ (entry.watched === true ? watchedChecks : providerChecks).push(name);
5450
+ const reproduce = entry.reproduce;
4566
5451
  if (reproduce === undefined || reproduce === null)
4567
5452
  return;
4568
- reproductionHints.set(providerChecks[index], parseReproductionHint(reproduce));
5453
+ reproductionHints.set(name, parseReproductionHint(reproduce));
4569
5454
  });
4570
5455
  const workerEnv = parseWorkerEnvList(o.worker_env);
5456
+ const dependencyInstall = parseDependencyInstallField(o.dependency_install);
5457
+ const ciDatabase = parseCiDatabaseField(o.ci_database);
5458
+ const mustOrderPaths = parseMustOrderPathsField(o.must_order_paths);
5459
+ const workerDatabase = parseWorkerDatabaseField(o.worker_database);
5460
+ const handoffDefault = parseHandoffDefaultField(o.verification_handoff_default);
4571
5461
  const commandsRaw = o.local_commands;
4572
5462
  if (!Array.isArray(commandsRaw) || commandsRaw.length > GATE_MAX_LOCAL_COMMANDS)
4573
5463
  throw readinessShapeError();
@@ -4624,8 +5514,14 @@ function parseGateProfileBody(raw) {
4624
5514
  return {
4625
5515
  kind,
4626
5516
  provider_checks: providerChecks,
5517
+ ...(watchedChecks.length > 0 ? { watched_checks: watchedChecks } : {}),
4627
5518
  ...(workerEnv ? { worker_env: workerEnv } : {}),
4628
5519
  ...(reproductionHints.size > 0 ? { reproduction_hints: reproductionHints } : {}),
5520
+ ...(dependencyInstall ? { dependency_install: dependencyInstall } : {}),
5521
+ ...(ciDatabase !== "unknown" ? { ci_database: ciDatabase } : {}),
5522
+ ...(workerDatabase ? { worker_database: workerDatabase } : {}),
5523
+ ...(handoffDefault ? { verification_handoff_default: handoffDefault } : {}),
5524
+ must_order_paths: mustOrderPaths,
4629
5525
  local_commands: localCommands,
4630
5526
  migration_guard: guard,
4631
5527
  customized_commands: customized.map((n) => gateName(n, GATE_MEMBER_NAME_MAX)),
@@ -4691,7 +5587,7 @@ export async function fetchConductorGateProfile(access, fetchImpl) {
4691
5587
  return parseConductorGateProfileResponse(body, access.repoName);
4692
5588
  }
4693
5589
  /**
4694
- * BAPI-1520 — which extension fields the older server rejected, and only when
5590
+ * BAPI-1520 (extended by BAPI-1551 and BAPI-1580) — which extension fields the older server rejected, and only when
4695
5591
  * the request actually carried them. `worker_env` counts only at exactly
4696
5592
  * `["body","worker_env"]`; `reproduce` only at exactly
4697
5593
  * `["body","provider_checks",<index>,"reproduce"]`. Any other 422 returns
@@ -4706,6 +5602,14 @@ export function classifyGateProfileExtensionRejection(err, request) {
4706
5602
  const confirm = request.action === "confirm" ? request : null;
4707
5603
  let workerEnv = false;
4708
5604
  let reproduce = false;
5605
+ // BAPI-1551: reported only when true, so the BAPI-1520 shape is unchanged.
5606
+ let dependencyInstall = false;
5607
+ let ciDatabase = false;
5608
+ // BAPI-1580: same rule.
5609
+ let mustOrderPaths = false;
5610
+ // BAPI-1598: same rule.
5611
+ let workerDatabase = false;
5612
+ let handoffDefault = false;
4709
5613
  for (const issue of issues) {
4710
5614
  if (issue.type !== "extra_forbidden")
4711
5615
  return null;
@@ -4715,6 +5619,31 @@ export function classifyGateProfileExtensionRejection(err, request) {
4715
5619
  return null;
4716
5620
  workerEnv = true;
4717
5621
  }
5622
+ else if (loc.length === 2 && loc[0] === "body" && loc[1] === "dependency_install") {
5623
+ if (!confirm || confirm.dependency_install === undefined)
5624
+ return null;
5625
+ dependencyInstall = true;
5626
+ }
5627
+ else if (loc.length === 2 && loc[0] === "body" && loc[1] === "ci_database") {
5628
+ if (!confirm || confirm.ci_database === undefined)
5629
+ return null;
5630
+ ciDatabase = true;
5631
+ }
5632
+ else if (loc.length === 2 && loc[0] === "body" && loc[1] === "must_order_paths") {
5633
+ if (!confirm || confirm.must_order_paths === undefined)
5634
+ return null;
5635
+ mustOrderPaths = true;
5636
+ }
5637
+ else if (loc.length === 2 && loc[0] === "body" && loc[1] === "worker_database") {
5638
+ if (!confirm || confirm.worker_database === undefined)
5639
+ return null;
5640
+ workerDatabase = true;
5641
+ }
5642
+ else if (loc.length === 2 && loc[0] === "body" && loc[1] === "verification_handoff_default") {
5643
+ if (!confirm || confirm.verification_handoff_default === undefined)
5644
+ return null;
5645
+ handoffDefault = true;
5646
+ }
4718
5647
  else if (loc.length === 4 &&
4719
5648
  loc[0] === "body" &&
4720
5649
  loc[1] === "provider_checks" &&
@@ -4729,7 +5658,15 @@ export function classifyGateProfileExtensionRejection(err, request) {
4729
5658
  return null;
4730
5659
  }
4731
5660
  }
4732
- return { worker_env: workerEnv, reproduce };
5661
+ return {
5662
+ worker_env: workerEnv,
5663
+ reproduce,
5664
+ ...(dependencyInstall ? { dependency_install: true } : {}),
5665
+ ...(ciDatabase ? { ci_database: true } : {}),
5666
+ ...(mustOrderPaths ? { must_order_paths: true } : {}),
5667
+ ...(workerDatabase ? { worker_database: true } : {}),
5668
+ ...(handoffDefault ? { verification_handoff_default: true } : {}),
5669
+ };
4733
5670
  }
4734
5671
  /** The safe refusal context of a failed write, or `undefined` when there is none. */
4735
5672
  function gateProfileRefusalDetail(err) {
@@ -4893,6 +5830,46 @@ export async function fetchConductorGateCheckHistory(access, names, fetchImpl) {
4893
5830
  * all read as unsupported, so the installer writes nothing.
4894
5831
  */
4895
5832
  export async function probeConductorGateProfileCapability(access, fetchImpl) {
5833
+ const read = await readGateProfileCapabilityTokens(access, fetchImpl);
5834
+ if (!read.ok)
5835
+ return { supported: false, reason: read.reason };
5836
+ return read.tokens.includes(GATE_PROFILE_CAPABILITY_TOKEN)
5837
+ ? { supported: true }
5838
+ : { supported: false, reason: "absent" };
5839
+ }
5840
+ /**
5841
+ * BAPI-1603 — the same capability read, answering whether the server stores a
5842
+ * provider check as WATCHED (`gate_profile.watched.v1`). NEVER throws and fails
5843
+ * closed: anything but an advertised token reads as unsupported, and the caller
5844
+ * then skips only its watched-member writes. It never reads as a request to turn
5845
+ * watched checks into required ones.
5846
+ */
5847
+ export async function probeConductorGateProfileWatchedCapability(access, fetchImpl) {
5848
+ const read = await readGateProfileCapabilityTokens(access, fetchImpl);
5849
+ if (!read.ok)
5850
+ return { supported: false, reason: read.reason };
5851
+ return read.tokens.includes(GATE_PROFILE_WATCHED_CAPABILITY_TOKEN)
5852
+ ? { supported: true }
5853
+ : { supported: false, reason: "absent" };
5854
+ }
5855
+ /**
5856
+ * BAPI-1598 — the same capability read, answering whether the server stores the
5857
+ * optional worker-database and hand-off-default settings
5858
+ * (`gate_profile.worker_setup.v1`). NEVER throws and fails closed: anything but an
5859
+ * advertised token reads as unsupported, and the caller then omits only those two
5860
+ * fields. It is informational and never a prerequisite for readiness, creation,
5861
+ * approval, or launch.
5862
+ */
5863
+ export async function probeConductorGateProfileWorkerSetupCapability(access, fetchImpl) {
5864
+ const read = await readGateProfileCapabilityTokens(access, fetchImpl);
5865
+ if (!read.ok)
5866
+ return { supported: false, reason: read.reason };
5867
+ return read.tokens.includes(GATE_PROFILE_WORKER_SETUP_CAPABILITY_TOKEN)
5868
+ ? { supported: true }
5869
+ : { supported: false, reason: "absent" };
5870
+ }
5871
+ /** The advertised capability tokens, or the closed reason they could not be read. */
5872
+ async function readGateProfileCapabilityTokens(access, fetchImpl) {
4896
5873
  let body;
4897
5874
  try {
4898
5875
  body = await fetchConductorJsonWithTimeout(gateProfileUrl(access, "capability/"), conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
@@ -4900,25 +5877,179 @@ export async function probeConductorGateProfileCapability(access, fetchImpl) {
4900
5877
  catch (err) {
4901
5878
  if (err instanceof ConductorBridgeApiError) {
4902
5879
  if (err.kind === "unauthorized")
4903
- return { supported: false, reason: "unauthorized" };
5880
+ return { ok: false, reason: "unauthorized" };
4904
5881
  if (err.kind === "network" || err.kind === "timeout")
4905
- return { supported: false, reason: "unreachable" };
5882
+ return { ok: false, reason: "unreachable" };
4906
5883
  if (err.kind === "invalid-input")
4907
- return { supported: false, reason: "unreadable" };
5884
+ return { ok: false, reason: "unreadable" };
4908
5885
  }
4909
- return { supported: false, reason: "absent" };
5886
+ return { ok: false, reason: "absent" };
4910
5887
  }
4911
5888
  if (typeof body !== "object" || body === null || Array.isArray(body)) {
4912
- return { supported: false, reason: "unreadable" };
5889
+ return { ok: false, reason: "unreadable" };
4913
5890
  }
4914
5891
  const o = body;
4915
5892
  const caps = o.capabilities;
4916
5893
  if (o.repo_name !== access.repoName || !Array.isArray(caps) || caps.some((c) => typeof c !== "string")) {
4917
- return { supported: false, reason: "unreadable" };
5894
+ return { ok: false, reason: "unreadable" };
5895
+ }
5896
+ return { ok: true, tokens: caps };
5897
+ }
5898
+ /**
5899
+ * GET the repository's learned-field counts. NEVER throws. Only a validated body
5900
+ * is `confirmed`; a 503 `STATE_UNAVAILABLE`, a missing route, a failed transport,
5901
+ * and a malformed or self-contradicting body are all `unknown`, so none of them
5902
+ * can authorize a "not learned" refusal.
5903
+ */
5904
+ export async function fetchConductorRepositoryLearning(access, fetchImpl) {
5905
+ let body;
5906
+ try {
5907
+ body = await fetchConductorJsonWithTimeout(buildConductorJiraUrl(access.baseUrl, `${EPIC_RUNS_API_PREFIX}/supervisor-setup/repository-learning/`, { repo_name: access.repoName }), conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
5908
+ }
5909
+ catch (err) {
5910
+ if (!(err instanceof ConductorBridgeApiError))
5911
+ return { status: "unknown", reason: "unreachable" };
5912
+ if (err.kind === "unauthorized")
5913
+ return { status: "unknown", reason: "unauthorized" };
5914
+ if (err.kind === "network" || err.kind === "timeout")
5915
+ return { status: "unknown", reason: "unreachable" };
5916
+ if (err.status === 404 || err.status === 405)
5917
+ return { status: "unknown", reason: "unsupported" };
5918
+ if (err.kind === "server" || err.errorCode === "STATE_UNAVAILABLE") {
5919
+ return { status: "unknown", reason: "unavailable" };
5920
+ }
5921
+ return { status: "unknown", reason: "unreadable" };
5922
+ }
5923
+ try {
5924
+ const o = requireObject(body);
5925
+ if (o.repo_name !== access.repoName)
5926
+ throw readinessShapeError();
5927
+ const learned = requireBool(o, "learned");
5928
+ const set = requireInt(o, "learned_fields_set");
5929
+ const total = requireInt(o, "learned_fields_total");
5930
+ // The server defines learned as "every field set"; a body that disagrees with
5931
+ // its own counts is unreadable evidence, never a confirmed answer.
5932
+ if (set < 0 || total < 0 || set > total || learned !== (total > 0 && set === total)) {
5933
+ throw readinessShapeError();
5934
+ }
5935
+ return { status: "confirmed", learned, learned_fields_set: set, learned_fields_total: total };
5936
+ }
5937
+ catch {
5938
+ return { status: "unknown", reason: "unreadable" };
5939
+ }
5940
+ }
5941
+ /** The server's cap on client hints; extra candidates are never sent. */
5942
+ export const LEARNED_TEST_COMMAND_MAX_CANDIDATES = 8;
5943
+ /** The closed reasons the server gives when it found no command to try. */
5944
+ export const LEARNED_TEST_COMMAND_NO_COMMAND_REASONS = [
5945
+ "no_testing_instructions",
5946
+ "llm_unavailable",
5947
+ "llm_output_invalid",
5948
+ "no_candidates",
5949
+ "working_directory_unsupported",
5950
+ "not_plain_argv",
5951
+ "command_not_allowed",
5952
+ "invalid_command",
5953
+ ];
5954
+ const LEARNED_COMMAND_DISPLAY_MAX = 4096;
5955
+ const LEARNED_COMMAND_MAX_DISPLAYED = 16;
5956
+ function learnedCommandText(value, max) {
5957
+ if (typeof value !== "string" || value.length === 0 || value.length > max || /[\u0000-\u001F\u007F]/.test(value)) {
5958
+ throw readinessShapeError();
5959
+ }
5960
+ return value;
5961
+ }
5962
+ /** Validate a learned-command 200 body, fail-closed. Throws the field-free shape error. */
5963
+ export function parseConductorLearnedTestCommandResponse(body, expectedRepoName) {
5964
+ const o = requireObject(body);
5965
+ if (o.repo_name !== expectedRepoName)
5966
+ throw readinessShapeError();
5967
+ const source = () => {
5968
+ if (o.source !== "learned" && o.source !== "owner")
5969
+ throw readinessShapeError();
5970
+ return o.source;
5971
+ };
5972
+ switch (o.outcome) {
5973
+ case "qualification_queued": {
5974
+ const jobId = requireInt(o, "job_id");
5975
+ const baseRevision = requireInt(o, "base_revision");
5976
+ if (jobId <= 0 || baseRevision < 0)
5977
+ throw readinessShapeError();
5978
+ const raw = o.commands;
5979
+ if (!Array.isArray(raw) || raw.length === 0 || raw.length > LEARNED_COMMAND_MAX_DISPLAYED) {
5980
+ throw readinessShapeError();
5981
+ }
5982
+ const commands = raw.map((item) => {
5983
+ const c = requireObject(item);
5984
+ return {
5985
+ name: learnedCommandText(c.name, GATE_COMMAND_NAME_MAX),
5986
+ command: learnedCommandText(c.command, LEARNED_COMMAND_DISPLAY_MAX),
5987
+ };
5988
+ });
5989
+ return { kind: "qualification_queued", source: source(), jobId, baseRevision, commands };
5990
+ }
5991
+ case "no_command": {
5992
+ const reason = o.reason;
5993
+ if (typeof reason !== "string" ||
5994
+ !LEARNED_TEST_COMMAND_NO_COMMAND_REASONS.includes(reason)) {
5995
+ throw readinessShapeError();
5996
+ }
5997
+ return {
5998
+ kind: "no_command",
5999
+ source: source(),
6000
+ reason: reason,
6001
+ };
6002
+ }
6003
+ case "not_needed":
6004
+ if (o.reason !== "local_gate_already_stored")
6005
+ throw readinessShapeError();
6006
+ return { kind: "not_needed" };
6007
+ default:
6008
+ throw readinessShapeError();
6009
+ }
6010
+ }
6011
+ /**
6012
+ * POST a learned-command request: extract (or validate the owner's) command and
6013
+ * queue one qualification trial bound to `expectedRevision`. NEVER throws. Nothing
6014
+ * is stored by this call; the trial runs on the owner's executor and the server
6015
+ * promotes the local gate only when every command passes.
6016
+ */
6017
+ export async function requestConductorLearnedTestCommand(access, request, fetchImpl) {
6018
+ const candidates = (request.candidates ?? [])
6019
+ .slice(0, LEARNED_TEST_COMMAND_MAX_CANDIDATES)
6020
+ .map((c) => (c.source === undefined ? { command: c.command } : { command: c.command, source: c.source }));
6021
+ const payload = { expected_revision: request.expectedRevision };
6022
+ if (candidates.length > 0)
6023
+ payload.candidates = candidates;
6024
+ if (request.ownerCommand !== undefined)
6025
+ payload.owner_command = request.ownerCommand;
6026
+ let body;
6027
+ try {
6028
+ body = await fetchConductorJsonWithMethodAndTimeout("POST", buildConductorJiraUrl(access.baseUrl, `${EPIC_RUNS_API_PREFIX}/supervisor-setup/learned-test-command/`, { repo_name: access.repoName }), conductorPostHeaders(access), JSON.stringify(payload), CONDUCTOR_LEARNED_TEST_COMMAND_TIMEOUT_MS, fetchImpl);
6029
+ }
6030
+ catch (err) {
6031
+ if (!(err instanceof ConductorBridgeApiError))
6032
+ return { kind: "uncertain" };
6033
+ if (err.errorCode === "STALE_REVISION")
6034
+ return { kind: "stale_revision" };
6035
+ if (err.errorCode === "STATE_UNAVAILABLE")
6036
+ return { kind: "state_unavailable" };
6037
+ if (err.kind === "unauthorized")
6038
+ return { kind: "refused", reason: "unauthorized" };
6039
+ if (err.unreadableSuccess === true)
6040
+ return { kind: "uncertain" };
6041
+ if (err.kind === "timeout" || err.kind === "network" || err.kind === "server")
6042
+ return { kind: "uncertain" };
6043
+ if (err.status === 404 || err.status === 405)
6044
+ return { kind: "unsupported" };
6045
+ return { kind: "refused", reason: "rejected" };
6046
+ }
6047
+ try {
6048
+ return parseConductorLearnedTestCommandResponse(body, access.repoName);
6049
+ }
6050
+ catch {
6051
+ return { kind: "malformed" };
4918
6052
  }
4919
- return caps.includes(GATE_PROFILE_CAPABILITY_TOKEN)
4920
- ? { supported: true }
4921
- : { supported: false, reason: "absent" };
4922
6053
  }
4923
6054
  const QUALIFICATION_REFUSAL_CODES = Object.freeze({
4924
6055
  PROFILE_NOT_CONFIRMED: "profile-not-confirmed",
@@ -4967,6 +6098,16 @@ export async function enqueueConductorGateQualification(access, request, fetchIm
4967
6098
  }
4968
6099
  return { kind: "accepted", jobId, jobStatus, revision };
4969
6100
  }
6101
+ /**
6102
+ * BAPI-1637 — how a completed qualification job's commands ended, as the server
6103
+ * derived it from stored evidence. Closed: an unknown token reads as `null`.
6104
+ */
6105
+ export const CONDUCTOR_GATE_QUALIFICATION_PHASES = [
6106
+ "dependency_preparation_failed",
6107
+ "could_not_start",
6108
+ "ran_and_failed",
6109
+ "passed",
6110
+ ];
4970
6111
  export function parseConductorGateQualificationJob(body, expectedRepoName, expectedJobId) {
4971
6112
  const o = requireObject(body);
4972
6113
  if (o.repo_name !== expectedRepoName || o.job_id !== expectedJobId)
@@ -4986,6 +6127,10 @@ export function parseConductorGateQualificationJob(body, expectedRepoName, expec
4986
6127
  qualification_state: (state ?? null),
4987
6128
  current_revision: requireNullableInt(o, "current_revision"),
4988
6129
  failure: (failure ?? null),
6130
+ phase: CONDUCTOR_GATE_QUALIFICATION_PHASES.includes(o.phase)
6131
+ ? o.phase
6132
+ : null,
6133
+ dependency_install_declared: typeof o.dependency_install_declared === "boolean" ? o.dependency_install_declared : null,
4989
6134
  };
4990
6135
  }
4991
6136
  /** GET one qualification job's verified state. Throws a sanitized error on failure. */
@@ -4996,6 +6141,163 @@ export async function fetchConductorGateQualificationJob(access, jobId, fetchImp
4996
6141
  /** Authenticated read-only preview of the same effective policy sent at creation. */
4997
6142
  export async function previewLaunchReadiness(access, policyJson, fetchImpl = globalThis.fetch) {
4998
6143
  const url = buildConductorJiraUrl(access.baseUrl, `${EPIC_RUNS_API_PREFIX}/launch-readiness`);
4999
- const body = await fetchConductorJsonPostWithTimeout(url, conductorPostHeaders(access), JSON.stringify({ repo_name: access.repoName, policy_json: policyJson }), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
6144
+ const body = await fetchConductorJsonPostWithTimeout(url, conductorPostHeaders(access), JSON.stringify({ repo_name: access.repoName, policy_json: policyJson }), CONDUCTOR_READINESS_FETCH_TIMEOUT_MS, fetchImpl);
5000
6145
  return parseConductorReadinessResponse(body);
5001
6146
  }
6147
+ /** BAPI-1567 combined policy transport. Artifacts live only in transient memory. */
6148
+ export const SETUP_POLICY_PROTOCOL = "bridge.setup-policy.v1";
6149
+ export class ConductorSetupPolicyError extends Error {
6150
+ reason;
6151
+ constructor(reason) {
6152
+ super(`Setup policy ${reason}`);
6153
+ this.reason = reason;
6154
+ }
6155
+ }
6156
+ function setupObject(value) {
6157
+ return !!value && typeof value === "object" && !Array.isArray(value);
6158
+ }
6159
+ function setupState(value) {
6160
+ return setupObject(value) && Object.keys(value).length === 2
6161
+ && Number.isSafeInteger(value.generation) && Number(value.generation) >= 0
6162
+ && Number.isSafeInteger(value.revision) && Number(value.revision) >= 0;
6163
+ }
6164
+ function setupProjection(value) {
6165
+ const exact = (object, fields) => Object.keys(object).sort().join() === fields.sort().join();
6166
+ if (!setupObject(value) || !exact(value, ["gate", "setup", "config", "sources", "qualification", "precedence"]))
6167
+ return false;
6168
+ if (!setupObject(value.setup) || !exact(value.setup, ["done_gate_config", "review_source", "min_approvals", "review_policy"]))
6169
+ return false;
6170
+ if (!setupObject(value.config) || !exact(value.config, ["teardown_enabled", "auto_rereview_enabled", "max_remediation_attempts", "max_remediation_no_progress_attempts", "worker_liveness_window_seconds", "auto_merge_enabled", "merge_approval_required", "merge_execution"]))
6171
+ return false;
6172
+ if (!setupObject(value.sources) || !exact(value.sources, ["setup", "config"]))
6173
+ return false;
6174
+ if (!["project_default", "built_in"].includes(String(value.sources.setup)) || !["project_default", "built_in"].includes(String(value.sources.config)))
6175
+ return false;
6176
+ if (!["qualified", "unqualified", "stale", "not_required"].includes(String(value.qualification)) || typeof value.precedence !== "string")
6177
+ return false;
6178
+ if (value.gate === null)
6179
+ return true;
6180
+ if (!setupObject(value.gate))
6181
+ return false;
6182
+ const gate = value.gate;
6183
+ const allowed = ["kind", "provider_checks", "local_commands", "migration_guard", "customized_commands", "failure_formats", "worker_env", "dependency_install", "ci_database", "must_order_paths", "worker_database", "verification_handoff_default", "source"];
6184
+ if (Object.keys(gate).some(k => !allowed.includes(k)) || !["provider", "mixed", "local", "none"].includes(String(gate.kind)))
6185
+ return false;
6186
+ // BAPI-1606: a provider entry is `{name}` (required) or `{name, watched: true}`.
6187
+ if (!Array.isArray(gate.provider_checks) || !gate.provider_checks.every(c => setupObject(c) && typeof c.name === "string"
6188
+ && (exact(c, ["name"]) || (exact(c, ["name", "watched"]) && c.watched === true))))
6189
+ return false;
6190
+ if (!Array.isArray(gate.local_commands) || !gate.local_commands.every(c => setupObject(c) && exact(c, ["name", "argv", "timeout_seconds"])
6191
+ && typeof c.name === "string" && Array.isArray(c.argv) && c.argv.every(a => typeof a === "string") && Number.isSafeInteger(c.timeout_seconds)))
6192
+ return false;
6193
+ if (gate.worker_env !== undefined && (!Array.isArray(gate.worker_env) || !gate.worker_env.every(e => setupObject(e) && exact(e, ["name"]) && typeof e.name === "string")))
6194
+ return false;
6195
+ return true;
6196
+ }
6197
+ function setupCanonical(value) {
6198
+ if (Array.isArray(value))
6199
+ return `[${value.map(setupCanonical).join(",")}]`;
6200
+ if (setupObject(value))
6201
+ return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${setupCanonical(v)}`).join(",")}}`;
6202
+ return JSON.stringify(value);
6203
+ }
6204
+ function parseSetupEnvelope(body, access) {
6205
+ if (!setupObject(body) || body.protocol !== SETUP_POLICY_PROTOCOL || body.repo_name !== access.repoName || !setupState(body.state)
6206
+ || (access.apiKey.length > 0 && JSON.stringify(body).includes(access.apiKey)))
6207
+ throw new ConductorSetupPolicyError("malformed");
6208
+ return body;
6209
+ }
6210
+ async function setupPolicyRequest(access, suffix, request, fetchImpl) {
6211
+ const controller = new AbortController();
6212
+ const timer = setTimeout(() => controller.abort(), CONDUCTOR_FETCH_TIMEOUT_MS);
6213
+ try {
6214
+ const url = buildConductorJiraUrl(access.baseUrl, `${EPIC_RUNS_API_PREFIX}/supervisor-setup/policy/${suffix}`, { repo_name: access.repoName });
6215
+ const response = request === undefined
6216
+ ? await fetchImpl(url, { headers: conductorGetHeaders(access), signal: controller.signal })
6217
+ : await fetchImpl(url, { method: "POST", headers: conductorPostHeaders(access), body: JSON.stringify(request), signal: controller.signal });
6218
+ let body;
6219
+ try {
6220
+ body = await response.json();
6221
+ }
6222
+ catch {
6223
+ throw new ConductorSetupPolicyError(response.ok ? "malformed" : "unavailable");
6224
+ }
6225
+ if (!response.ok) {
6226
+ const detail = setupObject(body) && setupObject(body.detail) ? body.detail : null;
6227
+ const compatible = detail?.protocol === SETUP_POLICY_PROTOCOL;
6228
+ if (compatible && detail?.error_code === "STALE_PREVIEW")
6229
+ throw new ConductorSetupPolicyError("stale");
6230
+ if (compatible && detail?.error_code === "UNSUPPORTED_VERSION")
6231
+ throw new ConductorSetupPolicyError("unsupported");
6232
+ throw new ConductorSetupPolicyError(response.status >= 500 || response.status === 404 ? "unavailable" : "refused");
6233
+ }
6234
+ return body;
6235
+ }
6236
+ catch (error) {
6237
+ if (error instanceof ConductorSetupPolicyError)
6238
+ throw error;
6239
+ throw new ConductorSetupPolicyError(suffix === "apply/" ? "uncertain" : "unavailable");
6240
+ }
6241
+ finally {
6242
+ clearTimeout(timer);
6243
+ }
6244
+ }
6245
+ export async function previewConductorSetupPolicy(access, request, fetchImpl) {
6246
+ const body = parseSetupEnvelope(await setupPolicyRequest(access, "preview/", request, fetchImpl), access);
6247
+ if (!setupProjection(body.before) || !setupProjection(body.after) || !Array.isArray(body.effects)
6248
+ || typeof body.approval_required !== "boolean" || body.approval_required !== (body.effects.length > 0)
6249
+ || typeof body.preview_artifact !== "string" || !body.preview_artifact || body.preview_artifact.length > 1024)
6250
+ throw new ConductorSetupPolicyError("malformed");
6251
+ const categories = ["gate", "setup", "config", "sources", "qualification"];
6252
+ for (const effect of body.effects) {
6253
+ if (!setupObject(effect) || effect.classification !== "consequential" || !categories.includes(String(effect.category))
6254
+ || Object.keys(effect).sort().join() !== "after,before,category,classification"
6255
+ || setupCanonical(effect.before) !== setupCanonical(body.before[effect.category])
6256
+ || setupCanonical(effect.after) !== setupCanonical(body.after[effect.category]))
6257
+ throw new ConductorSetupPolicyError("malformed");
6258
+ }
6259
+ for (const category of categories) {
6260
+ if (setupCanonical(body.before[category]) !== setupCanonical(body.after[category])
6261
+ && !body.effects.some(e => setupObject(e) && e.category === category))
6262
+ throw new ConductorSetupPolicyError("malformed");
6263
+ }
6264
+ if (request.gate?.provider_checks) {
6265
+ const checks = body.after.gate?.provider_checks;
6266
+ if (!Array.isArray(checks))
6267
+ throw new ConductorSetupPolicyError("malformed");
6268
+ const actual = checks.map(c => typeof c === "string" ? c : c?.name);
6269
+ // BAPI-1606: the server projects required members first and watched members
6270
+ // second, so the request is compared in that order, flags kept.
6271
+ const requested = request.gate.provider_checks;
6272
+ const serverOrder = [...requested.filter(c => c.watched !== true), ...requested.filter(c => c.watched === true)].map(c => c.name);
6273
+ const sameSequence = JSON.stringify(actual) === JSON.stringify(serverOrder);
6274
+ // An entry that omitted `watched` inherits the stored flag, so the position it
6275
+ // lands in is the server's to decide: accept the same names in either order.
6276
+ const inheritsFlag = requested.some(c => !("watched" in c));
6277
+ const sameNames = inheritsFlag && JSON.stringify([...actual].sort()) === JSON.stringify(requested.map(c => c.name).sort());
6278
+ if (!sameSequence && !sameNames)
6279
+ throw new ConductorSetupPolicyError("malformed");
6280
+ }
6281
+ const { preview_artifact: artifact, ...publicPreview } = body;
6282
+ if (JSON.stringify(publicPreview).includes(String(artifact)))
6283
+ throw new ConductorSetupPolicyError("malformed");
6284
+ const result = { protocol: SETUP_POLICY_PROTOCOL, repo_name: access.repoName, effects: body.effects,
6285
+ approval_required: body.approval_required, before: body.before, after: body.after, state: body.state };
6286
+ Object.defineProperty(result, "preview_artifact", { value: body.preview_artifact, enumerable: false });
6287
+ return result;
6288
+ }
6289
+ function parseSetupRead(body, access) {
6290
+ const parsed = parseSetupEnvelope(body, access);
6291
+ if (!setupProjection(parsed.policy))
6292
+ throw new ConductorSetupPolicyError("malformed");
6293
+ return { protocol: SETUP_POLICY_PROTOCOL, repo_name: access.repoName, policy: parsed.policy, state: parsed.state };
6294
+ }
6295
+ export async function applyConductorSetupPolicy(access, request, preview, approve, fetchImpl) {
6296
+ const body = await setupPolicyRequest(access, "apply/", { ...request, preview_artifact: preview.preview_artifact, approve }, fetchImpl);
6297
+ if (JSON.stringify(body).includes(preview.preview_artifact))
6298
+ throw new ConductorSetupPolicyError("malformed");
6299
+ return parseSetupRead(body, access);
6300
+ }
6301
+ export async function fetchConductorSetupPolicy(access, fetchImpl) {
6302
+ return parseSetupRead(await setupPolicyRequest(access, "", undefined, fetchImpl), access);
6303
+ }