@bridge_gpt/mcp-server 0.2.71 → 0.2.72

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 (116) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +19 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +4 -4
  5. package/build/bridge-permissions.js +4 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/claude-review-workflow.js +1 -1
  9. package/build/cli-help.js +6 -0
  10. package/build/codex-auto-recovery.js +126 -0
  11. package/build/codex-skill-adapter.js +2 -0
  12. package/build/commands.generated.js +5 -5
  13. package/build/conductor/bridge-api-client.js +518 -23
  14. package/build/conductor/doctor.js +84 -10
  15. package/build/conductor/epic-implementer-cli.js +51 -2
  16. package/build/conductor/gate-discovery.js +136 -10
  17. package/build/conductor/gate-settings-review.js +305 -5
  18. package/build/conductor/git-hooks-uninstall.js +112 -0
  19. package/build/conductor/git-hooks.js +81 -15
  20. package/build/conductor/guided-repair.js +10 -1
  21. package/build/conductor/install-doctor.js +2 -4
  22. package/build/conductor/launch-plan.js +42 -2
  23. package/build/conductor/local-merge.js +12 -1
  24. package/build/conductor/merge-execution-contract.js +1 -1
  25. package/build/conductor/merged-child-check.js +2 -1
  26. package/build/conductor/prerequisite-inputs.js +379 -0
  27. package/build/conductor/readiness-assessment.js +78 -0
  28. package/build/conductor/readiness-cli.js +10 -0
  29. package/build/conductor/readiness-prerequisites.js +53 -0
  30. package/build/conductor/readiness-sections.js +21 -8
  31. package/build/conductor/readiness.js +20 -2
  32. package/build/conductor/recovery-cli.js +223 -13
  33. package/build/conductor/recovery-operations.js +34 -4
  34. package/build/conductor/repair-contract.js +33 -0
  35. package/build/conductor/tools.js +34 -3
  36. package/build/conductor/wait-run-attention.js +115 -0
  37. package/build/conductor/wait-run-cli.js +96 -3
  38. package/build/conductor/worker-database-doctor-inspector.js +1 -0
  39. package/build/credential-store.js +25 -20
  40. package/build/dependency-install-declarations.js +157 -0
  41. package/build/docs.generated.js +4 -4
  42. package/build/doctor.js +37 -5
  43. package/build/drive-epic-help.js +2 -2
  44. package/build/drive-epic.js +52 -11
  45. package/build/epic-implementer-bin.js +118 -43
  46. package/build/epic-launch-profile.js +1 -1
  47. package/build/executor/cli.js +2 -0
  48. package/build/executor/completion-contract.js +16 -0
  49. package/build/executor/credentials.js +1 -1
  50. package/build/executor/delivery-observations.js +113 -0
  51. package/build/executor/delivery-outcome.js +30 -0
  52. package/build/executor/dependency-refresh-runner.js +132 -0
  53. package/build/executor/dependency-refresh.js +530 -0
  54. package/build/executor/deps.js +4 -0
  55. package/build/executor/env.js +67 -2
  56. package/build/executor/harness-coverage.js +19 -0
  57. package/build/executor/http-client.js +35 -1
  58. package/build/executor/index.js +2 -1
  59. package/build/executor/install-preflight.js +1 -1
  60. package/build/executor/job-runner.js +246 -28
  61. package/build/executor/likely-tests.js +94 -97
  62. package/build/executor/prompt-spec.js +13 -3
  63. package/build/executor/required-verification.js +28 -0
  64. package/build/executor/required-work-diagnostics.js +30 -0
  65. package/build/executor/required-work-ledger.js +19 -1
  66. package/build/executor/results.js +42 -0
  67. package/build/executor/service-discovery.js +42 -0
  68. package/build/executor/service-lifecycle.js +109 -2
  69. package/build/executor/service-uninstall.js +205 -0
  70. package/build/executor/service-unit.js +5 -3
  71. package/build/executor/test-clock.js +3 -0
  72. package/build/executor/verification-hints.js +179 -0
  73. package/build/executor/worker-command.js +54 -2
  74. package/build/executor/worker-database.js +271 -31
  75. package/build/executor/worker-finalization.js +65 -10
  76. package/build/executor/worker-guard-hook.js +10 -2
  77. package/build/executor/worker-verification-guidance.js +37 -2
  78. package/build/executor/worktree-inspection.js +42 -0
  79. package/build/github-sign-in.js +1 -1
  80. package/build/index.js +679 -278
  81. package/build/init.js +3 -3
  82. package/build/install-bridge-conductor-gate.js +236 -42
  83. package/build/install-bridge-conductor-setup.js +115 -26
  84. package/build/install-bridge-conductor.js +448 -350
  85. package/build/install-bridge.js +418 -123
  86. package/build/install-maintenance.js +104 -0
  87. package/build/install-reexec.js +1 -1
  88. package/build/local-cleanup.js +59 -0
  89. package/build/mcp-install-state.js +68 -2
  90. package/build/merge-workflow-install.js +2 -2
  91. package/build/package-script-semantics.js +10 -0
  92. package/build/pipeline-utils.js +1 -1
  93. package/build/pipelines.generated.js +5 -5
  94. package/build/plan-execution-ledger.js +148 -2
  95. package/build/plane/plane-freshness.js +6 -7
  96. package/build/plane/terminal-run-cleanup.js +5 -1
  97. package/build/plane/terminal-run-status.js +4 -0
  98. package/build/printed-remedy-commands.js +24 -4
  99. package/build/readiness-check.js +1 -78
  100. package/build/readiness-prerequisites.generated.js +199 -0
  101. package/build/readme.generated.js +1 -1
  102. package/build/repository-toolchains.js +50 -8
  103. package/build/setup-change-policy.js +32 -0
  104. package/build/setup-epic.js +2 -2
  105. package/build/setup-question.js +62 -0
  106. package/build/start-tickets.js +4 -0
  107. package/build/test-command-detection.js +32 -88
  108. package/build/test-support/notes-fs.js +40 -0
  109. package/build/ticket-delivery-enrollment.js +21 -8
  110. package/build/ticket-delivery-run-scope.js +128 -0
  111. package/build/version.generated.js +3 -3
  112. package/build/worker-guard-hook-bin.js +2 -2
  113. package/build/worktrees.js +105 -0
  114. package/docs/EPIC-IMPLEMENTER.md +5 -0
  115. package/docs/epic-implementer/getting-started.md +40 -15
  116. package/package.json +1 -1
@@ -1,3 +1,4 @@
1
+ import { parseAssessmentNegotiation } from './readiness-assessment.js';
1
2
  import { READINESS_PREREQUISITE_BY_ID } from "../readiness-prerequisites.generated.js";
2
3
  import { READINESS_PREREQUISITE_FIXES } from "../printed-remedy-commands.js";
3
4
  /**
@@ -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, } 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";
@@ -359,6 +361,8 @@ function formatValidationDetailItem(item) {
359
361
  const path = scoped.slice(0, CONDUCTOR_VALIDATION_LOC_MAX_PARTS).join(".");
360
362
  return path ? `${path}: ${msg}` : msg;
361
363
  }
364
+ /** BAPI-1550 — the shape of a closed executor-job-type token (e.g. `ci_fix`). */
365
+ const HOLDER_JOB_TYPE_RE = /^[a-z][a-z_]{0,39}$/;
362
366
  /**
363
367
  * Extract sanitized diagnostics from a parsed backend error body. Recognizes the
364
368
  * FastAPI/backend shapes `{ detail: { error_code, message } }`,
@@ -424,6 +428,21 @@ export function extractSanitizedErrorDiagnostics(body) {
424
428
  rawCurrentRowVersion >= 0) {
425
429
  diagnostics.currentRowVersion = rawCurrentRowVersion;
426
430
  }
431
+ // BAPI-1550: the allowlisted lane-holder pair. Accepted only together and only
432
+ // when well formed, so a half-pair or a free-form value is never forwarded.
433
+ const holderSource = detail && typeof detail === "object" && !Array.isArray(detail)
434
+ ? detail
435
+ : record;
436
+ const rawHolderId = holderSource["holder_job_id"];
437
+ const rawHolderType = holderSource["holder_job_type"];
438
+ if (typeof rawHolderId === "number" &&
439
+ Number.isSafeInteger(rawHolderId) &&
440
+ rawHolderId > 0 &&
441
+ typeof rawHolderType === "string" &&
442
+ HOLDER_JOB_TYPE_RE.test(rawHolderType)) {
443
+ diagnostics.holderJobId = rawHolderId;
444
+ diagnostics.holderJobType = rawHolderType;
445
+ }
427
446
  return diagnostics;
428
447
  }
429
448
  /** Redact exact secret substrings (e.g. the API key from the request headers). */
@@ -445,6 +464,11 @@ function redactDiagnosticValues(diagnostics, secrets) {
445
464
  if (typeof diagnostics.currentRowVersion === "number") {
446
465
  out.currentRowVersion = diagnostics.currentRowVersion;
447
466
  }
467
+ // BAPI-1550: validated at extraction (integer id, closed-token type).
468
+ if (diagnostics.holderJobId !== undefined && diagnostics.holderJobType !== undefined) {
469
+ out.holderJobId = diagnostics.holderJobId;
470
+ out.holderJobType = diagnostics.holderJobType;
471
+ }
448
472
  // BAPI-1520: pattern-checked at extraction, so there is nothing left to scrub.
449
473
  if (diagnostics.gateProfileEvidence)
450
474
  out.gateProfileEvidence = diagnostics.gateProfileEvidence;
@@ -510,6 +534,9 @@ export class ConductorBridgeApiError extends Error {
510
534
  * that need it read this field directly.
511
535
  */
512
536
  currentRowVersion;
537
+ /** BAPI-1550 — the queued job holding the serial lane (a complete pair, or absent). */
538
+ holderJobId;
539
+ holderJobType;
513
540
  /** BAPI-1520 — sanitized structural evidence of a gate-profile refusal. */
514
541
  gateProfileEvidence;
515
542
  constructor(kindOrMessage, status, diagnostics) {
@@ -541,6 +568,11 @@ export class ConductorBridgeApiError extends Error {
541
568
  if (typeof diagnostics?.currentRowVersion === "number") {
542
569
  this.currentRowVersion = diagnostics.currentRowVersion;
543
570
  }
571
+ if (typeof diagnostics?.holderJobId === "number" &&
572
+ typeof diagnostics?.holderJobType === "string") {
573
+ this.holderJobId = diagnostics.holderJobId;
574
+ this.holderJobType = diagnostics.holderJobType;
575
+ }
544
576
  if (diagnostics?.gateProfileEvidence)
545
577
  this.gateProfileEvidence = diagnostics.gateProfileEvidence;
546
578
  }
@@ -1026,9 +1058,20 @@ export async function claimEpicSupervisionLease(access, request, fetchImpl = glo
1026
1058
  * Returns the server payload verbatim — no ready-set computation, plan-hash
1027
1059
  * assertion, or derived control-loop fields are added.
1028
1060
  */
1029
- export async function fetchEpicRunState(access, epicKey, fetchImpl = globalThis.fetch) {
1061
+ export async function fetchEpicRunState(access, epicKey, fetchImpl = globalThis.fetch, options) {
1030
1062
  requireNonEmptyString(epicKey);
1031
- const url = buildConductorJiraUrl(access.baseUrl, `${epicRunApiPath(epicKey)}/state`, { repo_name: access.repoName });
1063
+ // Defaulted in the body, not the signature: the source-boundary test brace-matches
1064
+ // from the first open brace after the function name, so a default object literal
1065
+ // in the signature would hide the real body from it.
1066
+ const readOptions = options ?? {};
1067
+ // Bounds are added only when the caller supplied them, so every existing
1068
+ // caller keeps requesting the exact URL it always did.
1069
+ const params = { repo_name: access.repoName };
1070
+ if (readOptions.job_limit !== undefined)
1071
+ params.job_limit = String(readOptions.job_limit);
1072
+ if (readOptions.ticket_key !== undefined)
1073
+ params.ticket_key = readOptions.ticket_key;
1074
+ const url = buildConductorJiraUrl(access.baseUrl, `${epicRunApiPath(epicKey)}/state`, params);
1032
1075
  const parsed = await fetchConductorJsonWithTimeout(url, conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
1033
1076
  return parsed;
1034
1077
  }
@@ -1045,7 +1088,7 @@ export async function fetchEpicRunState(access, epicKey, fetchImpl = globalThis.
1045
1088
  * through the shared timeout/sanitization helper as a `ConductorBridgeApiError`,
1046
1089
  * so no response body ever reaches a caller.
1047
1090
  */
1048
- export async function fetchExplainRun(access, epicRunId, ticketKey, fetchImpl = globalThis.fetch) {
1091
+ export async function fetchExplainRun(access, epicRunId, ticketKey, fetchImpl = globalThis.fetch, options = {}) {
1049
1092
  requireNonEmptyString(epicRunId);
1050
1093
  let apiPath = `${epicRunApiPath(epicRunId)}/explain`;
1051
1094
  if (ticketKey !== undefined) {
@@ -1055,11 +1098,37 @@ export async function fetchExplainRun(access, epicRunId, ticketKey, fetchImpl =
1055
1098
  requireNoSlashPathSegment(ticketKey);
1056
1099
  apiPath = `${epicRunApiPath(epicRunId)}/tickets/${encodeURIComponent(ticketKey)}/explain`;
1057
1100
  }
1058
- const url = buildConductorJiraUrl(access.baseUrl, apiPath, {
1059
- repo_name: access.repoName,
1060
- });
1101
+ const params = { repo_name: access.repoName };
1102
+ // BAPI-1557: forwarded only when supplied, so the default request is unchanged.
1103
+ if (options.include_run !== undefined)
1104
+ params.include_run = String(options.include_run);
1105
+ const url = buildConductorJiraUrl(access.baseUrl, apiPath, params);
1061
1106
  return fetchConductorJsonWithTimeout(url, conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
1062
1107
  }
1108
+ /**
1109
+ * GET `/jira/tickets/{ticket_number}` and return only the key and description.
1110
+ *
1111
+ * The returned key must equal the requested one and `description` must be a
1112
+ * string (empty is accepted; missing, null or non-string is rejected). Failures
1113
+ * are a sanitized {@link ConductorBridgeApiError}: upstream text is limited to
1114
+ * the bounded `detail.error` code, never a raw body or an exception message.
1115
+ */
1116
+ export async function fetchStoredTicket(access, ticketNumber, fetchImpl = globalThis.fetch) {
1117
+ requireNonEmptyString(ticketNumber);
1118
+ requireNoSlashPathSegment(ticketNumber);
1119
+ const url = buildConductorJiraUrl(access.baseUrl, `/tickets/${encodeURIComponent(ticketNumber)}`, { repo_name: access.repoName });
1120
+ const parsed = await fetchConductorJsonWithTimeout(url, conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl, { readErrorField: true });
1121
+ const record = parsed && typeof parsed === "object" && !Array.isArray(parsed)
1122
+ ? parsed
1123
+ : undefined;
1124
+ if (!record ||
1125
+ record["ticket_number"] !== ticketNumber ||
1126
+ typeof record["description"] !== "string") {
1127
+ // Shape failures carry no upstream content at all.
1128
+ throw new ConductorBridgeApiError("http", 200);
1129
+ }
1130
+ return { ticket_number: ticketNumber, description: record["description"] };
1131
+ }
1063
1132
  // ---------------------------------------------------------------------------
1064
1133
  // Executor wind-down: read-only completion-state projection (BAPI-1010)
1065
1134
  // ---------------------------------------------------------------------------
@@ -1405,10 +1474,14 @@ export async function advanceEpicTicketStatus(access, request, fetchImpl = globa
1405
1474
  */
1406
1475
  async function postUnparkLikeRequest(url, headers, body, fetchImpl) {
1407
1476
  try {
1408
- const parsed = await fetchConductorJsonPostWithTimeout(url, headers, body, CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
1477
+ // BAPI-1554: opt in to the server's bounded `detail.error` explanation so a
1478
+ // refused unpark-like request tells the operator why. Same POST, URL, body,
1479
+ // timeout, and headers as the shared POST wrapper; only the error read widens.
1480
+ const parsed = await fetchConductorJsonWithMethodAndTimeout("POST", url, headers, body, CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl, { readErrorField: true });
1409
1481
  return parseAdvanceEpicTicketStatusResult(parsed);
1410
1482
  }
1411
1483
  catch (err) {
1484
+ // The stale-CAS translation stays first, before any generic validation text.
1412
1485
  if (err instanceof ConductorBridgeApiError &&
1413
1486
  err.status === 400 &&
1414
1487
  typeof err.currentRowVersion === "number") {
@@ -1672,7 +1745,7 @@ function parseDispatchRemediationResult(parsed) {
1672
1745
  throw new ConductorBridgeApiError("server");
1673
1746
  }
1674
1747
  const jobId = p["job_id"];
1675
- return {
1748
+ const result = {
1676
1749
  epic_run_id: p["epic_run_id"],
1677
1750
  ticket_key: p["ticket_key"],
1678
1751
  before: parseRepairNullableString(p["before"]),
@@ -1682,8 +1755,18 @@ function parseDispatchRemediationResult(parsed) {
1682
1755
  job_type: typeof p["job_type"] === "string" ? p["job_type"] : "",
1683
1756
  job_id: typeof jobId === "number" && Number.isSafeInteger(jobId) ? jobId : null,
1684
1757
  };
1758
+ // BAPI-1550: optional and backward compatible — an older server omits them, and
1759
+ // a malformed value is dropped rather than failing a dispatch that succeeded.
1760
+ if (typeof p["driver_context_delivered"] === "boolean") {
1761
+ result.driver_context_delivered = p["driver_context_delivered"];
1762
+ }
1763
+ const queuedBehind = p["queued_behind"];
1764
+ if (typeof queuedBehind === "number" && Number.isSafeInteger(queuedBehind) && queuedBehind > 0) {
1765
+ result.queued_behind = queuedBehind;
1766
+ }
1767
+ return result;
1685
1768
  }
1686
- function parseMergeChildRouteResponse(parsed) {
1769
+ function parseMergeChildRouteResponse(parsed, options = {}) {
1687
1770
  const p = parseRepairBase(parsed);
1688
1771
  const prNumber = p["pr_number"];
1689
1772
  if (typeof prNumber !== "number" || !Number.isSafeInteger(prNumber) || prNumber <= 0) {
@@ -1702,6 +1785,18 @@ function parseMergeChildRouteResponse(parsed) {
1702
1785
  expected_head_sha: sha,
1703
1786
  merge_method: parseRepairNullableString(l["merge_method"]),
1704
1787
  };
1788
+ // BAPI-1564 — a carry-gaps approval must name the base it was admitted for;
1789
+ // an older or malformed response is refused here, never executed unguarded.
1790
+ const base = l["expected_base_branch"];
1791
+ if (base !== undefined && base !== null) {
1792
+ if (typeof base !== "string" || base.trim().length === 0 || base.length > 255) {
1793
+ throw new ConductorBridgeApiError("server");
1794
+ }
1795
+ localExecution.expected_base_branch = base;
1796
+ }
1797
+ else if (options.requireExpectedBase) {
1798
+ throw new ConductorBridgeApiError("server");
1799
+ }
1705
1800
  }
1706
1801
  return {
1707
1802
  epic_run_id: p["epic_run_id"],
@@ -1813,6 +1908,46 @@ export async function resolveHandoff(access, request, fetchImpl = globalThis.fet
1813
1908
  }, fetchImpl);
1814
1909
  return parseResolveHandoffResult(parsed);
1815
1910
  }
1911
+ const ACKNOWLEDGE_GAPS_DIGEST_RE = /^[0-9a-f]{64}$/;
1912
+ const ACKNOWLEDGE_GAPS_RESULT_KEYS = new Set([
1913
+ "epic_run_id",
1914
+ "digest",
1915
+ "entry_count",
1916
+ "committed",
1917
+ "event_recorded",
1918
+ ]);
1919
+ function parseAcknowledgeGapsResult(parsed) {
1920
+ const p = parseRepairBase(parsed);
1921
+ const count = p["entry_count"];
1922
+ if (Object.keys(p).some((key) => !ACKNOWLEDGE_GAPS_RESULT_KEYS.has(key)) ||
1923
+ typeof p["digest"] !== "string" ||
1924
+ !ACKNOWLEDGE_GAPS_DIGEST_RE.test(p["digest"]) ||
1925
+ typeof count !== "number" ||
1926
+ !Number.isSafeInteger(count) ||
1927
+ count < 0) {
1928
+ throw new ConductorBridgeApiError("server");
1929
+ }
1930
+ return {
1931
+ epic_run_id: p["epic_run_id"],
1932
+ digest: p["digest"],
1933
+ entry_count: count,
1934
+ committed: p["committed"],
1935
+ event_recorded: p["event_recorded"],
1936
+ };
1937
+ }
1938
+ /**
1939
+ * POST `/jira/epic-runs/runs/{epic_run_id}/acknowledge-gaps` (BAPI-1562) — body
1940
+ * `{repo_name, digest, reason}` and nothing else. There is no actor field: the
1941
+ * SERVER records the verified request actor, and it recomputes the list digest
1942
+ * itself, refusing `GAP_DIGEST_STALE` when the named digest is not current.
1943
+ */
1944
+ export async function acknowledgeGaps(access, request, fetchImpl = globalThis.fetch) {
1945
+ requireNonEmptyString(request.epicRunId);
1946
+ requireNonEmptyString(request.digest);
1947
+ requireNonEmptyString(request.reason);
1948
+ const parsed = await postRepairRequest(access, `${epicRunApiPath(request.epicRunId)}/acknowledge-gaps`, { digest: request.digest, reason: request.reason }, fetchImpl);
1949
+ return parseAcknowledgeGapsResult(parsed);
1950
+ }
1816
1951
  /** The synthetic code an old server's missing escalate route is reported under. */
1817
1952
  export const ESCALATE_ROUTE_UNAVAILABLE_CODE = "ESCALATE_ROUTE_UNAVAILABLE";
1818
1953
  /** The fixed operator text for a server that has no `escalate` route. */
@@ -1962,15 +2097,20 @@ export async function rerunCi(access, request, fetchImpl = globalThis.fetch) {
1962
2097
  }
1963
2098
  /**
1964
2099
  * 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}.
2100
+ * `{repo_name, pr_number}`, plus `carry_gaps: true` only when `carryGaps` is set
2101
+ * (BAPI-1564). The server composes the head, gate, base, and action key. When the
2102
+ * repository merges locally the response carries a `local_execution` approval the
2103
+ * caller completes with {@link completeMergeChild}; a carry-gaps approval must
2104
+ * also name its `expected_base_branch`.
1968
2105
  */
1969
2106
  export async function mergeChild(access, request, fetchImpl = globalThis.fetch) {
1970
2107
  requireNonEmptyString(request.epicRunId);
1971
2108
  requirePositiveSafeInteger(request.prNumber);
1972
- const parsed = await postRepairRequest(access, `${epicRunApiPath(request.epicRunId)}/merge-child`, { pr_number: request.prNumber }, fetchImpl);
1973
- return parseMergeChildRouteResponse(parsed);
2109
+ const carryGaps = request.carryGaps === true;
2110
+ const parsed = await postRepairRequest(access, `${epicRunApiPath(request.epicRunId)}/merge-child`, carryGaps
2111
+ ? { pr_number: request.prNumber, carry_gaps: true }
2112
+ : { pr_number: request.prNumber }, fetchImpl);
2113
+ return parseMergeChildRouteResponse(parsed, { requireExpectedBase: carryGaps });
1974
2114
  }
1975
2115
  /**
1976
2116
  * POST `/jira/epic-runs/runs/{epic_run_id}/merge-child/complete` — body
@@ -2515,6 +2655,7 @@ export const CHILD_MERGE_EVIDENCE_SOURCES = ["delivery_binding", "feature_branch
2515
2655
  export const CHILD_MERGE_ANCESTRY_VALUES = ["covered", "behind", "unknown", "not_checked"];
2516
2656
  export const CHILD_MERGE_REASONS = [
2517
2657
  "merged_on_cut_commit",
2658
+ "merged_outside_run",
2518
2659
  "merged_without_delivery_record",
2519
2660
  "merged_after_index",
2520
2661
  "ancestry_unknown",
@@ -2917,6 +3058,153 @@ export async function triggerRepositoryParse(access, fetchImpl = globalThis.fetc
2917
3058
  const body = JSON.stringify({ repo_name: access.repoName });
2918
3059
  return fetchConductorJsonPostWithTimeout(url, conductorPostHeaders(access), body, CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
2919
3060
  }
3061
+ export const SETUP_RECOVERY_VERSION = "bridge.setup-parse.v1";
3062
+ export const SETUP_CORRECTION_VERSION = "bridge.setup-branch-correction.v1";
3063
+ const setupRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
3064
+ const setupBranch = (v) => typeof v === "string" && v.length > 0 && v.length <= 255 && v === v.trim() && !v.startsWith("-") && !/[\x00-\x1f\x7f]/.test(v);
3065
+ const setupSha = (v) => typeof v === "string" && /^[0-9a-f]{40}$/.test(v);
3066
+ const setupId = (v) => typeof v === "string" && /^[0-9a-f-]{36}$/.test(v);
3067
+ const setupPositive = (v) => Number.isSafeInteger(v) && Number(v) > 0;
3068
+ const setupRelation = (v) => ["equal", "contains_target", "behind", "diverged", "unknown"].includes(String(v));
3069
+ /** Strict boundary decode; never render unknown server error text or metadata as content. */
3070
+ export function decodeSetupRecoveryEvidence(value) {
3071
+ if (!setupRecord(value) || value.version !== SETUP_RECOVERY_VERSION || !setupPositive(value.setup_pr_number)
3072
+ || !["read", "missing", "unavailable"].includes(value.configuration_outcome)
3073
+ || !setupRelation(value.configured_relation) || !setupRelation(value.canonical_relation))
3074
+ return null;
3075
+ for (const key of ["configured_branch", "provider_default", "resolved_branch", "destination_branch"]) {
3076
+ if (value[key] !== null && !setupBranch(value[key]))
3077
+ return null;
3078
+ }
3079
+ for (const key of ["required_commit_sha", "resolved_head_sha", "canonical_commit_sha"]) {
3080
+ if (value[key] !== null && !setupSha(value[key]))
3081
+ return null;
3082
+ }
3083
+ if (value.configuration_fingerprint !== null && !/^v1:[0-9a-f]{64}$/.test(value.configuration_fingerprint))
3084
+ return null;
3085
+ if (value.canonical_identity !== null && (typeof value.canonical_identity !== "string" || !/^[A-Za-z0-9_.:-]{1,128}$/.test(value.canonical_identity)))
3086
+ return null;
3087
+ const reasons = [null, "configuration_unavailable", "configuration_missing", "default_branch_unknown", "configured_branch_unknown",
3088
+ "canonical_evidence_unknown", "lifecycle_unavailable", "request_history_unavailable", "ancestry_unknown", "provider_evidence_unavailable", "observation_deadline"];
3089
+ if (!reasons.includes(value.reason))
3090
+ return null;
3091
+ 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)))
3092
+ return null;
3093
+ const run = (r) => {
3094
+ if (!setupRecord(r) || !setupPositive(r.id) || !["queued", "in_progress", "failed", "succeeded"].includes(r.status))
3095
+ return null;
3096
+ for (const k of ["requested_branch", "actual_fetched_branch"])
3097
+ if (r[k] !== null && !setupBranch(r[k]))
3098
+ return null;
3099
+ for (const k of ["requested_target_sha", "actual_fetched_sha"])
3100
+ if (r[k] !== null && !setupSha(r[k]))
3101
+ return null;
3102
+ if (r.configuration_fingerprint !== null && !/^v1:[0-9a-f]{64}$/.test(r.configuration_fingerprint))
3103
+ return null;
3104
+ if (r.setup_request_id !== null && !setupId(r.setup_request_id))
3105
+ return null;
3106
+ return { id: r.id, status: r.status, requested_branch: r.requested_branch, requested_target_sha: r.requested_target_sha,
3107
+ configuration_fingerprint: r.configuration_fingerprint, setup_request_id: r.setup_request_id,
3108
+ actual_fetched_branch: r.actual_fetched_branch, actual_fetched_sha: r.actual_fetched_sha };
3109
+ };
3110
+ if (!Array.isArray(value.active_runs) || value.active_runs.length > 20)
3111
+ return null;
3112
+ const active = value.active_runs.map(run);
3113
+ if (active.some(r => r === null))
3114
+ return null;
3115
+ const latest = value.latest_run === null ? null : run(value.latest_run);
3116
+ if (value.latest_run !== null && latest === null)
3117
+ return null;
3118
+ const q = value.request;
3119
+ if (q !== null && (!setupRecord(q) || !setupId(q.id) || !Number.isSafeInteger(q.generation) || q.generation < 0
3120
+ || (q.parse_run_id !== null && !setupPositive(q.parse_run_id)) || ![null, "queued", "in_progress", "succeeded", "failed"].includes(q.status)))
3121
+ return null;
3122
+ if (value.retry_generation !== null && !setupPositive(value.retry_generation))
3123
+ return null;
3124
+ const canonical = decodeCanonicalProvenance(value);
3125
+ const observation = value.canonical_observation ?? "unknown";
3126
+ if (!["unknown", "absent", "unverified", "verified"].includes(observation))
3127
+ return null;
3128
+ if (["absent", "unverified"].includes(observation)
3129
+ && (canonical.verified || value.canonical_validity_state !== "unverified" || value.canonical_validity_verified !== false))
3130
+ return null;
3131
+ if (value.canonical_relation !== "unknown" && (!canonical.verified || canonical.sourceCommitSha !== value.canonical_commit_sha || canonical.generation !== value.canonical_identity))
3132
+ return null;
3133
+ return { version: SETUP_RECOVERY_VERSION, setup_pr_number: value.setup_pr_number, setup_pr_url: value.setup_pr_url,
3134
+ required_commit_sha: value.required_commit_sha, destination_branch: value.destination_branch,
3135
+ configuration_outcome: value.configuration_outcome, configured_branch: value.configured_branch,
3136
+ configuration_fingerprint: value.configuration_fingerprint, provider_default: value.provider_default,
3137
+ resolved_branch: value.resolved_branch, resolved_head_sha: value.resolved_head_sha, configured_relation: value.configured_relation,
3138
+ canonical_relation: value.canonical_relation, canonical_commit_sha: value.canonical_commit_sha,
3139
+ canonical_identity: value.canonical_identity, canonical, canonical_observation: observation, reason: value.reason, active_runs: active, latest_run: latest,
3140
+ 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 };
3141
+ }
3142
+ async function supportsSetupRecovery(access, fetchImpl) {
3143
+ const body = await fetchConductorJsonWithTimeout(buildConductorJiraUrl(access.baseUrl, "/ping", { repo_name: access.repoName }), conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
3144
+ if (!setupRecord(body) || !setupRecord(body.setup_recovery_contracts))
3145
+ return false;
3146
+ const c = body.setup_recovery_contracts;
3147
+ return c.nullable_correction === SETUP_CORRECTION_VERSION && c.setup_admission === SETUP_RECOVERY_VERSION && c.target_evidence === SETUP_RECOVERY_VERSION;
3148
+ }
3149
+ export async function fetchSetupRecoveryEvidence(access, prNumber, fetchImpl = globalThis.fetch) {
3150
+ if (!setupPositive(prNumber))
3151
+ return { supported: false, reason: "evidence_unavailable" };
3152
+ try {
3153
+ if (!await supportsSetupRecovery(access, fetchImpl))
3154
+ return { supported: false, reason: "upgrade_required" };
3155
+ 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);
3156
+ const evidence = decodeSetupRecoveryEvidence(raw);
3157
+ return evidence && evidence.setup_pr_number === prNumber ? { supported: true, evidence } : { supported: false, reason: "evidence_unavailable" };
3158
+ }
3159
+ catch {
3160
+ return { supported: false, reason: "evidence_unavailable" };
3161
+ }
3162
+ }
3163
+ export async function correctSetupBranch(access, expected, destination, fetchImpl = globalThis.fetch) {
3164
+ if ((expected !== null && !setupBranch(expected)) || !setupBranch(destination))
3165
+ return "refused";
3166
+ try {
3167
+ if (!await supportsSetupRecovery(access, fetchImpl))
3168
+ return "unsupported";
3169
+ 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);
3170
+ }
3171
+ catch (e) {
3172
+ if (e instanceof ConductorBridgeApiError && e.status === 409)
3173
+ return "conflict";
3174
+ if (e instanceof ConductorBridgeApiError && e.status !== undefined && e.status >= 400 && e.status < 500)
3175
+ return "refused";
3176
+ return "uncertain";
3177
+ }
3178
+ try {
3179
+ const body = await fetchConductorJsonWithTimeout(buildConductorJiraUrl(access.baseUrl, "/config-field/base_branch", { repo_name: access.repoName }), conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
3180
+ return setupRecord(body) && Object.hasOwn(body, "value") && body.value === destination ? "verified" : "readback_mismatch";
3181
+ }
3182
+ catch {
3183
+ return "readback_unavailable";
3184
+ }
3185
+ }
3186
+ export async function admitSetupRecovery(access, evidence, retryGeneration, fetchImpl = globalThis.fetch) {
3187
+ const unknown = { version: SETUP_RECOVERY_VERSION, outcome: "unknown", reason: "admission_response_unknown" };
3188
+ try {
3189
+ if (!await supportsSetupRecovery(access, fetchImpl))
3190
+ return { ...unknown, reason: "upgrade_required" };
3191
+ const body = await fetchConductorJsonPostWithTimeout(buildConductorJiraUrl(access.baseUrl, "/parse-repository"), conductorPostHeaders(access), JSON.stringify({ repo_name: access.repoName, setup_recovery: {
3192
+ version: SETUP_RECOVERY_VERSION, setup_pr_number: evidence.setup_pr_number, reviewed_branch: evidence.configured_branch,
3193
+ configuration_fingerprint: evidence.configuration_fingerprint, ...(retryGeneration === undefined ? {} : { retry_generation: retryGeneration }),
3194
+ } }), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
3195
+ if (!setupRecord(body) || body.version !== SETUP_RECOVERY_VERSION || !["created", "reused", "serialized_successor", "already_satisfied", "retry_required", "unknown"].includes(body.outcome))
3196
+ return unknown;
3197
+ if (body.request_id != null && !setupId(body.request_id))
3198
+ return unknown;
3199
+ if (body.parse_run_id != null && !setupPositive(body.parse_run_id))
3200
+ return unknown;
3201
+ return { version: SETUP_RECOVERY_VERSION, outcome: body.outcome, request_id: body.request_id, parse_run_id: body.parse_run_id,
3202
+ generation: Number.isSafeInteger(body.generation) ? body.generation : null, retry_generation: setupPositive(body.retry_generation) ? body.retry_generation : null };
3203
+ }
3204
+ catch (e) {
3205
+ return { ...unknown, reason: e instanceof ConductorBridgeApiError && e.status === 409 ? "configuration_changed" : "admission_response_unknown" };
3206
+ }
3207
+ }
2920
3208
  /**
2921
3209
  * Call the protected `DELETE /vcs/pull-requests/{pr_number}/branch` endpoint.
2922
3210
  * Treats 404-equivalent responses as idempotent success (already deleted).
@@ -3317,6 +3605,7 @@ export function parseConductorReadinessResponse(body) {
3317
3605
  const thr = requireObject(root.thresholds);
3318
3606
  const requiredChecksCount = requireInt(sup, "required_checks_count");
3319
3607
  return {
3608
+ ...(Object.hasOwn(root, 'assessment') ? { assessmentNegotiation: parseAssessmentNegotiation(root), ...(parseAssessmentNegotiation(root).status === 'available' ? { assessment: parseAssessmentNegotiation(root).assessment } : {}) } : {}),
3320
3609
  ...(typeof root.is_production === 'boolean' ? { is_production: root.is_production } : {}),
3321
3610
  ...(root.is_production === undefined || typeof root.is_production === 'boolean'
3322
3611
  ? { prerequisites: parseReadinessPrerequisites(root.prerequisites) } : {}),
@@ -3856,16 +4145,35 @@ export async function fetchConductorReadiness(access, fetchImpl = globalThis.fet
3856
4145
  const url = buildConductorJiraUrl(access.baseUrl, `${EPIC_RUNS_API_PREFIX}/conductor-readiness`, {
3857
4146
  repo_name: access.repoName,
3858
4147
  ...(options.epicRunId ? { epic_run_id: options.epicRunId } : {}),
4148
+ ...(options.assessmentVersion === 1 ? { assessment_version: "1" } : {}),
3859
4149
  });
3860
4150
  // BAPI-1455 — a `SCHEMA_INCOMPATIBLE` refusal explains itself in
3861
4151
  // `detail.error` (the applied stamp, the missing objects, the repair route),
3862
4152
  // 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);
4153
+ try {
4154
+ const body = await fetchConductorJsonWithTimeout(url, conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl, { readErrorField: true, errorFieldPreviewMax: SCHEMA_REFUSAL_PREVIEW_MAX, readErrorFieldOnlyFor: [SCHEMA_INCOMPATIBLE_ERROR_CODE] });
4155
+ const parsed = parseConductorReadinessResponse(body);
4156
+ if (options.assessmentVersion === 1) {
4157
+ const negotiation = parseAssessmentNegotiation(requireObject(body));
4158
+ // Scope and identity must describe this exact request.
4159
+ if (negotiation.status === 'available' && (negotiation.assessment.context.repo_name !== access.repoName ||
4160
+ negotiation.assessment.context.epic_run_id !== (options.epicRunId ?? null))) {
4161
+ const { assessment: _ignored, ...legacy } = parsed;
4162
+ return { ...legacy, assessmentNegotiation: { status: 'unavailable' } };
4163
+ }
4164
+ return { ...parsed, assessmentNegotiation: negotiation };
4165
+ }
4166
+ return parsed;
4167
+ }
4168
+ catch (error) {
4169
+ const issues = error instanceof ConductorBridgeApiError ? error.gateProfileEvidence?.issues : undefined;
4170
+ if (options.assessmentVersion === 1 && error instanceof ConductorBridgeApiError && error.status === 422 &&
4171
+ issues?.length === 1 && issues[0]?.type === 'literal_error' && issues[0]?.loc.join('.') === 'query.assessment_version') {
4172
+ const legacy = await fetchConductorReadiness(access, fetchImpl, { epicRunId: options.epicRunId });
4173
+ return { ...legacy, assessmentNegotiation: { status: 'unsupported' } };
4174
+ }
4175
+ throw error;
4176
+ }
3869
4177
  }
3870
4178
  /** The answer for every failure: an older server, a non-200, a timeout, a bad body. */
3871
4179
  export const REPOSITORY_USAGE_ADVISORY_UNAVAILABLE = Object.freeze({
@@ -4144,7 +4452,7 @@ export function classifySupervisorBootstrapFailure(err) {
4144
4452
  return "server";
4145
4453
  return "rejected";
4146
4454
  }
4147
- const CI_STOP_REASONS = new Set(["wait_expired", "verdict_unavailable", "repair_exhausted"]);
4455
+ const CI_STOP_REASONS = new Set(["wait_expired", "verdict_unavailable", "repair_exhausted", "required_check_not_reporting"]);
4148
4456
  const RESUME_CI_AUDIT_WARNING_MAX = 200;
4149
4457
  function isPlainRecord(value) {
4150
4458
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -4522,6 +4830,27 @@ function parseWorkerEnvList(raw) {
4522
4830
  }
4523
4831
  return entries.length > 0 ? entries : undefined;
4524
4832
  }
4833
+ /**
4834
+ * BAPI-1551 — parse a returned `dependency_install` list, fail-closed. Absent or
4835
+ * `null` is no declaration; any invalid entry throws the field-free shape error,
4836
+ * never a partly trusted list.
4837
+ */
4838
+ function parseDependencyInstallField(raw) {
4839
+ if (raw === undefined || raw === null)
4840
+ return undefined;
4841
+ const entries = parseDependencyInstallStrict(raw);
4842
+ if (entries === null)
4843
+ throw readinessShapeError();
4844
+ return entries.length > 0 ? entries : undefined;
4845
+ }
4846
+ /** BAPI-1551 — absent or `null` is `unknown`; any other non-enum value throws. */
4847
+ function parseCiDatabaseField(raw) {
4848
+ if (raw === undefined || raw === null)
4849
+ return CI_DATABASE_DEFAULT;
4850
+ if (!isCiDatabase(raw))
4851
+ throw readinessShapeError();
4852
+ return raw;
4853
+ }
4525
4854
  /** Parse a returned or proposed reproduction hint, fail-closed. */
4526
4855
  function parseReproductionHint(raw) {
4527
4856
  const o = requireObject(raw);
@@ -4568,6 +4897,8 @@ function parseGateProfileBody(raw) {
4568
4897
  reproductionHints.set(providerChecks[index], parseReproductionHint(reproduce));
4569
4898
  });
4570
4899
  const workerEnv = parseWorkerEnvList(o.worker_env);
4900
+ const dependencyInstall = parseDependencyInstallField(o.dependency_install);
4901
+ const ciDatabase = parseCiDatabaseField(o.ci_database);
4571
4902
  const commandsRaw = o.local_commands;
4572
4903
  if (!Array.isArray(commandsRaw) || commandsRaw.length > GATE_MAX_LOCAL_COMMANDS)
4573
4904
  throw readinessShapeError();
@@ -4626,6 +4957,8 @@ function parseGateProfileBody(raw) {
4626
4957
  provider_checks: providerChecks,
4627
4958
  ...(workerEnv ? { worker_env: workerEnv } : {}),
4628
4959
  ...(reproductionHints.size > 0 ? { reproduction_hints: reproductionHints } : {}),
4960
+ ...(dependencyInstall ? { dependency_install: dependencyInstall } : {}),
4961
+ ...(ciDatabase !== "unknown" ? { ci_database: ciDatabase } : {}),
4629
4962
  local_commands: localCommands,
4630
4963
  migration_guard: guard,
4631
4964
  customized_commands: customized.map((n) => gateName(n, GATE_MEMBER_NAME_MAX)),
@@ -4691,7 +5024,7 @@ export async function fetchConductorGateProfile(access, fetchImpl) {
4691
5024
  return parseConductorGateProfileResponse(body, access.repoName);
4692
5025
  }
4693
5026
  /**
4694
- * BAPI-1520 — which extension fields the older server rejected, and only when
5027
+ * BAPI-1520 (extended by BAPI-1551) — which extension fields the older server rejected, and only when
4695
5028
  * the request actually carried them. `worker_env` counts only at exactly
4696
5029
  * `["body","worker_env"]`; `reproduce` only at exactly
4697
5030
  * `["body","provider_checks",<index>,"reproduce"]`. Any other 422 returns
@@ -4706,6 +5039,9 @@ export function classifyGateProfileExtensionRejection(err, request) {
4706
5039
  const confirm = request.action === "confirm" ? request : null;
4707
5040
  let workerEnv = false;
4708
5041
  let reproduce = false;
5042
+ // BAPI-1551: reported only when true, so the BAPI-1520 shape is unchanged.
5043
+ let dependencyInstall = false;
5044
+ let ciDatabase = false;
4709
5045
  for (const issue of issues) {
4710
5046
  if (issue.type !== "extra_forbidden")
4711
5047
  return null;
@@ -4715,6 +5051,16 @@ export function classifyGateProfileExtensionRejection(err, request) {
4715
5051
  return null;
4716
5052
  workerEnv = true;
4717
5053
  }
5054
+ else if (loc.length === 2 && loc[0] === "body" && loc[1] === "dependency_install") {
5055
+ if (!confirm || confirm.dependency_install === undefined)
5056
+ return null;
5057
+ dependencyInstall = true;
5058
+ }
5059
+ else if (loc.length === 2 && loc[0] === "body" && loc[1] === "ci_database") {
5060
+ if (!confirm || confirm.ci_database === undefined)
5061
+ return null;
5062
+ ciDatabase = true;
5063
+ }
4718
5064
  else if (loc.length === 4 &&
4719
5065
  loc[0] === "body" &&
4720
5066
  loc[1] === "provider_checks" &&
@@ -4729,7 +5075,12 @@ export function classifyGateProfileExtensionRejection(err, request) {
4729
5075
  return null;
4730
5076
  }
4731
5077
  }
4732
- return { worker_env: workerEnv, reproduce };
5078
+ return {
5079
+ worker_env: workerEnv,
5080
+ reproduce,
5081
+ ...(dependencyInstall ? { dependency_install: true } : {}),
5082
+ ...(ciDatabase ? { ci_database: true } : {}),
5083
+ };
4733
5084
  }
4734
5085
  /** The safe refusal context of a failed write, or `undefined` when there is none. */
4735
5086
  function gateProfileRefusalDetail(err) {
@@ -4999,3 +5350,147 @@ export async function previewLaunchReadiness(access, policyJson, fetchImpl = glo
4999
5350
  const body = await fetchConductorJsonPostWithTimeout(url, conductorPostHeaders(access), JSON.stringify({ repo_name: access.repoName, policy_json: policyJson }), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
5000
5351
  return parseConductorReadinessResponse(body);
5001
5352
  }
5353
+ /** BAPI-1567 combined policy transport. Artifacts live only in transient memory. */
5354
+ export const SETUP_POLICY_PROTOCOL = "bridge.setup-policy.v1";
5355
+ export class ConductorSetupPolicyError extends Error {
5356
+ reason;
5357
+ constructor(reason) {
5358
+ super(`Setup policy ${reason}`);
5359
+ this.reason = reason;
5360
+ }
5361
+ }
5362
+ function setupObject(value) {
5363
+ return !!value && typeof value === "object" && !Array.isArray(value);
5364
+ }
5365
+ function setupState(value) {
5366
+ return setupObject(value) && Object.keys(value).length === 2
5367
+ && Number.isSafeInteger(value.generation) && Number(value.generation) >= 0
5368
+ && Number.isSafeInteger(value.revision) && Number(value.revision) >= 0;
5369
+ }
5370
+ function setupProjection(value) {
5371
+ const exact = (object, fields) => Object.keys(object).sort().join() === fields.sort().join();
5372
+ if (!setupObject(value) || !exact(value, ["gate", "setup", "config", "sources", "qualification", "precedence"]))
5373
+ return false;
5374
+ if (!setupObject(value.setup) || !exact(value.setup, ["done_gate_config", "review_source", "min_approvals", "review_policy"]))
5375
+ return false;
5376
+ 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"]))
5377
+ return false;
5378
+ if (!setupObject(value.sources) || !exact(value.sources, ["setup", "config"]))
5379
+ return false;
5380
+ if (!["project_default", "built_in"].includes(String(value.sources.setup)) || !["project_default", "built_in"].includes(String(value.sources.config)))
5381
+ return false;
5382
+ if (!["qualified", "unqualified", "stale", "not_required"].includes(String(value.qualification)) || typeof value.precedence !== "string")
5383
+ return false;
5384
+ if (value.gate === null)
5385
+ return true;
5386
+ if (!setupObject(value.gate))
5387
+ return false;
5388
+ const gate = value.gate;
5389
+ const allowed = ["kind", "provider_checks", "local_commands", "migration_guard", "customized_commands", "failure_formats", "worker_env", "dependency_install", "ci_database", "source"];
5390
+ if (Object.keys(gate).some(k => !allowed.includes(k)) || !["provider", "mixed", "local", "none"].includes(String(gate.kind)))
5391
+ return false;
5392
+ if (!Array.isArray(gate.provider_checks) || !gate.provider_checks.every(c => setupObject(c) && exact(c, ["name"]) && typeof c.name === "string"))
5393
+ return false;
5394
+ if (!Array.isArray(gate.local_commands) || !gate.local_commands.every(c => setupObject(c) && exact(c, ["name", "argv", "timeout_seconds"])
5395
+ && typeof c.name === "string" && Array.isArray(c.argv) && c.argv.every(a => typeof a === "string") && Number.isSafeInteger(c.timeout_seconds)))
5396
+ return false;
5397
+ if (gate.worker_env !== undefined && (!Array.isArray(gate.worker_env) || !gate.worker_env.every(e => setupObject(e) && exact(e, ["name"]) && typeof e.name === "string")))
5398
+ return false;
5399
+ return true;
5400
+ }
5401
+ function setupCanonical(value) {
5402
+ if (Array.isArray(value))
5403
+ return `[${value.map(setupCanonical).join(",")}]`;
5404
+ if (setupObject(value))
5405
+ return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${setupCanonical(v)}`).join(",")}}`;
5406
+ return JSON.stringify(value);
5407
+ }
5408
+ function parseSetupEnvelope(body, access) {
5409
+ if (!setupObject(body) || body.protocol !== SETUP_POLICY_PROTOCOL || body.repo_name !== access.repoName || !setupState(body.state)
5410
+ || (access.apiKey.length > 0 && JSON.stringify(body).includes(access.apiKey)))
5411
+ throw new ConductorSetupPolicyError("malformed");
5412
+ return body;
5413
+ }
5414
+ async function setupPolicyRequest(access, suffix, request, fetchImpl) {
5415
+ const controller = new AbortController();
5416
+ const timer = setTimeout(() => controller.abort(), CONDUCTOR_FETCH_TIMEOUT_MS);
5417
+ try {
5418
+ const url = buildConductorJiraUrl(access.baseUrl, `${EPIC_RUNS_API_PREFIX}/supervisor-setup/policy/${suffix}`, { repo_name: access.repoName });
5419
+ const response = request === undefined
5420
+ ? await fetchImpl(url, { headers: conductorGetHeaders(access), signal: controller.signal })
5421
+ : await fetchImpl(url, { method: "POST", headers: conductorPostHeaders(access), body: JSON.stringify(request), signal: controller.signal });
5422
+ let body;
5423
+ try {
5424
+ body = await response.json();
5425
+ }
5426
+ catch {
5427
+ throw new ConductorSetupPolicyError(response.ok ? "malformed" : "unavailable");
5428
+ }
5429
+ if (!response.ok) {
5430
+ const detail = setupObject(body) && setupObject(body.detail) ? body.detail : null;
5431
+ const compatible = detail?.protocol === SETUP_POLICY_PROTOCOL;
5432
+ if (compatible && detail?.error_code === "STALE_PREVIEW")
5433
+ throw new ConductorSetupPolicyError("stale");
5434
+ if (compatible && detail?.error_code === "UNSUPPORTED_VERSION")
5435
+ throw new ConductorSetupPolicyError("unsupported");
5436
+ throw new ConductorSetupPolicyError(response.status >= 500 || response.status === 404 ? "unavailable" : "refused");
5437
+ }
5438
+ return body;
5439
+ }
5440
+ catch (error) {
5441
+ if (error instanceof ConductorSetupPolicyError)
5442
+ throw error;
5443
+ throw new ConductorSetupPolicyError(suffix === "apply/" ? "uncertain" : "unavailable");
5444
+ }
5445
+ finally {
5446
+ clearTimeout(timer);
5447
+ }
5448
+ }
5449
+ export async function previewConductorSetupPolicy(access, request, fetchImpl) {
5450
+ const body = parseSetupEnvelope(await setupPolicyRequest(access, "preview/", request, fetchImpl), access);
5451
+ if (!setupProjection(body.before) || !setupProjection(body.after) || !Array.isArray(body.effects)
5452
+ || typeof body.approval_required !== "boolean" || body.approval_required !== (body.effects.length > 0)
5453
+ || typeof body.preview_artifact !== "string" || !body.preview_artifact || body.preview_artifact.length > 1024)
5454
+ throw new ConductorSetupPolicyError("malformed");
5455
+ const categories = ["gate", "setup", "config", "sources", "qualification"];
5456
+ for (const effect of body.effects) {
5457
+ if (!setupObject(effect) || effect.classification !== "consequential" || !categories.includes(String(effect.category))
5458
+ || Object.keys(effect).sort().join() !== "after,before,category,classification"
5459
+ || setupCanonical(effect.before) !== setupCanonical(body.before[effect.category])
5460
+ || setupCanonical(effect.after) !== setupCanonical(body.after[effect.category]))
5461
+ throw new ConductorSetupPolicyError("malformed");
5462
+ }
5463
+ for (const category of categories) {
5464
+ if (setupCanonical(body.before[category]) !== setupCanonical(body.after[category])
5465
+ && !body.effects.some(e => setupObject(e) && e.category === category))
5466
+ throw new ConductorSetupPolicyError("malformed");
5467
+ }
5468
+ if (request.gate?.provider_checks) {
5469
+ const checks = body.after.gate?.provider_checks;
5470
+ if (!Array.isArray(checks) || JSON.stringify(checks.map(c => typeof c === "string" ? c : c?.name))
5471
+ !== JSON.stringify(request.gate.provider_checks.map(c => c.name)))
5472
+ throw new ConductorSetupPolicyError("malformed");
5473
+ }
5474
+ const { preview_artifact: artifact, ...publicPreview } = body;
5475
+ if (JSON.stringify(publicPreview).includes(String(artifact)))
5476
+ throw new ConductorSetupPolicyError("malformed");
5477
+ const result = { protocol: SETUP_POLICY_PROTOCOL, repo_name: access.repoName, effects: body.effects,
5478
+ approval_required: body.approval_required, before: body.before, after: body.after, state: body.state };
5479
+ Object.defineProperty(result, "preview_artifact", { value: body.preview_artifact, enumerable: false });
5480
+ return result;
5481
+ }
5482
+ function parseSetupRead(body, access) {
5483
+ const parsed = parseSetupEnvelope(body, access);
5484
+ if (!setupProjection(parsed.policy))
5485
+ throw new ConductorSetupPolicyError("malformed");
5486
+ return { protocol: SETUP_POLICY_PROTOCOL, repo_name: access.repoName, policy: parsed.policy, state: parsed.state };
5487
+ }
5488
+ export async function applyConductorSetupPolicy(access, request, preview, approve, fetchImpl) {
5489
+ const body = await setupPolicyRequest(access, "apply/", { ...request, preview_artifact: preview.preview_artifact, approve }, fetchImpl);
5490
+ if (JSON.stringify(body).includes(preview.preview_artifact))
5491
+ throw new ConductorSetupPolicyError("malformed");
5492
+ return parseSetupRead(body, access);
5493
+ }
5494
+ export async function fetchConductorSetupPolicy(access, fetchImpl) {
5495
+ return parseSetupRead(await setupPolicyRequest(access, "", undefined, fetchImpl), access);
5496
+ }