@bridge_gpt/mcp-server 0.2.72 → 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 (146) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +3 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-permissions.js +27 -0
  5. package/build/ci-system-detection.js +50 -0
  6. package/build/ci-trigger-adapters.js +631 -0
  7. package/build/ci-trigger-install.js +106 -0
  8. package/build/codex-launcher-pin.js +33 -2
  9. package/build/codex-skill-adapter.js +3 -1
  10. package/build/command-host.js +33 -0
  11. package/build/commands.generated.js +7 -6
  12. package/build/conductor/bridge-api-client.js +842 -35
  13. package/build/conductor/bring-up-facts.js +18 -5
  14. package/build/conductor/command-drift-production.js +42 -17
  15. package/build/conductor/command-drift.js +47 -0
  16. package/build/conductor/declare-blocked.js +554 -0
  17. package/build/conductor/doctor.js +106 -21
  18. package/build/conductor/driver-commands.js +141 -0
  19. package/build/conductor/driver-guard.js +277 -0
  20. package/build/conductor/driver-lapse.js +321 -0
  21. package/build/conductor/driver-register.js +176 -0
  22. package/build/conductor/driver-release.js +174 -0
  23. package/build/conductor/driver-session-state.js +315 -0
  24. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  25. package/build/conductor/epic-implementer-cli.js +166 -15
  26. package/build/conductor/epic-server-database.js +162 -0
  27. package/build/conductor/epic-server-guidance.js +278 -0
  28. package/build/conductor/epic-server-journal.js +239 -0
  29. package/build/conductor/epic-server-processes.js +324 -0
  30. package/build/conductor/epic-server-recipe.js +397 -0
  31. package/build/conductor/epic-server-runtime.js +1207 -0
  32. package/build/conductor/epic-server-sfcc.js +107 -0
  33. package/build/conductor/epic-server-state.js +427 -0
  34. package/build/conductor/epic-server.js +594 -0
  35. package/build/conductor/gate-discovery.js +150 -5
  36. package/build/conductor/gate-settings-review.js +224 -4
  37. package/build/conductor/launch-need-probes.js +6 -53
  38. package/build/conductor/launch-plan.js +313 -156
  39. package/build/conductor/prerequisite-inputs.js +879 -45
  40. package/build/conductor/readiness-assessment.js +16 -1
  41. package/build/conductor/readiness-cli.js +20 -9
  42. package/build/conductor/readiness-prerequisites.js +28 -9
  43. package/build/conductor/readiness-sections.js +133 -126
  44. package/build/conductor/readiness.js +1 -1
  45. package/build/conductor/recovery-cli.js +13 -2
  46. package/build/conductor/tools.js +6 -5
  47. package/build/conductor/wait-run-attention.js +2 -2
  48. package/build/conductor/wait-run-cli.js +208 -22
  49. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  50. package/build/conductor/worker-setup-tally.js +27 -0
  51. package/build/credential-store.js +71 -1
  52. package/build/dependency-install-declarations.js +55 -0
  53. package/build/docs.generated.js +2 -2
  54. package/build/doctor.js +54 -3
  55. package/build/drive-epic-help.js +21 -2
  56. package/build/drive-epic.js +1811 -351
  57. package/build/engine-paths.js +20 -0
  58. package/build/epic-branch-ci-summary.js +140 -0
  59. package/build/epic-capability-statement.js +107 -0
  60. package/build/epic-ci-workflow-drift.js +30 -15
  61. package/build/epic-ci-workflow-install.js +110 -42
  62. package/build/epic-ci-workflow-v2.js +274 -0
  63. package/build/epic-ci-workflow.js +38 -12
  64. package/build/epic-implementer-bin.js +2101 -44
  65. package/build/epic-launch-context.js +607 -0
  66. package/build/epic-server-record.js +273 -0
  67. package/build/epic-shared/bridge-client.js +11 -3
  68. package/build/escalation-reachability.js +43 -0
  69. package/build/executor/ci-fix-test-runs.js +334 -0
  70. package/build/executor/completion-contract.js +8 -1
  71. package/build/executor/env.js +59 -22
  72. package/build/executor/epic-server-context.js +141 -0
  73. package/build/executor/gate-qualification-job.js +127 -26
  74. package/build/executor/http-client.js +52 -5
  75. package/build/executor/job-runner.js +423 -69
  76. package/build/executor/observation.js +8 -0
  77. package/build/executor/pre-pr-checks.js +363 -0
  78. package/build/executor/prompt-spec.js +114 -2
  79. package/build/executor/reconcile-overlap-job.js +5 -3
  80. package/build/executor/required-work-diagnostics.js +4 -2
  81. package/build/executor/required-work-ledger.js +936 -38
  82. package/build/executor/results.js +58 -0
  83. package/build/executor/terminal-mutation.js +8 -0
  84. package/build/executor/worker-command.js +72 -3
  85. package/build/executor/worker-database-config.js +281 -0
  86. package/build/executor/worker-database-target.js +16 -12
  87. package/build/executor/worker-database.js +320 -101
  88. package/build/executor/worker-finalization.js +7 -1
  89. package/build/executor/worker-resources.js +25 -3
  90. package/build/executor/worker-verification-guidance.js +18 -3
  91. package/build/executor/worktree.js +20 -1
  92. package/build/executor-launch.js +54 -2
  93. package/build/generated-assets-catalog.js +2 -2
  94. package/build/index.js +664 -335
  95. package/build/init.js +26 -11
  96. package/build/install-bridge-conductor-answers.js +465 -0
  97. package/build/install-bridge-conductor-apply.js +259 -0
  98. package/build/install-bridge-conductor-assessment.js +895 -0
  99. package/build/install-bridge-conductor-compact.js +161 -0
  100. package/build/install-bridge-conductor-contracts.js +63 -0
  101. package/build/install-bridge-conductor-gate.js +1197 -196
  102. package/build/install-bridge-conductor-setup.js +535 -79
  103. package/build/install-bridge-conductor.js +2885 -560
  104. package/build/install-bridge.js +199 -21
  105. package/build/install-maintenance.js +26 -3
  106. package/build/launcher-config-inspection.js +162 -1
  107. package/build/mcp-grant-candidates.js +767 -0
  108. package/build/mcp-grant-doctor.js +63 -0
  109. package/build/mcp-grant.js +288 -0
  110. package/build/mcp-host-targets.js +8 -0
  111. package/build/mcp-identity.js +23 -0
  112. package/build/mcp-invoke.js +126 -13
  113. package/build/mcp-presets.js +107 -0
  114. package/build/mcp-provisioning.js +134 -2
  115. package/build/mcp-registration-doctor.js +31 -2
  116. package/build/mcp-server-invocation.js +6 -1
  117. package/build/merge-workflow-install.js +234 -109
  118. package/build/pipelines.generated.js +5 -5
  119. package/build/plan-discovery.js +97 -4
  120. package/build/plan-execution-ledger.js +100 -7
  121. package/build/plan-generation-io.js +262 -0
  122. package/build/plan-generation.js +424 -0
  123. package/build/plane/build-freshness.js +6 -1
  124. package/build/plane/cli.js +75 -9
  125. package/build/plane/plane-freshness.js +17 -0
  126. package/build/plane/preflight.js +50 -10
  127. package/build/plane/shutdown.js +19 -0
  128. package/build/plane/terminal-run-cleanup.js +18 -4
  129. package/build/printed-remedy-commands.js +206 -12
  130. package/build/readiness-check.js +77 -0
  131. package/build/readiness-prerequisites.generated.js +122 -14
  132. package/build/readme.generated.js +1 -1
  133. package/build/repository-state-paths.js +38 -0
  134. package/build/run-unit-tests-launcher.js +8 -1
  135. package/build/setup-epic.js +1190 -196
  136. package/build/setup-progress.js +44 -0
  137. package/build/setup-question.js +122 -4
  138. package/build/third-party-mcp-targets.js +30 -0
  139. package/build/ticket-delivery-enrollment.js +9 -0
  140. package/build/upgrade-cli.js +85 -2
  141. package/build/v2-readiness-requirements.js +28 -1
  142. package/build/version.generated.js +3 -3
  143. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  144. package/docs/epic-implementer/getting-started.md +3 -1
  145. package/docs/epic-implementer/self-hosting.md +14 -1
  146. package/package.json +2 -2
@@ -1,5 +1,6 @@
1
1
  import { ticketReviewSummary } from "./ticket-review-summary.js";
2
2
  import { previewLaunchReadiness } from "./conductor/bridge-api-client.js";
3
+ import { READINESS_PREREQUISITE_FIXES } from "./printed-remedy-commands.js";
3
4
  import { previewObservationScopeMatches } from "./conductor/preview-observations.js";
4
5
  /**
5
6
  * `setup-epic` — one-command bootstrap for an Epic Implementer run.
@@ -85,7 +86,7 @@ import { previewObservationScopeMatches } from "./conductor/preview-observations
85
86
  import { readFile as fsReadFile, stat as fsStat } from "node:fs/promises";
86
87
  import os from "node:os";
87
88
  import { createProductionEpicIntegrationGhRunner, ensureEpicIntegrationPullRequest, formatEpicIntegrationPullRequestOutcome, } from "./epic-integration-pr.js";
88
- import { approveEpicPlan, buildConductorJiraUrl, conductorGetHeaders, createEpicRunWithDisposition, decodeCanonicalProvenance, fetchConductorReadiness, formatSchemaIncompatibleRefusal, isSchemaIncompatibleError, fetchEpicRunState, replaceEpicRunPolicy, resolveConductorBridgeApiAccess, resolveEpicLaunchBridgeApiAccess, safeDiagnosticMessage, storeEpicPlan, validateEpicPlan, ConductorBridgeApiError, } from "./conductor/bridge-api-client.js";
89
+ import { acquireConductorReadiness, approveEpicPlan, buildConductorJiraUrl, conductorGetHeaders, createEpicRunWithDisposition, decodeCanonicalProvenance, fetchConductorReadiness, formatSchemaIncompatibleRefusal, fetchEpicRunState, replaceEpicRunPolicy, resolveConductorBridgeApiAccess, resolveEpicLaunchBridgeApiAccess, safeDiagnosticMessage, storeEpicPlan, validateEpicPlan, ConductorBridgeApiError, ConductorMutationOutcomeUnknownError, } from "./conductor/bridge-api-client.js";
89
90
  import { formatEpicLaunchChannelIdentity, getPinnedEpicLaunchPolicy, readEpicLaunchProfile, } from "./epic-launch-profile.js";
90
91
  // BAPI-1133 (A2) — the single legacy-to-typed merge-execution-mode mapping and
91
92
  // its total legacy resolver live in `merge-pull-request.ts` (no import cycle:
@@ -110,14 +111,110 @@ import { getConfigFieldBaseBranch, getIndexScopeLifecycle, getParseStatus, } fro
110
111
  import { boundScopeLifecycleLabel, createExecFileRunCommand, ensureCommitResolvableLocally, performExactIndexScopeCut, pollIndexScopeLifecycle, readRemoteBranchHead, runGit, SCOPE_BOOTSTRAP_POLL_INTERVAL_MS, SCOPE_LIFECYCLE_LABELS, } from "./epic-shared/cut-protocol.js";
111
112
  import { hashPlan } from "./conductor/plan.js";
112
113
  import { PLACEHOLDER_NODE_KEY_RE } from "./conductor-bundle-artifacts.js";
113
- import { BRING_UP_REFUSAL_MESSAGES, firstBringUpRefusal, } from "./conductor/bring-up-facts.js";
114
+ import { BRING_UP_REFUSAL_MESSAGES, classifyBringUpFacts, firstProvenBringUpRefusal, } from "./conductor/bring-up-facts.js";
114
115
  import { MCP_PACKAGE_NAME } from "./mcp-identity.js";
116
+ import { PARALLEL_LIMIT_CHANGE_ADVISORY } from "./conductor/launch-plan.js";
115
117
  // BAPI-872: local plane-manifest binding, so `plane down` can later stop the
116
118
  // run this setup resolved WITHOUT guessing from repository-wide active-run
117
119
  // state. See `planeBinding` on `SetupEpicDeps` below.
118
120
  import { createPlaneFsDeps, createPlaneProcessDeps } from "./plane/defaults.js";
119
121
  import { bindPlaneManifestEpicRun, manifestHasLiveProcess, readPlaneManifest, } from "./plane/manifest.js";
120
122
  // ---------------------------------------------------------------------------
123
+ // Parallel limit (BAPI-1581)
124
+ // ---------------------------------------------------------------------------
125
+ /** The policy key the server stamps and enforces (BAPI-1578). */
126
+ export const SETUP_EPIC_MAX_PARALLEL_CHILDREN_KEY = "max_parallel_children";
127
+ /** The server-owned runtime narrowing of the limit (BAPI-1578). */
128
+ export const SETUP_EPIC_PARALLEL_THROTTLE_KEY = "parallel_throttle";
129
+ /**
130
+ * Parse a raw `--parallel` value. Only a bare whole number from 1 through 4 is
131
+ * accepted: no decimals, exponent notation, signs, padding, or words, and nothing
132
+ * is coerced.
133
+ */
134
+ export function parseParallelLimit(raw) {
135
+ if (raw === undefined || raw.trim() === "") {
136
+ return { ok: false, error: "--parallel requires a value." };
137
+ }
138
+ if (!/^[1-4]$/.test(raw)) {
139
+ return { ok: false, error: `--parallel must be a whole number from 1 to 4, got '${raw}'.` };
140
+ }
141
+ return { ok: true, value: Number(raw) };
142
+ }
143
+ /**
144
+ * Pure, side-effect-free preflight for a supplied `--parallel` limit.
145
+ *
146
+ * It judges only the CANDIDATE creation policy: the mode flags, the selected
147
+ * file or profile policy (raw), and the resolved default branch selection. It
148
+ * never reads a stored run policy, so it cannot reject a reuse on the strength of
149
+ * a speculative creation policy. It never mutates its input and never echoes a
150
+ * value read from the file.
151
+ *
152
+ * BAPI-1595: the selected policy is judged AFTER create's own fill-if-absent
153
+ * ({@link applySetupEpicUnattendedDefault}), never as the raw file. A
154
+ * posture-silent file that create would compose as unattended (an epic branch is
155
+ * selected and the run is not attended) is therefore accepted, because refusing
156
+ * it would reject a policy create accepts. Only the posture is filled here: the
157
+ * file's declared parallel limit is left as written, so a disagreement with
158
+ * `--parallel` is still named. `--attended`, `--into-base`, a declared
159
+ * non-unattended posture, and a parallel-policy-file conflict still refuse.
160
+ */
161
+ export function evaluateParallelPolicyPreflight(args) {
162
+ const requiresUnattended = (detail) => ({
163
+ ok: false,
164
+ reason: "parallel-requires-unattended",
165
+ message: `setup-epic REFUSED (parallel-requires-unattended): --parallel sets the limit of an ` +
166
+ `unattended run, and ${detail} Drop --parallel, or make the run unattended.`,
167
+ });
168
+ if (args.attended)
169
+ return requiresUnattended("--attended opts out of unattended operation.");
170
+ if (args.intoBase) {
171
+ return requiresUnattended("--into-base runs children directly into the repository base branch.");
172
+ }
173
+ if (args.filePolicy !== undefined) {
174
+ const composed = applySetupEpicUnattendedDefault(args.filePolicy, {
175
+ featureBranch: args.featureBranch,
176
+ attended: args.attended,
177
+ });
178
+ const postureSilentAndDeferred = args.postureFillDeferred === true && !("posture" in args.filePolicy);
179
+ if (!postureSilentAndDeferred && composed.posture !== SETUP_EPIC_UNATTENDED_POSTURE) {
180
+ return requiresUnattended('the selected policy file does not declare posture: "unattended".');
181
+ }
182
+ const declared = composed[SETUP_EPIC_MAX_PARALLEL_CHILDREN_KEY];
183
+ if (declared !== undefined && declared !== null && declared !== args.parallel) {
184
+ return {
185
+ ok: false,
186
+ reason: "parallel-policy-file-conflict",
187
+ message: `setup-epic REFUSED (parallel-policy-file-conflict): --parallel ${args.parallel} ` +
188
+ `disagrees with the ${SETUP_EPIC_MAX_PARALLEL_CHILDREN_KEY} the selected policy file ` +
189
+ `declares. setup-epic will not pick a winner between them: drop the flag, or fix the ` +
190
+ `policy file so both agree.`,
191
+ };
192
+ }
193
+ return { ok: true };
194
+ }
195
+ if (args.featureBranch === undefined) {
196
+ return requiresUnattended("this launch selects no epic branch, so no unattended policy would be composed.");
197
+ }
198
+ return { ok: true };
199
+ }
200
+ /** Read the governing limit and posture off a SERVER-STORED policy. Absent reads as 1. */
201
+ export function readStoredRunFacts(policy) {
202
+ const object = policy && typeof policy === "object" && !Array.isArray(policy)
203
+ ? policy : {};
204
+ const raw = object[SETUP_EPIC_MAX_PARALLEL_CHILDREN_KEY];
205
+ return {
206
+ parallelLimit: typeof raw === "number" && Number.isInteger(raw) && raw >= 1 && raw <= 4 ? raw : 1,
207
+ runPosture: object.posture === SETUP_EPIC_UNATTENDED_POSTURE ? "unattended" : "attended",
208
+ };
209
+ }
210
+ /** One informational line when a reused or adopted run keeps a different stored limit. */
211
+ export function retainedParallelLimitNotice(requested, stored) {
212
+ if (requested === undefined || requested === stored)
213
+ return null;
214
+ return (`Parallel: --parallel ${requested} applies to a new run only; this run keeps its stored ` +
215
+ `limit of ${stored}. ${PARALLEL_LIMIT_CHANGE_ADVISORY}`);
216
+ }
217
+ // ---------------------------------------------------------------------------
121
218
  // Verification hand-off choice (BAPI-1496)
122
219
  // ---------------------------------------------------------------------------
123
220
  /** The policy keys child 1 (BAPI-1492) declares on the server's `RunPolicy`. */
@@ -249,6 +346,32 @@ function readDeclaredHandoffExceptions(value) {
249
346
  }
250
347
  return normalizeVerificationHandoffExceptions(entries);
251
348
  }
349
+ /**
350
+ * BAPI-1585 — does a reused run's stored policy already hold exactly this
351
+ * verification hand-off choice? True only when BOTH keys are present and
352
+ * well-formed: the enabled flag is `true` and the exception list is a readable
353
+ * list. Exceptions compare as sets of `(ticket_key, step_class)` pairs, each pair
354
+ * encoded as a JSON array so no delimiter can blur two different pairs together.
355
+ * A missing, malformed, or unreadable stored value is `false`, never a match, and
356
+ * neither side's value is echoed.
357
+ */
358
+ export function storedVerificationHandoffMatches(stored, choice) {
359
+ if (!stored || typeof stored !== "object" || Array.isArray(stored))
360
+ return false;
361
+ const policy = stored;
362
+ const wanted = verificationHandoffPolicyKeys(choice);
363
+ if (policy[SETUP_EPIC_VERIFICATION_HANDOFF_ENABLED_KEY] !== wanted[SETUP_EPIC_VERIFICATION_HANDOFF_ENABLED_KEY]) {
364
+ return false;
365
+ }
366
+ const storedExceptions = readDeclaredHandoffExceptions(policy[SETUP_EPIC_VERIFICATION_HANDOFF_EXCEPTIONS_KEY]);
367
+ const wantedExceptions = readDeclaredHandoffExceptions(wanted[SETUP_EPIC_VERIFICATION_HANDOFF_EXCEPTIONS_KEY]);
368
+ if (storedExceptions === null || wantedExceptions === null)
369
+ return false;
370
+ const encode = (entries) => new Set(entries.map((entry) => JSON.stringify([entry.ticket_key, entry.step_class])));
371
+ const a = encode(storedExceptions);
372
+ const b = encode(wantedExceptions);
373
+ return a.size === b.size && [...a].every((pair) => b.has(pair));
374
+ }
252
375
  /**
253
376
  * The one `policy_json.posture` value that means "unattended" (BAPI-1102).
254
377
  *
@@ -418,6 +541,16 @@ export function getSetupEpicUsage() {
418
541
  ` Repeatable; class is one of ${SETUP_EPIC_VERIFICATION_HANDOFF_STEP_CLASSES.join(", ")}.`,
419
542
  " Required with block, refused with proceed. At most",
420
543
  ` ${SETUP_EPIC_MAX_VERIFICATION_HANDOFF_EXCEPTIONS} distinct entries.`,
544
+ " --parallel <1-4> Request the per-run limit of independent children that may",
545
+ " run at once, for a NEW unattended run only. Composed into",
546
+ " policy_json.max_parallel_children on create. Omitted, no",
547
+ " limit is sent and the server's default applies. Refused by",
548
+ " name with --attended, --into-base, or a policy file that",
549
+ " does not declare posture: unattended",
550
+ " (parallel-requires-unattended), and when a file or profile",
551
+ " declares a different max_parallel_children",
552
+ " (parallel-policy-file-conflict). A reused run keeps its",
553
+ " stored limit.",
421
554
  " --json Emit a single JSON result object on stdout",
422
555
  " --launch-profile <name> Passed by drive-epic: resolve the target, repository, and",
423
556
  " credential from a host-local launch profile (see",
@@ -524,11 +657,20 @@ export function parseSetupEpicArgs(argv) {
524
657
  let json = false;
525
658
  let launchProfile;
526
659
  let baseUrl;
660
+ let parallel;
527
661
  // BAPI-1496 — raw hand-off values; validated together after the loop.
528
662
  let verificationHandoffChoice;
529
663
  const verificationHandoffExceptions = [];
530
664
  for (let i = 0; i < argv.length; i++) {
531
665
  const arg = argv[i];
666
+ // BAPI-1581 — `--parallel=<n>` inline form.
667
+ if (arg.startsWith("--parallel=")) {
668
+ const parsedParallel = parseParallelLimit(arg.slice("--parallel=".length));
669
+ if (!parsedParallel.ok)
670
+ return { status: "error", message: parsedParallel.error };
671
+ parallel = parsedParallel.value;
672
+ continue;
673
+ }
532
674
  // BAPI-1496 — inline forms of the hand-off flags.
533
675
  if (arg.startsWith("--verification-handoff=")) {
534
676
  verificationHandoffChoice = arg.slice("--verification-handoff=".length).trim();
@@ -656,6 +798,15 @@ export function parseSetupEpicArgs(argv) {
656
798
  i++;
657
799
  break;
658
800
  }
801
+ case "--parallel": {
802
+ const v = takeValue(argv, i, arg);
803
+ const parsedParallel = parseParallelLimit(v ?? undefined);
804
+ if (!parsedParallel.ok)
805
+ return { status: "error", message: parsedParallel.error };
806
+ parallel = parsedParallel.value;
807
+ i++;
808
+ break;
809
+ }
659
810
  case "--verification-handoff":
660
811
  case "--verification-handoff-exception": {
661
812
  const v = takeValue(argv, i, arg);
@@ -735,6 +886,16 @@ export function parseSetupEpicArgs(argv) {
735
886
  });
736
887
  if (!handoff.ok)
737
888
  return { status: "error", message: handoff.error };
889
+ // BAPI-1581 — `--parallel` sets an UNATTENDED run's limit, so the explicit
890
+ // opt-outs contradict it whatever the argument order.
891
+ if (parallel !== undefined && (attended || intoBase)) {
892
+ return {
893
+ status: "error",
894
+ message: "setup-epic REFUSED (parallel-requires-unattended): --parallel sets the limit of an " +
895
+ `unattended run, and ${attended ? "--attended opts out of unattended operation" : "--into-base runs children directly into the repository base branch"}. ` +
896
+ "Drop --parallel, or make the run unattended.",
897
+ };
898
+ }
738
899
  if (replacePolicy && policyFile === undefined) {
739
900
  return {
740
901
  status: "error",
@@ -764,6 +925,8 @@ export function parseSetupEpicArgs(argv) {
764
925
  ...(baseUrl ? { baseUrl } : {}),
765
926
  // BAPI-1496 — only when supplied, so a legacy options object is unchanged.
766
927
  ...(handoff.value !== undefined ? { verificationHandoff: handoff.value } : {}),
928
+ // BAPI-1581 — only when supplied, so a legacy options object is unchanged.
929
+ ...(parallel !== undefined ? { parallel } : {}),
767
930
  },
768
931
  };
769
932
  }
@@ -1233,11 +1396,10 @@ export function validateEpicPlanSidecar(parsed) {
1233
1396
  // the server will not produce — a false hard-rejection warning trains authors
1234
1397
  // to distrust the whole validator. Reported for EVERY offending node in one
1235
1398
  // pass rather than stopping at the first.
1236
- warnings.push(`Node ${key} has no touched_files, so it opts out of preemptive ` +
1237
- `file-overlap serialization: the server accepts the plan but will not ` +
1238
- `pre-serialize ${key} against overlapping siblings (a conflict would ` +
1239
- `instead be caught reactively and rebased). Add touched_files to ${key} ` +
1240
- `to get that scheduling protection (use [] when no files are predicted).`);
1399
+ warnings.push(`Node ${key} has no touched_files. Declared touched_files are what repository-declared ` +
1400
+ `must-order paths match against, and those paths are the file-based mechanism for ` +
1401
+ `ordering siblings. Shared ordinary files may run in parallel, and any conflicts are ` +
1402
+ `resolved at merge time. Add touched_files to ${key} (use [] when no files are predicted).`);
1241
1403
  }
1242
1404
  }
1243
1405
  // BAPI-1366: refuse unfinalized `TBD-N` node keys before any graph, access, or
@@ -1443,6 +1605,14 @@ export function effectivePolicyFacts(policy, source, notificationSink) {
1443
1605
  escalation_channel: formatEpicLaunchChannelIdentity(source === "stored"
1444
1606
  ? storedEscalationChannel(notificationSink)
1445
1607
  : policyDeclaresNotifyWebhook(object) ? "configured webhook" : "account email"),
1608
+ parallel_limit: source === "stored"
1609
+ ? readStoredRunFacts(object).parallelLimit
1610
+ : typeof object[SETUP_EPIC_MAX_PARALLEL_CHILDREN_KEY] === "number"
1611
+ && Number.isInteger(object[SETUP_EPIC_MAX_PARALLEL_CHILDREN_KEY])
1612
+ && object[SETUP_EPIC_MAX_PARALLEL_CHILDREN_KEY] >= 1
1613
+ && object[SETUP_EPIC_MAX_PARALLEL_CHILDREN_KEY] <= 4
1614
+ ? object[SETUP_EPIC_MAX_PARALLEL_CHILDREN_KEY]
1615
+ : "server_default",
1446
1616
  };
1447
1617
  }
1448
1618
  /** Propose a conductor epic feature branch name for an epic key (BAPI-655). */
@@ -1521,10 +1691,11 @@ export function resolveFeatureBranchSelection(opts, planNodeCount, policyDeclare
1521
1691
  * comparing a CLI message with an API response would have no way to tell they
1522
1692
  * were the same refusal.
1523
1693
  *
1524
- * `readiness_unreadable` is the one code with no server twin, and it is
1525
- * deliberately generic and secret-free: an unreadable or older-server report has
1526
- * PROVEN nothing, and fail-closed is the only safe direction for a check that
1527
- * authorizes unattended merging.
1694
+ * BAPI-1595: an unreadable or older-server report has PROVEN nothing. It used to
1695
+ * refuse as `readiness_unreadable`; it now returns a warning
1696
+ * ({@link SetupEpicPrerequisiteWarning}) and the launch continues to the server's
1697
+ * create and approve, which re-check every fact this client copy mirrors. Only a
1698
+ * PROVEN `false` refuses.
1528
1699
  */
1529
1700
  /**
1530
1701
  * Does this policy declare a notify webhook the server would probe?
@@ -1617,18 +1788,88 @@ export async function worldReadableWebhookPolicyWarning(policyPath, policy, stat
1617
1788
  return (`[warn] Policy file '${policyPath}' holds a notify webhook URL and other users on this ` +
1618
1789
  `machine can read it. Restrict it with: chmod 600 '${policyPath}'`);
1619
1790
  }
1620
- export function evaluateSetupEpicUnattendedPrerequisites(readiness, requestedPolicy) {
1621
- const unattended = readiness?.unattended ?? null;
1622
- if (unattended === null) {
1791
+ function isReadinessSnapshot(input) {
1792
+ return input.kind === "snapshot";
1793
+ }
1794
+ /** Build the evaluators' evidence from a validated launch context; `null` when readiness is unknown there. */
1795
+ export function readinessSnapshotFromLaunchContext(context) {
1796
+ if (context.readiness.state !== "known")
1797
+ return null;
1798
+ const facts = context.readiness.value;
1799
+ return {
1800
+ kind: "snapshot",
1801
+ bringUp: facts.bring_up,
1802
+ unattended: {
1803
+ conductorAllowed: facts.unattended_conductor_allowed,
1804
+ repositoryReadinessConfirmed: facts.repository_readiness_confirmed,
1805
+ escalationEmailAvailable: facts.escalation_email_available,
1806
+ emailTransport: context.escalation_email_transport.state === "known" ? context.escalation_email_transport.value : "unknown",
1807
+ },
1808
+ mergeProbeSkippedReason: facts.merge_execution_probe_skipped_reason,
1809
+ };
1810
+ }
1811
+ /** Tally text and reason codes for the three evaluator warnings (exported; tests import them). */
1812
+ export const BRING_UP_UNKNOWN_WARNING = "bring-up: unknown, continuing; server create and approve decide";
1813
+ export const BRING_UP_UNKNOWN_REASON_CODE = "bring_up_unknown_continued";
1814
+ export const UNATTENDED_FACTS_UNKNOWN_WARNING = "unattended prerequisites: unknown, continuing; server create and approve decide";
1815
+ export const UNATTENDED_FACTS_UNKNOWN_REASON_CODE = "unattended_prerequisites_unknown_continued";
1816
+ export const MERGE_EXECUTION_UNKNOWN_WARNING = "merge execution: unknown, continuing; server create and approve decide";
1817
+ export const MERGE_EXECUTION_UNKNOWN_REASON_CODE = "merge_execution_unknown_continued";
1818
+ const UNCERTAINTY_WARNINGS = {
1819
+ bring_up_unknown: { code: BRING_UP_UNKNOWN_REASON_CODE, message: BRING_UP_UNKNOWN_WARNING },
1820
+ unattended_facts_unknown: { code: UNATTENDED_FACTS_UNKNOWN_REASON_CODE, message: UNATTENDED_FACTS_UNKNOWN_WARNING },
1821
+ merge_execution_unknown: { code: MERGE_EXECUTION_UNKNOWN_REASON_CODE, message: MERGE_EXECUTION_UNKNOWN_WARNING },
1822
+ };
1823
+ function uncertainty(reason) {
1824
+ return { warning: true, reason, ...UNCERTAINTY_WARNINGS[reason] };
1825
+ }
1826
+ /** True for an evaluator's warn outcome (as opposed to a refusal object). */
1827
+ export function isSetupEpicPrerequisiteWarning(value) {
1828
+ return typeof value === "object" && value !== null && value.warning === true;
1829
+ }
1830
+ /** The unattended facts of either input, each `null` when the input does not establish it. */
1831
+ function unattendedFactsOf(input) {
1832
+ if (input === null)
1833
+ return null;
1834
+ if (isReadinessSnapshot(input)) {
1623
1835
  return {
1624
- reason: "readiness_unreadable",
1625
- message: "the Bridge API did not report this repository's unattended prerequisites, so " +
1626
- "they could not be confirmed. Retry once the server is reachable and running a " +
1627
- "build that reports them, or pass --attended to create an attended run. No run " +
1628
- "was created.",
1836
+ conductorAllowed: input.unattended.conductorAllowed,
1837
+ // The snapshot does not carry the repository-level webhook default: unestablished.
1838
+ webhookDefaultDeclared: null,
1839
+ repositoryReadinessConfirmed: input.unattended.repositoryReadinessConfirmed,
1840
+ emailAvailable: input.unattended.escalationEmailAvailable,
1841
+ emailTransport: input.unattended.emailTransport,
1629
1842
  };
1630
1843
  }
1631
- if (!unattended.conductor_allowed) {
1844
+ const unattended = input.unattended ?? null;
1845
+ if (unattended === null)
1846
+ return null;
1847
+ const bool = (value) => (typeof value === "boolean" ? value : null);
1848
+ const transport = (input.diagnostics ?? []).find((d) => d.id === "escalation_email.transport_live");
1849
+ return {
1850
+ conductorAllowed: bool(unattended.conductor_allowed),
1851
+ webhookDefaultDeclared: bool(unattended.notify_webhook_default_declared),
1852
+ repositoryReadinessConfirmed: bool(unattended.repository_readiness_confirmed),
1853
+ emailAvailable: bool(unattended.escalation_email_available),
1854
+ emailTransport: transport !== undefined &&
1855
+ transport.severity !== null &&
1856
+ transport.applicability === "applicable" &&
1857
+ (transport.verdict === "passed" || transport.verdict === "failed")
1858
+ ? transport.verdict
1859
+ : "unknown",
1860
+ };
1861
+ }
1862
+ export function evaluateSetupEpicUnattendedPrerequisites(readiness, requestedPolicy) {
1863
+ const facts = unattendedFactsOf(readiness);
1864
+ // A missing `unattended` block proves nothing (an older server, or an unreadable
1865
+ // report): warn, and let the server's create and approve decide.
1866
+ if (facts === null)
1867
+ return uncertainty("unattended_facts_unknown");
1868
+ let unknown = false;
1869
+ // Refusals come in the fixed cheapest-first order the server uses, and each needs
1870
+ // a PROVEN `false`. A fact that is not established marks the result uncertain and
1871
+ // never refuses; a later proven `false` still refuses over an earlier unknown.
1872
+ if (facts.conductorAllowed === false) {
1632
1873
  return {
1633
1874
  reason: "target_not_allowed",
1634
1875
  message: "unattended runs are off for this repository. Turn on 'Allow unattended " +
@@ -1637,6 +1878,8 @@ export function evaluateSetupEpicUnattendedPrerequisites(readiness, requestedPol
1637
1878
  "email info@bridgegpt.ai. No run was created.",
1638
1879
  };
1639
1880
  }
1881
+ if (facts.conductorAllowed === null)
1882
+ unknown = true;
1640
1883
  // Two independent sources satisfy the escalation channel, and the check has to
1641
1884
  // consult BOTH or it refuses its own documented remedy. No column supplies a
1642
1885
  // repository-level notify default today, so `notify_webhook_default_declared`
@@ -1655,54 +1898,65 @@ export function evaluateSetupEpicUnattendedPrerequisites(readiness, requestedPol
1655
1898
  // its presence (never the address). A declared webhook stays authoritative;
1656
1899
  // email only fills the gap when none is declared. `notify.local_sink` still
1657
1900
  // satisfies nothing.
1658
- if (!unattended.notify_webhook_default_declared &&
1659
- !policyDeclaresNotifyWebhook(requestedPolicy) &&
1660
- unattended.escalation_email_available !== true) {
1661
- return {
1662
- reason: "webhook_unverified",
1663
- message: "an unattended run must have an escalation channel, and this repository, this " +
1664
- "run, and the account provide none. Supply a --policy-file declaring " +
1665
- "notify.webhook_url (notify.local_sink does not satisfy this), or add an email " +
1666
- "address to the account so escalation alerts can be emailed, or pass " +
1667
- "--attended to create an attended run. No run was created.",
1668
- };
1901
+ //
1902
+ // BAPI-1595 — "no channel" is proven only when BOTH absences are established: no
1903
+ // webhook declared anywhere (the run policy, and the repository default) and the
1904
+ // account email proven unavailable or its transport proven not live.
1905
+ if (!policyDeclaresNotifyWebhook(requestedPolicy) && facts.webhookDefaultDeclared !== true) {
1906
+ const emailAbsent = facts.emailAvailable === false || facts.emailTransport === "failed";
1907
+ if (facts.webhookDefaultDeclared === false && emailAbsent) {
1908
+ return {
1909
+ reason: "webhook_unverified",
1910
+ message: "an unattended run must have an escalation channel, and this repository, this " +
1911
+ "run, and the account provide none. Supply a --policy-file declaring " +
1912
+ "notify.webhook_url (notify.local_sink does not satisfy this), or add an email " +
1913
+ "address to the account so escalation alerts can be emailed, or pass " +
1914
+ "--attended to create an attended run. No run was created.",
1915
+ };
1916
+ }
1917
+ if (facts.emailAvailable !== true && facts.emailTransport !== "passed")
1918
+ unknown = true;
1669
1919
  }
1670
- if (!unattended.repository_readiness_confirmed) {
1920
+ if (facts.repositoryReadinessConfirmed === false) {
1671
1921
  // BAPI-1359: the shared formatter names the specific missing item; the reason
1672
- // code and the trailing sentence are unchanged.
1922
+ // code and the trailing sentence are unchanged. A snapshot carries no workflow
1923
+ // detail, so it gets the formatter's own generic fallback.
1673
1924
  return {
1674
1925
  reason: "repository_readiness_unconfirmed",
1675
1926
  message: "the unattended default authorizes automatic merge, which requires the review and " +
1676
1927
  "epic-implementer-ci workflows to be CONFIRMED on the default branch, and they are not. " +
1677
- `${repositoryWorkflowRemedy(readiness)} No run was created.`,
1928
+ `${repositoryWorkflowRemedy(readiness !== null && !isReadinessSnapshot(readiness) ? readiness : null)} No run was created.`,
1678
1929
  };
1679
1930
  }
1680
- return null;
1931
+ if (facts.repositoryReadinessConfirmed === null)
1932
+ unknown = true;
1933
+ return unknown ? uncertainty("unattended_facts_unknown") : null;
1681
1934
  }
1682
1935
  /** The closing sentence every pre-create refusal ends with. */
1683
1936
  const NO_RUN_WAS_CREATED = "No run was created.";
1684
1937
  /**
1685
- * Evaluate the bring-up facts against a readiness report.
1938
+ * Evaluate the bring-up facts against a readiness report or a snapshot.
1686
1939
  *
1687
- * Pure and total: `null` is a readiness read that failed, which has proven
1688
- * nothing and refuses as `readiness_unreadable`. Otherwise at most ONE refusal,
1689
- * in the fixed {@link BRING_UP_REFUSAL_REASONS} order — each fact's
1690
- * "unreadable" before its "bad", so an operator is never told to repair a
1691
- * condition that could not be read.
1940
+ * Pure and total. BAPI-1595 — it refuses ONLY on a proven bad fact: a second
1941
+ * reconciler, a database behind head, or a missing worker, each established by
1942
+ * a readable observation. An absent report (`null`), an unreported block, and an
1943
+ * unreadable fact are not proof of anything: the result is the bring-up warning
1944
+ * and the launch continues to the server's create and approve. At most ONE
1945
+ * refusal, in the fixed {@link BRING_UP_REFUSAL_REASONS} order.
1946
+ *
1947
+ * `firstBringUpRefusal`'s own null contract is unchanged; a `null` input is handled
1948
+ * here, before the classifier is reached.
1692
1949
  */
1693
1950
  export function evaluateSetupEpicBringUpPrerequisites(readiness) {
1694
- if (readiness === null) {
1695
- return {
1696
- reason: "readiness_unreadable",
1697
- message: "the Epic Implementer readiness report could not be read, so the database " +
1698
- "migration, worker presence, and single-reconciler facts could not be confirmed. " +
1699
- `Retry once the server is reachable. ${NO_RUN_WAS_CREATED}`,
1700
- };
1701
- }
1702
- const reason = firstBringUpRefusal(readiness.bring_up ?? null);
1703
- if (reason === null)
1704
- return null;
1705
- return { reason, message: `${BRING_UP_REFUSAL_MESSAGES[reason]} ${NO_RUN_WAS_CREATED}` };
1951
+ if (readiness === null)
1952
+ return uncertainty("bring_up_unknown");
1953
+ const bringUp = isReadinessSnapshot(readiness) ? readiness.bringUp : (readiness.bring_up ?? null);
1954
+ const proven = firstProvenBringUpRefusal(bringUp);
1955
+ if (proven !== null)
1956
+ return { reason: proven, message: `${BRING_UP_REFUSAL_MESSAGES[proven]} ${NO_RUN_WAS_CREATED}` };
1957
+ return classifyBringUpFacts(bringUp).every((verdict) => verdict.state === "ok")
1958
+ ? null
1959
+ : uncertainty("bring_up_unknown");
1706
1960
  }
1707
1961
  /**
1708
1962
  * Read the composed policy's typed `merge_execution_mode`, if it declares one.
@@ -1718,51 +1972,124 @@ export function policyDeclaresGitHubActionsMerge(policy) {
1718
1972
  return policy.merge_execution_mode === MERGE_EXECUTION_MODE_GITHUB_ACTIONS;
1719
1973
  }
1720
1974
  /**
1721
- * Evaluate merge-execution eligibility against a readiness report.
1975
+ * One fixed human sentence per approval reason token the server can report
1976
+ * (BAPI-1601). Written from the server's own meanings in
1977
+ * `GATE_STAMP_REASON_MESSAGES`; the server's text is never relayed, so nothing a
1978
+ * server sends can reach a terminal except a token this build maps or a token that
1979
+ * already matched the closed `^[a-z0-9_]+$` shape.
1980
+ */
1981
+ const SETUP_EPIC_STAMP_REASON_MESSAGES = new Map([
1982
+ [
1983
+ "epic_branch_auto_merge_kept",
1984
+ "Auto-merge stays on for the epic branch. No automated check is configured. " +
1985
+ "The final merge into the base branch still needs a person.",
1986
+ ],
1987
+ [
1988
+ "none_profile_requires_merge_approval",
1989
+ "The repository's gate profile names no checks, so merges need a person's approval.",
1990
+ ],
1991
+ [
1992
+ "local_gate_direct_to_base",
1993
+ "Local checks alone do not gate a run that merges straight into the base branch.",
1994
+ ],
1995
+ ["local_gate_verification_disabled", "Local check verification is off."],
1996
+ [
1997
+ "repository_policy_auto_merge_kept_without_ci",
1998
+ "Auto-merge stays on under the repository's own merge rules. Bridge has not verified CI.",
1999
+ ],
2000
+ ["operator_ci_key_kept", "The run's own CI setting was kept."],
2001
+ ["operator_no_ci_gate_override", "The run declared itself ungated, and that choice was kept."],
2002
+ ["epic_branch_ci_declined", "Epic-branch CI was declined."],
2003
+ ["no_automated_check", "No automated check is configured."],
2004
+ // BAPI-1606: the server's own fixed message for this reason, word for word.
2005
+ [
2006
+ "watched_checks_only",
2007
+ "Only watched checks were set at approval. A failing watched check still stops a merge. A missing one only warns.",
2008
+ ],
2009
+ ["plan_node_required_checks_gate_the_run", "The plan's own required checks gate the run."],
2010
+ ]);
2011
+ /**
2012
+ * The human lines for the server's approval-time auto-merge stamp (BAPI-1601).
2013
+ * An unknown reason token is shown verbatim rather than dropped.
2014
+ */
2015
+ export function describeSetupEpicAutoMergeStamp(stamp) {
2016
+ if (typeof stamp.autoMerge !== "boolean") {
2017
+ return ["Auto-merge: unknown (the server did not report it)"];
2018
+ }
2019
+ if (stamp.reasons.length === 0) {
2020
+ return [stamp.autoMerge ? "Auto-merge: on" : "Auto-merge: off (the server gave no reason)"];
2021
+ }
2022
+ return [
2023
+ stamp.autoMerge ? "Auto-merge: on, with a warning" : "Auto-merge: off",
2024
+ ...stamp.reasons.map((reason) => ` ${SETUP_EPIC_STAMP_REASON_MESSAGES.get(reason) ?? reason}`),
2025
+ ];
2026
+ }
2027
+ /** The one skip marker the server sends for a mode that never merges via GitHub Actions. */
2028
+ export const MERGE_EXECUTION_PROBE_SKIPPED_NOT_GITHUB_ACTIONS = "merge_execution_mode_not_github_actions";
2029
+ /** The advisory said once when the local merge check could not run (BAPI-1601). */
2030
+ export const SETUP_EPIC_MERGE_CHECK_NOT_RUN_LOCALLY = "Merge check: not run locally. The server checks it when the run is created and approved.";
2031
+ /**
2032
+ * Did a SUCCESSFULLY read readiness report leave the merge check unrun?
2033
+ *
2034
+ * True for exactly two cases and no others: the server skipped the probe with the
2035
+ * one known marker, or the report has no `merge_execution` block at all (the
2036
+ * shared classifier's `block_unreported`). A probe that ran and failed, a proven
2037
+ * `not_eligible`, an unrecognized skip reason, and an unreadable report are not
2038
+ * this: they keep their existing outcome. The classifier itself is not changed.
2039
+ */
2040
+ export function mergeExecutionCheckUnrunLocally(readiness, requestedPolicy) {
2041
+ if (readiness === null)
2042
+ return false;
2043
+ if (!policyDeclaresGitHubActionsMerge(requestedPolicy))
2044
+ return false;
2045
+ if (isReadinessSnapshot(readiness)) {
2046
+ return readiness.mergeProbeSkippedReason === MERGE_EXECUTION_PROBE_SKIPPED_NOT_GITHUB_ACTIONS;
2047
+ }
2048
+ if (readiness.merge_execution?.probe_skipped_reason ===
2049
+ MERGE_EXECUTION_PROBE_SKIPPED_NOT_GITHUB_ACTIONS) {
2050
+ return true;
2051
+ }
2052
+ return classifyMergeExecutionEligibility(readiness).reason === "block_unreported";
2053
+ }
2054
+ /**
2055
+ * Evaluate merge-execution eligibility against a readiness report or snapshot.
1722
2056
  *
1723
2057
  * Pure and total. Returns `null` — no refusal — for every policy that does not
1724
2058
  * declare `github_actions` mode, without reading the report at all.
1725
2059
  *
2060
+ * BAPI-1595 — only PROVEN ineligibility refuses (`not_eligible`). Evidence that was
2061
+ * not established (no report, a snapshot that holds no eligibility detail, or a
2062
+ * `could_not_verify` verdict) returns the merge-execution warning and defers to the
2063
+ * server, which re-checks it at create and approve. A deliberately skipped probe is
2064
+ * not unknown evidence, so it returns `null` without a warning or a retry.
2065
+ *
1726
2066
  * Uses {@link classifyMergeExecutionEligibility}, the same classifier readiness
1727
2067
  * and `drive-epic` read, so all three agree on the status AND on the first
1728
2068
  * blocker. A client that classified the block itself here would eventually
1729
2069
  * disagree with the row an operator had just been shown.
1730
2070
  *
1731
- * BOTH `not_eligible` and `could_not_verify` return
1732
- * `merge_execution_ineligible`. One code, because the operator's next action is
1733
- * the same and splitting it would put the burden of telling "not proven" from
1734
- * "proven absent" on the person least able to check. The MESSAGE keeps the
1735
- * capability category explicit, so the distinction survives where it is
1736
- * actionable.
1737
- *
1738
- * The message is built from the shared remedy constant, ends with the exact
2071
+ * The refusal message is built from the shared remedy constant, ends with the exact
1739
2072
  * standalone sentence `No run was created.`, and carries no GitHub payload, URL,
1740
2073
  * branch name, workflow source, credential, or exception text.
1741
2074
  */
1742
2075
  export function evaluateSetupEpicMergeExecutionPrerequisites(readiness, requestedPolicy) {
1743
2076
  if (!policyDeclaresGitHubActionsMerge(requestedPolicy))
1744
2077
  return null;
1745
- if (readiness === null) {
1746
- return {
1747
- reason: MERGE_EXECUTION_INELIGIBLE,
1748
- message: "this run declares merge_execution_mode: github_actions, and the Epic " +
1749
- "Implementer readiness report could not be read, so the repository's merge " +
1750
- "capability could not be confirmed. Retry once the server is reachable. If " +
1751
- "readiness then reports the merge workflow missing or out of date, resolve it " +
1752
- `with \`${MERGE_WORKFLOW_REMEDY_COMMAND}\`. ${MERGE_WORKFLOW_CODEOWNER_INSTRUCTION} ` +
1753
- NO_RUN_WAS_CREATED,
1754
- };
1755
- }
2078
+ // BAPI-1601 — a successful report that proves nothing either way is locally
2079
+ // unchecked, not a refusal; the server checks at create and approval.
2080
+ if (mergeExecutionCheckUnrunLocally(readiness, requestedPolicy))
2081
+ return null;
2082
+ if (readiness === null || isReadinessSnapshot(readiness))
2083
+ return uncertainty("merge_execution_unknown");
1756
2084
  const verdict = classifyMergeExecutionEligibility(readiness);
1757
2085
  if (verdict.status === "eligible")
1758
2086
  return null;
1759
- const category = verdict.status === "could_not_verify"
1760
- ? "could not be confirmed"
1761
- : "is not sufficient";
2087
+ if (verdict.status === "could_not_verify")
2088
+ return uncertainty("merge_execution_unknown");
1762
2089
  return {
1763
2090
  reason: MERGE_EXECUTION_INELIGIBLE,
1764
2091
  message: "this run declares merge_execution_mode: github_actions, and this repository's " +
1765
- `merge capability ${category}: ${verdict.detail}. Resolve it with ` +
2092
+ `merge capability is not sufficient: ${verdict.detail}. Resolve it with ` +
1766
2093
  `\`${MERGE_WORKFLOW_REMEDY_COMMAND}\`, then re-run. ` +
1767
2094
  `${MERGE_WORKFLOW_CODEOWNER_INSTRUCTION} ${NO_RUN_WAS_CREATED}`,
1768
2095
  };
@@ -1841,6 +2168,9 @@ export function composeDefaultSetupEpicPolicy(args) {
1841
2168
  if (args.verificationHandoff !== undefined) {
1842
2169
  Object.assign(policy, verificationHandoffPolicyKeys(args.verificationHandoff));
1843
2170
  }
2171
+ if (args.parallel !== undefined) {
2172
+ policy[SETUP_EPIC_MAX_PARALLEL_CHILDREN_KEY] = args.parallel;
2173
+ }
1844
2174
  }
1845
2175
  }
1846
2176
  if (args.reviewPolicy !== undefined) {
@@ -1869,10 +2199,17 @@ export function composeDefaultSetupEpicPolicy(args) {
1869
2199
  * FILL-IF-ABSENT, on the strictest reading of absent, and the boundaries are the
1870
2200
  * contract:
1871
2201
  *
1872
- * * **The file declared a `posture`** → untouched, whatever it says. A file that
1873
- * answered the question owns the answer; that is what `--policy-file` means,
1874
- * and the one case where it contradicts `--attended` is already a named
1875
- * refusal upstream (`attended_with_policy_file_posture`).
2202
+ * * **The file declared a `posture` other than `"unattended"`** → untouched,
2203
+ * whatever it says (`""`, a number, and `null` included). A file that answered
2204
+ * the question owns the answer; that is what `--policy-file` means, and the one
2205
+ * case where it contradicts `--attended` is already a named refusal upstream
2206
+ * (`attended_with_policy_file_posture`).
2207
+ * * **The file declared `posture: "unattended"`** (BAPI-1601) → the same three
2208
+ * absent-key fills as a posture-silent file, and nothing else. Declaring the
2209
+ * posture used to skip them, so a file that said "unattended" created a run
2210
+ * with no auto-merge and no integration preparation, and every child merge
2211
+ * parked `v2_merge_approval_required`. The fill is by key PRESENCE, never
2212
+ * truthiness: `false`, `null`, and an invalid mode all count as declared.
1876
2213
  * * **`--attended`** → untouched. It is the explicit opt-out from a default, and
1877
2214
  * this is the default it opts out of.
1878
2215
  * * **No feature branch** → untouched. Identical to the no-file composer's own
@@ -1899,25 +2236,165 @@ export function composeDefaultSetupEpicPolicy(args) {
1899
2236
  export function applySetupEpicUnattendedDefault(policy, args) {
1900
2237
  if (args.attended)
1901
2238
  return policy;
1902
- if (args.featureBranch === undefined)
2239
+ if (args.featureBranch === undefined && args.parallel === undefined)
1903
2240
  return policy;
1904
- if ("posture" in policy)
2241
+ if ("posture" in policy) {
2242
+ if (policy.posture !== SETUP_EPIC_UNATTENDED_POSTURE)
2243
+ return policy;
2244
+ let declared = policy;
2245
+ if (args.parallel !== undefined &&
2246
+ (policy[SETUP_EPIC_MAX_PARALLEL_CHILDREN_KEY] === undefined ||
2247
+ policy[SETUP_EPIC_MAX_PARALLEL_CHILDREN_KEY] === null)) {
2248
+ declared = { ...policy, [SETUP_EPIC_MAX_PARALLEL_CHILDREN_KEY]: args.parallel };
2249
+ }
2250
+ if (args.featureBranch === undefined)
2251
+ return declared;
2252
+ // BAPI-1601 — a copy, never the caller's object, and only when there is
2253
+ // something absent to fill.
2254
+ return fillAbsentUnattendedDefaults(declared, args.mergeExecutionMode);
2255
+ }
2256
+ if (args.featureBranch === undefined)
1905
2257
  return policy;
1906
2258
  const composed = { ...policy };
1907
- composed.posture = SETUP_EPIC_UNATTENDED_POSTURE;
1908
- if (!(SETUP_EPIC_AUTO_MERGE_POLICY_KEY in composed)) {
1909
- composed[SETUP_EPIC_AUTO_MERGE_POLICY_KEY] = true;
1910
- }
1911
- if (!(SETUP_EPIC_MERGE_EXECUTION_MODE_POLICY_KEY in composed) &&
1912
- args.mergeExecutionMode !== undefined) {
1913
- composed[SETUP_EPIC_MERGE_EXECUTION_MODE_POLICY_KEY] = args.mergeExecutionMode;
2259
+ if (args.parallel !== undefined &&
2260
+ (composed[SETUP_EPIC_MAX_PARALLEL_CHILDREN_KEY] === undefined ||
2261
+ composed[SETUP_EPIC_MAX_PARALLEL_CHILDREN_KEY] === null)) {
2262
+ composed[SETUP_EPIC_MAX_PARALLEL_CHILDREN_KEY] = args.parallel;
1914
2263
  }
1915
- if (!(SETUP_EPIC_INTEGRATION_PREPARATION_POLICY_KEY in composed)) {
1916
- composed[SETUP_EPIC_INTEGRATION_PREPARATION_POLICY_KEY] = {
2264
+ composed.posture = SETUP_EPIC_UNATTENDED_POSTURE;
2265
+ return fillAbsentUnattendedDefaults(composed, args.mergeExecutionMode) ?? composed;
2266
+ }
2267
+ /**
2268
+ * Fill the three unattended defaults that a policy leaves ABSENT (BAPI-1601).
2269
+ *
2270
+ * Presence, not truthiness: `v2_auto_merge_enabled: false`, an explicit `null`,
2271
+ * and an invalid `merge_execution_mode` are all declared values and are forwarded
2272
+ * unchanged for the server's own validation to judge. The merge-execution mode is
2273
+ * filled only when the caller resolved one; otherwise the key stays absent.
2274
+ *
2275
+ * Pure. Returns the SAME object when nothing was absent, and a copy otherwise.
2276
+ */
2277
+ function fillAbsentUnattendedDefaults(policy, mergeExecutionMode) {
2278
+ const needsAutoMerge = !(SETUP_EPIC_AUTO_MERGE_POLICY_KEY in policy);
2279
+ const needsMode = !(SETUP_EPIC_MERGE_EXECUTION_MODE_POLICY_KEY in policy) && mergeExecutionMode !== undefined;
2280
+ const needsPreparation = !(SETUP_EPIC_INTEGRATION_PREPARATION_POLICY_KEY in policy);
2281
+ if (!needsAutoMerge && !needsMode && !needsPreparation)
2282
+ return policy;
2283
+ const filled = { ...policy };
2284
+ if (needsAutoMerge)
2285
+ filled[SETUP_EPIC_AUTO_MERGE_POLICY_KEY] = true;
2286
+ if (needsMode)
2287
+ filled[SETUP_EPIC_MERGE_EXECUTION_MODE_POLICY_KEY] = mergeExecutionMode;
2288
+ if (needsPreparation) {
2289
+ filled[SETUP_EPIC_INTEGRATION_PREPARATION_POLICY_KEY] = {
1917
2290
  ...SETUP_EPIC_INTEGRATION_PREPARATION_DEFAULT,
1918
2291
  };
1919
2292
  }
1920
- return composed;
2293
+ return filled;
2294
+ }
2295
+ /**
2296
+ * The ONE composition of the policy a prospective create would send (BAPI-1601).
2297
+ *
2298
+ * Preview, dry-run, both prerequisite gates, and the create request all read the
2299
+ * object this returns, so they cannot drift apart. It owns no rule of its own:
2300
+ * a policy that passed the gate goes through {@link applySetupEpicUnattendedDefault}
2301
+ * and a launch with no policy through {@link composeDefaultSetupEpicPolicy}.
2302
+ *
2303
+ * `featureBranch` is the EFFECTIVE branch (a flag, else the file's `base_branch`).
2304
+ * `mergeExecutionMode` is the mode the caller resolved from repository
2305
+ * configuration; an absent one stays absent, which is what the offline
2306
+ * `--local-only` path does — it keeps an explicit file mode and invents none.
2307
+ *
2308
+ * `--attended` keeps its legacy wire shape exactly: no default-filled property,
2309
+ * the same keys in the same order.
2310
+ */
2311
+ export function composeSetupEpicCreatePolicy(args) {
2312
+ if (args.policy !== undefined) {
2313
+ return applySetupEpicUnattendedDefault(args.policy, {
2314
+ featureBranch: args.featureBranch,
2315
+ attended: args.attended,
2316
+ ...(args.mergeExecutionMode !== undefined ? { mergeExecutionMode: args.mergeExecutionMode } : {}),
2317
+ ...(args.parallel !== undefined ? { parallel: args.parallel } : {}),
2318
+ });
2319
+ }
2320
+ return composeDefaultSetupEpicPolicy({
2321
+ featureBranch: args.featureBranch,
2322
+ attended: args.attended,
2323
+ reviewPolicy: args.reviewPolicy,
2324
+ ...(args.mergeExecutionMode !== undefined ? { mergeExecutionMode: args.mergeExecutionMode } : {}),
2325
+ ...(args.verificationHandoff !== undefined ? { verificationHandoff: args.verificationHandoff } : {}),
2326
+ ...(args.parallel !== undefined ? { parallel: args.parallel } : {}),
2327
+ });
2328
+ }
2329
+ export function projectSetupEpicCreatePolicy(policy) {
2330
+ const source = policy !== null && typeof policy === "object" && !Array.isArray(policy)
2331
+ ? policy
2332
+ : {};
2333
+ const read = (key) => (key in source ? source[key] : null);
2334
+ return {
2335
+ posture: read("posture"),
2336
+ v2_auto_merge_enabled: read(SETUP_EPIC_AUTO_MERGE_POLICY_KEY),
2337
+ merge_execution_mode: read(SETUP_EPIC_MERGE_EXECUTION_MODE_POLICY_KEY),
2338
+ integration_preparation: read(SETUP_EPIC_INTEGRATION_PREPARATION_POLICY_KEY),
2339
+ };
2340
+ }
2341
+ export const SETUP_EPIC_AUTO_MERGE_OFF_NO_EPIC_BRANCH = "No epic branch is selected.";
2342
+ export const SETUP_EPIC_AUTO_MERGE_OFF_ATTENDED = "--attended was passed.";
2343
+ export const SETUP_EPIC_AUTO_MERGE_OFF_FILE_FALSE = "the policy sets v2_auto_merge_enabled to false.";
2344
+ export const SETUP_EPIC_AUTO_MERGE_OFF_POSTURE = "the policy declares a posture other than unattended.";
2345
+ /**
2346
+ * Derive the auto-merge INTENT from a composed (or projected) policy and what the
2347
+ * client knows about the launch (BAPI-1601).
2348
+ *
2349
+ * Display logic only. It never changes the policy that is submitted, and it never
2350
+ * reads a missing or malformed setting as `false`: no usable boolean and no other
2351
+ * known cause is `unavailable`. The order is the whole contract:
2352
+ *
2353
+ * 1. No epic branch is `off`. The line names the branch it merges into, and the
2354
+ * composed boolean stays on the create payload for the server to judge.
2355
+ * 2. A real boolean decides next. A declared attended posture with an explicit
2356
+ * `true` and an epic branch is therefore still `on`; the server confirms at
2357
+ * approval.
2358
+ * 3. Only without a boolean do client facts explain `off`: `--attended`, then a
2359
+ * declared posture other than unattended.
2360
+ *
2361
+ * `null` reads as absent, so a four-key projection (where absent is `null`) and a
2362
+ * composed policy resolve the same way.
2363
+ */
2364
+ export function resolveSetupEpicAutoMergeIntent(policy, context) {
2365
+ if (context.epicBranch === undefined) {
2366
+ return { state: "off", reason: SETUP_EPIC_AUTO_MERGE_OFF_NO_EPIC_BRANCH };
2367
+ }
2368
+ const source = policy !== null && typeof policy === "object" && !Array.isArray(policy)
2369
+ ? policy
2370
+ : {};
2371
+ const flag = source[SETUP_EPIC_AUTO_MERGE_POLICY_KEY];
2372
+ if (flag === true)
2373
+ return { state: "on" };
2374
+ if (flag === false)
2375
+ return { state: "off", reason: SETUP_EPIC_AUTO_MERGE_OFF_FILE_FALSE };
2376
+ if (flag === undefined || flag === null) {
2377
+ if (context.attended)
2378
+ return { state: "off", reason: SETUP_EPIC_AUTO_MERGE_OFF_ATTENDED };
2379
+ const posture = source.posture;
2380
+ if (posture !== undefined && posture !== null && posture !== SETUP_EPIC_UNATTENDED_POSTURE) {
2381
+ return { state: "off", reason: SETUP_EPIC_AUTO_MERGE_OFF_POSTURE };
2382
+ }
2383
+ }
2384
+ return { state: "unavailable" };
2385
+ }
2386
+ /**
2387
+ * The one human line for an auto-merge intent, shared by setup-epic and
2388
+ * drive-epic so the preview can never word it differently. `unavailable` has no
2389
+ * line here: each caller says why it has nothing to show.
2390
+ */
2391
+ export function formatSetupEpicAutoMergeIntent(intent, epicBranch) {
2392
+ if (intent.state === "unavailable")
2393
+ return null;
2394
+ const subject = epicBranch === undefined ? "Auto-merge" : `Auto-merge into ${epicBranch}`;
2395
+ return intent.state === "on"
2396
+ ? `${subject}: on (the server confirms at approval)`
2397
+ : `${subject}: off — ${intent.reason}`;
1921
2398
  }
1922
2399
  /**
1923
2400
  * One line naming the selected branch strategy AND why it was selected.
@@ -1934,7 +2411,12 @@ function describeBranchStrategy(opts, featureBranch, policyDeclaresBranch,
1934
2411
  * policy the file supplied would be a statement setup-epic cannot make: the
1935
2412
  * file may declare any posture, or none, and this function never reads it.
1936
2413
  */
1937
- composesDefaultPolicy = true) {
2414
+ composesDefaultPolicy = true,
2415
+ /**
2416
+ * BAPI-1601 — the composed auto-merge intent. The posture suffix claims
2417
+ * auto-merge only when the composed setting says so, never from posture alone.
2418
+ */
2419
+ autoMergeIntent) {
1938
2420
  const cutNote = "cut on origin with local git at the canonical indexed commit; " +
1939
2421
  "validated server-side at approval";
1940
2422
  // BAPI-1102: the posture is stated ALONGSIDE the branch, on the same line, and
@@ -1944,8 +2426,11 @@ composesDefaultPolicy = true) {
1944
2426
  ? ""
1945
2427
  : opts.attended
1946
2428
  ? "; ATTENDED posture (--attended): no auto-merge authorization"
1947
- : "; UNATTENDED posture with auto-merge into the epic branch " +
1948
- "(the integration PR stays human-gated) — pass --attended to opt out";
2429
+ : autoMergeIntent !== undefined && autoMergeIntent.state !== "on"
2430
+ ? "; UNATTENDED posture (auto-merge into the epic branch is not composed) — " +
2431
+ "pass --attended to opt out"
2432
+ : "; UNATTENDED posture with auto-merge into the epic branch " +
2433
+ "(the integration PR stays human-gated) — pass --attended to opt out";
1949
2434
  if (featureBranch !== undefined) {
1950
2435
  if (opts.featureBranch !== undefined) {
1951
2436
  return `${featureBranch} (explicit --feature-branch override; ${cutNote}${posture})`;
@@ -1977,9 +2462,26 @@ function errorDetail(err) {
1977
2462
  * disposition the human output describes.
1978
2463
  */
1979
2464
  async function applyReusedRunPolicy(args) {
2465
+ // BAPI-1581 — the concurrency keys are SERVER-owned. The server retains them when a
2466
+ // request omits them, so an omitted key is not a divergence: carry the stored
2467
+ // value into the requested policy before comparing, and genuine omission stays
2468
+ // omission. A key the file DECLARES follows the ordinary reconciliation. The
2469
+ // creation-only `--parallel` value never reaches this function.
2470
+ const storedObject = args.storedPolicy && typeof args.storedPolicy === "object" && !Array.isArray(args.storedPolicy)
2471
+ ? args.storedPolicy : {};
2472
+ const requestedForReuse = { ...args.requestedPolicy };
2473
+ for (const key of [SETUP_EPIC_MAX_PARALLEL_CHILDREN_KEY, SETUP_EPIC_PARALLEL_THROTTLE_KEY]) {
2474
+ const storedValue = storedObject[key];
2475
+ const requestedOmits = key === SETUP_EPIC_MAX_PARALLEL_CHILDREN_KEY
2476
+ ? requestedForReuse[key] === undefined || requestedForReuse[key] === null
2477
+ : !(key in requestedForReuse);
2478
+ if (requestedOmits && typeof storedValue === "number" && Number.isInteger(storedValue)) {
2479
+ requestedForReuse[key] = storedValue;
2480
+ }
2481
+ }
1980
2482
  const outcome = reconcileReusedRunPolicy({
1981
2483
  storedPolicy: args.storedPolicy,
1982
- requestedPolicy: args.requestedPolicy,
2484
+ requestedPolicy: requestedForReuse,
1983
2485
  replacePolicy: args.replacePolicy,
1984
2486
  });
1985
2487
  if (outcome.kind === "noop") {
@@ -1998,8 +2500,15 @@ async function applyReusedRunPolicy(args) {
1998
2500
  `or drop --policy-file to reuse the run unchanged.`);
1999
2501
  return false;
2000
2502
  }
2503
+ let authoritativePolicy;
2001
2504
  try {
2002
- await replaceEpicRunPolicy(args.access, { epicRunId: args.epicRunId, policyJson: args.requestedPolicy }, args.deps.fetch);
2505
+ const replaced = await replaceEpicRunPolicy(args.access, { epicRunId: args.epicRunId, policyJson: requestedForReuse }, args.deps.fetch);
2506
+ authoritativePolicy = replaced?.policy_json;
2507
+ if (authoritativePolicy === undefined || authoritativePolicy === null) {
2508
+ // The replacement supplied no policy: fall back to the established stored-state read.
2509
+ const state = await fetchEpicRunState(args.access, args.epicKey, args.deps.fetch);
2510
+ authoritativePolicy = state?.epic_run?.policy_json;
2511
+ }
2003
2512
  }
2004
2513
  catch (err) {
2005
2514
  args.result.policy_applied = "refused_divergent";
@@ -2009,18 +2518,118 @@ async function applyReusedRunPolicy(args) {
2009
2518
  }
2010
2519
  args.result.policy_applied = "replaced";
2011
2520
  args.result.effective_policy = effectivePolicyFacts(args.requestedPolicy, "explicit");
2521
+ // BAPI-1581 — the limit and posture come from the SERVER-stored policy, never
2522
+ // from the submitted request or the pre-check snapshot.
2523
+ if (authoritativePolicy !== undefined && authoritativePolicy !== null) {
2524
+ recordStoredRunFacts(args.runIdSink, authoritativePolicy);
2525
+ args.result.effective_policy = {
2526
+ ...args.result.effective_policy,
2527
+ parallel_limit: readStoredRunFacts(authoritativePolicy).parallelLimit,
2528
+ };
2529
+ }
2012
2530
  args.say("Policy: policy applied: replaced");
2013
2531
  for (const line of outcome.diffLines)
2014
2532
  args.say(line);
2015
2533
  return true;
2016
2534
  }
2535
+ const defaultRereadSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2536
+ /** One bounded re-read through the authoritative state endpoint. */
2537
+ function rereadRun(ctx, identifier) {
2538
+ return rereadLaunchOutcome({
2539
+ identifier,
2540
+ readState: (id, timeoutMs) => fetchEpicRunState(ctx.access, id, ctx.deps.fetch, undefined, timeoutMs),
2541
+ now: ctx.deps.monotonicNow ?? (() => performance.now()),
2542
+ sleep: ctx.deps.sleep ?? defaultRereadSleep,
2543
+ });
2544
+ }
2545
+ /** Finish an invocation whose outcome is now known, printing the JSON result when asked. */
2546
+ function finishRecovered(ctx, outcome, exitCode) {
2547
+ ctx.runIdSink.launchOutcome = outcome;
2548
+ ctx.result.launch_outcome = outcome;
2549
+ if (ctx.opts.json)
2550
+ ctx.deps.log(JSON.stringify(ctx.result, null, 2));
2551
+ return { kind: "exit", exitCode };
2552
+ }
2553
+ /**
2554
+ * BAPI-1593 — no re-read saw the run. Never the generic failure line and never
2555
+ * exit 1: the server may have done the work, so the operator reconnects.
2556
+ */
2557
+ function finishNotConfirmed(ctx, mutation, reads) {
2558
+ const message = `${OUTCOME_NOT_CONFIRMED_PHRASE}: the ${mutation} answer was lost (${ctx.uncertainty}) and ` +
2559
+ `${reads} re-read(s) did not see the run. The server may still have done it — nothing was ` +
2560
+ `sent twice. Reconnect with: ${launchReconnectCommand(ctx.opts.epicKey, ctx.access)}`;
2561
+ ctx.observe("outcome_not_confirmed", `${mutation} ${OUTCOME_NOT_CONFIRMED_PHRASE} after ${reads} read(s)`);
2562
+ ctx.result.warnings.push(message);
2563
+ ctx.say(`Run: [warn] ${message}`);
2564
+ return finishRecovered(ctx, "not_confirmed", 0);
2565
+ }
2566
+ /** Record a re-read run as this invocation's run. */
2567
+ function adoptRereadRun(ctx, run) {
2568
+ ctx.result.epic_run_id = run.epic_run_id;
2569
+ ctx.result.status = run.status;
2570
+ ctx.runIdSink.epicRunId = run.epic_run_id;
2571
+ ctx.runIdSink.runStatus = run.status;
2572
+ recordStoredRunFacts(ctx.runIdSink, run.policy_json);
2573
+ }
2017
2574
  /**
2018
- * Emit the post-access refusal summary and the non-zero exit status.
2575
+ * Report a re-read run and stop without changing it: active, waiting, blocked, or
2576
+ * terminal. Nothing is approved, unblocked, or re-created here.
2577
+ */
2578
+ function finishPassive(ctx, run, mutation) {
2579
+ if (run.status === "active") {
2580
+ ctx.say(`Run: ${run.epic_run_id} is active`);
2581
+ return finishRecovered(ctx, "active", 0);
2582
+ }
2583
+ if (TERMINAL_RUN_STATUSES.has(run.status)) {
2584
+ ctx.say(`Run: ${run.epic_run_id} is ${run.status}; nothing will dispatch for it.`);
2585
+ return finishRecovered(ctx, "terminal", 1);
2586
+ }
2587
+ ctx.say(mutation === "approve" && run.status === "planning"
2588
+ ? `Run: ${run.epic_run_id}: ${RUN_WAITING_FOR_APPROVAL_PHRASE}`
2589
+ : `Run: ${run.epic_run_id} is ${run.status}; attaching without changing it`);
2590
+ return finishRecovered(ctx, "pending_activation", 0);
2591
+ }
2592
+ /**
2593
+ * BAPI-1593 — an uncertain create. Re-read by epic key: the server resolves it to
2594
+ * the repository's single live run, and a 404 is "not created yet".
2019
2595
  *
2020
- * A refusal happens after the run state is known, so `--json` consumers still get
2021
- * the canonical result object — `policy_applied: "refused_divergent"` is a real
2022
- * outcome to record, not an absence of one.
2596
+ * A fresh, untouched planning run (no plan stored, nothing approved) continues
2597
+ * on the normal created-run path, so plane binding, the cut, the plan store, and
2598
+ * the first approval all still happen. The pre-check found no live run, so it is
2599
+ * this invocation's create — or a concurrent setup's, which the create-race
2600
+ * adoption path already treats the same way. Any other state is reported and
2601
+ * attached to without a mutation, because this invocation cannot show it owns it.
2602
+ */
2603
+ async function recoverUncertainCreate(ctx) {
2604
+ ctx.say(`Run: create answer lost (${ctx.uncertainty}); re-reading instead of sending it again`);
2605
+ const reread = await rereadRun(ctx, ctx.opts.epicKey);
2606
+ if (reread.kind === "not_confirmed")
2607
+ return finishNotConfirmed(ctx, "create", reread.reads);
2608
+ const run = reread.run;
2609
+ ctx.observe("launch_outcome_reread", `create re-read saw ${run.status} after ${reread.reads} read(s)`);
2610
+ adoptRereadRun(ctx, run);
2611
+ if (run.status === "planning" && run.approved_plan_hash === null && run.current_plan_version === 0) {
2612
+ return { kind: "continue", run };
2613
+ }
2614
+ return finishPassive(ctx, run, "create");
2615
+ }
2616
+ /**
2617
+ * BAPI-1593 — an uncertain approve. Re-read the known run: `active` continues on
2618
+ * the normal approved path, and every other state is reported without a second
2619
+ * approval.
2023
2620
  */
2621
+ async function recoverUncertainApproval(ctx) {
2622
+ ctx.say(`Plan: approve answer lost (${ctx.uncertainty}); re-reading the run instead of approving again`);
2623
+ const reread = await rereadRun(ctx, ctx.result.epic_run_id);
2624
+ if (reread.kind === "not_confirmed")
2625
+ return finishNotConfirmed(ctx, "approve", reread.reads);
2626
+ const run = reread.run;
2627
+ ctx.observe("launch_outcome_reread", `approve re-read saw ${run.status} after ${reread.reads} read(s)`);
2628
+ adoptRereadRun(ctx, run);
2629
+ if (run.status === "active")
2630
+ return { kind: "continue", planHash: run.approved_plan_hash };
2631
+ return finishPassive(ctx, run, "approve");
2632
+ }
2024
2633
  function emitRefusal(deps, opts, result) {
2025
2634
  if (opts.json)
2026
2635
  deps.log(JSON.stringify(result, null, 2));
@@ -2253,6 +2862,78 @@ function describeScopeTransition(state, status) {
2253
2862
  }
2254
2863
  return `Scope: ${label}…`;
2255
2864
  }
2865
+ /** BAPI-1593 — the warning an unknown readiness acquisition prints, verbatim. */
2866
+ export const READINESS_UNKNOWN_CONTINUING_WARNING = "readiness: unknown, continuing; approve decides";
2867
+ /**
2868
+ * BAPI-1595 — the harm each server-owned pre-create launch refusal guards, keyed by the
2869
+ * server's closed `error_code`. The server decides; this only names why it stops.
2870
+ */
2871
+ export const SERVER_PRE_CREATE_REFUSAL_HARM = {
2872
+ escalation_webhook_unreachable: "an unattended run whose declared webhook does not answer would lose its escalations.",
2873
+ provider_default_branch_unreadable: "the delivery and merge guards could not check the base branch.",
2874
+ };
2875
+ /** BAPI-1593 — the phrase every unconfirmed re-read prints. */
2876
+ export const OUTCOME_NOT_CONFIRMED_PHRASE = "outcome not confirmed";
2877
+ /** BAPI-1593 — the planning re-read line after an uncertain approval. */
2878
+ export const RUN_WAITING_FOR_APPROVAL_PHRASE = "the run exists and is waiting for approval";
2879
+ /** The one overall deadline for a launch-outcome re-read. */
2880
+ export const LAUNCH_OUTCOME_REREAD_DEADLINE_MS = 15_000;
2881
+ /** One immediate read plus at most two more. */
2882
+ export const LAUNCH_OUTCOME_REREAD_MAX_READS = 3;
2883
+ /** Pauses between re-reads, each capped to the time left. */
2884
+ const LAUNCH_OUTCOME_REREAD_BACKOFF_MS = [2_000, 4_000];
2885
+ const TERMINAL_RUN_STATUSES = new Set(["done", "abandoned"]);
2886
+ /**
2887
+ * BAPI-1593 — re-read a run after an uncertain create or approve.
2888
+ *
2889
+ * One immediate read, then at most two more, all inside ONE deadline: every GET
2890
+ * timeout and every pause is capped to the time left, and nothing is attempted
2891
+ * once it is spent. The first readable state ends it — this window confirms an
2892
+ * outcome, it does not wait for one. Any failed read (a 404 for a run not
2893
+ * visible yet included) is "not seen yet" and the next read is tried.
2894
+ *
2895
+ * `identifier` is the known run id, or the epic key when create returned none:
2896
+ * the server resolves an epic key to the repository's single non-terminal run,
2897
+ * so no run is ever selected client-side.
2898
+ */
2899
+ export async function rereadLaunchOutcome(args) {
2900
+ const deadline = args.now() + (args.deadlineMs ?? LAUNCH_OUTCOME_REREAD_DEADLINE_MS);
2901
+ let reads = 0;
2902
+ while (reads < LAUNCH_OUTCOME_REREAD_MAX_READS) {
2903
+ const remaining = deadline - args.now();
2904
+ if (remaining <= 0)
2905
+ break;
2906
+ reads += 1;
2907
+ try {
2908
+ const state = await args.readState(args.identifier, remaining);
2909
+ const run = state?.epic_run;
2910
+ if (run && typeof run.epic_run_id === "string" && run.epic_run_id !== "" && typeof run.status === "string") {
2911
+ return { kind: "read", run, reads };
2912
+ }
2913
+ }
2914
+ catch {
2915
+ // Not readable yet; the next read decides.
2916
+ }
2917
+ if (reads >= LAUNCH_OUTCOME_REREAD_MAX_READS)
2918
+ break;
2919
+ const pause = Math.min(LAUNCH_OUTCOME_REREAD_BACKOFF_MS[reads - 1] ?? 0, deadline - args.now());
2920
+ if (pause <= 0)
2921
+ break;
2922
+ await args.sleep(pause);
2923
+ }
2924
+ return { kind: "not_confirmed", reads };
2925
+ }
2926
+ /** The repository- and target-scoped command that reconnects to this epic's run. */
2927
+ export function launchReconnectCommand(epicKey, access) {
2928
+ return (`npx -y ${MCP_PACKAGE_NAME} drive-epic ${epicKey} --repo ${access.repoName} ` +
2929
+ `--base-url ${access.baseUrl}`);
2930
+ }
2931
+ /** Record the governing facts of a server-stored policy on the workflow sink. */
2932
+ function recordStoredRunFacts(sink, storedPolicy) {
2933
+ const facts = readStoredRunFacts(storedPolicy);
2934
+ sink.parallelLimit = facts.parallelLimit;
2935
+ sink.runPosture = facts.runPosture;
2936
+ }
2256
2937
  /**
2257
2938
  * Run the whole `setup-epic` workflow and return its authoritative result.
2258
2939
  *
@@ -2270,6 +2951,13 @@ export async function runSetupEpicWorkflow(argv, overrides = {}, handoff) {
2270
2951
  ...(sink.runCreated !== undefined ? { runCreated: sink.runCreated } : {}),
2271
2952
  ...(sink.planStored !== undefined ? { planStored: sink.planStored } : {}),
2272
2953
  ...(sink.reusedExistingRun !== undefined ? { reusedExistingRun: sink.reusedExistingRun } : {}),
2954
+ ...(sink.parallelLimit !== undefined ? { parallelLimit: sink.parallelLimit } : {}),
2955
+ ...(sink.runPosture !== undefined ? { runPosture: sink.runPosture } : {}),
2956
+ ...(sink.launchOutcome !== undefined ? { launchOutcome: sink.launchOutcome } : {}),
2957
+ ...(sink.runStatus !== undefined ? { runStatus: sink.runStatus } : {}),
2958
+ ...(sink.observations !== undefined && sink.observations.length > 0
2959
+ ? { observations: [...sink.observations] }
2960
+ : {}),
2273
2961
  };
2274
2962
  }
2275
2963
  /**
@@ -2295,6 +2983,10 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2295
2983
  const opts = parsed.options;
2296
2984
  // With --json, stdout carries the single result object and nothing else.
2297
2985
  const say = opts.json ? deps.errorLog : deps.log;
2986
+ // BAPI-1593 — bookkeeping observations for the session tally, in order.
2987
+ const observe = (code, message) => {
2988
+ (runIdSink.observations ??= []).push({ code, message });
2989
+ };
2298
2990
  if (handoff && (handoff.access.baseUrl !== handoff.selection.baseUrl ||
2299
2991
  handoff.access.repoName !== handoff.selection.repoName ||
2300
2992
  (opts.baseUrl !== undefined && opts.baseUrl !== handoff.selection.baseUrl) ||
@@ -2369,6 +3061,44 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2369
3061
  selectedProfilePolicyPath = profileRead.profile.policyRef?.path;
2370
3062
  }
2371
3063
  }
3064
+ // --- `--parallel` preflight (BAPI-1581) ------------------------------------
3065
+ // Local only: the mode flags, the candidate file/profile policy, and the plan's
3066
+ // node count. It runs before the live-run read and before the BAPI-1510
3067
+ // attach-only return, so an ineligible request never reaches a request. It
3068
+ // judges the CANDIDATE creation policy; it never consults a stored run policy.
3069
+ const runParallelPreflight = async (profilePolicyPath) => {
3070
+ if (opts.parallel === undefined)
3071
+ return null;
3072
+ const candidatePath = opts.policyFile ?? profilePolicyPath;
3073
+ let candidatePolicy;
3074
+ if (candidatePath !== undefined) {
3075
+ if (pinnedLaunchPolicy !== undefined) {
3076
+ candidatePolicy = pinnedLaunchPolicy;
3077
+ }
3078
+ else {
3079
+ const candidateRead = await readSetupEpicPolicyFile(candidatePath, deps.readFile);
3080
+ if (!candidateRead.ok) {
3081
+ deps.errorLog(candidateRead.error);
3082
+ return 1;
3083
+ }
3084
+ candidatePolicy = candidateRead.policy;
3085
+ }
3086
+ }
3087
+ const candidateDeclaresBranch = candidatePolicy !== undefined &&
3088
+ ["base_branch", "baseBranch"].some((key) => candidatePolicy[key] !== undefined && candidatePolicy[key] !== null);
3089
+ const verdict = evaluateParallelPolicyPreflight({
3090
+ parallel: opts.parallel,
3091
+ attended: opts.attended,
3092
+ intoBase: opts.intoBase,
3093
+ ...(candidatePolicy !== undefined ? { filePolicy: candidatePolicy } : {}),
3094
+ featureBranch: resolveFeatureBranchSelection(opts, plan.nodes.length, candidateDeclaresBranch),
3095
+ });
3096
+ if (!verdict.ok) {
3097
+ deps.errorLog(verdict.message);
3098
+ return 1;
3099
+ }
3100
+ return null;
3101
+ };
2372
3102
  let observations;
2373
3103
  let existingRunId = null;
2374
3104
  let existingTicketReview;
@@ -2423,6 +3153,11 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2423
3153
  selectedProfilePolicyPath = "profile" in accessResult
2424
3154
  ? accessResult.profile?.policyRef?.path
2425
3155
  : undefined;
3156
+ {
3157
+ const parallelRefusal = await runParallelPreflight(selectedProfilePolicyPath);
3158
+ if (parallelRefusal !== null)
3159
+ return parallelRefusal;
3160
+ }
2426
3161
  // --- Step 0: pre-check ---------------------------------------------------
2427
3162
  // Never create on an ambiguous read. A wrong answer here mints a duplicate run.
2428
3163
  try {
@@ -2435,6 +3170,10 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2435
3170
  const existingPolicy = state?.epic_run?.policy_json;
2436
3171
  existingPolicyJson = existingPolicy ?? null;
2437
3172
  existingNotificationSink = state?.notification_sink ?? null;
3173
+ // BAPI-1581 — the live run's governing facts, captured the moment it resolves
3174
+ // so every later early return (attach-only, refusal, failure) still has them.
3175
+ if (existingRunId !== null)
3176
+ recordStoredRunFacts(runIdSink, existingPolicy);
2438
3177
  const existingBase = existingPolicy && typeof existingPolicy === "object"
2439
3178
  ? existingPolicy.base_branch
2440
3179
  : undefined;
@@ -2488,6 +3227,9 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2488
3227
  runIdSink.epicRunId = existingRunId;
2489
3228
  runIdSink.reusedExistingRun = true;
2490
3229
  say(`Run: reusing ${existingRunId} (status: ${existingStatus}); existing runs are unchanged`);
3230
+ const retainedNotice = retainedParallelLimitNotice(opts.parallel, runIdSink.parallelLimit ?? 1);
3231
+ if (retainedNotice !== null)
3232
+ say(retainedNotice);
2491
3233
  return 0;
2492
3234
  }
2493
3235
  // --- Read the policy file (still no network) ------------------------------
@@ -2536,12 +3278,17 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2536
3278
  // network and asks no question, so running it here is what makes `--local-only`
2537
3279
  // and an ordinary invocation report the same strategy for the same plan.
2538
3280
  const featureBranch = resolveFeatureBranchSelection(opts, plan.nodes.length, policyDeclaresBranch);
2539
- const branchStrategyLine = describeBranchStrategy(opts, featureBranch, policyDeclaresBranch,
3281
+ // BAPI-1601 — the strategy line states the COMPOSED auto-merge intent, so it is
3282
+ // built from the composed policy once that exists (below, on each path).
3283
+ const describeStrategy = (composed, epicBranch) => describeBranchStrategy(opts, featureBranch, policyDeclaresBranch,
2540
3284
  // `filePolicy` is set exactly when `--policy-file` was supplied, and a
2541
3285
  // supplied file supersedes composition entirely — so this is the same
2542
3286
  // predicate as "this command composes the policy", available here, several
2543
3287
  // statements before the gate resolves `requestedPolicy`.
2544
- filePolicy === undefined);
3288
+ filePolicy === undefined, resolveSetupEpicAutoMergeIntent(composed, {
3289
+ epicBranch,
3290
+ attended: opts.attended,
3291
+ }));
2545
3292
  // --- Consolidated policy preflight (BAPI-1054) ---------------------------
2546
3293
  // ONE gate, run BEFORE credential resolution and before any request, over the
2547
3294
  // whole flag-backed choice-set. It sits above the `--local-only` return
@@ -2570,6 +3317,25 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2570
3317
  // Nothing below this point is reachable without the network, and the whole
2571
3318
  // point of the flag is to not touch it — not even to resolve a credential.
2572
3319
  if (opts.localOnly) {
3320
+ {
3321
+ const parallelRefusal = await runParallelPreflight(selectedProfilePolicyPath);
3322
+ if (parallelRefusal !== null)
3323
+ return parallelRefusal;
3324
+ }
3325
+ // BAPI-1581 — the creation policy this launch would resolve LOCALLY (no merge
3326
+ // mode lookup), so an explicit limit shows up in the offline preview.
3327
+ // BAPI-1601 — through the one composition helper, with no resolved mode: an
3328
+ // explicit file mode survives, and an absent one stays absent offline.
3329
+ const localEpicBranch = resolveEffectiveFeatureBranch(featureBranch, policyGate.policy);
3330
+ const localCreationPolicy = composeSetupEpicCreatePolicy({
3331
+ policy: policyGate.policy,
3332
+ featureBranch: localEpicBranch,
3333
+ attended: opts.attended,
3334
+ reviewPolicy: opts.reviewPolicy,
3335
+ ...(opts.verificationHandoff !== undefined ? { verificationHandoff: opts.verificationHandoff } : {}),
3336
+ ...(opts.parallel !== undefined ? { parallel: opts.parallel } : {}),
3337
+ });
3338
+ const branchStrategyLine = describeStrategy(localCreationPolicy, localEpicBranch);
2573
3339
  // The policy gate above already composed and validated; nothing is repeated
2574
3340
  // here, so the offline path and the real path refuse the same set.
2575
3341
  say(`Epic: ${opts.epicKey}`);
@@ -2596,7 +3362,13 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2596
3362
  server_validated: false,
2597
3363
  feature_branch: opts.intoBase ? null : resolveEffectiveFeatureBranch(featureBranch, policyGate.policy) ?? null,
2598
3364
  policy_applied: "absent",
2599
- effective_policy: effectivePolicyFacts(policyGate.policy, selectedPolicySource),
3365
+ effective_policy: {
3366
+ ...effectivePolicyFacts(policyGate.policy, selectedPolicySource),
3367
+ parallel_limit: effectivePolicyFacts(localCreationPolicy, selectedPolicySource).parallel_limit,
3368
+ },
3369
+ // BAPI-1601 — the four-key projection of the policy this launch would
3370
+ // compose locally; never the whole policy.
3371
+ create_policy: projectSetupEpicCreatePolicy(localCreationPolicy),
2600
3372
  warnings,
2601
3373
  }, null, 2));
2602
3374
  }
@@ -2607,7 +3379,8 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2607
3379
  // of any secondary policy detail, because it is the one decision that changes
2608
3380
  // where every child PR lands — an operator who reads nothing else must still
2609
3381
  // see which topology this run is about to bootstrap.
2610
- say(`Branch: ${branchStrategyLine}`);
3382
+ // BAPI-1601 — said below, once the policy is composed, so the strategy line can
3383
+ // state the composed auto-merge intent instead of guessing it from posture.
2611
3384
  // --- The requested run policy (BAPI-754; gated by BAPI-1054) -------------
2612
3385
  // Composition and every contradiction refusal already happened in the policy
2613
3386
  // preflight above, before credentials were resolved. This is the SAME object
@@ -2626,11 +3399,18 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2626
3399
  // and (for the file path) no `posture` already declared — so this never
2627
3400
  // performs the new configuration read for `--attended` or `--into-base` runs,
2628
3401
  // and never for a file that already answered the posture question itself.
3402
+ //
3403
+ // BAPI-1601: a file that DECLARES `posture: "unattended"` is eligible too — it
3404
+ // gets the same absent-key fills — and any explicit mode, an invalid one or
3405
+ // `null` included, answers the question itself and suppresses the read.
2629
3406
  const unattendedDefaultEligible = !opts.attended &&
2630
3407
  effectiveFeatureBranch !== undefined &&
2631
- (requestedPolicy === undefined || !("posture" in requestedPolicy));
3408
+ (requestedPolicy === undefined ||
3409
+ !("posture" in requestedPolicy) ||
3410
+ requestedPolicy.posture === SETUP_EPIC_UNATTENDED_POSTURE);
3411
+ const modeDeclaredByPolicy = requestedPolicy !== undefined && SETUP_EPIC_MERGE_EXECUTION_MODE_POLICY_KEY in requestedPolicy;
2632
3412
  let declaredMergeExecutionMode;
2633
- if (unattendedDefaultEligible) {
3413
+ if (unattendedDefaultEligible && !modeDeclaredByPolicy) {
2634
3414
  const mergeExecutionModeResolverDeps = {
2635
3415
  repoName: access.repoName,
2636
3416
  buildGetUrl: (path, params) => buildConductorJiraUrl(access.baseUrl, path, params),
@@ -2646,19 +3426,24 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2646
3426
  // only on the create branch below; the reuse branch reconciles the RAW file
2647
3427
  // against the run's stored policy, because adding a posture there would let
2648
3428
  // `--replace-policy` newly authorize auto-merge on a run that never had it.
2649
- const composedForCreate = requestedPolicy !== undefined
2650
- ? applySetupEpicUnattendedDefault(requestedPolicy, {
2651
- featureBranch: effectiveFeatureBranch,
2652
- attended: opts.attended,
2653
- mergeExecutionMode: declaredMergeExecutionMode,
2654
- })
2655
- : composeDefaultSetupEpicPolicy({
2656
- featureBranch,
2657
- attended: opts.attended,
2658
- reviewPolicy: opts.reviewPolicy,
2659
- mergeExecutionMode: declaredMergeExecutionMode,
2660
- ...(opts.verificationHandoff !== undefined ? { verificationHandoff: opts.verificationHandoff } : {}),
2661
- });
3429
+ //
3430
+ // BAPI-1601: ONE composition. The readiness preview, the dry-run projection,
3431
+ // both prerequisite evaluators, and the create request all read this object.
3432
+ const composedForCreate = composeSetupEpicCreatePolicy({
3433
+ policy: requestedPolicy,
3434
+ featureBranch: effectiveFeatureBranch,
3435
+ attended: opts.attended,
3436
+ reviewPolicy: opts.reviewPolicy,
3437
+ ...(declaredMergeExecutionMode !== undefined ? { mergeExecutionMode: declaredMergeExecutionMode } : {}),
3438
+ ...(opts.verificationHandoff !== undefined ? { verificationHandoff: opts.verificationHandoff } : {}),
3439
+ ...(opts.parallel !== undefined ? { parallel: opts.parallel } : {}),
3440
+ });
3441
+ const autoMergeIntent = resolveSetupEpicAutoMergeIntent(composedForCreate, {
3442
+ epicBranch: effectiveFeatureBranch,
3443
+ attended: opts.attended,
3444
+ });
3445
+ const branchStrategyLine = describeStrategy(composedForCreate, effectiveFeatureBranch);
3446
+ say(`Branch: ${branchStrategyLine}`);
2662
3447
  // Reuse the actual composition result; drive-epic never interprets policy files.
2663
3448
  let launchReadiness = null;
2664
3449
  if (!opts.localOnly) {
@@ -2675,7 +3460,8 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2675
3460
  }
2676
3461
  const selectedTicketReview = ticketReviewSummary(existingTicketReview, existingRunId !== null ? existingPolicyJson ?? {} : composedForCreate);
2677
3462
  const selectedEffectivePolicyFacts = effectivePolicyFacts(existingRunId !== null ? existingPolicyJson : composedForCreate, selectedPolicySource, existingRunId !== null ? existingNotificationSink : undefined);
2678
- say(`Policy: effective ${selectedEffectivePolicyFacts.source}; serial execution; ` +
3463
+ say(`Policy: effective ${selectedEffectivePolicyFacts.source}; parallel limit ` +
3464
+ `${selectedEffectivePolicyFacts.parallel_limit === "server_default" ? "server default" : selectedEffectivePolicyFacts.parallel_limit}; ` +
2679
3465
  `caps ${selectedEffectivePolicyFacts.caps ? JSON.stringify(selectedEffectivePolicyFacts.caps) : "unavailable"}; ` +
2680
3466
  `timeouts ${selectedEffectivePolicyFacts.job_timeouts ? JSON.stringify(selectedEffectivePolicyFacts.job_timeouts) : "unavailable"}; ` +
2681
3467
  `channel ${selectedEffectivePolicyFacts.escalation_channel}`);
@@ -2702,17 +3488,38 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2702
3488
  // path that could create an auto-merging run without ever printing that it
2703
3489
  // had — the exact thing this line exists to prevent. "Complete run policy"
2704
3490
  // is likewise no longer said when this command added the posture to it.
2705
- const inherited = composedForCreate !== requestedPolicy
2706
- ? "; UNATTENDED posture with auto-merge into the epic branch composed by " +
2707
- "default over a posture-silent file (the integration PR stays " +
2708
- "human-gated) — pass --attended to opt out"
2709
- : "";
3491
+ //
3492
+ // BAPI-1601: the wording follows the COMPOSED boolean, never the posture
3493
+ // alone, and a file that declared `unattended` is told which absent keys this
3494
+ // command filled (key names only — never a value).
3495
+ const composedAutoMerge = composedForCreate[SETUP_EPIC_AUTO_MERGE_POLICY_KEY];
3496
+ const composedAutoMergeWord = composedAutoMerge === true ? "on" : composedAutoMerge === false ? "off" : "not declared";
3497
+ const filledKeys = [
3498
+ SETUP_EPIC_AUTO_MERGE_POLICY_KEY,
3499
+ SETUP_EPIC_MERGE_EXECUTION_MODE_POLICY_KEY,
3500
+ SETUP_EPIC_INTEGRATION_PREPARATION_POLICY_KEY,
3501
+ ].filter((key) => key in composedForCreate && !(key in requestedPolicy));
3502
+ const inherited = !("posture" in requestedPolicy) && "posture" in composedForCreate
3503
+ ? `; UNATTENDED defaults composed over a posture-silent file (auto-merge ` +
3504
+ `${composedAutoMergeWord}; the integration PR stays human-gated) — ` +
3505
+ "pass --attended to opt out"
3506
+ : requestedPolicy.posture === SETUP_EPIC_UNATTENDED_POSTURE && filledKeys.length > 0
3507
+ ? `; absent unattended defaults filled in: ${filledKeys.join(", ")} ` +
3508
+ `(auto-merge ${composedAutoMergeWord}; the integration PR stays human-gated)`
3509
+ : "";
2710
3510
  const shape = inherited === "" ? "complete run policy" : "run policy";
2711
3511
  // BAPI-1397 (F1): the RESOLVED path and source — `opts.policyFile` is
2712
3512
  // undefined for a profile-selected or composed policy.
2713
3513
  say(`Policy: ${describeSelectedPolicy(selectedPolicyPath, policyLabelSource)} ` +
2714
3514
  `(${shape}, applied at creation${inherited})`);
2715
3515
  }
3516
+ // BAPI-1601 — labeled INTENT: a create race can still adopt another run, whose
3517
+ // stored policy is the one that governs. Printed only for a run this command is
3518
+ // about to create; a reused run's policy is reconciled, not composed.
3519
+ if (existingRunId === null) {
3520
+ const intentLine = formatSetupEpicAutoMergeIntent(autoMergeIntent, effectiveFeatureBranch);
3521
+ say(`Intent: ${intentLine ?? "Auto-merge: unavailable (the policy does not declare a valid auto-merge setting)"}`);
3522
+ }
2716
3523
  if (effectiveFeatureBranch !== undefined && featureBranch === undefined) {
2717
3524
  say(`Feature: ${effectiveFeatureBranch} (from the policy file; cut on origin with local ` +
2718
3525
  `git at the canonical indexed commit; validated server-side at approval)`);
@@ -2733,7 +3540,14 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2733
3540
  // BAPI-1496 — the hand-off flags compose a NEW run's policy only. A live run's
2734
3541
  // policy changes through `patch-policy`; reusing it here would either drop the
2735
3542
  // owner's answer silently or patch a live run behind the operator's back.
2736
- if (existingRunId && opts.verificationHandoff !== undefined) {
3543
+ if (existingRunId &&
3544
+ opts.verificationHandoff !== undefined &&
3545
+ storedVerificationHandoffMatches(existingPolicyJson, opts.verificationHandoff)) {
3546
+ // BAPI-1585 — an idempotent re-run: the flag repeats what the live run already
3547
+ // holds, so there is nothing to patch and nothing to refuse.
3548
+ say("Handoff: --verification-handoff matches the stored policy.");
3549
+ }
3550
+ else if (existingRunId && opts.verificationHandoff !== undefined) {
2737
3551
  deps.errorLog(`Epic ${opts.epicKey} already has a live run (${existingRunId}). --verification-handoff ` +
2738
3552
  "sets the policy of a NEW run only. Change a live run's verification hand-off with " +
2739
3553
  "`epic-implementer patch-policy`, or re-run without --verification-handoff to reuse it.");
@@ -2805,51 +3619,57 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2805
3619
  // BAPI-1027 — the evidence the successful validation was given, carried onto
2806
3620
  // the later store call so both lanes judge the plan against the same facts.
2807
3621
  let trackedPathEvidence;
3622
+ // BAPI-1595 — every launch validates, preview-delegated or not. The stored preview
3623
+ // snapshot cannot bind the launched plan (the server's plan digest is not
3624
+ // recomputable locally), and create runs before store, so skipping would let an
3625
+ // invalid or edited plan take a run row and the automation-start charge first.
2808
3626
  try {
2809
- validated = await validateEpicPlan(access, {
2810
- planVersion: plan.plan_version,
2811
- planBlob: plan,
2812
- epicKey: opts.epicKey,
2813
- }, deps.fetch);
2814
- // BAPI-1027 — phase two of the two-phase exchange. The server names the
2815
- // cited-document paths it could not resolve; only THEN does the CLI touch
2816
- // git, and only for those exact paths. The rules stay server-side: the CLI
2817
- // supplies facts and never decides whether a plan passes.
2818
- //
2819
- // Skipped entirely when the first response already carries blocking
2820
- // rejections. Those are unrelated to trackedness, the plan is going to be
2821
- // refused either way, and running git plus a second billable-free round trip
2822
- // to enrich a verdict that will not change is pure latency.
2823
- const unresolved = unresolvedCitedDocPaths(validated);
2824
- if (validated.rejections.length === 0 && unresolved.length > 0) {
2825
- const oracleRun = deps.runCommand;
2826
- if (!oracleRun) {
2827
- deps.errorLog(`Validation could not be completed: ${unresolved.length} cited document ` +
2828
- `path(s) need a git trackedness check, but no local command runner is ` +
2829
- `available in this environment. No run was created and no ` +
2830
- `automation-start charge occurred.`);
2831
- return 1;
2832
- }
2833
- const resolution = await resolveTrackedPaths(deps.cwd, unresolved, {
2834
- runCommand: oracleRun,
2835
- });
2836
- if (!resolution.ok) {
2837
- // An unresolved oracle is "validation could not be completed", NEVER
2838
- // "these documents are missing". Continuing would store a plan whose
2839
- // citations were never checked while reporting a clean preflight.
2840
- deps.errorLog(`Validation could not be completed: the cited documents in this plan ` +
2841
- `could not be checked against version control.\n${resolution.error}\n` +
2842
- `No run was created and no automation-start charge occurred. Re-run ` +
2843
- `from inside the repository working tree once git is available.`);
2844
- return 1;
2845
- }
2846
- trackedPathEvidence = resolution.facts;
3627
+ {
2847
3628
  validated = await validateEpicPlan(access, {
2848
3629
  planVersion: plan.plan_version,
2849
3630
  planBlob: plan,
2850
3631
  epicKey: opts.epicKey,
2851
- trackedPaths: trackedPathEvidence,
2852
3632
  }, deps.fetch);
3633
+ // BAPI-1027 — phase two of the two-phase exchange. The server names the
3634
+ // cited-document paths it could not resolve; only THEN does the CLI touch
3635
+ // git, and only for those exact paths. The rules stay server-side: the CLI
3636
+ // supplies facts and never decides whether a plan passes.
3637
+ //
3638
+ // Skipped entirely when the first response already carries blocking
3639
+ // rejections. Those are unrelated to trackedness, the plan is going to be
3640
+ // refused either way, and running git plus a second billable-free round trip
3641
+ // to enrich a verdict that will not change is pure latency.
3642
+ const unresolved = unresolvedCitedDocPaths(validated);
3643
+ if (validated.rejections.length === 0 && unresolved.length > 0) {
3644
+ const oracleRun = deps.runCommand;
3645
+ if (!oracleRun) {
3646
+ deps.errorLog(`Validation could not be completed: ${unresolved.length} cited document ` +
3647
+ `path(s) need a git trackedness check, but no local command runner is ` +
3648
+ `available in this environment. No run was created and no ` +
3649
+ `automation-start charge occurred.`);
3650
+ return 1;
3651
+ }
3652
+ const resolution = await resolveTrackedPaths(deps.cwd, unresolved, {
3653
+ runCommand: oracleRun,
3654
+ });
3655
+ if (!resolution.ok) {
3656
+ // An unresolved oracle is "validation could not be completed", NEVER
3657
+ // "these documents are missing". Continuing would store a plan whose
3658
+ // citations were never checked while reporting a clean preflight.
3659
+ deps.errorLog(`Validation could not be completed: the cited documents in this plan ` +
3660
+ `could not be checked against version control.\n${resolution.error}\n` +
3661
+ `No run was created and no automation-start charge occurred. Re-run ` +
3662
+ `from inside the repository working tree once git is available.`);
3663
+ return 1;
3664
+ }
3665
+ trackedPathEvidence = resolution.facts;
3666
+ validated = await validateEpicPlan(access, {
3667
+ planVersion: plan.plan_version,
3668
+ planBlob: plan,
3669
+ epicKey: opts.epicKey,
3670
+ trackedPaths: trackedPathEvidence,
3671
+ }, deps.fetch);
3672
+ }
2853
3673
  }
2854
3674
  }
2855
3675
  catch (err) {
@@ -2965,9 +3785,8 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2965
3785
  say(` coverage: ${validated.coverageScope}`);
2966
3786
  if (validated.undeclaredNodes > 0 || validated.undeclaredPairsSkipped > 0) {
2967
3787
  deps.errorLog(`WARNING: ${validated.undeclaredNodes} node(s) declared no touched_files, so ` +
2968
- `${validated.undeclaredPairsSkipped} pair(s) were never evaluated. Serialization ` +
2969
- `proves ordering only for paths BOTH nodes declared — it cannot show that these ` +
2970
- `tickets will avoid each other.`);
3788
+ `${validated.undeclaredPairsSkipped} pair(s) were never evaluated. Ordering is ` +
3789
+ `reported only for paths BOTH nodes declared.`);
2971
3790
  }
2972
3791
  }
2973
3792
  }
@@ -3078,6 +3897,9 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3078
3897
  server_validated: validated !== null,
3079
3898
  policy_applied: "absent",
3080
3899
  effective_policy: selectedEffectivePolicyFacts,
3900
+ // BAPI-1601 — the four-key projection: the stored policy for a reused
3901
+ // run, the composed one for a prospective create. Never the whole policy.
3902
+ create_policy: projectSetupEpicCreatePolicy(existingRunId !== null ? existingPolicyJson : composedForCreate),
3081
3903
  launch_readiness: launchReadiness,
3082
3904
  ticket_review: selectedTicketReview,
3083
3905
  ...(validated
@@ -3178,10 +4000,15 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3178
4000
  notificationSink: existingNotificationSink,
3179
4001
  requestedPolicy,
3180
4002
  replacePolicy: opts.replacePolicy,
4003
+ runIdSink,
4004
+ epicKey: opts.epicKey,
3181
4005
  });
3182
4006
  if (!outcome)
3183
4007
  return emitRefusal(deps, opts, result);
3184
4008
  }
4009
+ const retainedNotice = retainedParallelLimitNotice(opts.parallel, runIdSink.parallelLimit ?? 1);
4010
+ if (retainedNotice !== null)
4011
+ say(retainedNotice);
3185
4012
  }
3186
4013
  else {
3187
4014
  // --- BAPI-1102: the pre-create unattended prerequisite gate -------------
@@ -3207,28 +4034,67 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3207
4034
  // EVERY create — attended included — because the bring-up gate below applies
3208
4035
  // to every run. Before any create request, manifest binding, or lane.
3209
4036
  {
3210
- let readiness = null;
3211
- try {
3212
- readiness = await fetchConductorReadiness(access, deps.fetch);
3213
- }
3214
- catch (err) {
4037
+ // BAPI-1593 — ONE acquisition per launch: drive-epic hands its settled
4038
+ // result over (an `unknown` one included), and only standalone setup reads.
4039
+ //
4040
+ // BAPI-1595 — a launch delegated from drive-epic after a preview reads NOTHING
4041
+ // here: the preview owns acquisition, and the launch-context snapshot (or its
4042
+ // absence) travels in the handoff. Only a standalone `setup-epic`, with no
4043
+ // preview hand-off, keeps its own bounded acquisition.
4044
+ const delegatedToPreview = handoff?.readinessDisposition === "preview_handoff";
4045
+ const acquired = delegatedToPreview
4046
+ ? null
4047
+ : handoff?.readiness ??
4048
+ (await acquireConductorReadiness(() => fetchConductorReadiness(access, deps.fetch), {
4049
+ ...(deps.sleep !== undefined ? { sleep: deps.sleep } : {}),
4050
+ onRetry: (reason) => observe("readiness_read_retried", `readiness read uncertain (${reason}); retrying once`),
4051
+ }));
4052
+ if (acquired?.kind === "refused") {
3215
4053
  // BAPI-1455 — the one readable refusal: a proven-incompatible local
3216
4054
  // schema. Its explanation is server-authored from a maintained list.
3217
- if (isSchemaIncompatibleError(err)) {
3218
- deps.errorLog(formatSchemaIncompatibleRefusal("setup-epic", err).join("\n"));
3219
- return 1;
4055
+ runIdSink.launchOutcome = "refused";
4056
+ deps.errorLog(formatSchemaIncompatibleRefusal("setup-epic", acquired.error).join("\n"));
4057
+ return 1;
4058
+ }
4059
+ // The evidence every evaluator reads: the full report (standalone), the
4060
+ // narrow snapshot (delegated), or nothing (unknown — each evaluator warns).
4061
+ const readiness = delegatedToPreview
4062
+ ? (handoff?.launchEvidence ?? null)
4063
+ : acquired?.kind === "ready"
4064
+ ? acquired.readiness
4065
+ : null;
4066
+ if (!delegatedToPreview && readiness === null) {
4067
+ // BAPI-1593 — unknown readiness is bookkeeping, not proven harm (design
4068
+ // principle Context 5). The server's create and approve still enforce
4069
+ // every prerequisite these client copies mirror, so the launch warns and
4070
+ // continues to them. A READABLE report that proves a problem still
4071
+ // refuses below, exactly as before.
4072
+ // A handed-over result was already warned about by the caller.
4073
+ warnings.push(READINESS_UNKNOWN_CONTINUING_WARNING);
4074
+ if (handoff?.readiness === undefined) {
4075
+ observe("readiness_unknown_continued", READINESS_UNKNOWN_CONTINUING_WARNING);
4076
+ say(`Readiness: [warn] ${READINESS_UNKNOWN_CONTINUING_WARNING}`);
3220
4077
  }
3221
- // Fail CLOSED, and silently as to WHY: the thrown value can carry a URL
3222
- // or a response excerpt, and this refusal is rendered to a terminal. The
3223
- // generic `readiness_unreadable` message says what to do about it.
3224
- readiness = null;
3225
4078
  }
4079
+ // BAPI-1595 — an evaluator that finds its evidence unestablished returns a
4080
+ // warning, never a refusal. Each warning is said once and tallied under its
4081
+ // stable reason code; the launch continues.
4082
+ const warnOnce = (outcome) => {
4083
+ if (warnings.includes(outcome.message))
4084
+ return;
4085
+ warnings.push(outcome.message);
4086
+ observe(outcome.code, outcome.message);
4087
+ say(`Readiness: [warn] ${outcome.message}`);
4088
+ };
3226
4089
  // Bring-up first: a behind database or a missing worker makes the
3227
4090
  // unattended questions moot, and refusing on the cheaper, universal fact
3228
4091
  // keeps the first-named blocker the same for attended and unattended runs.
3229
- const bringUpRefusal = evaluateSetupEpicBringUpPrerequisites(readiness);
3230
- if (bringUpRefusal !== null) {
3231
- deps.errorLog(`setup-epic REFUSED (${bringUpRefusal.reason}): ${bringUpRefusal.message}`);
4092
+ const bringUp = evaluateSetupEpicBringUpPrerequisites(readiness);
4093
+ if (isSetupEpicPrerequisiteWarning(bringUp)) {
4094
+ warnOnce(bringUp);
4095
+ }
4096
+ else if (bringUp !== null) {
4097
+ deps.errorLog(`setup-epic REFUSED (${bringUp.reason}): ${bringUp.message}`);
3232
4098
  return 1;
3233
4099
  }
3234
4100
  // BAPI-1135 — merge-execution eligibility, AFTER the universal bring-up
@@ -3241,18 +4107,29 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3241
4107
  // `--attended` run that declares `github_actions` mode is gated too. The
3242
4108
  // evaluator itself returns null for every policy that does not declare the
3243
4109
  // mode, so no other run's behavior changes.
3244
- const mergeExecutionRefusal = evaluateSetupEpicMergeExecutionPrerequisites(readiness, composedForCreate);
3245
- if (mergeExecutionRefusal !== null) {
3246
- deps.errorLog(`setup-epic REFUSED (${mergeExecutionRefusal.reason}): ${mergeExecutionRefusal.message}`);
4110
+ const mergeExecution = evaluateSetupEpicMergeExecutionPrerequisites(readiness, composedForCreate);
4111
+ if (isSetupEpicPrerequisiteWarning(mergeExecution)) {
4112
+ warnOnce(mergeExecution);
4113
+ }
4114
+ else if (mergeExecution !== null) {
4115
+ deps.errorLog(`setup-epic REFUSED (${mergeExecution.reason}): ${mergeExecution.message}`);
3247
4116
  return 1;
3248
4117
  }
4118
+ // BAPI-1601 — said once, then the launch continues to the ordinary create
4119
+ // boundary, where the server enforces what this client could not check.
4120
+ if (mergeExecutionCheckUnrunLocally(readiness, composedForCreate)) {
4121
+ say(SETUP_EPIC_MERGE_CHECK_NOT_RUN_LOCALLY);
4122
+ }
3249
4123
  if (requestedPolicyIsUnattended(composedForCreate, opts.attended)) {
3250
4124
  // The COMPOSED policy, not the flags: a --policy-file declaring
3251
4125
  // notify.webhook_url satisfies the escalation-channel prerequisite, and
3252
4126
  // it is the same object the create request carries.
3253
- const refusal = evaluateSetupEpicUnattendedPrerequisites(readiness, composedForCreate);
3254
- if (refusal !== null) {
3255
- deps.errorLog(`setup-epic REFUSED (${refusal.reason}): ${refusal.message}`);
4127
+ const unattended = evaluateSetupEpicUnattendedPrerequisites(readiness, composedForCreate);
4128
+ if (isSetupEpicPrerequisiteWarning(unattended)) {
4129
+ warnOnce(unattended);
4130
+ }
4131
+ else if (unattended !== null) {
4132
+ deps.errorLog(`setup-epic REFUSED (${unattended.reason}): ${unattended.message}`);
3256
4133
  return 1;
3257
4134
  }
3258
4135
  }
@@ -3282,13 +4159,39 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3282
4159
  const createRequest = Object.keys(policyJson).length > 0 || requestedPolicy !== undefined
3283
4160
  ? { epicKey: opts.epicKey, policyJson }
3284
4161
  : { epicKey: opts.epicKey };
3285
- const { run, created } = await createEpicRunWithDisposition(access, createRequest, deps.fetch);
4162
+ let createResponse;
4163
+ try {
4164
+ createResponse = await createEpicRunWithDisposition(access, createRequest, deps.fetch);
4165
+ }
4166
+ catch (createErr) {
4167
+ if (!(createErr instanceof ConductorMutationOutcomeUnknownError))
4168
+ throw createErr;
4169
+ // BAPI-1593 — the create may have been applied. Re-read by epic key (the
4170
+ // server resolves the single live run); the POST is never sent again.
4171
+ const recovered = await recoverUncertainCreate({
4172
+ access,
4173
+ deps,
4174
+ say,
4175
+ observe,
4176
+ result,
4177
+ runIdSink,
4178
+ opts,
4179
+ uncertainty: createErr.uncertainty,
4180
+ });
4181
+ if (recovered.kind === "exit")
4182
+ return recovered.exitCode;
4183
+ createResponse = { run: recovered.run, created: true };
4184
+ }
4185
+ const { run, created } = createResponse;
3286
4186
  result.epic_run_id = run.epic_run_id;
3287
4187
  // BAPI-1102 — the create path's authoritative id. `createEpicRunWithDisposition`
3288
4188
  // returns the server's run for a fresh creation AND for a create-race
3289
4189
  // adoption (`created: false`), so both are captured by this one assignment.
3290
4190
  runIdSink.epicRunId = run.epic_run_id;
3291
4191
  runIdSink.runCreated = created;
4192
+ // BAPI-1581 — read from the returned run (fresh creation AND race adoption),
4193
+ // never from the request, before the two cases branch.
4194
+ recordStoredRunFacts(runIdSink, run.policy_json);
3292
4195
  result.status = run.status;
3293
4196
  result.run_created = created;
3294
4197
  if (created) {
@@ -3315,8 +4218,12 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3315
4218
  `\`epic-implementer abandon-run --epic-run-id ${run.epic_run_id}\` to start over.`);
3316
4219
  // BAPI-1510 — attach-only: a race-adopted run is never touched by a
3317
4220
  // trimmed launch (no policy replacement, cut, plan store, or approval).
3318
- if (handoff?.attachOnlyOnReuse === true)
4221
+ if (handoff?.attachOnlyOnReuse === true) {
4222
+ const attachNotice = retainedParallelLimitNotice(opts.parallel, runIdSink.parallelLimit ?? 1);
4223
+ if (attachNotice !== null)
4224
+ say(attachNotice);
3319
4225
  return 0;
4226
+ }
3320
4227
  if (requestedPolicy !== undefined) {
3321
4228
  const outcome = await applyReusedRunPolicy({
3322
4229
  access,
@@ -3327,10 +4234,15 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3327
4234
  storedPolicy: run.policy_json,
3328
4235
  requestedPolicy,
3329
4236
  replacePolicy: opts.replacePolicy,
4237
+ runIdSink,
4238
+ epicKey: opts.epicKey,
3330
4239
  });
3331
4240
  if (!outcome)
3332
4241
  return emitRefusal(deps, opts, result);
3333
4242
  }
4243
+ const retainedNotice = retainedParallelLimitNotice(opts.parallel, runIdSink.parallelLimit ?? 1);
4244
+ if (retainedNotice !== null)
4245
+ say(retainedNotice);
3334
4246
  }
3335
4247
  }
3336
4248
  catch (err) {
@@ -3355,7 +4267,20 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3355
4267
  `named field in the policy file and re-run.`);
3356
4268
  return 1;
3357
4269
  }
4270
+ // BAPI-1595 — the server's own pre-create launch refusals (BAPI-1585) are not
4271
+ // client copies. Show each as the SERVER's decision, with the harm it guards,
4272
+ // rather than as a transport failure.
4273
+ const serverHarm = err instanceof ConductorBridgeApiError && status === 409 && typeof err.errorCode === "string"
4274
+ ? SERVER_PRE_CREATE_REFUSAL_HARM[err.errorCode]
4275
+ : undefined;
4276
+ if (serverHarm !== undefined && err instanceof ConductorBridgeApiError) {
4277
+ deps.errorLog(`The server refused to create the run (${err.errorCode}).\n${errorDetail(err)}\n` +
4278
+ `Why it stops: ${serverHarm}\nNo run was created.`);
4279
+ runIdSink.launchOutcome = "refused";
4280
+ return 1;
4281
+ }
3358
4282
  deps.errorLog(`Failed to create the epic run: ${errorDetail(err)}`);
4283
+ runIdSink.launchOutcome = "refused";
3359
4284
  return 1;
3360
4285
  }
3361
4286
  }
@@ -3365,6 +4290,10 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3365
4290
  // of guessing from repository-wide active-run state (which risks stopping
3366
4291
  // the WRONG run). Absence of a local plane — remote runs, CI, any non-plane
3367
4292
  // workflow — is normal and produces neither an attempt nor a warning.
4293
+ // BAPI-1585 — true only when THIS run was bound (or already bound) to a live
4294
+ // plane, so the closing lines do not tell the operator to start an executor a
4295
+ // plane already provides. An attempted bind that failed leaves it false.
4296
+ let planeServesRun = false;
3368
4297
  if (deps.planeBinding) {
3369
4298
  try {
3370
4299
  const manifestRead = await deps.planeBinding.readManifest(deps.cwd);
@@ -3376,6 +4305,7 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3376
4305
  if (isLive) {
3377
4306
  const bound = await deps.planeBinding.bind(deps.cwd, manifest.planeId, result.epic_run_id);
3378
4307
  if (bound.ok) {
4308
+ planeServesRun = true;
3379
4309
  say(bound.alreadyBound
3380
4310
  ? `Plane: already bound to run ${result.epic_run_id}`
3381
4311
  : `Plane: bound to run ${result.epic_run_id} — \`plane down\` will stop it automatically`);
@@ -3523,8 +4453,13 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3523
4453
  if (effectiveFeatureBranch !== undefined) {
3524
4454
  say(`Branch: validating origin/${effectiveFeatureBranch} server-side (App read) and preparing the index scope…`);
3525
4455
  }
3526
- const approval = await approveEpicPlan(access, { epicKey: opts.epicKey, planVersion: plan.plan_version }, deps.fetch).catch((err) => {
3527
- if (effectiveFeatureBranch !== undefined &&
4456
+ let approvalUncertain = null;
4457
+ let approval = await approveEpicPlan(access, { epicKey: opts.epicKey, planVersion: plan.plan_version }, deps.fetch).catch((err) => {
4458
+ if (err instanceof ConductorMutationOutcomeUnknownError) {
4459
+ // BAPI-1593 — not a failure: re-read below, never re-send.
4460
+ approvalUncertain = err;
4461
+ }
4462
+ else if (effectiveFeatureBranch !== undefined &&
3528
4463
  err instanceof ConductorBridgeApiError &&
3529
4464
  err.errorCode === "FEATURE_BRANCH_PROVISIONING") {
3530
4465
  deps.errorLog(`Failed to provision the feature branch '${effectiveFeatureBranch}' — child-ticket ` +
@@ -3556,13 +4491,50 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3556
4491
  }
3557
4492
  return null;
3558
4493
  });
3559
- if (approval === null)
4494
+ if (approval === null && approvalUncertain !== null) {
4495
+ const recovered = await recoverUncertainApproval({
4496
+ access,
4497
+ deps,
4498
+ say,
4499
+ observe,
4500
+ result,
4501
+ runIdSink,
4502
+ opts,
4503
+ uncertainty: approvalUncertain.uncertainty,
4504
+ });
4505
+ if (recovered.kind === "exit")
4506
+ return recovered.exitCode;
4507
+ approval = { ok: true, plan_hash: recovered.planHash ?? localHash };
4508
+ }
4509
+ if (approval === null) {
4510
+ runIdSink.launchOutcome = "refused";
3560
4511
  return 1;
4512
+ }
3561
4513
  if (approval.ok) {
3562
4514
  result.plan_approved = true;
3563
4515
  result.plan_hash = approval.plan_hash;
3564
4516
  result.status = "active";
4517
+ runIdSink.launchOutcome = "active";
4518
+ runIdSink.runStatus = "active";
3565
4519
  say(`Plan: approved v${plan.plan_version}`);
4520
+ // BAPI-1601 — the server's own account of the auto-merge it stamped. Purely
4521
+ // observational: a missing or malformed stamp is "unknown" and never changes
4522
+ // the outcome, the exit code, or what is sent. A recovered approval (the
4523
+ // answer was lost and the run re-read) carries no stamp, so it reads unknown.
4524
+ const stamp = approval.gateProfileStamp ?? { autoMerge: "unknown", reasons: [] };
4525
+ result.auto_merge_stamp = { auto_merge: stamp.autoMerge, reasons: stamp.reasons };
4526
+ for (const line of describeSetupEpicAutoMergeStamp(stamp))
4527
+ say(line);
4528
+ // BAPI-1602 — a declared webhook that failed verification while live account
4529
+ // email carries escalations. A warning only: it never changes the outcome or
4530
+ // the exit code, and the run's channel stays the webhook.
4531
+ if (approval.escalationWarning !== undefined) {
4532
+ const text = approval.escalationWarning === "webhook_failed_email_available"
4533
+ ? READINESS_PREREQUISITE_FIXES.webhook_failed_email_available
4534
+ : `Escalation warning: ${approval.escalationWarning}.`;
4535
+ result.warnings.push(text);
4536
+ say(`Escalation: [warn] ${text}`);
4537
+ }
3566
4538
  const prov = approval.featureBranchProvisioning;
3567
4539
  if (prov) {
3568
4540
  result.feature_branch_provisioning = prov;
@@ -3578,9 +4550,28 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3578
4550
  }
3579
4551
  }
3580
4552
  }
4553
+ else if (approval.kind === "refused") {
4554
+ // BAPI-1585 — the server refused the approval for a real reason. Print the
4555
+ // closed tokens it gave (never a URL, host, or body) and stop. The run was
4556
+ // created and sits in 'planning' with no approved plan.
4557
+ say(`Plan: approval REFUSED (${approval.error_code}, predicate ${approval.predicate}, ` +
4558
+ `reason ${approval.reason_code})`);
4559
+ if (approval.predicate === "webhook") {
4560
+ say(`Remedy: start or fix the declared notify sink so it answers 2xx, or turn on ` +
4561
+ `live account email, then re-run setup-epic. Or launch with --attended.`);
4562
+ }
4563
+ result.approval_refusal = {
4564
+ error_code: approval.error_code,
4565
+ predicate: approval.predicate,
4566
+ reason_code: approval.reason_code,
4567
+ };
4568
+ runIdSink.launchOutcome = "refused";
4569
+ return emitRefusal(deps, opts, result);
4570
+ }
3581
4571
  else if (approval.reason === "multiple_active_runs") {
3582
4572
  deps.errorLog(`Epic ${opts.epicKey} has MULTIPLE active runs — the plan could not be approved ` +
3583
4573
  `and the epic is wedged. Abandon the duplicate run, then re-run setup-epic.`);
4574
+ runIdSink.launchOutcome = "refused";
3584
4575
  return 1;
3585
4576
  }
3586
4577
  else {
@@ -3720,6 +4711,9 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3720
4711
  if (handoff) {
3721
4712
  say("The launcher starts or reuses the executor appropriate for this run.");
3722
4713
  }
4714
+ else if (planeServesRun) {
4715
+ say("A plane serves this run; no separate executor is needed.");
4716
+ }
3723
4717
  else {
3724
4718
  say("To execute this run's claimed jobs on this machine, run:");
3725
4719
  say(` npx -y ${MCP_PACKAGE_NAME} executor --repo ${access.repoName} ` +