@bridge_gpt/mcp-server 0.2.72 → 0.2.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +15 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-config.js +7 -1
  5. package/build/bridge-permissions.js +30 -0
  6. package/build/ci-system-detection.js +50 -0
  7. package/build/ci-trigger-adapters.js +631 -0
  8. package/build/ci-trigger-install.js +106 -0
  9. package/build/codex-launcher-pin.js +33 -2
  10. package/build/codex-skill-adapter.js +3 -1
  11. package/build/command-host.js +33 -0
  12. package/build/command-provisioning.js +4 -3
  13. package/build/commands.generated.js +7 -6
  14. package/build/conductor/bridge-api-client.js +867 -35
  15. package/build/conductor/bring-up-facts.js +18 -5
  16. package/build/conductor/command-drift-production.js +42 -17
  17. package/build/conductor/command-drift.js +48 -1
  18. package/build/conductor/declare-blocked.js +554 -0
  19. package/build/conductor/declared-extras.js +335 -0
  20. package/build/conductor/doctor.js +108 -21
  21. package/build/conductor/driver-commands.js +141 -0
  22. package/build/conductor/driver-guard.js +277 -0
  23. package/build/conductor/driver-lapse.js +321 -0
  24. package/build/conductor/driver-pass-output.js +104 -0
  25. package/build/conductor/driver-pass.js +571 -0
  26. package/build/conductor/driver-register.js +176 -0
  27. package/build/conductor/driver-release.js +174 -0
  28. package/build/conductor/driver-session-state.js +315 -0
  29. package/build/conductor/epic-branch-ci-inspection.js +281 -43
  30. package/build/conductor/epic-implementer-cli.js +199 -15
  31. package/build/conductor/epic-server-database.js +162 -0
  32. package/build/conductor/epic-server-guidance.js +278 -0
  33. package/build/conductor/epic-server-journal.js +239 -0
  34. package/build/conductor/epic-server-processes.js +324 -0
  35. package/build/conductor/epic-server-recipe.js +397 -0
  36. package/build/conductor/epic-server-runtime.js +1207 -0
  37. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  38. package/build/conductor/epic-server-sfcc.js +85 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +647 -0
  41. package/build/conductor/gate-discovery.js +196 -11
  42. package/build/conductor/gate-settings-review.js +261 -4
  43. package/build/conductor/launch-need-probes.js +6 -53
  44. package/build/conductor/launch-plan.js +313 -156
  45. package/build/conductor/prerequisite-inputs.js +879 -45
  46. package/build/conductor/readiness-assessment.js +16 -1
  47. package/build/conductor/readiness-cli.js +20 -9
  48. package/build/conductor/readiness-prerequisites.js +28 -9
  49. package/build/conductor/readiness-sections.js +133 -126
  50. package/build/conductor/readiness.js +1 -1
  51. package/build/conductor/recovery-cli.js +13 -2
  52. package/build/conductor/tools.js +6 -5
  53. package/build/conductor/wait-run-attention.js +2 -2
  54. package/build/conductor/wait-run-cli.js +208 -22
  55. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  56. package/build/conductor/worker-setup-tally.js +27 -0
  57. package/build/credential-delivery.js +280 -0
  58. package/build/credential-launch-safety.js +142 -0
  59. package/build/credential-materialization.js +91 -16
  60. package/build/credential-references-node-deps.js +29 -0
  61. package/build/credential-references.js +1394 -0
  62. package/build/credential-references.test-fixtures.js +211 -0
  63. package/build/credential-scan-conventions.js +145 -0
  64. package/build/credential-scan.js +517 -0
  65. package/build/credential-store.js +121 -1
  66. package/build/credentials-cli.js +252 -3
  67. package/build/dependency-install-declarations.js +102 -1
  68. package/build/docs.generated.js +10 -3
  69. package/build/doctor.js +95 -3
  70. package/build/drive-epic-help.js +21 -2
  71. package/build/drive-epic.js +2095 -375
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +157 -0
  74. package/build/epic-capability-statement.js +175 -0
  75. package/build/epic-ci-workflow-drift.js +77 -23
  76. package/build/epic-ci-workflow-install.js +137 -44
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow-v3.js +273 -0
  79. package/build/epic-ci-workflow.js +165 -18
  80. package/build/epic-implementer-bin.js +2204 -56
  81. package/build/epic-launch-context.js +702 -0
  82. package/build/epic-server-record.js +288 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/completion-contract.js +8 -1
  87. package/build/executor/credential-delivery-step.js +168 -0
  88. package/build/executor/deps.js +3 -1
  89. package/build/executor/env.js +98 -23
  90. package/build/executor/epic-server-context.js +157 -0
  91. package/build/executor/gate-qualification-job.js +127 -26
  92. package/build/executor/guarded-fast-forward-push.js +13 -8
  93. package/build/executor/http-client.js +52 -5
  94. package/build/executor/job-runner.js +577 -81
  95. package/build/executor/observation.js +8 -0
  96. package/build/executor/permissions.js +85 -3
  97. package/build/executor/pre-pr-checks.js +363 -0
  98. package/build/executor/prompt-spec.js +149 -3
  99. package/build/executor/reconcile-overlap-job.js +5 -3
  100. package/build/executor/required-work-diagnostics.js +4 -2
  101. package/build/executor/required-work-ledger.js +936 -38
  102. package/build/executor/results.js +58 -0
  103. package/build/executor/terminal-mutation.js +8 -0
  104. package/build/executor/worker-command.js +72 -3
  105. package/build/executor/worker-database-config.js +281 -0
  106. package/build/executor/worker-database-target.js +16 -12
  107. package/build/executor/worker-database.js +320 -101
  108. package/build/executor/worker-finalization.js +7 -1
  109. package/build/executor/worker-resources.js +25 -3
  110. package/build/executor/worker-verification-guidance.js +18 -3
  111. package/build/executor/worktree.js +20 -1
  112. package/build/executor-launch.js +58 -4
  113. package/build/generated-assets-catalog.js +2 -2
  114. package/build/git-exclude-lock.js +187 -0
  115. package/build/index.js +824 -366
  116. package/build/init.js +26 -11
  117. package/build/install-bridge-conductor-answers.js +528 -0
  118. package/build/install-bridge-conductor-apply.js +288 -0
  119. package/build/install-bridge-conductor-assessment.js +1222 -0
  120. package/build/install-bridge-conductor-compact.js +186 -0
  121. package/build/install-bridge-conductor-contracts.js +72 -0
  122. package/build/install-bridge-conductor-gate.js +1312 -198
  123. package/build/install-bridge-conductor-setup.js +577 -83
  124. package/build/install-bridge-conductor.js +3381 -544
  125. package/build/install-bridge.js +280 -25
  126. package/build/install-doctor.js +38 -8
  127. package/build/install-maintenance.js +26 -3
  128. package/build/install-sfcc-detection.js +120 -0
  129. package/build/install-sfcc-setup.js +185 -0
  130. package/build/launcher-config-inspection.js +162 -1
  131. package/build/mcp-grant-candidates.js +779 -0
  132. package/build/mcp-grant-doctor.js +63 -0
  133. package/build/mcp-grant.js +288 -0
  134. package/build/mcp-host-targets.js +8 -0
  135. package/build/mcp-identity.js +23 -0
  136. package/build/mcp-invoke.js +292 -15
  137. package/build/mcp-presets.js +107 -0
  138. package/build/mcp-provisioning.js +155 -6
  139. package/build/mcp-registration-doctor.js +31 -2
  140. package/build/mcp-server-invocation.js +19 -1
  141. package/build/merge-workflow-install.js +243 -110
  142. package/build/pipelines.generated.js +7 -6
  143. package/build/plan-discovery.js +97 -4
  144. package/build/plan-execution-ledger.js +100 -7
  145. package/build/plan-generation-io.js +262 -0
  146. package/build/plan-generation.js +424 -0
  147. package/build/plane/build-freshness.js +6 -1
  148. package/build/plane/cli.js +75 -9
  149. package/build/plane/plane-freshness.js +17 -0
  150. package/build/plane/preflight.js +50 -10
  151. package/build/plane/shutdown.js +19 -0
  152. package/build/plane/status.js +8 -2
  153. package/build/plane/terminal-run-cleanup.js +18 -4
  154. package/build/printed-remedy-commands.js +211 -12
  155. package/build/project-root.js +40 -0
  156. package/build/readiness-check.js +77 -0
  157. package/build/readiness-prerequisites.generated.js +122 -14
  158. package/build/readme.generated.js +1 -1
  159. package/build/repository-state-paths.js +41 -0
  160. package/build/repository-toolchains.js +6 -3
  161. package/build/run-unit-tests-launcher.js +8 -1
  162. package/build/setup-epic.js +1305 -210
  163. package/build/setup-progress.js +44 -0
  164. package/build/setup-question.js +122 -4
  165. package/build/sfcc/credentials.js +3 -2
  166. package/build/sfcc/hostname.js +98 -2
  167. package/build/sfcc/tool-wrapper.js +6 -95
  168. package/build/start-tickets.js +193 -29
  169. package/build/test-support/executor-source-files.js +200 -0
  170. package/build/testing-config-client.js +25 -2
  171. package/build/third-party-mcp-targets.js +63 -2
  172. package/build/ticket-delivery-enrollment.js +9 -0
  173. package/build/upgrade-cli.js +85 -2
  174. package/build/v2-readiness-requirements.js +28 -1
  175. package/build/version.generated.js +3 -3
  176. package/build/with-credentials.js +208 -0
  177. package/build/worktree-credential-delivery.js +340 -0
  178. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  179. package/docs/epic-implementer/getting-started.md +3 -1
  180. package/docs/epic-implementer/self-hosting.md +14 -1
  181. package/package.json +2 -2
@@ -1,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.
1939
+ *
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.
1686
1946
  *
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.
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;
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;
1910
2263
  }
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;
1914
- }
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
+ }
2017
2553
  /**
2018
- * Emit the post-access refusal summary and the non-zero exit status.
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
+ }
2574
+ /**
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.
2023
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.
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));
@@ -2175,6 +2784,41 @@ export async function readCanonicalParseTruth(access, fetchImpl) {
2175
2784
  }
2176
2785
  return { ok: true, cutCommitSha: evidence.sourceCommitSha };
2177
2786
  }
2787
+ /**
2788
+ * Classify a remote epic branch against an authoritative target SHA. One decision,
2789
+ * shared by the preview and the create-time preflight.
2790
+ *
2791
+ * Remote reads and commit-object acquisition only: it reads the remote tip, makes
2792
+ * both commit objects resolvable locally with a read-only fetch by SHA, and
2793
+ * compares ancestry. It never updates a branch (local or remote), and it never
2794
+ * trusts a local `origin/{base}` tracking ref: the target is supplied by the caller.
2795
+ */
2796
+ export async function classifyRemoteEpicBranch(deps, branch, targetSha) {
2797
+ const unreadable = (tipSha, detail) => ({ status: "unknown", tipSha, detail });
2798
+ try {
2799
+ const head = await readRemoteBranchHead(deps, branch);
2800
+ if (!head.ok)
2801
+ return unreadable(null, head.error);
2802
+ if (head.sha === null)
2803
+ return { status: "absent" };
2804
+ const tipSha = head.sha;
2805
+ if (tipSha === targetSha)
2806
+ return { status: "at_target", tipSha };
2807
+ if (!(await ensureCommitResolvableLocally(deps, targetSha)) ||
2808
+ !(await ensureCommitResolvableLocally(deps, tipSha))) {
2809
+ return unreadable(tipSha, `Could not resolve origin/${branch} (${tipSha}) and ${targetSha} locally.`);
2810
+ }
2811
+ const ancestry = await runGit(deps, ["merge-base", "--is-ancestor", tipSha, targetSha]);
2812
+ if (ancestry.exitCode === 0)
2813
+ return { status: "behind_target", tipSha, targetSha };
2814
+ if (ancestry.exitCode === 1)
2815
+ return { status: "has_own_commits", tipSha, targetSha };
2816
+ return unreadable(tipSha, `Could not compare origin/${branch} (${tipSha}) with ${targetSha}.`);
2817
+ }
2818
+ catch {
2819
+ return unreadable(null, `Could not classify origin/${branch}.`);
2820
+ }
2821
+ }
2178
2822
  /** The strict subset of `SetupEpicDeps` the shared cut protocol consumes. */
2179
2823
  function cutProtocolDeps(deps, runCommand) {
2180
2824
  return {
@@ -2253,6 +2897,78 @@ function describeScopeTransition(state, status) {
2253
2897
  }
2254
2898
  return `Scope: ${label}…`;
2255
2899
  }
2900
+ /** BAPI-1593 — the warning an unknown readiness acquisition prints, verbatim. */
2901
+ export const READINESS_UNKNOWN_CONTINUING_WARNING = "readiness: unknown, continuing; approve decides";
2902
+ /**
2903
+ * BAPI-1595 — the harm each server-owned pre-create launch refusal guards, keyed by the
2904
+ * server's closed `error_code`. The server decides; this only names why it stops.
2905
+ */
2906
+ export const SERVER_PRE_CREATE_REFUSAL_HARM = {
2907
+ escalation_webhook_unreachable: "an unattended run whose declared webhook does not answer would lose its escalations.",
2908
+ provider_default_branch_unreadable: "the delivery and merge guards could not check the base branch.",
2909
+ };
2910
+ /** BAPI-1593 — the phrase every unconfirmed re-read prints. */
2911
+ export const OUTCOME_NOT_CONFIRMED_PHRASE = "outcome not confirmed";
2912
+ /** BAPI-1593 — the planning re-read line after an uncertain approval. */
2913
+ export const RUN_WAITING_FOR_APPROVAL_PHRASE = "the run exists and is waiting for approval";
2914
+ /** The one overall deadline for a launch-outcome re-read. */
2915
+ export const LAUNCH_OUTCOME_REREAD_DEADLINE_MS = 15_000;
2916
+ /** One immediate read plus at most two more. */
2917
+ export const LAUNCH_OUTCOME_REREAD_MAX_READS = 3;
2918
+ /** Pauses between re-reads, each capped to the time left. */
2919
+ const LAUNCH_OUTCOME_REREAD_BACKOFF_MS = [2_000, 4_000];
2920
+ const TERMINAL_RUN_STATUSES = new Set(["done", "abandoned"]);
2921
+ /**
2922
+ * BAPI-1593 — re-read a run after an uncertain create or approve.
2923
+ *
2924
+ * One immediate read, then at most two more, all inside ONE deadline: every GET
2925
+ * timeout and every pause is capped to the time left, and nothing is attempted
2926
+ * once it is spent. The first readable state ends it — this window confirms an
2927
+ * outcome, it does not wait for one. Any failed read (a 404 for a run not
2928
+ * visible yet included) is "not seen yet" and the next read is tried.
2929
+ *
2930
+ * `identifier` is the known run id, or the epic key when create returned none:
2931
+ * the server resolves an epic key to the repository's single non-terminal run,
2932
+ * so no run is ever selected client-side.
2933
+ */
2934
+ export async function rereadLaunchOutcome(args) {
2935
+ const deadline = args.now() + (args.deadlineMs ?? LAUNCH_OUTCOME_REREAD_DEADLINE_MS);
2936
+ let reads = 0;
2937
+ while (reads < LAUNCH_OUTCOME_REREAD_MAX_READS) {
2938
+ const remaining = deadline - args.now();
2939
+ if (remaining <= 0)
2940
+ break;
2941
+ reads += 1;
2942
+ try {
2943
+ const state = await args.readState(args.identifier, remaining);
2944
+ const run = state?.epic_run;
2945
+ if (run && typeof run.epic_run_id === "string" && run.epic_run_id !== "" && typeof run.status === "string") {
2946
+ return { kind: "read", run, reads };
2947
+ }
2948
+ }
2949
+ catch {
2950
+ // Not readable yet; the next read decides.
2951
+ }
2952
+ if (reads >= LAUNCH_OUTCOME_REREAD_MAX_READS)
2953
+ break;
2954
+ const pause = Math.min(LAUNCH_OUTCOME_REREAD_BACKOFF_MS[reads - 1] ?? 0, deadline - args.now());
2955
+ if (pause <= 0)
2956
+ break;
2957
+ await args.sleep(pause);
2958
+ }
2959
+ return { kind: "not_confirmed", reads };
2960
+ }
2961
+ /** The repository- and target-scoped command that reconnects to this epic's run. */
2962
+ export function launchReconnectCommand(epicKey, access) {
2963
+ return (`npx -y ${MCP_PACKAGE_NAME} drive-epic ${epicKey} --repo ${access.repoName} ` +
2964
+ `--base-url ${access.baseUrl}`);
2965
+ }
2966
+ /** Record the governing facts of a server-stored policy on the workflow sink. */
2967
+ function recordStoredRunFacts(sink, storedPolicy) {
2968
+ const facts = readStoredRunFacts(storedPolicy);
2969
+ sink.parallelLimit = facts.parallelLimit;
2970
+ sink.runPosture = facts.runPosture;
2971
+ }
2256
2972
  /**
2257
2973
  * Run the whole `setup-epic` workflow and return its authoritative result.
2258
2974
  *
@@ -2261,15 +2977,25 @@ function describeScopeTransition(state, status) {
2261
2977
  * same exit codes — and differs only in what it hands back.
2262
2978
  */
2263
2979
  export async function runSetupEpicWorkflow(argv, overrides = {}, handoff) {
2264
- const sink = {};
2980
+ const sink = { createRequestAttempted: false };
2265
2981
  const exitCode = await executeSetupEpic(argv, overrides, sink, handoff);
2266
2982
  return {
2267
2983
  exitCode,
2984
+ ...(exitCode !== 0 && sink.createRequestAttempted === false && sink.existingRunEstablished !== true &&
2985
+ sink.epicRunId === undefined ? { refusedBeforeCreate: true } : {}),
2986
+ ...(sink.branchMove !== undefined ? { branchMove: { ...sink.branchMove } } : {}),
2268
2987
  ...(sink.epicRunId !== undefined ? { epicRunId: sink.epicRunId } : {}),
2269
2988
  ...(sink.epicRunId !== undefined ? { runExists: true } : {}),
2270
2989
  ...(sink.runCreated !== undefined ? { runCreated: sink.runCreated } : {}),
2271
2990
  ...(sink.planStored !== undefined ? { planStored: sink.planStored } : {}),
2272
2991
  ...(sink.reusedExistingRun !== undefined ? { reusedExistingRun: sink.reusedExistingRun } : {}),
2992
+ ...(sink.parallelLimit !== undefined ? { parallelLimit: sink.parallelLimit } : {}),
2993
+ ...(sink.runPosture !== undefined ? { runPosture: sink.runPosture } : {}),
2994
+ ...(sink.launchOutcome !== undefined ? { launchOutcome: sink.launchOutcome } : {}),
2995
+ ...(sink.runStatus !== undefined ? { runStatus: sink.runStatus } : {}),
2996
+ ...(sink.observations !== undefined && sink.observations.length > 0
2997
+ ? { observations: [...sink.observations] }
2998
+ : {}),
2273
2999
  };
2274
3000
  }
2275
3001
  /**
@@ -2295,6 +3021,10 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2295
3021
  const opts = parsed.options;
2296
3022
  // With --json, stdout carries the single result object and nothing else.
2297
3023
  const say = opts.json ? deps.errorLog : deps.log;
3024
+ // BAPI-1593 — bookkeeping observations for the session tally, in order.
3025
+ const observe = (code, message) => {
3026
+ (runIdSink.observations ??= []).push({ code, message });
3027
+ };
2298
3028
  if (handoff && (handoff.access.baseUrl !== handoff.selection.baseUrl ||
2299
3029
  handoff.access.repoName !== handoff.selection.repoName ||
2300
3030
  (opts.baseUrl !== undefined && opts.baseUrl !== handoff.selection.baseUrl) ||
@@ -2369,6 +3099,44 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2369
3099
  selectedProfilePolicyPath = profileRead.profile.policyRef?.path;
2370
3100
  }
2371
3101
  }
3102
+ // --- `--parallel` preflight (BAPI-1581) ------------------------------------
3103
+ // Local only: the mode flags, the candidate file/profile policy, and the plan's
3104
+ // node count. It runs before the live-run read and before the BAPI-1510
3105
+ // attach-only return, so an ineligible request never reaches a request. It
3106
+ // judges the CANDIDATE creation policy; it never consults a stored run policy.
3107
+ const runParallelPreflight = async (profilePolicyPath) => {
3108
+ if (opts.parallel === undefined)
3109
+ return null;
3110
+ const candidatePath = opts.policyFile ?? profilePolicyPath;
3111
+ let candidatePolicy;
3112
+ if (candidatePath !== undefined) {
3113
+ if (pinnedLaunchPolicy !== undefined) {
3114
+ candidatePolicy = pinnedLaunchPolicy;
3115
+ }
3116
+ else {
3117
+ const candidateRead = await readSetupEpicPolicyFile(candidatePath, deps.readFile);
3118
+ if (!candidateRead.ok) {
3119
+ deps.errorLog(candidateRead.error);
3120
+ return 1;
3121
+ }
3122
+ candidatePolicy = candidateRead.policy;
3123
+ }
3124
+ }
3125
+ const candidateDeclaresBranch = candidatePolicy !== undefined &&
3126
+ ["base_branch", "baseBranch"].some((key) => candidatePolicy[key] !== undefined && candidatePolicy[key] !== null);
3127
+ const verdict = evaluateParallelPolicyPreflight({
3128
+ parallel: opts.parallel,
3129
+ attended: opts.attended,
3130
+ intoBase: opts.intoBase,
3131
+ ...(candidatePolicy !== undefined ? { filePolicy: candidatePolicy } : {}),
3132
+ featureBranch: resolveFeatureBranchSelection(opts, plan.nodes.length, candidateDeclaresBranch),
3133
+ });
3134
+ if (!verdict.ok) {
3135
+ deps.errorLog(verdict.message);
3136
+ return 1;
3137
+ }
3138
+ return null;
3139
+ };
2372
3140
  let observations;
2373
3141
  let existingRunId = null;
2374
3142
  let existingTicketReview;
@@ -2423,6 +3191,11 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2423
3191
  selectedProfilePolicyPath = "profile" in accessResult
2424
3192
  ? accessResult.profile?.policyRef?.path
2425
3193
  : undefined;
3194
+ {
3195
+ const parallelRefusal = await runParallelPreflight(selectedProfilePolicyPath);
3196
+ if (parallelRefusal !== null)
3197
+ return parallelRefusal;
3198
+ }
2426
3199
  // --- Step 0: pre-check ---------------------------------------------------
2427
3200
  // Never create on an ambiguous read. A wrong answer here mints a duplicate run.
2428
3201
  try {
@@ -2435,6 +3208,12 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2435
3208
  const existingPolicy = state?.epic_run?.policy_json;
2436
3209
  existingPolicyJson = existingPolicy ?? null;
2437
3210
  existingNotificationSink = state?.notification_sink ?? null;
3211
+ // BAPI-1581 — the live run's governing facts, captured the moment it resolves
3212
+ // so every later early return (attach-only, refusal, failure) still has them.
3213
+ if (existingRunId !== null) {
3214
+ recordStoredRunFacts(runIdSink, existingPolicy);
3215
+ runIdSink.existingRunEstablished = true;
3216
+ }
2438
3217
  const existingBase = existingPolicy && typeof existingPolicy === "object"
2439
3218
  ? existingPolicy.base_branch
2440
3219
  : undefined;
@@ -2488,6 +3267,9 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2488
3267
  runIdSink.epicRunId = existingRunId;
2489
3268
  runIdSink.reusedExistingRun = true;
2490
3269
  say(`Run: reusing ${existingRunId} (status: ${existingStatus}); existing runs are unchanged`);
3270
+ const retainedNotice = retainedParallelLimitNotice(opts.parallel, runIdSink.parallelLimit ?? 1);
3271
+ if (retainedNotice !== null)
3272
+ say(retainedNotice);
2491
3273
  return 0;
2492
3274
  }
2493
3275
  // --- Read the policy file (still no network) ------------------------------
@@ -2536,12 +3318,17 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2536
3318
  // network and asks no question, so running it here is what makes `--local-only`
2537
3319
  // and an ordinary invocation report the same strategy for the same plan.
2538
3320
  const featureBranch = resolveFeatureBranchSelection(opts, plan.nodes.length, policyDeclaresBranch);
2539
- const branchStrategyLine = describeBranchStrategy(opts, featureBranch, policyDeclaresBranch,
3321
+ // BAPI-1601 — the strategy line states the COMPOSED auto-merge intent, so it is
3322
+ // built from the composed policy once that exists (below, on each path).
3323
+ const describeStrategy = (composed, epicBranch) => describeBranchStrategy(opts, featureBranch, policyDeclaresBranch,
2540
3324
  // `filePolicy` is set exactly when `--policy-file` was supplied, and a
2541
3325
  // supplied file supersedes composition entirely — so this is the same
2542
3326
  // predicate as "this command composes the policy", available here, several
2543
3327
  // statements before the gate resolves `requestedPolicy`.
2544
- filePolicy === undefined);
3328
+ filePolicy === undefined, resolveSetupEpicAutoMergeIntent(composed, {
3329
+ epicBranch,
3330
+ attended: opts.attended,
3331
+ }));
2545
3332
  // --- Consolidated policy preflight (BAPI-1054) ---------------------------
2546
3333
  // ONE gate, run BEFORE credential resolution and before any request, over the
2547
3334
  // whole flag-backed choice-set. It sits above the `--local-only` return
@@ -2570,6 +3357,25 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2570
3357
  // Nothing below this point is reachable without the network, and the whole
2571
3358
  // point of the flag is to not touch it — not even to resolve a credential.
2572
3359
  if (opts.localOnly) {
3360
+ {
3361
+ const parallelRefusal = await runParallelPreflight(selectedProfilePolicyPath);
3362
+ if (parallelRefusal !== null)
3363
+ return parallelRefusal;
3364
+ }
3365
+ // BAPI-1581 — the creation policy this launch would resolve LOCALLY (no merge
3366
+ // mode lookup), so an explicit limit shows up in the offline preview.
3367
+ // BAPI-1601 — through the one composition helper, with no resolved mode: an
3368
+ // explicit file mode survives, and an absent one stays absent offline.
3369
+ const localEpicBranch = resolveEffectiveFeatureBranch(featureBranch, policyGate.policy);
3370
+ const localCreationPolicy = composeSetupEpicCreatePolicy({
3371
+ policy: policyGate.policy,
3372
+ featureBranch: localEpicBranch,
3373
+ attended: opts.attended,
3374
+ reviewPolicy: opts.reviewPolicy,
3375
+ ...(opts.verificationHandoff !== undefined ? { verificationHandoff: opts.verificationHandoff } : {}),
3376
+ ...(opts.parallel !== undefined ? { parallel: opts.parallel } : {}),
3377
+ });
3378
+ const branchStrategyLine = describeStrategy(localCreationPolicy, localEpicBranch);
2573
3379
  // The policy gate above already composed and validated; nothing is repeated
2574
3380
  // here, so the offline path and the real path refuse the same set.
2575
3381
  say(`Epic: ${opts.epicKey}`);
@@ -2596,7 +3402,13 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2596
3402
  server_validated: false,
2597
3403
  feature_branch: opts.intoBase ? null : resolveEffectiveFeatureBranch(featureBranch, policyGate.policy) ?? null,
2598
3404
  policy_applied: "absent",
2599
- effective_policy: effectivePolicyFacts(policyGate.policy, selectedPolicySource),
3405
+ effective_policy: {
3406
+ ...effectivePolicyFacts(policyGate.policy, selectedPolicySource),
3407
+ parallel_limit: effectivePolicyFacts(localCreationPolicy, selectedPolicySource).parallel_limit,
3408
+ },
3409
+ // BAPI-1601 — the four-key projection of the policy this launch would
3410
+ // compose locally; never the whole policy.
3411
+ create_policy: projectSetupEpicCreatePolicy(localCreationPolicy),
2600
3412
  warnings,
2601
3413
  }, null, 2));
2602
3414
  }
@@ -2607,7 +3419,8 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2607
3419
  // of any secondary policy detail, because it is the one decision that changes
2608
3420
  // where every child PR lands — an operator who reads nothing else must still
2609
3421
  // see which topology this run is about to bootstrap.
2610
- say(`Branch: ${branchStrategyLine}`);
3422
+ // BAPI-1601 — said below, once the policy is composed, so the strategy line can
3423
+ // state the composed auto-merge intent instead of guessing it from posture.
2611
3424
  // --- The requested run policy (BAPI-754; gated by BAPI-1054) -------------
2612
3425
  // Composition and every contradiction refusal already happened in the policy
2613
3426
  // preflight above, before credentials were resolved. This is the SAME object
@@ -2626,11 +3439,18 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2626
3439
  // and (for the file path) no `posture` already declared — so this never
2627
3440
  // performs the new configuration read for `--attended` or `--into-base` runs,
2628
3441
  // and never for a file that already answered the posture question itself.
3442
+ //
3443
+ // BAPI-1601: a file that DECLARES `posture: "unattended"` is eligible too — it
3444
+ // gets the same absent-key fills — and any explicit mode, an invalid one or
3445
+ // `null` included, answers the question itself and suppresses the read.
2629
3446
  const unattendedDefaultEligible = !opts.attended &&
2630
3447
  effectiveFeatureBranch !== undefined &&
2631
- (requestedPolicy === undefined || !("posture" in requestedPolicy));
3448
+ (requestedPolicy === undefined ||
3449
+ !("posture" in requestedPolicy) ||
3450
+ requestedPolicy.posture === SETUP_EPIC_UNATTENDED_POSTURE);
3451
+ const modeDeclaredByPolicy = requestedPolicy !== undefined && SETUP_EPIC_MERGE_EXECUTION_MODE_POLICY_KEY in requestedPolicy;
2632
3452
  let declaredMergeExecutionMode;
2633
- if (unattendedDefaultEligible) {
3453
+ if (unattendedDefaultEligible && !modeDeclaredByPolicy) {
2634
3454
  const mergeExecutionModeResolverDeps = {
2635
3455
  repoName: access.repoName,
2636
3456
  buildGetUrl: (path, params) => buildConductorJiraUrl(access.baseUrl, path, params),
@@ -2646,19 +3466,24 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2646
3466
  // only on the create branch below; the reuse branch reconciles the RAW file
2647
3467
  // against the run's stored policy, because adding a posture there would let
2648
3468
  // `--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
- });
3469
+ //
3470
+ // BAPI-1601: ONE composition. The readiness preview, the dry-run projection,
3471
+ // both prerequisite evaluators, and the create request all read this object.
3472
+ const composedForCreate = composeSetupEpicCreatePolicy({
3473
+ policy: requestedPolicy,
3474
+ featureBranch: effectiveFeatureBranch,
3475
+ attended: opts.attended,
3476
+ reviewPolicy: opts.reviewPolicy,
3477
+ ...(declaredMergeExecutionMode !== undefined ? { mergeExecutionMode: declaredMergeExecutionMode } : {}),
3478
+ ...(opts.verificationHandoff !== undefined ? { verificationHandoff: opts.verificationHandoff } : {}),
3479
+ ...(opts.parallel !== undefined ? { parallel: opts.parallel } : {}),
3480
+ });
3481
+ const autoMergeIntent = resolveSetupEpicAutoMergeIntent(composedForCreate, {
3482
+ epicBranch: effectiveFeatureBranch,
3483
+ attended: opts.attended,
3484
+ });
3485
+ const branchStrategyLine = describeStrategy(composedForCreate, effectiveFeatureBranch);
3486
+ say(`Branch: ${branchStrategyLine}`);
2662
3487
  // Reuse the actual composition result; drive-epic never interprets policy files.
2663
3488
  let launchReadiness = null;
2664
3489
  if (!opts.localOnly) {
@@ -2675,7 +3500,8 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2675
3500
  }
2676
3501
  const selectedTicketReview = ticketReviewSummary(existingTicketReview, existingRunId !== null ? existingPolicyJson ?? {} : composedForCreate);
2677
3502
  const selectedEffectivePolicyFacts = effectivePolicyFacts(existingRunId !== null ? existingPolicyJson : composedForCreate, selectedPolicySource, existingRunId !== null ? existingNotificationSink : undefined);
2678
- say(`Policy: effective ${selectedEffectivePolicyFacts.source}; serial execution; ` +
3503
+ say(`Policy: effective ${selectedEffectivePolicyFacts.source}; parallel limit ` +
3504
+ `${selectedEffectivePolicyFacts.parallel_limit === "server_default" ? "server default" : selectedEffectivePolicyFacts.parallel_limit}; ` +
2679
3505
  `caps ${selectedEffectivePolicyFacts.caps ? JSON.stringify(selectedEffectivePolicyFacts.caps) : "unavailable"}; ` +
2680
3506
  `timeouts ${selectedEffectivePolicyFacts.job_timeouts ? JSON.stringify(selectedEffectivePolicyFacts.job_timeouts) : "unavailable"}; ` +
2681
3507
  `channel ${selectedEffectivePolicyFacts.escalation_channel}`);
@@ -2702,17 +3528,38 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2702
3528
  // path that could create an auto-merging run without ever printing that it
2703
3529
  // had — the exact thing this line exists to prevent. "Complete run policy"
2704
3530
  // 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
- : "";
3531
+ //
3532
+ // BAPI-1601: the wording follows the COMPOSED boolean, never the posture
3533
+ // alone, and a file that declared `unattended` is told which absent keys this
3534
+ // command filled (key names only — never a value).
3535
+ const composedAutoMerge = composedForCreate[SETUP_EPIC_AUTO_MERGE_POLICY_KEY];
3536
+ const composedAutoMergeWord = composedAutoMerge === true ? "on" : composedAutoMerge === false ? "off" : "not declared";
3537
+ const filledKeys = [
3538
+ SETUP_EPIC_AUTO_MERGE_POLICY_KEY,
3539
+ SETUP_EPIC_MERGE_EXECUTION_MODE_POLICY_KEY,
3540
+ SETUP_EPIC_INTEGRATION_PREPARATION_POLICY_KEY,
3541
+ ].filter((key) => key in composedForCreate && !(key in requestedPolicy));
3542
+ const inherited = !("posture" in requestedPolicy) && "posture" in composedForCreate
3543
+ ? `; UNATTENDED defaults composed over a posture-silent file (auto-merge ` +
3544
+ `${composedAutoMergeWord}; the integration PR stays human-gated) — ` +
3545
+ "pass --attended to opt out"
3546
+ : requestedPolicy.posture === SETUP_EPIC_UNATTENDED_POSTURE && filledKeys.length > 0
3547
+ ? `; absent unattended defaults filled in: ${filledKeys.join(", ")} ` +
3548
+ `(auto-merge ${composedAutoMergeWord}; the integration PR stays human-gated)`
3549
+ : "";
2710
3550
  const shape = inherited === "" ? "complete run policy" : "run policy";
2711
3551
  // BAPI-1397 (F1): the RESOLVED path and source — `opts.policyFile` is
2712
3552
  // undefined for a profile-selected or composed policy.
2713
3553
  say(`Policy: ${describeSelectedPolicy(selectedPolicyPath, policyLabelSource)} ` +
2714
3554
  `(${shape}, applied at creation${inherited})`);
2715
3555
  }
3556
+ // BAPI-1601 — labeled INTENT: a create race can still adopt another run, whose
3557
+ // stored policy is the one that governs. Printed only for a run this command is
3558
+ // about to create; a reused run's policy is reconciled, not composed.
3559
+ if (existingRunId === null) {
3560
+ const intentLine = formatSetupEpicAutoMergeIntent(autoMergeIntent, effectiveFeatureBranch);
3561
+ say(`Intent: ${intentLine ?? "Auto-merge: unavailable (the policy does not declare a valid auto-merge setting)"}`);
3562
+ }
2716
3563
  if (effectiveFeatureBranch !== undefined && featureBranch === undefined) {
2717
3564
  say(`Feature: ${effectiveFeatureBranch} (from the policy file; cut on origin with local ` +
2718
3565
  `git at the canonical indexed commit; validated server-side at approval)`);
@@ -2733,7 +3580,14 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2733
3580
  // BAPI-1496 — the hand-off flags compose a NEW run's policy only. A live run's
2734
3581
  // policy changes through `patch-policy`; reusing it here would either drop the
2735
3582
  // owner's answer silently or patch a live run behind the operator's back.
2736
- if (existingRunId && opts.verificationHandoff !== undefined) {
3583
+ if (existingRunId &&
3584
+ opts.verificationHandoff !== undefined &&
3585
+ storedVerificationHandoffMatches(existingPolicyJson, opts.verificationHandoff)) {
3586
+ // BAPI-1585 — an idempotent re-run: the flag repeats what the live run already
3587
+ // holds, so there is nothing to patch and nothing to refuse.
3588
+ say("Handoff: --verification-handoff matches the stored policy.");
3589
+ }
3590
+ else if (existingRunId && opts.verificationHandoff !== undefined) {
2737
3591
  deps.errorLog(`Epic ${opts.epicKey} already has a live run (${existingRunId}). --verification-handoff ` +
2738
3592
  "sets the policy of a NEW run only. Change a live run's verification hand-off with " +
2739
3593
  "`epic-implementer patch-policy`, or re-run without --verification-handoff to reuse it.");
@@ -2805,51 +3659,57 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2805
3659
  // BAPI-1027 — the evidence the successful validation was given, carried onto
2806
3660
  // the later store call so both lanes judge the plan against the same facts.
2807
3661
  let trackedPathEvidence;
3662
+ // BAPI-1595 — every launch validates, preview-delegated or not. The stored preview
3663
+ // snapshot cannot bind the launched plan (the server's plan digest is not
3664
+ // recomputable locally), and create runs before store, so skipping would let an
3665
+ // invalid or edited plan take a run row and the automation-start charge first.
2808
3666
  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;
3667
+ {
2847
3668
  validated = await validateEpicPlan(access, {
2848
3669
  planVersion: plan.plan_version,
2849
3670
  planBlob: plan,
2850
3671
  epicKey: opts.epicKey,
2851
- trackedPaths: trackedPathEvidence,
2852
3672
  }, deps.fetch);
3673
+ // BAPI-1027 — phase two of the two-phase exchange. The server names the
3674
+ // cited-document paths it could not resolve; only THEN does the CLI touch
3675
+ // git, and only for those exact paths. The rules stay server-side: the CLI
3676
+ // supplies facts and never decides whether a plan passes.
3677
+ //
3678
+ // Skipped entirely when the first response already carries blocking
3679
+ // rejections. Those are unrelated to trackedness, the plan is going to be
3680
+ // refused either way, and running git plus a second billable-free round trip
3681
+ // to enrich a verdict that will not change is pure latency.
3682
+ const unresolved = unresolvedCitedDocPaths(validated);
3683
+ if (validated.rejections.length === 0 && unresolved.length > 0) {
3684
+ const oracleRun = deps.runCommand;
3685
+ if (!oracleRun) {
3686
+ deps.errorLog(`Validation could not be completed: ${unresolved.length} cited document ` +
3687
+ `path(s) need a git trackedness check, but no local command runner is ` +
3688
+ `available in this environment. No run was created and no ` +
3689
+ `automation-start charge occurred.`);
3690
+ return 1;
3691
+ }
3692
+ const resolution = await resolveTrackedPaths(deps.cwd, unresolved, {
3693
+ runCommand: oracleRun,
3694
+ });
3695
+ if (!resolution.ok) {
3696
+ // An unresolved oracle is "validation could not be completed", NEVER
3697
+ // "these documents are missing". Continuing would store a plan whose
3698
+ // citations were never checked while reporting a clean preflight.
3699
+ deps.errorLog(`Validation could not be completed: the cited documents in this plan ` +
3700
+ `could not be checked against version control.\n${resolution.error}\n` +
3701
+ `No run was created and no automation-start charge occurred. Re-run ` +
3702
+ `from inside the repository working tree once git is available.`);
3703
+ return 1;
3704
+ }
3705
+ trackedPathEvidence = resolution.facts;
3706
+ validated = await validateEpicPlan(access, {
3707
+ planVersion: plan.plan_version,
3708
+ planBlob: plan,
3709
+ epicKey: opts.epicKey,
3710
+ trackedPaths: trackedPathEvidence,
3711
+ }, deps.fetch);
3712
+ }
2853
3713
  }
2854
3714
  }
2855
3715
  catch (err) {
@@ -2965,9 +3825,8 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2965
3825
  say(` coverage: ${validated.coverageScope}`);
2966
3826
  if (validated.undeclaredNodes > 0 || validated.undeclaredPairsSkipped > 0) {
2967
3827
  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.`);
3828
+ `${validated.undeclaredPairsSkipped} pair(s) were never evaluated. Ordering is ` +
3829
+ `reported only for paths BOTH nodes declared.`);
2971
3830
  }
2972
3831
  }
2973
3832
  }
@@ -3078,6 +3937,9 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3078
3937
  server_validated: validated !== null,
3079
3938
  policy_applied: "absent",
3080
3939
  effective_policy: selectedEffectivePolicyFacts,
3940
+ // BAPI-1601 — the four-key projection: the stored policy for a reused
3941
+ // run, the composed one for a prospective create. Never the whole policy.
3942
+ create_policy: projectSetupEpicCreatePolicy(existingRunId !== null ? existingPolicyJson : composedForCreate),
3081
3943
  launch_readiness: launchReadiness,
3082
3944
  ticket_review: selectedTicketReview,
3083
3945
  ...(validated
@@ -3123,20 +3985,79 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3123
3985
  `created and no branch was changed.`);
3124
3986
  return 1;
3125
3987
  }
3126
- const remoteHead = await readRemoteBranchHead(gitDeps, effectiveFeatureBranch);
3127
- if (!remoteHead.ok) {
3128
- deps.errorLog(`${remoteHead.error} No run was created and no branch was changed.`);
3129
- return 1;
3988
+ if (existingRunId === null) {
3989
+ // A NEW run: classify the leftover branch against the exact cut.
3990
+ const branch = effectiveFeatureBranch;
3991
+ const classified = await classifyRemoteEpicBranch(gitDeps, branch, cutCommitSha);
3992
+ if (classified.status === "has_own_commits") {
3993
+ deps.errorLog(`origin/${branch} already exists at ${classified.tipSha} and holds commits that are not in ` +
3994
+ `the canonical indexed commit ${cutCommitSha}. setup-epic never force-updates an existing ` +
3995
+ `branch. Inspect it with: git log origin/${scopeBaseBranch}..origin/${branch}. ` +
3996
+ `Then finish that work, or delete the branch with: git push origin --delete ${branch}. ` +
3997
+ `No run was created and no branch was changed.`);
3998
+ return 1;
3999
+ }
4000
+ if (classified.status === "unknown") {
4001
+ deps.errorLog(classified.tipSha === null
4002
+ ? `${classified.detail} No run was created and no branch was changed.`
4003
+ : `origin/${branch} already exists at ${classified.tipSha}, and its relationship to the ` +
4004
+ `canonical indexed commit ${cutCommitSha} could not be established. setup-epic never ` +
4005
+ `force-updates an existing branch: delete it, or finish the previous run first. ` +
4006
+ `No run was created and no branch was changed.`);
4007
+ return 1;
4008
+ }
4009
+ if (classified.status === "behind_target") {
4010
+ // One plain push (no force, no leading '+'). Whatever it returns, the remote
4011
+ // is re-read once; only an exact match with the cut lets setup continue.
4012
+ try {
4013
+ await runGit(gitDeps, ["push", "origin", `${cutCommitSha}:refs/heads/${branch}`]);
4014
+ }
4015
+ catch { /* judged by the re-read below */ }
4016
+ let reread;
4017
+ try {
4018
+ reread = await readRemoteBranchHead(gitDeps, branch);
4019
+ }
4020
+ catch {
4021
+ reread = { ok: false, error: `git ls-remote could not read origin/${branch}.` };
4022
+ }
4023
+ if (!reread.ok || reread.sha !== cutCommitSha) {
4024
+ deps.errorLog(!reread.ok
4025
+ ? `Tried to move origin/${branch} from ${classified.tipSha} to the canonical indexed commit ` +
4026
+ `${cutCommitSha}, but could not read the branch afterwards. Check it with: ` +
4027
+ `git ls-remote origin refs/heads/${branch}. No run was created.`
4028
+ : reread.sha === null
4029
+ ? `Tried to move origin/${branch} to the canonical indexed commit ${cutCommitSha}, but the ` +
4030
+ `branch is now absent. No run was created.`
4031
+ : `Tried to move origin/${branch} to the canonical indexed commit ${cutCommitSha}, but it is ` +
4032
+ `now at ${reread.sha}. No run was created.`);
4033
+ return 1;
4034
+ }
4035
+ runIdSink.branchMove = { branch, from: classified.tipSha, to: cutCommitSha };
4036
+ say(`Branch: moved origin/${branch} from ${classified.tipSha} to the cut commit ${cutCommitSha}`);
4037
+ }
4038
+ else {
4039
+ say(classified.status === "absent"
4040
+ ? `Branch: origin/${branch} is absent; it will be cut at ${cutCommitSha}`
4041
+ : `Branch: origin/${branch} already sits at the cut commit ${cutCommitSha}`);
4042
+ }
3130
4043
  }
3131
- if (remoteHead.sha !== null && remoteHead.sha !== cutCommitSha) {
3132
- deps.errorLog(`origin/${effectiveFeatureBranch} already exists at ${remoteHead.sha}, which is not the ` +
3133
- `canonical indexed commit ${cutCommitSha}. setup-epic never force-updates an existing ` +
3134
- `branch: delete it, or finish the previous run first. No run was created and no branch was changed.`);
3135
- return 1;
4044
+ else {
4045
+ // A reused run keeps its prior cut validation unchanged: no branch is ever moved.
4046
+ const remoteHead = await readRemoteBranchHead(gitDeps, effectiveFeatureBranch);
4047
+ if (!remoteHead.ok) {
4048
+ deps.errorLog(`${remoteHead.error} No run was created and no branch was changed.`);
4049
+ return 1;
4050
+ }
4051
+ if (remoteHead.sha !== null && remoteHead.sha !== cutCommitSha) {
4052
+ deps.errorLog(`origin/${effectiveFeatureBranch} already exists at ${remoteHead.sha}, which is not the ` +
4053
+ `canonical indexed commit ${cutCommitSha}. setup-epic never force-updates an existing ` +
4054
+ `branch: delete it, or finish the previous run first. No run was created and no branch was changed.`);
4055
+ return 1;
4056
+ }
4057
+ say(remoteHead.sha === null
4058
+ ? `Branch: origin/${effectiveFeatureBranch} is absent; it will be cut at ${cutCommitSha}`
4059
+ : `Branch: origin/${effectiveFeatureBranch} already sits at the cut commit ${cutCommitSha}`);
3136
4060
  }
3137
- say(remoteHead.sha === null
3138
- ? `Branch: origin/${effectiveFeatureBranch} is absent; it will be cut at ${cutCommitSha}`
3139
- : `Branch: origin/${effectiveFeatureBranch} already sits at the cut commit ${cutCommitSha}`);
3140
4061
  }
3141
4062
  const result = {
3142
4063
  epic_run_id: existingRunId ?? "",
@@ -3178,10 +4099,15 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3178
4099
  notificationSink: existingNotificationSink,
3179
4100
  requestedPolicy,
3180
4101
  replacePolicy: opts.replacePolicy,
4102
+ runIdSink,
4103
+ epicKey: opts.epicKey,
3181
4104
  });
3182
4105
  if (!outcome)
3183
4106
  return emitRefusal(deps, opts, result);
3184
4107
  }
4108
+ const retainedNotice = retainedParallelLimitNotice(opts.parallel, runIdSink.parallelLimit ?? 1);
4109
+ if (retainedNotice !== null)
4110
+ say(retainedNotice);
3185
4111
  }
3186
4112
  else {
3187
4113
  // --- BAPI-1102: the pre-create unattended prerequisite gate -------------
@@ -3207,28 +4133,67 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3207
4133
  // EVERY create — attended included — because the bring-up gate below applies
3208
4134
  // to every run. Before any create request, manifest binding, or lane.
3209
4135
  {
3210
- let readiness = null;
3211
- try {
3212
- readiness = await fetchConductorReadiness(access, deps.fetch);
3213
- }
3214
- catch (err) {
4136
+ // BAPI-1593 — ONE acquisition per launch: drive-epic hands its settled
4137
+ // result over (an `unknown` one included), and only standalone setup reads.
4138
+ //
4139
+ // BAPI-1595 — a launch delegated from drive-epic after a preview reads NOTHING
4140
+ // here: the preview owns acquisition, and the launch-context snapshot (or its
4141
+ // absence) travels in the handoff. Only a standalone `setup-epic`, with no
4142
+ // preview hand-off, keeps its own bounded acquisition.
4143
+ const delegatedToPreview = handoff?.readinessDisposition === "preview_handoff";
4144
+ const acquired = delegatedToPreview
4145
+ ? null
4146
+ : handoff?.readiness ??
4147
+ (await acquireConductorReadiness(() => fetchConductorReadiness(access, deps.fetch), {
4148
+ ...(deps.sleep !== undefined ? { sleep: deps.sleep } : {}),
4149
+ onRetry: (reason) => observe("readiness_read_retried", `readiness read uncertain (${reason}); retrying once`),
4150
+ }));
4151
+ if (acquired?.kind === "refused") {
3215
4152
  // BAPI-1455 — the one readable refusal: a proven-incompatible local
3216
4153
  // 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;
4154
+ runIdSink.launchOutcome = "refused";
4155
+ deps.errorLog(formatSchemaIncompatibleRefusal("setup-epic", acquired.error).join("\n"));
4156
+ return 1;
4157
+ }
4158
+ // The evidence every evaluator reads: the full report (standalone), the
4159
+ // narrow snapshot (delegated), or nothing (unknown — each evaluator warns).
4160
+ const readiness = delegatedToPreview
4161
+ ? (handoff?.launchEvidence ?? null)
4162
+ : acquired?.kind === "ready"
4163
+ ? acquired.readiness
4164
+ : null;
4165
+ if (!delegatedToPreview && readiness === null) {
4166
+ // BAPI-1593 — unknown readiness is bookkeeping, not proven harm (design
4167
+ // principle Context 5). The server's create and approve still enforce
4168
+ // every prerequisite these client copies mirror, so the launch warns and
4169
+ // continues to them. A READABLE report that proves a problem still
4170
+ // refuses below, exactly as before.
4171
+ // A handed-over result was already warned about by the caller.
4172
+ warnings.push(READINESS_UNKNOWN_CONTINUING_WARNING);
4173
+ if (handoff?.readiness === undefined) {
4174
+ observe("readiness_unknown_continued", READINESS_UNKNOWN_CONTINUING_WARNING);
4175
+ say(`Readiness: [warn] ${READINESS_UNKNOWN_CONTINUING_WARNING}`);
3220
4176
  }
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
4177
  }
4178
+ // BAPI-1595 — an evaluator that finds its evidence unestablished returns a
4179
+ // warning, never a refusal. Each warning is said once and tallied under its
4180
+ // stable reason code; the launch continues.
4181
+ const warnOnce = (outcome) => {
4182
+ if (warnings.includes(outcome.message))
4183
+ return;
4184
+ warnings.push(outcome.message);
4185
+ observe(outcome.code, outcome.message);
4186
+ say(`Readiness: [warn] ${outcome.message}`);
4187
+ };
3226
4188
  // Bring-up first: a behind database or a missing worker makes the
3227
4189
  // unattended questions moot, and refusing on the cheaper, universal fact
3228
4190
  // 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}`);
4191
+ const bringUp = evaluateSetupEpicBringUpPrerequisites(readiness);
4192
+ if (isSetupEpicPrerequisiteWarning(bringUp)) {
4193
+ warnOnce(bringUp);
4194
+ }
4195
+ else if (bringUp !== null) {
4196
+ deps.errorLog(`setup-epic REFUSED (${bringUp.reason}): ${bringUp.message}`);
3232
4197
  return 1;
3233
4198
  }
3234
4199
  // BAPI-1135 — merge-execution eligibility, AFTER the universal bring-up
@@ -3241,18 +4206,29 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3241
4206
  // `--attended` run that declares `github_actions` mode is gated too. The
3242
4207
  // evaluator itself returns null for every policy that does not declare the
3243
4208
  // 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}`);
4209
+ const mergeExecution = evaluateSetupEpicMergeExecutionPrerequisites(readiness, composedForCreate);
4210
+ if (isSetupEpicPrerequisiteWarning(mergeExecution)) {
4211
+ warnOnce(mergeExecution);
4212
+ }
4213
+ else if (mergeExecution !== null) {
4214
+ deps.errorLog(`setup-epic REFUSED (${mergeExecution.reason}): ${mergeExecution.message}`);
3247
4215
  return 1;
3248
4216
  }
4217
+ // BAPI-1601 — said once, then the launch continues to the ordinary create
4218
+ // boundary, where the server enforces what this client could not check.
4219
+ if (mergeExecutionCheckUnrunLocally(readiness, composedForCreate)) {
4220
+ say(SETUP_EPIC_MERGE_CHECK_NOT_RUN_LOCALLY);
4221
+ }
3249
4222
  if (requestedPolicyIsUnattended(composedForCreate, opts.attended)) {
3250
4223
  // The COMPOSED policy, not the flags: a --policy-file declaring
3251
4224
  // notify.webhook_url satisfies the escalation-channel prerequisite, and
3252
4225
  // 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}`);
4226
+ const unattended = evaluateSetupEpicUnattendedPrerequisites(readiness, composedForCreate);
4227
+ if (isSetupEpicPrerequisiteWarning(unattended)) {
4228
+ warnOnce(unattended);
4229
+ }
4230
+ else if (unattended !== null) {
4231
+ deps.errorLog(`setup-epic REFUSED (${unattended.reason}): ${unattended.message}`);
3256
4232
  return 1;
3257
4233
  }
3258
4234
  }
@@ -3282,13 +4258,41 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3282
4258
  const createRequest = Object.keys(policyJson).length > 0 || requestedPolicy !== undefined
3283
4259
  ? { epicKey: opts.epicKey, policyJson }
3284
4260
  : { epicKey: opts.epicKey };
3285
- const { run, created } = await createEpicRunWithDisposition(access, createRequest, deps.fetch);
4261
+ let createResponse;
4262
+ try {
4263
+ // From here a create request may commit even if its response is lost.
4264
+ runIdSink.createRequestAttempted = true;
4265
+ createResponse = await createEpicRunWithDisposition(access, createRequest, deps.fetch);
4266
+ }
4267
+ catch (createErr) {
4268
+ if (!(createErr instanceof ConductorMutationOutcomeUnknownError))
4269
+ throw createErr;
4270
+ // BAPI-1593 — the create may have been applied. Re-read by epic key (the
4271
+ // server resolves the single live run); the POST is never sent again.
4272
+ const recovered = await recoverUncertainCreate({
4273
+ access,
4274
+ deps,
4275
+ say,
4276
+ observe,
4277
+ result,
4278
+ runIdSink,
4279
+ opts,
4280
+ uncertainty: createErr.uncertainty,
4281
+ });
4282
+ if (recovered.kind === "exit")
4283
+ return recovered.exitCode;
4284
+ createResponse = { run: recovered.run, created: true };
4285
+ }
4286
+ const { run, created } = createResponse;
3286
4287
  result.epic_run_id = run.epic_run_id;
3287
4288
  // BAPI-1102 — the create path's authoritative id. `createEpicRunWithDisposition`
3288
4289
  // returns the server's run for a fresh creation AND for a create-race
3289
4290
  // adoption (`created: false`), so both are captured by this one assignment.
3290
4291
  runIdSink.epicRunId = run.epic_run_id;
3291
4292
  runIdSink.runCreated = created;
4293
+ // BAPI-1581 — read from the returned run (fresh creation AND race adoption),
4294
+ // never from the request, before the two cases branch.
4295
+ recordStoredRunFacts(runIdSink, run.policy_json);
3292
4296
  result.status = run.status;
3293
4297
  result.run_created = created;
3294
4298
  if (created) {
@@ -3315,8 +4319,12 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3315
4319
  `\`epic-implementer abandon-run --epic-run-id ${run.epic_run_id}\` to start over.`);
3316
4320
  // BAPI-1510 — attach-only: a race-adopted run is never touched by a
3317
4321
  // trimmed launch (no policy replacement, cut, plan store, or approval).
3318
- if (handoff?.attachOnlyOnReuse === true)
4322
+ if (handoff?.attachOnlyOnReuse === true) {
4323
+ const attachNotice = retainedParallelLimitNotice(opts.parallel, runIdSink.parallelLimit ?? 1);
4324
+ if (attachNotice !== null)
4325
+ say(attachNotice);
3319
4326
  return 0;
4327
+ }
3320
4328
  if (requestedPolicy !== undefined) {
3321
4329
  const outcome = await applyReusedRunPolicy({
3322
4330
  access,
@@ -3327,10 +4335,15 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3327
4335
  storedPolicy: run.policy_json,
3328
4336
  requestedPolicy,
3329
4337
  replacePolicy: opts.replacePolicy,
4338
+ runIdSink,
4339
+ epicKey: opts.epicKey,
3330
4340
  });
3331
4341
  if (!outcome)
3332
4342
  return emitRefusal(deps, opts, result);
3333
4343
  }
4344
+ const retainedNotice = retainedParallelLimitNotice(opts.parallel, runIdSink.parallelLimit ?? 1);
4345
+ if (retainedNotice !== null)
4346
+ say(retainedNotice);
3334
4347
  }
3335
4348
  }
3336
4349
  catch (err) {
@@ -3355,7 +4368,20 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3355
4368
  `named field in the policy file and re-run.`);
3356
4369
  return 1;
3357
4370
  }
4371
+ // BAPI-1595 — the server's own pre-create launch refusals (BAPI-1585) are not
4372
+ // client copies. Show each as the SERVER's decision, with the harm it guards,
4373
+ // rather than as a transport failure.
4374
+ const serverHarm = err instanceof ConductorBridgeApiError && status === 409 && typeof err.errorCode === "string"
4375
+ ? SERVER_PRE_CREATE_REFUSAL_HARM[err.errorCode]
4376
+ : undefined;
4377
+ if (serverHarm !== undefined && err instanceof ConductorBridgeApiError) {
4378
+ deps.errorLog(`The server refused to create the run (${err.errorCode}).\n${errorDetail(err)}\n` +
4379
+ `Why it stops: ${serverHarm}\nNo run was created.`);
4380
+ runIdSink.launchOutcome = "refused";
4381
+ return 1;
4382
+ }
3358
4383
  deps.errorLog(`Failed to create the epic run: ${errorDetail(err)}`);
4384
+ runIdSink.launchOutcome = "refused";
3359
4385
  return 1;
3360
4386
  }
3361
4387
  }
@@ -3365,6 +4391,10 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3365
4391
  // of guessing from repository-wide active-run state (which risks stopping
3366
4392
  // the WRONG run). Absence of a local plane — remote runs, CI, any non-plane
3367
4393
  // workflow — is normal and produces neither an attempt nor a warning.
4394
+ // BAPI-1585 — true only when THIS run was bound (or already bound) to a live
4395
+ // plane, so the closing lines do not tell the operator to start an executor a
4396
+ // plane already provides. An attempted bind that failed leaves it false.
4397
+ let planeServesRun = false;
3368
4398
  if (deps.planeBinding) {
3369
4399
  try {
3370
4400
  const manifestRead = await deps.planeBinding.readManifest(deps.cwd);
@@ -3376,6 +4406,7 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3376
4406
  if (isLive) {
3377
4407
  const bound = await deps.planeBinding.bind(deps.cwd, manifest.planeId, result.epic_run_id);
3378
4408
  if (bound.ok) {
4409
+ planeServesRun = true;
3379
4410
  say(bound.alreadyBound
3380
4411
  ? `Plane: already bound to run ${result.epic_run_id}`
3381
4412
  : `Plane: bound to run ${result.epic_run_id} — \`plane down\` will stop it automatically`);
@@ -3458,7 +4489,7 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3458
4489
  // and a fresh probe would just re-confirm what a prior run already ensured
3459
4490
  // or deferred). Non-fatal in every outcome: setup-epic's provisioning
3460
4491
  // workflow (plan storage, approval, scope polling) proceeds unchanged.
3461
- if (cut.branchCreated && scopeBaseBranch !== null) {
4492
+ if ((cut.branchCreated || runIdSink.branchMove !== undefined) && scopeBaseBranch !== null) {
3462
4493
  const ghRunner = deps.epicIntegrationGh ?? createProductionEpicIntegrationGhRunner();
3463
4494
  let outcome;
3464
4495
  try {
@@ -3523,8 +4554,13 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3523
4554
  if (effectiveFeatureBranch !== undefined) {
3524
4555
  say(`Branch: validating origin/${effectiveFeatureBranch} server-side (App read) and preparing the index scope…`);
3525
4556
  }
3526
- const approval = await approveEpicPlan(access, { epicKey: opts.epicKey, planVersion: plan.plan_version }, deps.fetch).catch((err) => {
3527
- if (effectiveFeatureBranch !== undefined &&
4557
+ let approvalUncertain = null;
4558
+ let approval = await approveEpicPlan(access, { epicKey: opts.epicKey, planVersion: plan.plan_version }, deps.fetch).catch((err) => {
4559
+ if (err instanceof ConductorMutationOutcomeUnknownError) {
4560
+ // BAPI-1593 — not a failure: re-read below, never re-send.
4561
+ approvalUncertain = err;
4562
+ }
4563
+ else if (effectiveFeatureBranch !== undefined &&
3528
4564
  err instanceof ConductorBridgeApiError &&
3529
4565
  err.errorCode === "FEATURE_BRANCH_PROVISIONING") {
3530
4566
  deps.errorLog(`Failed to provision the feature branch '${effectiveFeatureBranch}' — child-ticket ` +
@@ -3556,13 +4592,50 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3556
4592
  }
3557
4593
  return null;
3558
4594
  });
3559
- if (approval === null)
4595
+ if (approval === null && approvalUncertain !== null) {
4596
+ const recovered = await recoverUncertainApproval({
4597
+ access,
4598
+ deps,
4599
+ say,
4600
+ observe,
4601
+ result,
4602
+ runIdSink,
4603
+ opts,
4604
+ uncertainty: approvalUncertain.uncertainty,
4605
+ });
4606
+ if (recovered.kind === "exit")
4607
+ return recovered.exitCode;
4608
+ approval = { ok: true, plan_hash: recovered.planHash ?? localHash };
4609
+ }
4610
+ if (approval === null) {
4611
+ runIdSink.launchOutcome = "refused";
3560
4612
  return 1;
4613
+ }
3561
4614
  if (approval.ok) {
3562
4615
  result.plan_approved = true;
3563
4616
  result.plan_hash = approval.plan_hash;
3564
4617
  result.status = "active";
4618
+ runIdSink.launchOutcome = "active";
4619
+ runIdSink.runStatus = "active";
3565
4620
  say(`Plan: approved v${plan.plan_version}`);
4621
+ // BAPI-1601 — the server's own account of the auto-merge it stamped. Purely
4622
+ // observational: a missing or malformed stamp is "unknown" and never changes
4623
+ // the outcome, the exit code, or what is sent. A recovered approval (the
4624
+ // answer was lost and the run re-read) carries no stamp, so it reads unknown.
4625
+ const stamp = approval.gateProfileStamp ?? { autoMerge: "unknown", reasons: [] };
4626
+ result.auto_merge_stamp = { auto_merge: stamp.autoMerge, reasons: stamp.reasons };
4627
+ for (const line of describeSetupEpicAutoMergeStamp(stamp))
4628
+ say(line);
4629
+ // BAPI-1602 — a declared webhook that failed verification while live account
4630
+ // email carries escalations. A warning only: it never changes the outcome or
4631
+ // the exit code, and the run's channel stays the webhook.
4632
+ if (approval.escalationWarning !== undefined) {
4633
+ const text = approval.escalationWarning === "webhook_failed_email_available"
4634
+ ? READINESS_PREREQUISITE_FIXES.webhook_failed_email_available
4635
+ : `Escalation warning: ${approval.escalationWarning}.`;
4636
+ result.warnings.push(text);
4637
+ say(`Escalation: [warn] ${text}`);
4638
+ }
3566
4639
  const prov = approval.featureBranchProvisioning;
3567
4640
  if (prov) {
3568
4641
  result.feature_branch_provisioning = prov;
@@ -3578,9 +4651,28 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3578
4651
  }
3579
4652
  }
3580
4653
  }
4654
+ else if (approval.kind === "refused") {
4655
+ // BAPI-1585 — the server refused the approval for a real reason. Print the
4656
+ // closed tokens it gave (never a URL, host, or body) and stop. The run was
4657
+ // created and sits in 'planning' with no approved plan.
4658
+ say(`Plan: approval REFUSED (${approval.error_code}, predicate ${approval.predicate}, ` +
4659
+ `reason ${approval.reason_code})`);
4660
+ if (approval.predicate === "webhook") {
4661
+ say(`Remedy: start or fix the declared notify sink so it answers 2xx, or turn on ` +
4662
+ `live account email, then re-run setup-epic. Or launch with --attended.`);
4663
+ }
4664
+ result.approval_refusal = {
4665
+ error_code: approval.error_code,
4666
+ predicate: approval.predicate,
4667
+ reason_code: approval.reason_code,
4668
+ };
4669
+ runIdSink.launchOutcome = "refused";
4670
+ return emitRefusal(deps, opts, result);
4671
+ }
3581
4672
  else if (approval.reason === "multiple_active_runs") {
3582
4673
  deps.errorLog(`Epic ${opts.epicKey} has MULTIPLE active runs — the plan could not be approved ` +
3583
4674
  `and the epic is wedged. Abandon the duplicate run, then re-run setup-epic.`);
4675
+ runIdSink.launchOutcome = "refused";
3584
4676
  return 1;
3585
4677
  }
3586
4678
  else {
@@ -3720,6 +4812,9 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3720
4812
  if (handoff) {
3721
4813
  say("The launcher starts or reuses the executor appropriate for this run.");
3722
4814
  }
4815
+ else if (planeServesRun) {
4816
+ say("A plane serves this run; no separate executor is needed.");
4817
+ }
3723
4818
  else {
3724
4819
  say("To execute this run's claimed jobs on this machine, run:");
3725
4820
  say(` npx -y ${MCP_PACKAGE_NAME} executor --repo ${access.repoName} ` +