@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,9 +1,10 @@
1
- import { sanitizeHarnessCoverage } from "./executor/harness-coverage.js";
2
1
  import { isTerminalRunCleanupStatus } from "./plane/terminal-run-status.js";
2
+ import { resolveDeclaredRunBaseBranch } from "./conductor/run-branch.js";
3
3
  import { monotonicNow, elapsedMs, measurePrecheck } from "./conductor/precheck-timings.js";
4
- import { buildLaunchPlan } from "./conductor/launch-plan.js";
4
+ import { buildLaunchPlan, LAUNCH_PRE_CREATE_CODES, PARALLEL_LIMIT_CHANGE_ADVISORY, PARALLEL_LIMIT_MEANING_COPY, SERVER_WEBHOOK_ROW_ID, } from "./conductor/launch-plan.js";
5
5
  import { ticketReviewSummary } from "./ticket-review-summary.js";
6
6
  import { parseConductorReadinessResponse } from "./conductor/bridge-api-client.js";
7
+ import { workerSetupTallyEntries } from "./conductor/worker-setup-tally.js";
7
8
  import { READINESS_PRE_CREATE_CODES, READINESS_PREREQUISITE_BY_ID, READINESS_LEGACY_IDS } from "./readiness-prerequisites.generated.js";
8
9
  /**
9
10
  * `drive-epic` — the one universal conductor entry point (BAPI-887).
@@ -63,34 +64,42 @@ import { READINESS_PRE_CREATE_CODES, READINESS_PREREQUISITE_BY_ID, READINESS_LEG
63
64
  import { access as fsAccess, readdir, readFile, realpath, stat as fsStat } from "node:fs/promises";
64
65
  import { constants as fsConstants } from "node:fs";
65
66
  import path, { dirname, join } from "node:path";
66
- import { ConductorBridgeApiError, resolveEpicLaunchBridgeApiAccess, fetchConductorReadiness, fetchRepositoryUsageAdvisory, REPOSITORY_USAGE_ADVISORY_UNAVAILABLE, formatSchemaIncompatibleRefusal, isSchemaIncompatibleError, SCHEMA_INCOMPATIBLE_REPAIR_ROUTE, fetchEpicRunState, isProviderRepositoryIdentity, safeDiagnosticMessage, classifyChildMergeStatus as classifyChildMergeStatusClient, recordSkippedChildren as recordSkippedChildrenClient, } from "./conductor/bridge-api-client.js";
67
+ import { ConductorBridgeApiError, createReadinessAcquisition, resolveEpicLaunchBridgeApiAccess, fetchConductorReadiness, isSchemaIncompatibleError, SCHEMA_INCOMPATIBLE_REPAIR_ROUTE, fetchEpicRunState, isProviderRepositoryIdentity, safeDiagnosticMessage, classifyChildMergeStatus as classifyChildMergeStatusClient, recordSkippedChildren as recordSkippedChildrenClient, fetchEpicChildren, fetchStoredTicketDescription, resolveConductorBridgeApiAccess, validateEpicPlan, } from "./conductor/bridge-api-client.js";
67
68
  import { CHILD_MERGE_STATUS_BATCH_SIZE, buildAlreadyDoneEntries, classifyPlanChildren, selectSkips, } from "./conductor/merged-child-check.js";
68
69
  import { trimDonePlanNodes } from "./conductor/plan-trim.js";
69
70
  import { withPlanPath } from "./conductor/temporary-plan.js";
70
- import { ESCALATION_REACHABILITY_CHECK_ID, buildEscalationReachabilityCheck, } from "./escalation-reachability.js";
71
- import { EPIC_LAUNCH_PROFILE_NAME_PATTERN, epicLaunchPolicyDigest, pinEpicLaunchPolicy, renderEpicLaunchCommand, resolveEpicLaunchSelection, shellQuote, } from "./epic-launch-profile.js";
71
+ import { ESCALATION_REACHABILITY_CHECK_ID, buildEscalationReachabilityCheck, classifyEscalationReachabilityPresentation, } from "./escalation-reachability.js";
72
+ import { EPIC_LAUNCH_PROFILE_NAME_PATTERN, epicLaunchPolicyDigest, getPinnedEpicLaunchPolicy, pinEpicLaunchPolicy, renderEpicLaunchCommand, resolveEpicLaunchSelection, shellQuote, } from "./epic-launch-profile.js";
72
73
  import { validateHttpBaseUrl, describeBaseUrlRejection } from "./base-url.js";
73
- import { BRING_UP_REFUSAL_MESSAGES, BRING_UP_RUNBOOK, firstBringUpRefusal, } from "./conductor/bring-up-facts.js";
74
- import { V2_READINESS_REQUIREMENTS, buildLaunchReadinessChecks, firstLaunchEvidenceBlocker, formatLaunchReadinessSummary, projectReadinessRowBlocking, unattendedPostureCheck, } from "./v2-readiness-requirements.js";
74
+ import { BRING_UP_REFUSAL_MESSAGES, BRING_UP_RUNBOOK, firstBringUpRefusal, firstProvenBringUpRefusal, } from "./conductor/bring-up-facts.js";
75
+ import { V2_READINESS_REQUIREMENTS, buildLaunchEvidenceChecks, buildLaunchReadinessChecks, firstLaunchEvidenceBlocker, projectReadinessRowBlocking, unattendedPostureCheck, } from "./v2-readiness-requirements.js";
75
76
  import { classifyLocalGhPreflight, probeLocalMergeCapability, } from "./conductor/local-merge.js";
77
+ import { statusOnly } from "./credential-references.js";
78
+ import { createNodeCredentialReferenceDeps } from "./credential-references-node-deps.js";
76
79
  import { nodeGithubMergeCredentialReadDeps, resolveMergeCredentialAtAction, } from "./conductor/stored-merge-credential.js";
77
80
  import { resolveWorktreeSettingsExclude, } from "./executor/permissions.js";
78
- import { collectWorkerDatabaseDoctorSection, sanitizeOwnerRoles, sanitizeOwnerRoleTotal, WORKER_DATABASE_DOCTOR_TIMEOUT_MS, } from "./conductor/doctor.js";
79
- import { buildEpicBranchBehindBaseLaunchRow, buildHostPowerLaunchRow, buildSelfHostedRunnerLaunchRow, buildUsageResetAfterRunLaunchRow, buildWorkerDbRoleLaunchRow, hostPowerFactFromReport, workerDatabaseReadinessChecks, } from "./conductor/readiness-sections.js";
80
- import { createWorkflowSource, inspectEpicBranchBehindBase, inspectRequiredSelfHostedRunners, } from "./conductor/launch-need-probes.js";
81
+ import { collectWorkerDatabaseDoctorSection, WORKER_DATABASE_DOCTOR_TIMEOUT_MS, } from "./conductor/doctor.js";
82
+ import { buildHostPowerLaunchRow, buildSelfHostedRunnerLaunchRow, buildWorkerDbRoleLaunchRow, hostPowerFactFromReport, LAUNCH_NEED_ROW_IDS, workerDatabaseReadinessChecks, } from "./conductor/readiness-sections.js";
83
+ import { createWorkflowSource, inspectRequiredSelfHostedRunners, } from "./conductor/launch-need-probes.js";
81
84
  import { createWorkerDatabaseDoctorInspector } from "./conductor/worker-database-doctor-inspector.js";
82
- import { policyDeclaresNotifyWebhook, policyNotifyDestinationsConflict, notifyDestinationsConflictMessage, effectivePolicyFacts, readSetupEpicPolicyFile, readCanonicalParseTruth as readSetupCanonicalParseTruth, runSetupEpicWorkflow, } from "./setup-epic.js";
85
+ import { ENGINE_PATHS } from "./engine-paths.js";
86
+ import { policyDeclaresNotifyWebhook, policyNotifyDestinationsConflict, notifyDestinationsConflictMessage, effectivePolicyFacts, evaluateParallelPolicyPreflight, parseParallelLimit, readSetupEpicPolicyFile, retainedParallelLimitNotice, resolveFeatureBranchSelection, readCanonicalParseTruth as readSetupCanonicalParseTruth, runSetupEpicWorkflow, launchReconnectCommand, READINESS_UNKNOWN_CONTINUING_WARNING, RUN_WAITING_FOR_APPROVAL_PHRASE, classifyRemoteEpicBranch, formatSetupEpicAutoMergeIntent, resolveSetupEpicAutoMergeIntent, readinessSnapshotFromLaunchContext, } from "./setup-epic.js";
87
+ import { getConfigFieldBaseBranch } from "./epic-shared/bridge-client.js";
88
+ import { createExecFileRunCommand, normalizeCommitSha } from "./epic-shared/cut-protocol.js";
83
89
  import { EPIC_KEY_PATTERN } from "./drive-epic-key.js";
90
+ import { buildEpicLaunchContext, projectWorkerDatabase, readEpicLaunchContext, writeEpicLaunchContext, writeEpicLaunchOutcome, } from "./epic-launch-context.js";
84
91
  import { flushProcessStdout, writeJsonDocument } from "./conductor/json-output.js";
85
92
  import { BRIDGE_LAUNCHER_ENV } from "./bridge-permissions.js";
86
93
  import { checkPlaneBuildFreshness, PLANE_BUILD_FIX_REMEDIATION } from "./plane/build-freshness.js";
87
- import { discoverEpicPlan, } from "./plan-discovery.js";
88
- import { formatPlaneDiagnostic, launchPlaneControlPlane, requestPlaneScopedLanes, runDefaultPlanePreflight, runPlaneCli, } from "./plane/cli.js";
89
- import { PLANE_PORT_PROBE_TIMEOUT_MS, describePlanePortOccupant, isBridgeEngineRepository, } from "./plane/preflight.js";
94
+ import { discoverEpicPlan, isPlanGenerationEligible, unrelatedMissingMetaPaths, } from "./plan-discovery.js";
95
+ import { attemptPlanGeneration, createDefaultPlanPublicationFs, generatedPlanFolder, listTrackedFilesWithGit, publishGeneratedPlan, validateGeneratedPlan, } from "./plan-generation-io.js";
96
+ import { PLAN_GENERATION_FAILURE_TEXT, } from "./plan-generation.js";
97
+ import { DEFAULT_RUN_PARALLEL_LIMIT, formatPlaneDiagnostic, isPlaneExecutorLaneMember, launchPlaneControlPlane, parallelLimitToExecutorLanes, requestPlaneScopedLanes, runDefaultPlanePreflight, runPlaneCli, } from "./plane/cli.js";
98
+ import { PLANE_PORT_PROBE_TIMEOUT_MS, describePlanePortOccupant, classifyBridgeCheckout, } from "./plane/preflight.js";
90
99
  import { createPlaneExecFile, createPlaneFsDeps, probeAutomationHealth, probeTcpPort, resolveHostname, } from "./plane/defaults.js";
91
100
  import { readPlaneManifest } from "./plane/manifest.js";
92
- import { cleanupTerminalRunPlane, createTerminalRunCleanupDeps, terminalRunCleanupStderrLine, } from "./plane/terminal-run-cleanup.js";
93
- import { checkPlaneFreshness, inspectHostSleep, PLANE_DATABASE_HEAD_ID, PLANE_DATABASE_HEAD_REMEDY, PLANE_FRESHNESS_UNVERIFIED_REMEDY, PLANE_HOST_SLEEP_ID, PLANE_SLEEP_REMEDY, formatBoundPlaneStaleRemedy, PLANE_SNAPSHOT_FRESHNESS_ID, PLANE_SNAPSHOT_STALE_REMEDY, } from "./plane/plane-freshness.js";
101
+ import { cleanupTerminalRunPlane, createTerminalRunCleanupDeps, readOtherLiveRun, terminalRunCleanupStderrLine, } from "./plane/terminal-run-cleanup.js";
102
+ import { checkPlaneFreshness, inspectHostSleep, PLANE_DATABASE_HEAD_ID, PLANE_DATABASE_HEAD_REMEDY, PLANE_FRESHNESS_UNVERIFIED_REMEDY, PLANE_HOST_SLEEP_ID, PLANE_SLEEP_REMEDY, formatBoundPlaneStaleRemedy, formatSharedPlaneStaleRemedy, PLANE_SNAPSHOT_FRESHNESS_ID, PLANE_SNAPSHOT_STALE_REMEDY, } from "./plane/plane-freshness.js";
94
103
  import { baseUrlNamesPlaneEndpoint, planeEndpointForTarget } from "./plane/endpoint.js";
95
104
  import { resolvePlaneServerEndpoint, } from "./plane/member-roster.js";
96
105
  import { resolveMemberInstanceId } from "./plane/supervisor.js";
@@ -102,7 +111,7 @@ import { isTerminalEpicRunStatus } from "./epic-run-status.js";
102
111
  import { MCP_PACKAGE_NAME } from "./mcp-identity.js";
103
112
  import { getDriveEpicAdvancedUsage, getDriveEpicUsage } from "./drive-epic-help.js";
104
113
  export { getDriveEpicUsage };
105
- import { CONSUMER_GUIDE_POINTER, PRINTED_CHECK_NAME_INSTRUCTION, PRINTED_CONDUCTOR_INSTALL_COMMAND, PRINTED_DOCTOR_COMMAND, } from "./printed-remedy-commands.js";
114
+ import { CONSUMER_GUIDE_POINTER, PRINTED_CHECK_NAME_INSTRUCTION, PRINTED_CONDUCTOR_INSTALL_COMMAND, PRINTED_DOCTOR_COMMAND, READINESS_PREREQUISITE_FIXES, resolveReadinessRemedy, } from "./printed-remedy-commands.js";
106
115
  /** The conductor paths. Derived types below come from this constant. */
107
116
  export const DRIVE_EPIC_CONDUCTORS = ["v2"];
108
117
  /**
@@ -153,6 +162,21 @@ const MERGE_CREDENTIAL_ROW = "conductor.merge-credential-capability";
153
162
  * three competing actions has to work out which to do first, and the order here
154
163
  * already encodes that (setup, then config, then credentials).
155
164
  */
165
+ /** The reason id of a PROVEN mandatory-diagnostic failure (unchanged by BAPI-1595). */
166
+ const MANDATORY_DIAGNOSTIC_FAILED_ID = "mandatory-diagnostic-unverified";
167
+ const MANDATORY_DIAGNOSTIC_FAILED_REMEDY = "Resolve the mandatory diagnostic at the selected Bridge API target and retry.";
168
+ /**
169
+ * BAPI-1595 — whether any diagnostic is uncertain: missing severity or
170
+ * applicability, or a mandatory applicable one whose verdict was not established.
171
+ * Such a finding warns (it is never a proven failure) and the launch continues.
172
+ */
173
+ export function mandatoryDiagnosticsUncertain(diagnostics) {
174
+ return (diagnostics ?? []).some((diagnostic) => diagnostic.severity === null ||
175
+ diagnostic.applicability === null ||
176
+ (diagnostic.applicability === "applicable" &&
177
+ diagnostic.severity === "mandatory" &&
178
+ diagnostic.verdict === "unknown"));
179
+ }
156
180
  export function classifyV2Readiness(readiness, options = {},
157
181
  /**
158
182
  * BAPI-1452 — the value-free launch evidence (credential probe verdict and
@@ -163,21 +187,17 @@ export function classifyV2Readiness(readiness, options = {},
163
187
  * posture is never read from here — only from the server report.
164
188
  */
165
189
  launchEvidence) {
190
+ // BAPI-1595 — only a PROVEN failure refuses: a diagnostic that is explicitly
191
+ // mandatory, explicitly applicable, and `failed`. An unknown verdict, or one whose
192
+ // severity or applicability was not established, is uncertainty (see
193
+ // {@link mandatoryDiagnosticsUncertain}), never a stop.
166
194
  for (const diagnostic of readiness.diagnostics ?? []) {
167
- if (diagnostic.severity === null || diagnostic.applicability === null) {
168
- return {
169
- kind: "operator_blocked",
170
- id: "diagnostic-metadata-unknown",
171
- describe: "Additional readiness diagnostics",
172
- remedy: "Upgrade or repair the readiness producer, then retry the selected target.",
173
- };
174
- }
175
- if (diagnostic.applicability === "applicable" && diagnostic.severity === "mandatory" && diagnostic.verdict !== "passed") {
195
+ if (diagnostic.applicability === "applicable" && diagnostic.severity === "mandatory" && diagnostic.verdict === "failed") {
176
196
  return {
177
197
  kind: "operator_blocked",
178
- id: "mandatory-diagnostic-unverified",
198
+ id: MANDATORY_DIAGNOSTIC_FAILED_ID,
179
199
  describe: "Additional readiness diagnostics",
180
- remedy: "Resolve the mandatory diagnostic at the selected Bridge API target and retry.",
200
+ remedy: MANDATORY_DIAGNOSTIC_FAILED_REMEDY,
181
201
  };
182
202
  }
183
203
  }
@@ -268,16 +288,47 @@ launchEvidence) {
268
288
  if (blocker) {
269
289
  return {
270
290
  kind: "operator_blocked",
271
- id: { "server.indexed-workflows": READINESS_PRE_CREATE_CODES.INDEXED_WORKFLOWS_NOT_MET, "server.unattended-notify-default": READINESS_PRE_CREATE_CODES.ESCALATION_CHANNEL_NOT_MET, "server.test-command": READINESS_PRE_CREATE_CODES.TEST_COMMAND_NOT_MET }[blocker.id] ?? blocker.id,
291
+ id: { "server.indexed-workflows": READINESS_PRE_CREATE_CODES.INDEXED_WORKFLOWS_NOT_MET, "server.unattended-notify-default": READINESS_PRE_CREATE_CODES.ESCALATION_CHANNEL_NOT_MET, "server.escalation-webhook-reachable": LAUNCH_PRE_CREATE_CODES.ESCALATION_WEBHOOK_UNREACHABLE, "server.provider-default-branch-readable": LAUNCH_PRE_CREATE_CODES.PROVIDER_DEFAULT_BRANCH_UNREADABLE }[blocker.id] ?? blocker.id,
272
292
  describe: blocker.describe,
273
293
  ...(() => {
274
- const remedy = blocker.remedyFor?.(readiness) ?? blocker.remedy;
294
+ const remedy = blocker.id === INDEXED_WORKFLOWS_ROW_ID
295
+ ? indexedWorkflowsRemedy(readiness)
296
+ : blocker.remedyFor?.(readiness) ?? blocker.remedy;
275
297
  return remedy ? { remedy } : {};
276
298
  })(),
277
299
  };
278
300
  }
279
301
  return { kind: "runtime_only", unmetIds: unmet.map((req) => req.id) };
280
302
  }
303
+ const INDEXED_WORKFLOWS_ROW_ID = "server.indexed-workflows";
304
+ /**
305
+ * BAPI-1635 — the refusal guidance for an unmet indexed-workflows row, chosen from
306
+ * the row the server already sent. No new read is made.
307
+ *
308
+ * The server sends a wire-compatible EMPTY fix for the richer remedies, so an empty
309
+ * or missing fix resolves by prerequisite ID (the repository is not indexed). An
310
+ * explicit published remedy keeps its meaning: `no_index` re-indexes, `pending_index`
311
+ * waits, and only a fix that actually carries the setup remedy tells the owner to
312
+ * merge the setup pull request. Anything else known-but-unclassified says the
313
+ * determining state could not be established, so no pending pull request is guessed.
314
+ */
315
+ function indexedWorkflowsRemedy(readiness) {
316
+ const row = readiness.prerequisites?.find((p) => p.id === INDEXED_WORKFLOWS_ROW_ID);
317
+ if (row === undefined)
318
+ return INDEXED_WORKFLOWS_UNCLASSIFIED;
319
+ const fix = row.fix.length > 0
320
+ ? row.fix
321
+ : resolveReadinessRemedy({ id: INDEXED_WORKFLOWS_ROW_ID, state: row.check_status === "unknown" ? "unknown" : "not_met" });
322
+ if (fix === READINESS_PREREQUISITE_FIXES.no_index || fix === READINESS_PREREQUISITE_FIXES.reindex_manual) {
323
+ return READINESS_PREREQUISITE_FIXES.reindex_manual;
324
+ }
325
+ if (fix === READINESS_PREREQUISITE_FIXES.pending_index)
326
+ return "Wait for indexing to finish, then run drive-epic again.";
327
+ if (fix.includes("Merge the setup pull request") || fix === READINESS_PREREQUISITE_FIXES.setup || fix.includes("merge the workflow changes"))
328
+ return fix;
329
+ return INDEXED_WORKFLOWS_UNCLASSIFIED;
330
+ }
331
+ const INDEXED_WORKFLOWS_UNCLASSIFIED = "The state blocking the indexed workflows could not be established; run readiness again to read it.";
281
332
  /**
282
333
  * Parse argv. Rejects malformed input BEFORE any side effect — no readiness
283
334
  * read, no credential resolution, no delegation.
@@ -334,12 +385,25 @@ export function parseDriveEpicArgs(argv) {
334
385
  const keepChildren = [];
335
386
  const skipChildren = [];
336
387
  let noMergedCheck = false;
388
+ // BAPI-1581 — validated for shape with setup-epic's own parser; forwarded verbatim.
389
+ let parallel;
337
390
  for (let i = 0; i < argv.length; i++) {
338
391
  const arg = argv[i];
339
392
  if (arg === "--all") {
340
393
  all = true;
341
394
  continue;
342
395
  }
396
+ if (arg === "--parallel" || arg.startsWith("--parallel=")) {
397
+ const inline = arg.startsWith("--parallel=");
398
+ const raw = inline ? arg.slice("--parallel=".length) : argv[i + 1];
399
+ const parsedParallel = parseParallelLimit(!inline && (raw === undefined || raw.startsWith("-")) ? undefined : raw);
400
+ if (!parsedParallel.ok)
401
+ return { status: "error", message: parsedParallel.error };
402
+ parallel = parsedParallel.value;
403
+ if (!inline)
404
+ i++;
405
+ continue;
406
+ }
343
407
  if (arg === "--no-merged-check") {
344
408
  noMergedCheck = true;
345
409
  continue;
@@ -490,6 +554,16 @@ export function parseDriveEpicArgs(argv) {
490
554
  "form of the read-only launch preview, and a real launch has no JSON output.",
491
555
  };
492
556
  }
557
+ // BAPI-1581 — an unattended-only request against an explicit opt-out, refused by
558
+ // name whatever the argument order, before any request or local service.
559
+ if (parallel !== undefined && (attended || intoBase)) {
560
+ return {
561
+ status: "error",
562
+ message: "drive-epic REFUSED (parallel-requires-unattended): --parallel sets the limit of an " +
563
+ `unattended run, and ${attended ? "--attended opts out of unattended operation" : "--into-base runs children directly into the repository base branch"}. ` +
564
+ "Drop --parallel, or make the run unattended.",
565
+ };
566
+ }
493
567
  // BAPI-1510 — contradictory child intent is refused before any file read or launch.
494
568
  const overlap = keepChildren.filter((key) => skipChildren.includes(key));
495
569
  if (overlap.length > 0) {
@@ -559,6 +633,7 @@ export function parseDriveEpicArgs(argv) {
559
633
  // Added only when supplied, so the no-flag options object stays byte-identical.
560
634
  ...(attended ? { attended: true } : {}),
561
635
  ...(policyFile ? { policyFile } : {}),
636
+ ...(parallel !== undefined ? { parallel } : {}),
562
637
  ...(reviewPolicy ? { reviewPolicy } : {}),
563
638
  ...(replacePolicy ? { replacePolicy: true } : {}),
564
639
  ...(launchProfile ? { launchProfile } : {}),
@@ -598,7 +673,7 @@ export function parseDriveEpicArgs(argv) {
598
673
  * about to be created.
599
674
  */
600
675
  export function selectConductor(readiness) {
601
- const missing = V2_READINESS_REQUIREMENTS.filter((req) => req.unattendedOnly !== true && req.advisoryOnly !== true && !req.satisfied(readiness));
676
+ const missing = V2_READINESS_REQUIREMENTS.filter((req) => req.unattendedOnly !== true && req.launchOnly !== true && req.advisoryOnly !== true && !req.satisfied(readiness));
602
677
  if (missing.length === 0) {
603
678
  return {
604
679
  kind: "selected",
@@ -624,7 +699,7 @@ export function selectConductor(readiness) {
624
699
  * no quoting to get wrong.
625
700
  */
626
701
  export function buildSetupEpicArgv(options) {
627
- const { epicKey, planFile, repo, featureBranch, intoBase, attended, policyFile, reviewPolicy, replacePolicy, launchProfile, baseUrl, verificationHandoff, verificationHandoffExceptions, } = options;
702
+ const { epicKey, planFile, repo, featureBranch, intoBase, attended, policyFile, reviewPolicy, replacePolicy, launchProfile, baseUrl, verificationHandoff, verificationHandoffExceptions, parallel, } = options;
628
703
  return [
629
704
  "--epic-key",
630
705
  epicKey,
@@ -649,6 +724,9 @@ export function buildSetupEpicArgv(options) {
649
724
  // when supplied, so every pre-existing argv stays byte-identical.
650
725
  ...(verificationHandoff !== undefined ? ["--verification-handoff", verificationHandoff] : []),
651
726
  ...(verificationHandoffExceptions ?? []).flatMap((entry) => ["--verification-handoff-exception", entry]),
727
+ // BAPI-1581 — the operator's requested limit, appended last and only when
728
+ // supplied, so every pre-existing argv stays byte-identical.
729
+ ...(parallel !== undefined ? ["--parallel", String(parallel)] : []),
652
730
  ];
653
731
  }
654
732
  /**
@@ -681,7 +759,9 @@ launch = { profile: null },
681
759
  * BAPI-1285 — what discovery found. Absent reads as "no metadata named this
682
760
  * epic", with the searched directory left as its placeholder.
683
761
  */
684
- discovery, presentation = "default") {
762
+ discovery, presentation = "default",
763
+ /** BAPI-1621 — why automatic plan generation stopped, when it was tried. */
764
+ generationReason) {
685
765
  // BAPI-1496 — an owner's explicit verification hand-off choice survives the
686
766
  // re-run command verbatim. Nothing is derived: no flag, no flag added.
687
767
  const handoffSuffix = [
@@ -713,6 +793,13 @@ discovery, presentation = "default") {
713
793
  ...discovery.candidates.map((candidate) => ` - ${candidate}`),
714
794
  ]
715
795
  : [`No epic-plan.meta.json under ${plansDir} names ${epicKey}.`];
796
+ const generation = generationReason !== undefined
797
+ ? [
798
+ "",
799
+ `Automatic plan generation was tried and stopped (${generationReason}): ` +
800
+ `${PLAN_GENERATION_FAILURE_TEXT[generationReason]}. Nothing was written.`,
801
+ ]
802
+ : [];
716
803
  const skipped = discovery !== undefined && discovery.skipped.length > 0
717
804
  ? [
718
805
  "",
@@ -729,6 +816,7 @@ discovery, presentation = "default") {
729
816
  : `${epicKey}: ${selection.reason}, but no plan was supplied and none could be selected.`,
730
817
  "",
731
818
  ...outcome,
819
+ ...generation,
732
820
  ...skipped,
733
821
  "",
734
822
  "Discovery reads only epic-plan.meta.json ({\"epic_key\": ...}). It never matches a",
@@ -771,8 +859,8 @@ const PLANE_DOWN_SELECTION = {
771
859
  * The one text both the preview and a real launch print for the guarded
772
860
  * plane-down no-plan stop, so the preview is a verbatim part of the real output.
773
861
  */
774
- function planeDownNoPlanStopText(epicKey, launch, discovery) {
775
- const text = renderConductorHandoff(PLANE_DOWN_SELECTION, epicKey, launch, discovery, "plane_not_running")
862
+ function planeDownNoPlanStopText(epicKey, launch, discovery, generationReason) {
863
+ const text = renderConductorHandoff(PLANE_DOWN_SELECTION, epicKey, launch, discovery, "plane_not_running", generationReason)
776
864
  .lines.join("\n");
777
865
  assertSingleConductorInvocation(text);
778
866
  return text;
@@ -1044,9 +1132,16 @@ function createDefaultPlanDiscoveryFs() {
1044
1132
  readFile: (filePath) => readFile(filePath, "utf8"),
1045
1133
  };
1046
1134
  }
1135
+ /**
1136
+ * The server's terminal code for more than one active run on one epic
1137
+ * (`api/library/db/epic_runs.py:EPIC_RUN_CODE_ACTIVE_RUN_EXISTS`). The only 409
1138
+ * the live-run read counts as a wedged epic (BAPI-1595).
1139
+ */
1140
+ export const ACTIVE_EPIC_RUN_EXISTS_ERROR_CODE = "ACTIVE_EPIC_RUN_EXISTS";
1047
1141
  /**
1048
1142
  * BAPI-1285 — map the by-epic-key run read the way `setup-epic`'s Step 0 does:
1049
- * 404 is no run, 409 is a wedged epic, and every other failure is unknown.
1143
+ * 404 is no run, a 409 carrying `ACTIVE_EPIC_RUN_EXISTS` is a wedged epic, and
1144
+ * every other failure (any other 409 included) is unknown.
1050
1145
  * Nothing but a status and an error kind is ever kept from a failure.
1051
1146
  */
1052
1147
  export async function readLiveEpicRunByKey(access, epicKey, fetchImpl = globalThis.fetch) {
@@ -1077,8 +1172,12 @@ export async function readLiveEpicRunByKey(access, epicKey, fetchImpl = globalTh
1077
1172
  if (err instanceof ConductorBridgeApiError) {
1078
1173
  if (err.status === 404)
1079
1174
  return { kind: "none" };
1080
- if (err.status === 409)
1175
+ // BAPI-1595 — a 409 is a wedged epic ONLY when its typed `errorCode` says so.
1176
+ // Any other 409, or one with no readable code, proves nothing about whether a
1177
+ // second run exists, so it is unknown (the server's idempotent create decides).
1178
+ if (err.status === 409 && err.errorCode === ACTIVE_EPIC_RUN_EXISTS_ERROR_CODE) {
1081
1179
  return { kind: "conflict" };
1180
+ }
1082
1181
  return {
1083
1182
  kind: "unknown",
1084
1183
  reason: `kind=${err.kind}${typeof err.status === "number" ? ` status=${err.status}` : ""}`,
@@ -1096,7 +1195,20 @@ export function createDefaultDriveEpicDeps() {
1096
1195
  if (!top.ok || !path.isAbsolute(top.stdout.trim()))
1097
1196
  throw new Error("repository_root_unverifiable");
1098
1197
  const repoRoot = await realpath(top.stdout.trim());
1099
- return { repoRoot, isBridge: await isBridgeEngineRepository(repoRoot, createPlaneFsDeps()) };
1198
+ // BAPI-1595 — tri-state: only all-markers-absent is non-Bridge. A partial
1199
+ // checkout stays Bridge-applicable, and a marker that cannot be inspected
1200
+ // keeps the existing `repository-identity-unverifiable` refusal.
1201
+ const applicability = await classifyBridgeCheckout(repoRoot, createPlaneFsDeps());
1202
+ if (applicability === "unknown")
1203
+ throw new Error("repository_identity_unverifiable");
1204
+ return { repoRoot, isBridge: applicability === "bridge" };
1205
+ },
1206
+ readCredentialReferenceStatus: (repoName) => statusOnly(repoName, createNodeCredentialReferenceDeps(process.env)),
1207
+ readScopeBaseBranch: async (access) => {
1208
+ const configured = await getConfigFieldBaseBranch(access, globalThis.fetch);
1209
+ if (!configured.ok)
1210
+ return null;
1211
+ return configured.value.base_branch !== null ? configured.value.base_branch : "main";
1100
1212
  },
1101
1213
  resolveAccess: async (repo, cwd, launch) => {
1102
1214
  // BAPI-1260: the target-first launch contract. BAPI-1272: with no target
@@ -1117,6 +1229,9 @@ export function createDefaultDriveEpicDeps() {
1117
1229
  process.env.BAPI_BASE_URL = baseUrl;
1118
1230
  },
1119
1231
  readReadiness: (access) => fetchConductorReadiness(access, globalThis.fetch),
1232
+ writeLaunchContext: (context) => writeEpicLaunchContext(context),
1233
+ writeLaunchOutcome: (input) => writeEpicLaunchOutcome(input),
1234
+ reportLaunch: (report) => console.error(`${LAUNCH_REPORT_PREFIX}${JSON.stringify(report)}`),
1120
1235
  runSetupEpic: (argv, handoff) => runSetupEpicWorkflow(argv, {}, handoff),
1121
1236
  readEligibilityArtifact: (path) => readFile(path, "utf8"),
1122
1237
  runPlanePreflight: (repoRoot) => runDefaultPlanePreflight(repoRoot),
@@ -1137,7 +1252,10 @@ export function createDefaultDriveEpicDeps() {
1137
1252
  cwd: () => process.cwd(),
1138
1253
  resolvePlaneEndpoint: () => resolvePlaneServerEndpoint(process.env),
1139
1254
  probePlanePort: (host, port) => probeTcpPort(host, port, PLANE_PORT_PROBE_TIMEOUT_MS),
1140
- checkExecutorBuildFreshness: (repoRoot) => checkPlaneBuildFreshness(repoRoot, { fs: createPlaneFsDeps() }),
1255
+ checkExecutorBuildFreshness: (repoRoot, applicability) => checkPlaneBuildFreshness(repoRoot, {
1256
+ fs: createPlaneFsDeps(),
1257
+ ...(applicability?.isBridge === false ? { isBridge: false } : {}),
1258
+ }),
1141
1259
  collectPlaneFreshness: ({ repoRoot, ownsManifest, expectedPlaneId }) => checkPlaneFreshness(repoRoot, {
1142
1260
  execFile: createPlaneExecFile(),
1143
1261
  fileExists: (filePath) => fsStat(filePath).then((entry) => entry.isFile(), () => false),
@@ -1152,10 +1270,30 @@ export function createDefaultDriveEpicDeps() {
1152
1270
  execFile: createPlaneExecFile(),
1153
1271
  workflows: createWorkflowSource(),
1154
1272
  }),
1155
- inspectEpicBranchBehind: ({ repoRoot, branch, baseBranch }) => inspectEpicBranchBehindBase({ repoRoot, branch, baseBranch, execFile: createPlaneExecFile() }),
1156
- fetchUsageAdvisory: (access) => fetchRepositoryUsageAdvisory(access),
1157
- inspectWorkerDatabase: (repoRoot) => createWorkerDatabaseDoctorInspector({ env: process.env, cwd: repoRoot ?? process.cwd() })(),
1273
+ // A launch shows only the role and the boundary (BAPI-1594); `doctor` keeps the full inspection.
1274
+ inspectWorkerDatabase: (repoRoot, config) => createWorkerDatabaseDoctorInspector({ env: process.env, cwd: repoRoot ?? process.cwd(), scope: "launch" })(config),
1275
+ // BAPI-1596 — child 5's validated cache, read-only: no claim, no write, bounded in time.
1276
+ readPrerequisiteCache: async ({ epicKey, children, access }) => {
1277
+ const { readCachedPrerequisites } = await import("./conductor/prerequisite-inputs.js");
1278
+ const { fetchStoredTicket } = await import("./conductor/bridge-api-client.js");
1279
+ let timer;
1280
+ const deadline = new Promise((resolve) => {
1281
+ timer = setTimeout(() => resolve({ kind: "unavailable" }), PREREQUISITE_CACHE_READ_TIMEOUT_MS);
1282
+ });
1283
+ try {
1284
+ return await Promise.race([
1285
+ readCachedPrerequisites({ epicKey, children, fetchTicket: (key) => fetchStoredTicket(access, key) }),
1286
+ deadline,
1287
+ ]);
1288
+ }
1289
+ finally {
1290
+ if (timer !== undefined)
1291
+ clearTimeout(timer);
1292
+ }
1293
+ },
1294
+ execEngineStatus: createPlaneExecFile(),
1158
1295
  cleanupTerminalRunPlane: (input) => cleanupTerminalRunPlane(input, createTerminalRunCleanupDeps(process.env)),
1296
+ listLiveRunIds: (access) => createTerminalRunCleanupDeps(process.env).listLiveRunIds(access),
1159
1297
  readRunState: async (access, epicRunId) => {
1160
1298
  const state = await fetchEpicRunState(access, epicRunId, globalThis.fetch);
1161
1299
  const run = state.epic_run;
@@ -1187,12 +1325,39 @@ export function createDefaultDriveEpicDeps() {
1187
1325
  }),
1188
1326
  discoveryFs: createDefaultPlanDiscoveryFs(),
1189
1327
  readPlanDag: (filePath) => readFile(filePath, "utf8"),
1328
+ // BAPI-1621 — the general resolver, never the launch profile: generation runs
1329
+ // before any local plane is up, exactly like `prerequisite-inputs`.
1330
+ attemptPlanGeneration: (epicKey) => attemptPlanGeneration(epicKey, {
1331
+ resolveAccess: () => resolveConductorBridgeApiAccess(),
1332
+ readLiveRun: async (access, key) => (await readLiveEpicRunByKey(access, key)).kind,
1333
+ fetchChildren: (access, key) => fetchEpicChildren(access, key),
1334
+ fetchTicket: async (access, key) => ({ description: await fetchStoredTicketDescription(access, key) }),
1335
+ listTrackedFiles: () => listTrackedFilesWithGit(process.cwd()),
1336
+ validatePlan: (access, request) => validateEpicPlan(access, request),
1337
+ }),
1338
+ publishGeneratedPlan: ({ epicKey, docsDir, dag, summary, access }) => publishGeneratedPlan({
1339
+ epicKey,
1340
+ docsDir,
1341
+ dag,
1342
+ summary,
1343
+ fs: createDefaultPlanPublicationFs(),
1344
+ validate: () => validateGeneratedPlan(access, epicKey, dag, (a, request) => validateEpicPlan(a, request)),
1345
+ rediscover: () => discoverEpicPlan(epicKey, docsDir, createDefaultPlanDiscoveryFs()),
1346
+ }),
1190
1347
  readPolicyFile: (filePath) => readFile(filePath, "utf8"),
1191
1348
  readLiveEpicRun: (access, epicKey) => readLiveEpicRunByKey(access, epicKey),
1192
- previewSetupEpic: async ({ argv, baseUrl, handoff, observations }) => {
1349
+ previewSetupEpic: async ({ argv, baseUrl, handoff, observations, planContents }) => {
1193
1350
  const stdout = [];
1194
1351
  const stderr = [];
1195
1352
  const result = await runSetupEpicWorkflow(argv, {
1353
+ ...(planContents !== undefined
1354
+ ? {
1355
+ readFile: (filePath) => {
1356
+ const inline = planContents.get(filePath);
1357
+ return inline !== undefined ? Promise.resolve(inline) : readFile(filePath, "utf8");
1358
+ },
1359
+ }
1360
+ : {}),
1196
1361
  // A COPY carrying the resolved target: the preview never mutates
1197
1362
  // `process.env`, so a dry run leaves the process exactly as it found it.
1198
1363
  env: { ...process.env, BAPI_BASE_URL: baseUrl },
@@ -1259,11 +1424,16 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1259
1424
  return 1;
1260
1425
  }
1261
1426
  const { epicKey, planFile, repo, featureBranch, intoBase } = parsed.options;
1262
- const { bridgeWorktreeCleanupAdvisory } = await import("./bridge-worktree-inspection.js");
1263
- const cleanupAdvisory = await bridgeWorktreeCleanupAdvisory(deps.cwd());
1264
- if (cleanupAdvisory)
1265
- deps.errorLog(cleanupAdvisory);
1266
1427
  const launch = launchSelectionOf(parsed.options);
1428
+ // BAPI-1581 — a supplied `--parallel` against an explicit policy file is judged
1429
+ // locally, before any request, readiness probe, setup call, or local service
1430
+ // start. Only the explicit file is read here; a profile or default composition
1431
+ // is judged on the creation routes, where a candidate creation policy exists.
1432
+ const earlyParallelRefusal = await explicitPolicyParallelRefusal(deps, parsed.options);
1433
+ if (earlyParallelRefusal !== null) {
1434
+ deps.errorLog(earlyParallelRefusal);
1435
+ return 1;
1436
+ }
1267
1437
  // BAPI-1285 — the read-only preview is its own path from here. It shares the
1268
1438
  // classification and refusal builders below and none of the launch code.
1269
1439
  if (parsed.options.dryRun === true) {
@@ -1302,6 +1472,11 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1302
1472
  targetSource: accessResult.targetSource ?? "default",
1303
1473
  freshness: createPlaneFreshnessCache(),
1304
1474
  launchCredential: {},
1475
+ launchObservations: [],
1476
+ liveObservation: {},
1477
+ invokedAt: new Date((deps.now ?? Date.now)()).toISOString(),
1478
+ launchReportState: { reported: false },
1479
+ launchOutcomeState: { warned: false },
1305
1480
  };
1306
1481
  // BAPI-1285 — with no `--plan-file`, look for the plan BEFORE readiness. A
1307
1482
  // discovered plan must count as a supplied one for the BAPI-1153 cold-start
@@ -1316,10 +1491,17 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1316
1491
  // discovered plan is a convenience, not approved input: it may still be used to
1317
1492
  // create a run, but a live run is attached to first and the plan stays unused.
1318
1493
  let planWasDiscovered = false;
1494
+ // BAPI-1621 — why automatic generation stopped, for the no-plan stop text.
1495
+ let generationReason;
1319
1496
  if (planFile === undefined) {
1320
1497
  const docs = await deps.resolveDocsDir();
1321
1498
  if (docs.ok) {
1322
1499
  discovered = await discoverEpicPlan(epicKey, docs.docsDir, deps.discoveryFs);
1500
+ if (discovered.status === "plan_not_found") {
1501
+ const generated = await generateMissingPlanForLaunch(ctx, docs.docsDir, discovered);
1502
+ discovered = generated.discovery;
1503
+ generationReason = generated.reason;
1504
+ }
1323
1505
  if (discovered.status === "found") {
1324
1506
  planWasDiscovered = true;
1325
1507
  ctx = { ...ctx, options: { ...ctx.options, planFile: discovered.path } };
@@ -1331,73 +1513,68 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1331
1513
  }
1332
1514
  let foundPlanAnnounced = false;
1333
1515
  /** Names the found plan once, BEFORE anything is created, and surfaces its advisory. */
1334
- const announceFoundPlan = async (surfaceAdvisory = true) => {
1516
+ const announceFoundPlan = async () => {
1335
1517
  if (foundPlanAnnounced || discovered?.status !== "found")
1336
1518
  return;
1337
1519
  foundPlanAnnounced = true;
1338
1520
  deps.log(`${epicKey}: using the plan found by epic key: ${discovered.path}`);
1339
- if (surfaceAdvisory)
1340
- await surfaceContainmentAdvisory(deps, discovered.path);
1341
1521
  };
1342
- // --- Read readiness. Any failure here is UNKNOWN — with ONE exception. ---
1343
- let readiness;
1344
- try {
1345
- readiness = await deps.readReadiness(accessResult.access);
1346
- }
1347
- catch (err) {
1348
- // BAPI-1455 — a proven-incompatible local schema is a terminal refusal,
1349
- // not an unknown: the server read the catalog and named what is missing.
1350
- if (isSchemaIncompatibleError(err))
1351
- return refuse(deps, formatSchemaIncompatibleRefusal(epicKey, err));
1352
- // BAPI-1153 — the cold-start case. With a plan file, a readiness read that
1353
- // failed at the TRANSPORT against the plane's own endpoint, on a port that
1354
- // actively refuses connections, is not "unknown": it is "no server yet".
1355
- // Everything else — a non-plane base URL, an HTTP or auth or shape error, a
1356
- // timeout, any other probe result — keeps today's escalation byte for byte,
1357
- // because there unknown is still fatal (R14).
1358
- if (ctx.options.planFile !== undefined &&
1359
- planeTarget &&
1360
- err instanceof ConductorBridgeApiError &&
1361
- err.kind === "network") {
1362
- const endpoint = planeEndpointForBaseUrl(deps, accessResult.access.baseUrl);
1363
- // BAPI-1260 — only a SELECTED LOCAL plane is ever started here. A
1364
- // profile approved for durable execution names an authority this
1365
- // machine does not own, so a refused port is that authority being
1366
- // down — never permission to launch a local replacement.
1367
- if (endpoint !== null && launchProfile !== null && launchProfile.executionMode !== "local") {
1368
- return escalate(deps, epicKey, `launch profile '${launchProfile.name}' selects durable execution, and its control plane is ` +
1369
- "not answering; no local replacement was started");
1370
- }
1371
- if (endpoint !== null) {
1372
- const probe = await deps.probePlanePort(endpoint.host, endpoint.port);
1373
- if (probe.kind === "refused") {
1374
- // `coldStartPlane` surfaces the containment advisory itself.
1375
- await announceFoundPlan(false);
1376
- return await coldStartPlane(ctx);
1522
+ // --- No readiness read at launch (BAPI-1595). -----------------------------
1523
+ // The preview owns readiness acquisition (one attempt plus one retry). A real
1524
+ // launch reads nothing: it reuses the preview's stored snapshot when that
1525
+ // snapshot is bound to THIS launch, and otherwise writes one fixed tally line
1526
+ // and carries on with every evaluator on its unknown (warn) path. The server's
1527
+ // create and approve stay the gate.
1528
+ //
1529
+ // A cold start used to be recognized from a failed readiness read. It is now
1530
+ // recognized from the plane port itself: a refused port IS "no server yet".
1531
+ const planeEndpoint = planeTarget ? planeEndpointForBaseUrl(deps, accessResult.access.baseUrl) : null;
1532
+ const noPlanDiscovery = launchProfile?.executionMode !== "durable" &&
1533
+ discovered !== null &&
1534
+ (discovered.status === "plan_not_found" || discovered.status === "plan_ambiguous")
1535
+ ? discovered
1536
+ : null;
1537
+ if (planeEndpoint !== null && (ctx.options.planFile !== undefined || noPlanDiscovery !== null)) {
1538
+ const probe = await deps.probePlanePort(planeEndpoint.host, planeEndpoint.port).catch(() => ({ kind: "error" }));
1539
+ if (probe.kind === "refused") {
1540
+ if (ctx.options.planFile !== undefined) {
1541
+ // BAPI-1260 — only a SELECTED LOCAL plane is ever started here. A
1542
+ // profile approved for durable execution names an authority this
1543
+ // machine does not own, so a refused port is that authority being
1544
+ // down — never permission to launch a local replacement.
1545
+ if (launchProfile !== null && launchProfile.executionMode !== "local") {
1546
+ return escalate(deps, epicKey, `launch profile '${launchProfile.name}' selects durable execution, and its control plane is ` +
1547
+ "not answering; no local replacement was started");
1377
1548
  }
1549
+ // `coldStartPlane` surfaces the containment advisory itself.
1550
+ await announceFoundPlan();
1551
+ return await coldStartPlane(ctx);
1378
1552
  }
1379
- }
1380
- // The narrow no-plan stop: a local, non-durable plane that refuses
1381
- // connections, with no usable plan supplied or discovered. Readiness was
1382
- // never read, so this is the existing stop outcome — not a new refusal.
1383
- // Nothing is started or created.
1384
- if (ctx.options.planFile === undefined &&
1385
- planeTarget &&
1386
- err instanceof ConductorBridgeApiError &&
1387
- err.kind === "network" &&
1388
- launchProfile?.executionMode !== "durable" &&
1389
- discovered !== null &&
1390
- (discovered.status === "plan_not_found" || discovered.status === "plan_ambiguous")) {
1391
- const endpoint = planeEndpointForBaseUrl(deps, accessResult.access.baseUrl);
1392
- if (endpoint !== null) {
1393
- const probe = await deps.probePlanePort(endpoint.host, endpoint.port).catch(() => ({ kind: "error" }));
1394
- if (probe.kind === "refused") {
1395
- deps.errorLog(planeDownNoPlanStopText(epicKey, { profile: launchProfile, options: parsed.options }, discovered));
1396
- return 1;
1397
- }
1553
+ // The narrow no-plan stop: a local, non-durable plane that refuses
1554
+ // connections, with no usable plan supplied or discovered. This is the
1555
+ // existing stop outcome, not a new refusal. Nothing is started or created.
1556
+ if (noPlanDiscovery !== null) {
1557
+ deps.errorLog(planeDownNoPlanStopText(epicKey, { profile: launchProfile, options: parsed.options }, noPlanDiscovery, generationReason));
1558
+ return 1;
1398
1559
  }
1399
1560
  }
1400
- return escalate(deps, epicKey, `Epic Implementer readiness could not be read: ${safeDiagnosticMessage(err, "readiness request failed")}`);
1561
+ }
1562
+ const resolvedSnapshot = await resolveLaunchSnapshot(ctx);
1563
+ ctx = {
1564
+ ...ctx,
1565
+ launchSnapshot: resolvedSnapshot.snapshot,
1566
+ ...(resolvedSnapshot.previewRepository !== undefined
1567
+ ? { previewRepository: resolvedSnapshot.previewRepository }
1568
+ : {}),
1569
+ };
1570
+ const readiness = launchFullReadiness();
1571
+ // BAPI-1595 — a launch from a VERIFIED non-Bridge checkout runs none of the
1572
+ // Bridge-only checks, so no repository-root, build-entrypoint, plane database
1573
+ // head, or worker-database finding exists to render. Each skip is written to the
1574
+ // tally exactly once.
1575
+ if (isConfirmedNonBridge(ctx)) {
1576
+ for (const skip of Object.values(BRIDGE_ONLY_SKIPS))
1577
+ tallyBridgeOnlySkip(ctx, skip);
1401
1578
  }
1402
1579
  // BAPI-1532 — an EXPLICIT plan selects its setup now. A discovered plan does
1403
1580
  // not: plan selection, approval, and the create-time escalation-channel checks
@@ -1414,15 +1591,9 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1414
1591
  ctx = { ...ctx, handoff: prepared.handoff };
1415
1592
  }
1416
1593
  // --- Route. Exactly one path from here on. -------------------------------
1417
- const selection = selectConductor(readiness);
1418
- // BAPI-1022: surface any containment-hazard advisory before dispatch or
1419
- // handoff. Read only when a plan file was supplied (the sidecar has no
1420
- // other resolvable location). Fail-open: any failure here — missing
1421
- // artifact, bad JSON, malformed/inconsistent shape, an unsafe rendered
1422
- // value — silently yields no advisory and never affects routing, the
1423
- // delegated argv, or the exit code.
1424
- if (planFile)
1425
- await surfaceContainmentAdvisory(deps, planFile);
1594
+ // BAPI-1593 — an unknown report selects the one engine there is (v2) and
1595
+ // takes the green route below; nothing here is decided from it.
1596
+ const selection = readiness === null ? READINESS_UNKNOWN_SELECTION : selectConductor(readiness);
1426
1597
  // BAPI-1285 — no `--plan-file`: find the plan from the epic key, and read the
1427
1598
  // epic's live run. Readiness has already been resolved (unknown escalated
1428
1599
  // above), so nothing here can be a discovery-driven create on unknown.
@@ -1434,13 +1605,15 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1434
1605
  if (docsRootUnresolved || discovered === null) {
1435
1606
  return refuse(deps, docsRootRefusal(epicKey).lines);
1436
1607
  }
1437
- const live = await deps.readLiveEpicRun(accessResult.access, epicKey);
1438
- // Wedged or unreadable: never a create and never an attach, whatever
1439
- // discovery found. Guessing here is how a duplicate run gets minted.
1608
+ // BAPI-1595 — the launch's ONE pre-mutation live-run observation (one retry on
1609
+ // unknown), shared by every pre-create consumer below.
1610
+ const live = await acquireObservedLive(ctx);
1611
+ // Wedged (the server's typed `ACTIVE_EPIC_RUN_EXISTS`): never a create and
1612
+ // never an attach, whatever discovery found. An UNKNOWN read is not that: it
1613
+ // warned in the tally, and the server's idempotent create returns the existing
1614
+ // run if there is one, so it continues as "no run seen".
1440
1615
  if (live.kind === "conflict")
1441
1616
  return refuse(deps, liveRunAmbiguousRefusal(epicKey).lines);
1442
- if (live.kind === "unknown")
1443
- return refuse(deps, liveRunUnknownRefusal(epicKey, live.reason).lines);
1444
1617
  if (discovered.status === "found") {
1445
1618
  if (live.kind === "live") {
1446
1619
  // BAPI-1532 — attach FIRST. The discovered plan is dropped from the
@@ -1484,11 +1657,13 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1484
1657
  // reads: whatever a `--policy-file` says stays opaque here, exactly as it
1485
1658
  // always has. Its mere PRESENCE defers the escalation-channel requirement
1486
1659
  // to `setup-epic`, which composes the policy and can actually read it.
1487
- const classification = classifyV2Readiness(readiness, {
1488
- attended: parsed.options.attended === true,
1489
- intoBase: parsed.options.intoBase === true,
1490
- effectivePolicy: ctx.handoff?.selection,
1491
- });
1660
+ const classification = readiness === null
1661
+ ? classifySnapshotDiagnostics(ctx)
1662
+ : classifyV2Readiness(readiness, {
1663
+ attended: parsed.options.attended === true,
1664
+ intoBase: parsed.options.intoBase === true,
1665
+ effectivePolicy: ctx.handoff?.selection,
1666
+ });
1492
1667
  // Green: create the run, then make sure something will claim its jobs
1493
1668
  // (BAPI-1279). Before this, green delegated to setup-epic and nothing
1494
1669
  // else, so a production launch — or any second run — created a run no
@@ -1512,8 +1687,11 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1512
1687
  const probe = endpoint
1513
1688
  ? await deps.probePlanePort(endpoint.host, endpoint.port).catch(() => ({ kind: "error" }))
1514
1689
  : null;
1515
- if (probe?.kind === "refused")
1690
+ // BAPI-1593 — a fresh plane is a fresh server, so the stopped plane's
1691
+ // answer (and any stored snapshot of it) is never reused for it.
1692
+ if (probe?.kind === "refused") {
1516
1693
  return await coldStartPlane(ctx);
1694
+ }
1517
1695
  }
1518
1696
  const attachable = await findAttachablePlane(ctx);
1519
1697
  if (attachable !== null) {
@@ -1551,12 +1729,14 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1551
1729
  deps.errorLog(refusal);
1552
1730
  return 1;
1553
1731
  }
1732
+ // Only a READABLE report reaches here: an unknown one took the green route.
1733
+ const report = readiness;
1554
1734
  // BAPI-1279 — runtime-only against a target that is NOT this machine's
1555
1735
  // plane: starting anything here could not help, because the missing
1556
1736
  // reconciler belongs to that deployment. One named reason, and nothing
1557
1737
  // local is touched.
1558
1738
  if (!planeTarget) {
1559
- return refuseRemoteRuntime(ctx, readiness);
1739
+ return refuseRemoteRuntime(ctx, report);
1560
1740
  }
1561
1741
  // Runtime-only: this invocation composes bring-up with run creation.
1562
1742
  const repoRoot = deps.cwd();
@@ -1598,7 +1778,7 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1598
1778
  return 1;
1599
1779
  }
1600
1780
  if (attachManifest !== null) {
1601
- return await attachToPlane(ctx, attachManifest, readiness);
1781
+ return await attachToPlane(ctx, attachManifest, report);
1602
1782
  }
1603
1783
  // ---- PHASE ONE: the control plane, and NOTHING that claims jobs --------
1604
1784
  //
@@ -1616,7 +1796,13 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1616
1796
  deps.log(`${epicKey}: the Epic Implementer runtime is not live; starting its control plane before creating the run.`);
1617
1797
  // The SAME preflight result is handed to the launch, so the port that was
1618
1798
  // probed is the port that gets launched and the two cannot disagree.
1619
- const controlPlane = await deps.launchControlPlane({ preflight, executors: 1 });
1799
+ const parallelCreationRefusal = await parallelCreationCandidateRefusal(ctx);
1800
+ if (parallelCreationRefusal !== null) {
1801
+ deps.errorLog(`${epicKey}: ${parallelCreationRefusal}\nNothing was started.`);
1802
+ return 1;
1803
+ }
1804
+ const startedLanes = parallelLimitToExecutorLanes(ctx.options.parallel ?? DEFAULT_RUN_PARALLEL_LIMIT);
1805
+ const controlPlane = await deps.launchControlPlane({ preflight, executors: startedLanes });
1620
1806
  if (!controlPlane.ok) {
1621
1807
  // The launch already reported why, in its own words, and it rolls its own
1622
1808
  // startup back. No run was created here.
@@ -1644,7 +1830,8 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1644
1830
  repoRoot,
1645
1831
  planeId: controlPlane.planeId,
1646
1832
  awaitPlaneReady: controlPlane.awaitPlaneReady,
1647
- }, readiness);
1833
+ laneCount: startedLanes,
1834
+ }, report);
1648
1835
  }
1649
1836
  // No plan file, and readiness is not green: v2 is not ready and there is no
1650
1837
  // second conductor to offer. Report it as a not-ready refusal on stderr with
@@ -1664,7 +1851,7 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1664
1851
  }
1665
1852
  // BAPI-1285 — reached only after discovery came back empty or ambiguous and no
1666
1853
  // live run exists. Nothing was created, so this is a stop, not a success.
1667
- const handoff = renderConductorHandoff(selection, epicKey, { profile: launchProfile, options: parsed.options }, discoveryStop);
1854
+ const handoff = renderConductorHandoff(selection, epicKey, { profile: launchProfile, options: parsed.options }, discoveryStop, "default", generationReason);
1668
1855
  const text = handoff.lines.join("\n");
1669
1856
  assertSingleConductorInvocation(text);
1670
1857
  deps.errorLog(text);
@@ -1678,28 +1865,6 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1678
1865
  return 1;
1679
1866
  }
1680
1867
  }
1681
- /**
1682
- * BAPI-1022: surface any containment-hazard advisory before dispatch or handoff.
1683
- *
1684
- * Read only when a plan file was supplied (the sidecar has no other resolvable
1685
- * location). Fail-open: any failure — missing artifact, bad JSON,
1686
- * malformed/inconsistent shape, an unsafe rendered value — silently yields no
1687
- * advisory and never affects routing, the delegated argv, or the exit code.
1688
- * One helper, so the cold-start path (BAPI-1153) cannot drift from the rest.
1689
- */
1690
- async function surfaceContainmentAdvisory(deps, planFile) {
1691
- try {
1692
- const advisory = await readContainmentEligibilityAdvisory(planFile, deps.readEligibilityArtifact);
1693
- if (advisory) {
1694
- const rendered = renderContainmentEligibilityAdvisory(advisory);
1695
- if (rendered)
1696
- deps.log(rendered);
1697
- }
1698
- }
1699
- catch {
1700
- // Fail open — a containment advisory is never allowed to block dispatch.
1701
- }
1702
- }
1703
1868
  /**
1704
1869
  * BAPI-1285 — the one remedy sentence an unknown-readiness escalation ends with.
1705
1870
  * A constant so the preview's `readiness.remedy` is the very line the real
@@ -1719,34 +1884,471 @@ function operatorBlockedRemedy(classification) {
1719
1884
  return `${remedy} See ${CONSUMER_GUIDE_POINTER}.`;
1720
1885
  }
1721
1886
  /**
1722
- * The escalation branch. Prints NO conductor invocation at all — naming a
1723
- * fallback here is the dual-authority hazard, and an operator who does not know
1724
- * which authority owns an epic must not be nudged toward either one.
1887
+ * The stop for a launch that cannot reach its target: no usable credential, or a
1888
+ * durable profile's control plane that does not answer. Both are needs only a
1889
+ * person can meet. Prints NO conductor invocation.
1890
+ *
1891
+ * BAPI-1593 — an unknown readiness read no longer comes here: it warns and
1892
+ * continues to the server's create and approve. There is one engine
1893
+ * (`DRIVE_EPIC_CONDUCTORS = ["v2"]`), so there is no "wrong engine" to start.
1725
1894
  */
1726
1895
  function escalate(deps, epicKey, reason) {
1727
- const lines = [
1728
- `Cannot determine which engine owns ${epicKey}: ${reason}`,
1729
- "",
1730
- "This is not a not-ready result — it is an unknown one, and starting the wrong",
1731
- "engine on an epic wedges it permanently.",
1732
- ESCALATE_REMEDY,
1733
- ];
1896
+ const lines = [`Cannot start ${epicKey}: ${reason}`, "", ESCALATE_REMEDY];
1734
1897
  const text = lines.join("\n");
1735
1898
  assertSingleConductorInvocation(text);
1736
1899
  deps.errorLog(text);
1737
1900
  return 1;
1738
1901
  }
1902
+ /** BAPI-1686 — said on every healthy-launch success output. */
1903
+ export const KEEP_TERMINAL_OPEN_LINE = "Keep this terminal open and this machine awake. If the run stops moving, re-run this command: it attaches to the live run.";
1904
+ /** The prefix of the default launch-report line. */
1905
+ export const LAUNCH_REPORT_PREFIX = "Launch report: ";
1906
+ /** How long drive-epic watches a planning run for activation after an uncertain approve. */
1907
+ export const ACTIVATION_ATTACH_WINDOW_MS = 10 * 60_000;
1908
+ /** The pause between activation reads, capped to the time left. */
1909
+ export const ACTIVATION_POLL_INTERVAL_MS = 15_000;
1910
+ /** The warning printed when the attach window ends with the run still waiting. */
1911
+ export const APPROVAL_NOT_CONFIRMED_WARNING = "approval not confirmed: the run is still waiting for approval";
1912
+ /** The selection an unknown report takes: the one engine there is. */
1913
+ const READINESS_UNKNOWN_SELECTION = {
1914
+ kind: "selected",
1915
+ conductor: DRIVE_EPIC_PREFERRED_CONDUCTOR,
1916
+ reason: "readiness is unknown",
1917
+ };
1918
+ const defaultLaunchSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1919
+ function launchNowIso(ctx) {
1920
+ return new Date((ctx.deps.now ?? Date.now)()).toISOString();
1921
+ }
1922
+ /** BAPI-1621 — the tally reason code for a published generated plan. */
1923
+ export const PLAN_GENERATED_REASON_CODE = "plan_generated";
1924
+ /**
1925
+ * BAPI-1621 — the real launch's generation step, run only after discovery
1926
+ * returned `plan_not_found` with no `--plan-file`.
1927
+ *
1928
+ * It rebuilds from current stored ticket data (never the preview's copy),
1929
+ * publishes by one folder rename, and runs discovery again so the published plan
1930
+ * continues through the ordinary found-plan path. A live run, an ineligible
1931
+ * discovery, or any failure returns the original `plan_not_found` (with a fixed
1932
+ * reason when one applies), so today's attach and stop behavior is unchanged. A
1933
+ * successful rename ends generation's ownership: nothing later removes the folder.
1934
+ */
1935
+ async function generateMissingPlanForLaunch(ctx, docsDir, discovery) {
1936
+ const { deps, epicKey } = ctx;
1937
+ if (deps.attemptPlanGeneration === undefined || deps.publishGeneratedPlan === undefined)
1938
+ return { discovery };
1939
+ if (!(await planGenerationAllowed(deps.discoveryFs, epicKey, discovery))) {
1940
+ return { discovery, reason: "discovery_blocked" };
1941
+ }
1942
+ deps.log(`${epicKey}: no plan found; checking epic children and building a deterministic plan…`);
1943
+ let attempt;
1944
+ try {
1945
+ attempt = await deps.attemptPlanGeneration(epicKey);
1946
+ }
1947
+ catch {
1948
+ return { discovery, reason: "children_unreadable" };
1949
+ }
1950
+ if (attempt.kind === "not_attempted")
1951
+ return { discovery };
1952
+ if (attempt.kind === "failed")
1953
+ return { discovery, reason: attempt.reason };
1954
+ if (!(await planGenerationAllowed(deps.discoveryFs, epicKey, discovery, attempt))) {
1955
+ return { discovery, reason: "discovery_blocked" };
1956
+ }
1957
+ let published;
1958
+ try {
1959
+ published = await deps.publishGeneratedPlan({
1960
+ epicKey,
1961
+ docsDir,
1962
+ dag: attempt.dag,
1963
+ summary: attempt.summary,
1964
+ access: attempt.access,
1965
+ });
1966
+ }
1967
+ catch {
1968
+ return { discovery, reason: "publish_failed" };
1969
+ }
1970
+ if (published.kind === "failed")
1971
+ return { discovery, reason: published.reason };
1972
+ if (published.kind === "collision")
1973
+ return { discovery: published.discovery };
1974
+ const relative = path.relative(docsDir, published.dagPath).split(path.sep).join("/");
1975
+ observeLaunch(ctx, PLAN_GENERATED_REASON_CODE, `plan: generated ${relative}`);
1976
+ deps.log(`${epicKey}: plan: generated ${published.dagPath}`);
1977
+ const after = await discoverEpicPlan(epicKey, docsDir, deps.discoveryFs);
1978
+ return after.status === "plan_not_found" ? { discovery: after, reason: "publish_failed" } : { discovery: after };
1979
+ }
1980
+ /**
1981
+ * Whether discovery's skipped entries allow generation. A DAG with no metadata
1982
+ * blocks only when it names the epic or one of its children, or can't be read.
1983
+ * Before the attempt only the epic key is known; after a generated attempt, every
1984
+ * child it accounts for (its nodes and the spikes it left out) is checked too.
1985
+ */
1986
+ async function planGenerationAllowed(fs, epicKey, discovery, attempt) {
1987
+ const related = [epicKey];
1988
+ if (attempt !== undefined) {
1989
+ related.push(...attempt.dag.nodes.map((node) => node.ticket_key));
1990
+ related.push(...attempt.summary.excluded.map((entry) => entry.ticket_key));
1991
+ }
1992
+ return isPlanGenerationEligible(discovery, await unrelatedMissingMetaPaths(discovery, related, fs));
1993
+ }
1994
+ /** Record one bookkeeping observation for the launch report. */
1995
+ function observeLaunch(ctx, code, message) {
1996
+ ctx.launchObservations?.push({ code, message, at: launchNowIso(ctx) });
1997
+ }
1998
+ // ---------------------------------------------------------------------------
1999
+ // BAPI-1595 — fixed tally lines and stable reason codes
2000
+ // ---------------------------------------------------------------------------
2001
+ // Each constant sits beside the function that writes it, and a test imports it
2002
+ // rather than retyping the text. None carries a path, a credential, an email
2003
+ // address, a payload, or exception text.
2004
+ /** The launch could not reuse the preview's stored snapshot, so it asked nothing and went on. */
2005
+ export const SNAPSHOT_EXPIRED_WARNING = "readiness snapshot expired; server create and approve decide";
2006
+ export const SNAPSHOT_EXPIRED_REASON_CODE = "readiness_snapshot_expired";
2007
+ /** The pause before the one retry of the pre-mutation live-run read. */
2008
+ export const LIVE_RUN_RETRY_BACKOFF_MS = 1_500;
2009
+ export const LIVE_RUN_RETRY_REASON_CODE = "live_run_read_retried";
2010
+ export const LIVE_RUN_RETRY_MESSAGE = "live run read uncertain; retrying once";
2011
+ /** The live-run read stayed unknown after its retry: the idempotent create decides. */
2012
+ export const LIVE_RUN_UNKNOWN_WARNING = "live run: unknown, continuing; create is idempotent";
2013
+ export const LIVE_RUN_UNKNOWN_REASON_CODE = "live_run_unknown_continued";
2014
+ /** A mandatory diagnostic whose verdict or classification was not established. */
2015
+ export const MANDATORY_DIAGNOSTIC_UNKNOWN_WARNING = "mandatory diagnostic: unknown, continuing; server create and approve decide";
2016
+ export const MANDATORY_DIAGNOSTIC_UNKNOWN_REASON_CODE = "mandatory_diagnostic_unknown_continued";
2017
+ /** The escalation channel evidence was not established, so no "no channel" claim is made. */
2018
+ export const ESCALATION_CHANNEL_UNCERTAIN_WARNING = "escalation channel: unconfirmed, continuing; server create and approve decide";
2019
+ export const ESCALATION_CHANNEL_UNCERTAIN_REASON_CODE = "escalation_channel_unconfirmed_continued";
2020
+ /** Written once whenever the reachability line is left out of the output. */
2021
+ export const ESCALATION_LINE_SUPPRESSED_LINE = "escalation reachability line omitted: a no-channel condition is not established";
2022
+ export const ESCALATION_LINE_SUPPRESSED_REASON_CODE = "escalation_reachability_line_suppressed";
2023
+ /** One Bridge-only check skipped on a verified non-Bridge checkout. */
2024
+ export const BRIDGE_ONLY_SKIPS = {
2025
+ repositoryRoot: {
2026
+ id: "repository-root",
2027
+ reasonCode: "bridge_only_check_skipped_repository_root",
2028
+ line: "repository root check skipped: not a Bridge checkout",
2029
+ },
2030
+ executorBuild: {
2031
+ id: "executor-build",
2032
+ reasonCode: "bridge_only_check_skipped_executor_build",
2033
+ line: "build entrypoint check skipped: not a Bridge checkout",
2034
+ },
2035
+ planeDatabaseHead: {
2036
+ id: "plane-database-head",
2037
+ reasonCode: "bridge_only_check_skipped_plane_database_head",
2038
+ line: "plane database head check skipped: not a Bridge checkout",
2039
+ },
2040
+ workerDatabase: {
2041
+ id: "worker-database",
2042
+ reasonCode: "bridge_only_check_skipped_worker_database",
2043
+ line: "worker database check skipped: not a Bridge checkout",
2044
+ },
2045
+ };
2046
+ /** Write one tally observation and its warning line, once per (code, message) per launch. */
2047
+ function tallyOnce(ctx, code, message, printed = true) {
2048
+ const seen = ctx.launchObservations?.some((entry) => entry.code === code && entry.message === message);
2049
+ if (seen === true)
2050
+ return;
2051
+ if (printed)
2052
+ ctx.deps.errorLog(`${ctx.epicKey}: [warn] ${message}`);
2053
+ observeLaunch(ctx, code, message);
2054
+ }
2055
+ /** Record that a Bridge-only check was skipped, exactly once per launch. */
2056
+ function tallyBridgeOnlySkip(ctx, skip) {
2057
+ // Informational, not a warning: it goes to the launch report's observations, not the terminal.
2058
+ tallyOnce(ctx, skip.reasonCode, skip.line, false);
2059
+ }
2060
+ /**
2061
+ * Whether the launch may skip Bridge-only checks: only a verified, carried
2062
+ * `isBridge === false`. An absent identity, a Bridge, and a partial checkout all
2063
+ * keep the checks.
2064
+ */
2065
+ function isConfirmedNonBridge(ctx) {
2066
+ return ctx.previewRepository?.isBridge === false;
2067
+ }
2068
+ /**
2069
+ * The full readiness report a real launch holds: none. The preview acquires it and
2070
+ * the launch reads only the narrow, validated snapshot. A function rather than a
2071
+ * literal so the paths that still accept a report keep their signature and TypeScript
2072
+ * does not narrow the null away.
2073
+ */
2074
+ function launchFullReadiness() {
2075
+ return null;
2076
+ }
2077
+ /**
2078
+ * BAPI-1595 — the mandatory-diagnostic decision for a launch that holds only the
2079
+ * preview's snapshot. A diagnostic recorded as `failed` was explicitly mandatory and
2080
+ * applicable when it was projected, so it keeps today's refusal. One recorded as
2081
+ * `unknown` (an unknown verdict, or severity / applicability not established)
2082
+ * warns under a stable reason code and the launch continues. No readiness read is
2083
+ * ever made here.
2084
+ */
2085
+ function classifySnapshotDiagnostics(ctx) {
2086
+ const readiness = ctx.launchSnapshot?.context.readiness;
2087
+ if (readiness === undefined || readiness.state !== "known")
2088
+ return { kind: "green" };
2089
+ const diagnostics = readiness.value.mandatory_diagnostics;
2090
+ if (diagnostics.some((entry) => entry.verdict === "failed")) {
2091
+ return {
2092
+ kind: "operator_blocked",
2093
+ id: MANDATORY_DIAGNOSTIC_FAILED_ID,
2094
+ describe: "Additional readiness diagnostics",
2095
+ remedy: MANDATORY_DIAGNOSTIC_FAILED_REMEDY,
2096
+ };
2097
+ }
2098
+ if (diagnostics.some((entry) => entry.verdict === "unknown")) {
2099
+ tallyOnce(ctx, MANDATORY_DIAGNOSTIC_UNKNOWN_REASON_CODE, MANDATORY_DIAGNOSTIC_UNKNOWN_WARNING);
2100
+ }
2101
+ return { kind: "green" };
2102
+ }
2103
+ /**
2104
+ * Resolve the preview's stored snapshot for THIS launch (BAPI-1595). Never throws,
2105
+ * never reads the readiness report, and never refuses.
2106
+ *
2107
+ * The identity is recomputed locally here only to BIND the snapshot; the preview's
2108
+ * verified classification (carried in the snapshot) stays the applicability
2109
+ * authority. An unavailable or mismatched local identity makes the snapshot
2110
+ * unusable, and an unusable snapshot is never read as "not a Bridge checkout".
2111
+ */
2112
+ async function resolveLaunchSnapshot(ctx) {
2113
+ const { deps } = ctx;
2114
+ let local = null;
2115
+ try {
2116
+ local = await deps.inspectRepositoryIdentity();
2117
+ }
2118
+ catch {
2119
+ local = null;
2120
+ }
2121
+ let baseBranch = null;
2122
+ try {
2123
+ baseBranch = (await deps.readScopeBaseBranch?.(ctx.access)) ?? null;
2124
+ }
2125
+ catch {
2126
+ baseBranch = null;
2127
+ }
2128
+ const binding = {
2129
+ epicKey: ctx.epicKey,
2130
+ baseBranch,
2131
+ targetBaseUrl: ctx.access.baseUrl,
2132
+ repository: local !== null ? { repoName: ctx.access.repoName, isBridge: local.isBridge } : null,
2133
+ now: new Date((deps.now ?? Date.now)()),
2134
+ };
2135
+ let result;
2136
+ try {
2137
+ result = await (deps.readLaunchContext ?? ((b) => readEpicLaunchContext(b)))(binding);
2138
+ }
2139
+ catch {
2140
+ result = { kind: "unusable", reason: "unreadable" };
2141
+ }
2142
+ if (result.kind === "usable" && local !== null) {
2143
+ return { snapshot: result.value, previewRepository: local };
2144
+ }
2145
+ tallyOnce(ctx, SNAPSHOT_EXPIRED_REASON_CODE, SNAPSHOT_EXPIRED_WARNING);
2146
+ return { snapshot: null };
2147
+ }
2148
+ /**
2149
+ * The launch's ONE pre-mutation live-run observation (BAPI-1595).
2150
+ *
2151
+ * Read once; an `unknown` answer spends ONE retry (its own budget, separate from
2152
+ * readiness), and a second `unknown` warns and continues — a create is idempotent
2153
+ * (`POST /runs` returns the existing run) and the unique index allows one active
2154
+ * run per epic. The result is memoized on the launch's shared holder, so every
2155
+ * pre-create consumer reads the same value instead of asking again. This is
2156
+ * never evidence of what a later create or approve committed; post-mutation
2157
+ * reconciliation reads for itself.
2158
+ */
2159
+ async function acquireObservedLive(ctx) {
2160
+ const holder = ctx.liveObservation;
2161
+ if (holder?.pending !== undefined)
2162
+ return holder.pending;
2163
+ const acquire = async () => {
2164
+ let live = await ctx.deps.readLiveEpicRun(ctx.access, ctx.epicKey);
2165
+ if (live.kind !== "unknown")
2166
+ return live;
2167
+ observeLaunch(ctx, LIVE_RUN_RETRY_REASON_CODE, LIVE_RUN_RETRY_MESSAGE);
2168
+ await (ctx.deps.launchSleep ?? defaultLaunchSleep)(LIVE_RUN_RETRY_BACKOFF_MS);
2169
+ live = await ctx.deps.readLiveEpicRun(ctx.access, ctx.epicKey);
2170
+ if (live.kind === "unknown")
2171
+ tallyOnce(ctx, LIVE_RUN_UNKNOWN_REASON_CODE, LIVE_RUN_UNKNOWN_WARNING);
2172
+ return live;
2173
+ };
2174
+ const pending = acquire();
2175
+ if (holder !== undefined)
2176
+ holder.pending = pending;
2177
+ return pending;
2178
+ }
2179
+ /**
2180
+ * Print the launch report once per invocation. Setup's observations follow
2181
+ * drive's own, in order, with exact duplicates dropped.
2182
+ */
2183
+ async function reportLaunchOutcome(ctx, outcome, facts) {
2184
+ const state = ctx.launchReportState;
2185
+ if (state === undefined || state.reported)
2186
+ return;
2187
+ state.reported = true;
2188
+ const at = launchNowIso(ctx);
2189
+ const observations = [];
2190
+ const seen = new Set();
2191
+ for (const entry of [...(ctx.launchObservations ?? []), ...(facts.observations ?? []).map((o) => ({ ...o, at }))]) {
2192
+ const key = `${entry.code}\u0000${entry.message}`;
2193
+ if (seen.has(key))
2194
+ continue;
2195
+ seen.add(key);
2196
+ observations.push(entry);
2197
+ }
2198
+ const report = {
2199
+ launch_outcome: outcome,
2200
+ epic_key: ctx.epicKey,
2201
+ epic_run_id: facts.epicRunId ?? null,
2202
+ run_status: facts.runStatus ?? null,
2203
+ invoked_at: ctx.invokedAt ?? at,
2204
+ first_claimed_job_at: "pending",
2205
+ observations,
2206
+ };
2207
+ ctx.deps.reportLaunch?.(report);
2208
+ // The durable record: best-effort, so a write failure never changes the exit code.
2209
+ const record = {
2210
+ outcome,
2211
+ ...(facts.epicRunId !== undefined ? { epicRunId: facts.epicRunId } : {}),
2212
+ ...(facts.runStatus !== undefined ? { runStatus: facts.runStatus } : {}),
2213
+ ...(facts.refusedBeforeCreate === true ? { refusedBeforeCreate: true } : {}),
2214
+ ...(facts.branchMove !== undefined ? { branchMove: facts.branchMove } : {}),
2215
+ observations: observations.map((o) => ({ code: o.code })),
2216
+ };
2217
+ if (ctx.launchOutcomeState !== undefined)
2218
+ ctx.launchOutcomeState.last = record;
2219
+ await writeLaunchOutcomeRecord(ctx, record, "not_applicable");
2220
+ }
2221
+ /**
2222
+ * Write `launch-outcome.json` for this invocation. Awaited, never throws, and
2223
+ * never a stop: a failed or refused write prints one fixed warning per invocation
2224
+ * and the caller carries on with its primary exit code.
2225
+ */
2226
+ async function writeLaunchOutcomeRecord(ctx, record, windDown) {
2227
+ const write = ctx.deps.writeLaunchOutcome;
2228
+ if (write === undefined)
2229
+ return true;
2230
+ let ok = false;
2231
+ try {
2232
+ const written = await write({
2233
+ epicKey: ctx.epicKey,
2234
+ invokedAt: ctx.invokedAt ?? launchNowIso(ctx),
2235
+ writtenAt: launchNowIso(ctx),
2236
+ launchOutcome: record.outcome,
2237
+ epicRunId: record.epicRunId ?? null,
2238
+ runStatus: record.runStatus ?? null,
2239
+ refusedBeforeCreate: record.refusedBeforeCreate === true,
2240
+ branchMove: record.branchMove ?? null,
2241
+ windDown,
2242
+ observations: record.observations,
2243
+ });
2244
+ ok = written.ok;
2245
+ }
2246
+ catch {
2247
+ ok = false;
2248
+ }
2249
+ if (!ok && ctx.launchOutcomeState !== undefined && !ctx.launchOutcomeState.warned) {
2250
+ ctx.launchOutcomeState.warned = true;
2251
+ ctx.deps.errorLog(`${ctx.epicKey}: [warn] The launch outcome record could not be written; the exit code is unchanged.`);
2252
+ }
2253
+ return ok;
2254
+ }
2255
+ /** A refusal that also settles the launch outcome. */
2256
+ async function refuseLaunch(ctx, lines) {
2257
+ await reportLaunchOutcome(ctx, "refused", {});
2258
+ return refuse(ctx.deps, lines);
2259
+ }
2260
+ /**
2261
+ * Watch a planning run for activation after an uncertain approve. Reads only —
2262
+ * it never approves. A failed read keeps the known id and tries again. Bounded
2263
+ * by {@link ACTIVATION_ATTACH_WINDOW_MS}; every pause is capped to the time left.
2264
+ */
2265
+ async function awaitRunActivation(ctx, epicRunId) {
2266
+ const now = ctx.deps.launchClock ?? (() => performance.now());
2267
+ const sleep = ctx.deps.launchSleep ?? defaultLaunchSleep;
2268
+ const deadline = now() + ACTIVATION_ATTACH_WINDOW_MS;
2269
+ for (;;) {
2270
+ const remaining = deadline - now();
2271
+ if (remaining <= 0)
2272
+ return { kind: "exhausted" };
2273
+ await sleep(Math.min(ACTIVATION_POLL_INTERVAL_MS, remaining));
2274
+ let status;
2275
+ try {
2276
+ status = (await ctx.deps.readRunState(ctx.access, epicRunId)).status;
2277
+ }
2278
+ catch {
2279
+ continue;
2280
+ }
2281
+ if (status === "active")
2282
+ return { kind: "active" };
2283
+ if (status !== "planning")
2284
+ return { kind: "changed", status };
2285
+ }
2286
+ }
2287
+ /**
2288
+ * Settle what setup established. `active` continues to the caller's ordinary
2289
+ * lane or executor dispatch. A planning run after an uncertain approve is watched
2290
+ * until it activates (then dispatched the same way) or the window ends. Every
2291
+ * other outcome is reported here and handled: nothing claims jobs for it.
2292
+ */
2293
+ async function settleSetupLaunch(ctx, setup) {
2294
+ const { deps, epicKey } = ctx;
2295
+ const facts = {
2296
+ ...(setup.epicRunId !== undefined ? { epicRunId: setup.epicRunId } : {}),
2297
+ ...(setup.runStatus !== undefined ? { runStatus: setup.runStatus } : {}),
2298
+ ...(setup.observations !== undefined ? { observations: setup.observations } : {}),
2299
+ ...(setup.refusedBeforeCreate === true ? { refusedBeforeCreate: true } : {}),
2300
+ ...(setup.branchMove !== undefined ? { branchMove: setup.branchMove } : {}),
2301
+ };
2302
+ if (setup.exitCode !== 0) {
2303
+ await reportLaunchOutcome(ctx, setup.launchOutcome === "terminal" ? "terminal" : "refused", facts);
2304
+ return setup;
2305
+ }
2306
+ if (setup.launchOutcome === "not_confirmed") {
2307
+ await reportLaunchOutcome(ctx, "not_confirmed", facts);
2308
+ return { ...setup, launchHandled: true };
2309
+ }
2310
+ if (setup.launchOutcome === "pending_activation" && setup.epicRunId !== undefined) {
2311
+ if (setup.runStatus !== "planning") {
2312
+ deps.log(`${epicKey}: run ${setup.epicRunId} is ${setup.runStatus ?? "not active"}; attached without changing it.`);
2313
+ await reportLaunchOutcome(ctx, "pending_activation", facts);
2314
+ return { ...setup, launchHandled: true };
2315
+ }
2316
+ deps.errorLog(`${epicKey}: run ${setup.epicRunId}: ${RUN_WAITING_FOR_APPROVAL_PHRASE}. Watching for activation ` +
2317
+ "for up to 10 minutes; nothing is approved from here.");
2318
+ const activation = await awaitRunActivation(ctx, setup.epicRunId);
2319
+ if (activation.kind === "active") {
2320
+ observeLaunch(ctx, "launch_outcome_reread", "approve re-read: run activated while attached");
2321
+ await reportLaunchOutcome(ctx, "active", { ...facts, runStatus: "active" });
2322
+ return { ...setup, launchOutcome: "active", runStatus: "active" };
2323
+ }
2324
+ if (activation.kind === "changed") {
2325
+ const terminal = isTerminalEpicRunStatus(activation.status);
2326
+ deps.log(`${epicKey}: run ${setup.epicRunId} is ${activation.status}; attached without changing it.`);
2327
+ await reportLaunchOutcome(ctx, terminal ? "terminal" : "pending_activation", { ...facts, runStatus: activation.status });
2328
+ return { ...setup, exitCode: terminal ? 1 : 0, launchHandled: true };
2329
+ }
2330
+ deps.errorLog(`${epicKey}: [warn] ${APPROVAL_NOT_CONFIRMED_WARNING}. Re-run setup with: ` +
2331
+ launchReconnectCommand(epicKey, ctx.access));
2332
+ await reportLaunchOutcome(ctx, "pending_activation", facts);
2333
+ return { ...setup, launchHandled: true };
2334
+ }
2335
+ // Never inferred from exit 0: only a reported `active` status counts.
2336
+ await reportLaunchOutcome(ctx, setup.launchOutcome === "active" || setup.runStatus === "active" ? "active" : "pending_activation", facts);
2337
+ return setup;
2338
+ }
1739
2339
  /** Resolve policy intent once for the setup delegation, after a fresh run read. */
1740
2340
  /** Narrow an effective-policy channel label to the closed identity set. */
1741
2341
  function channelIdentityOf(label) {
1742
2342
  return label === "configured webhook" || label === "account email" ? label : "unavailable";
1743
2343
  }
1744
2344
  async function prepareSetupSelection(ctx, coldStart = false, observedLive) {
1745
- const live = coldStart ? { kind: "none" } : observedLive ?? await ctx.deps.readLiveEpicRun(ctx.access, ctx.epicKey);
1746
- if (live.kind === "conflict")
2345
+ // BAPI-1595 — one observation per launch, reused here instead of a fresh read. An
2346
+ // unknown one (already retried and warned about) is treated as "no run seen":
2347
+ // `POST /runs` is idempotent, so it returns the existing run if there is one.
2348
+ const observed = coldStart ? { kind: "none" } : observedLive ?? await acquireObservedLive(ctx);
2349
+ if (observed.kind === "conflict")
1747
2350
  return { ok: false, reasonId: "live-run-ambiguous" };
1748
- if (live.kind === "unknown")
1749
- return { ok: false, reasonId: "live-run-unknown" };
2351
+ const live = observed.kind === "unknown" ? { kind: "none" } : observed;
1750
2352
  const explicit = ctx.options.policyFile;
1751
2353
  const selectedPath = explicit ?? (live.kind === "none" ? ctx.profile?.policyRef?.path : undefined);
1752
2354
  let pinnedPolicy;
@@ -1929,14 +2531,118 @@ async function recordSkippedChildrenBestEffort(ctx, epicRunId, skipped) {
1929
2531
  deps.errorLog("The run was created, but the skipped-child record could not be saved.");
1930
2532
  }
1931
2533
  }
2534
+ // ---------------------------------------------------------------------------
2535
+ // BAPI-1581 — parallel limit: local preflight and capacity reporting
2536
+ // ---------------------------------------------------------------------------
2537
+ /**
2538
+ * The refusal for a supplied `--parallel` judged against an EXPLICIT policy
2539
+ * file, or `null`. Read-only and local: it reads the one file the operator named,
2540
+ * and an unreadable file is left to the existing policy-read handling.
2541
+ */
2542
+ async function explicitPolicyParallelRefusal(deps, options) {
2543
+ if (options.parallel === undefined || options.policyFile === undefined)
2544
+ return null;
2545
+ const read = await readSetupEpicPolicyFile(options.policyFile, (filePath) => deps.readPolicyFile(filePath));
2546
+ if (!read.ok)
2547
+ return null;
2548
+ const verdict = evaluateParallelPolicyPreflight({
2549
+ parallel: options.parallel,
2550
+ attended: options.attended === true,
2551
+ intoBase: options.intoBase === true,
2552
+ filePolicy: read.policy,
2553
+ // BAPI-1595 — the plan is not read yet, so whether create would select an epic
2554
+ // branch (and fill a posture-silent file as unattended) is not known. The
2555
+ // creation routes judge that case with the branch selection in hand.
2556
+ postureFillDeferred: true,
2557
+ });
2558
+ return verdict.ok ? null : verdict.message.replace(/^setup-epic REFUSED/, `${options.epicKey}: REFUSED`);
2559
+ }
2560
+ /**
2561
+ * The refusal for a supplied `--parallel` judged against the CANDIDATE creation
2562
+ * policy (pinned file/profile policy, or the default composition for this plan),
2563
+ * or `null`. Called only on routes that are about to start a plane and create a
2564
+ * run, so it never judges an existing run's stored policy.
2565
+ */
2566
+ async function parallelCreationCandidateRefusal(ctx) {
2567
+ const parallel = ctx.options.parallel;
2568
+ if (parallel === undefined)
2569
+ return null;
2570
+ const planPath = ctx.options.planFile;
2571
+ if (planPath === undefined)
2572
+ return null;
2573
+ const children = await readPlanChildren(ctx.deps, planPath);
2574
+ if (children === null)
2575
+ return null;
2576
+ const pinned = ctx.handoff ? getPinnedEpicLaunchPolicy(ctx.handoff.selection) : undefined;
2577
+ const declaresBranch = pinned !== undefined && resolveDeclaredRunBaseBranch(pinned) !== undefined;
2578
+ const verdict = evaluateParallelPolicyPreflight({
2579
+ parallel,
2580
+ attended: ctx.options.attended === true,
2581
+ intoBase: ctx.options.intoBase === true,
2582
+ ...(pinned !== undefined ? { filePolicy: pinned } : {}),
2583
+ featureBranch: resolveFeatureBranchSelection({
2584
+ epicKey: ctx.epicKey,
2585
+ featureBranch: ctx.options.featureBranch,
2586
+ intoBase: ctx.options.intoBase === true,
2587
+ }, children.keys.length, declaresBranch),
2588
+ });
2589
+ return verdict.ok ? null : verdict.message.replace(/^setup-epic REFUSED/, "REFUSED");
2590
+ }
2591
+ /** The durable-profile capacity line: the stored limit, and where concurrency is configured. */
2592
+ function durableCapacityLine(storedLimit) {
2593
+ return (`The run's parallel limit is ${storedLimit}. Concurrency of the durable executor is configured on its ` +
2594
+ "host; this command starts no executor and cannot change it.");
2595
+ }
2596
+ /** Executor lanes an attached plane's manifest records: `executor-N` members only, no liveness filter. */
2597
+ function attachedPlaneLaneCount(manifest) {
2598
+ return manifest.members.filter((member) => isPlaneExecutorLaneMember(member.name)).length;
2599
+ }
2600
+ /**
2601
+ * Warn, once, when the plane's known lane count is below the run's stored
2602
+ * parallel limit. Never an action: nothing is stopped, parked, refused, or resized.
2603
+ */
2604
+ function reportPlaneCapacity(ctx, lanes, storedLimit, posture) {
2605
+ if (lanes === undefined || storedLimit === undefined || posture !== "unattended")
2606
+ return;
2607
+ if (lanes >= storedLimit)
2608
+ return;
2609
+ ctx.deps.errorLog(`${ctx.epicKey}: [warn] this plane has ${lanes} executor lane${lanes === 1 ? "" : "s"}, but the run's ` +
2610
+ `parallel limit is ${storedLimit}. Each lane serves one job at a time, so capacity is reduced to ` +
2611
+ `${lanes} job${lanes === 1 ? "" : "s"} at once. Nothing was stopped. To use the full limit, wind the ` +
2612
+ `plane down after the run or between runs, then relaunch with \`--parallel ${storedLimit}\`.`);
2613
+ }
2614
+ /**
2615
+ * BAPI-1593 — delegate to setup-epic, then settle what it established before
2616
+ * anything claims jobs. A `launchHandled` result was fully reported here, and
2617
+ * its caller returns its exit code without requesting lanes or an executor.
2618
+ */
1932
2619
  async function runSelectedSetupEpic(ctx) {
1933
- const prepared = ctx.handoff
2620
+ return settleSetupLaunch(ctx, await runSelectedSetupEpicWorkflow(ctx));
2621
+ }
2622
+ async function runSelectedSetupEpicWorkflow(ctx) {
2623
+ const selected = ctx.handoff
1934
2624
  ? { ok: true, handoff: ctx.handoff }
1935
2625
  : await prepareSetupSelection(ctx);
1936
- if (!prepared.ok) {
1937
- ctx.deps.errorLog(`${ctx.epicKey}: REFUSED (${prepared.reasonId}) — the selected run or policy could not be verified.`);
1938
- return { exitCode: 1 };
1939
- }
2626
+ if (!selected.ok) {
2627
+ ctx.deps.errorLog(`${ctx.epicKey}: REFUSED (${selected.reasonId}) — the selected run or policy could not be verified.`);
2628
+ return { exitCode: 1, refusedBeforeCreate: true };
2629
+ }
2630
+ // BAPI-1595 — readiness is acquired by the PREVIEW and never by a launch. The
2631
+ // hand-off says so explicitly (an in-process contract, not an argv flag), and
2632
+ // carries the narrow evidence the stored snapshot held, or `null` when none was
2633
+ // usable: setup-epic then reads nothing, every evaluator takes its warn path, and
2634
+ // the server's create and approve decide.
2635
+ const snapshotEvidence = ctx.launchSnapshot !== undefined && ctx.launchSnapshot !== null
2636
+ ? readinessSnapshotFromLaunchContext(ctx.launchSnapshot.context)
2637
+ : null;
2638
+ const prepared = {
2639
+ ok: true,
2640
+ handoff: {
2641
+ ...selected.handoff,
2642
+ readinessDisposition: "preview_handoff",
2643
+ launchEvidence: snapshotEvidence,
2644
+ },
2645
+ };
1940
2646
  const { deps, options, epicKey } = ctx;
1941
2647
  // BAPI-1510 — fresh classification immediately before setup. Preview verdicts are
1942
2648
  // never consumed: each create starts from the ORIGINAL plan and re-checks.
@@ -1948,7 +2654,7 @@ async function runSelectedSetupEpic(ctx) {
1948
2654
  if (evaluation.refusals.length > 0) {
1949
2655
  deps.errorLog(`${epicKey}: REFUSED (skip-child-refused) — ${skipRefusalRemedy(evaluation.refusals)}`);
1950
2656
  deps.errorLog("No run was created.");
1951
- return { exitCode: 1 };
2657
+ return { exitCode: 1, refusedBeforeCreate: true };
1952
2658
  }
1953
2659
  if (evaluation.state.status === "not_checked") {
1954
2660
  if (evaluation.state.reason === "cut_commit_unavailable" || evaluation.state.reason === "check_failed") {
@@ -1962,7 +2668,7 @@ async function runSelectedSetupEpic(ctx) {
1962
2668
  if (evaluation.skipKeys.size >= evaluation.childKeys.length) {
1963
2669
  deps.errorLog(`${epicKey}: REFUSED (${EPIC_ALREADY_COMPLETE_REASON_ID}) — ${EPIC_ALREADY_COMPLETE_REMEDY}`);
1964
2670
  deps.errorLog("No run was created.");
1965
- return { exitCode: 1 };
2671
+ return { exitCode: 1, refusedBeforeCreate: true };
1966
2672
  }
1967
2673
  const skipped = evaluation.childKeys
1968
2674
  .filter((key) => evaluation.skipKeys.has(key))
@@ -2015,7 +2721,14 @@ function isUnattendedLaunch(options) {
2015
2721
  return options.attended !== true && options.intoBase !== true;
2016
2722
  }
2017
2723
  /** The launch row ids a launch can be refused on, without their namespace. */
2018
- const LAUNCH_REFUSAL_IDS = ["merge-credential-capability", "worktree-preparation", ...Object.values(READINESS_PRE_CREATE_CODES)];
2724
+ /**
2725
+ * BAPI-1585 — the two pre-create refusal codes the server added after the
2726
+ * generator's regex was written. The generator is read-only for this ticket, so
2727
+ * they are spelled once in `conductor/launch-plan.ts` (which also renders them)
2728
+ * and pinned against `pre_create_refusal.py` in
2729
+ * `readiness-prerequisites-contract.test.ts`.
2730
+ */
2731
+ const LAUNCH_REFUSAL_IDS = ["merge-credential-capability", "worktree-preparation", ...Object.values(READINESS_PRE_CREATE_CODES), ...Object.values(LAUNCH_PRE_CREATE_CODES)];
2019
2732
  /**
2020
2733
  * The credential evidence. Probes ONLY a locally owned executor's credential in
2021
2734
  * `local` / `machine_token` mode, against the server's explicit `owner/name`;
@@ -2114,9 +2827,12 @@ async function launchCredentialForExecutor(ctx, readiness) {
2114
2827
  if (box !== undefined && box.resolved !== undefined) {
2115
2828
  return box.resolved?.kind === "local" ? box.resolved : null;
2116
2829
  }
2117
- if (readiness.resolved_merge_execution_mode !== "local")
2830
+ // BAPI-1595 — the mode and repository come from the full report when one is held,
2831
+ // otherwise from the preview's validated snapshot. No usable source: no credential.
2832
+ const source = readiness ?? credentialFactsOfSnapshot(ctx);
2833
+ if (source === null || source.resolved_merge_execution_mode !== "local")
2118
2834
  return null;
2119
- const repository = readiness.provider_repository;
2835
+ const repository = source.provider_repository;
2120
2836
  if (typeof repository !== "string" || !isProviderRepositoryIdentity(repository))
2121
2837
  return null;
2122
2838
  const resolved = await resolveLaunchCredentialOnce(ctx.deps, "local", repository, box);
@@ -2156,6 +2872,50 @@ async function collectLaunchEvidence(deps, readiness, topology, box) {
2156
2872
  worktree: await collectWorktreeEvidence(deps, topology),
2157
2873
  };
2158
2874
  }
2875
+ /**
2876
+ * BAPI-1595 — the two facts the merge-credential probe reads, taken from the
2877
+ * preview's validated snapshot. `null` when no usable snapshot (or no known facts)
2878
+ * is held. Never a rebuilt readiness report: only these two members exist.
2879
+ */
2880
+ function credentialFactsOfSnapshot(ctx) {
2881
+ const readiness = ctx.launchSnapshot?.context.readiness;
2882
+ if (readiness === undefined || readiness.state !== "known")
2883
+ return null;
2884
+ const mode = readiness.value.resolved_merge_execution_mode;
2885
+ return {
2886
+ resolved_merge_execution_mode: mode === "local" || mode === "machine_token" || mode === "github_actions" ? mode : null,
2887
+ provider_repository: readiness.value.provider_repository,
2888
+ };
2889
+ }
2890
+ /**
2891
+ * BAPI-1595 — the local launch-evidence gate for a launch that holds the preview's
2892
+ * snapshot but no full readiness report. It keeps the AC-3 local refusals — a merge
2893
+ * credential that is PROVEN missing, invalid, or without access, and a worktree
2894
+ * exclude proven unwritable — and nothing else. With no usable snapshot there is
2895
+ * nothing to probe against, and the server's create and approve decide.
2896
+ */
2897
+ async function snapshotLaunchEvidenceGate(ctx, topology, outcome) {
2898
+ const facts = credentialFactsOfSnapshot(ctx);
2899
+ if (facts === null)
2900
+ return null;
2901
+ const { deps, epicKey } = ctx;
2902
+ const evidence = {
2903
+ credential: await collectCredentialEvidence(deps, facts, topology, ctx.launchCredential),
2904
+ worktree: await collectWorktreeEvidence(deps, topology),
2905
+ };
2906
+ const blocker = firstLaunchEvidenceBlocker(buildLaunchEvidenceChecks({ attended: false, intoBase: false }, evidence));
2907
+ if (blocker === null)
2908
+ return null;
2909
+ const describe = blocker.id === MERGE_CREDENTIAL_ROW
2910
+ ? "a merge credential that has push and can read pull requests"
2911
+ : "an executor clone whose shared git exclude can be prepared";
2912
+ const remedy = `${blocker.detail ?? blocker.label}. ${blocker.remediation} See ${CONSUMER_GUIDE_POINTER}.`;
2913
+ return refuse(deps, [
2914
+ `${epicKey}: REFUSED (${blocker.id.slice(blocker.id.indexOf(".") + 1)}) — the launch still needs ${describe}.`,
2915
+ remedy,
2916
+ outcome,
2917
+ ]);
2918
+ }
2159
2919
  /**
2160
2920
  * The launch capability gate (BAPI-1452). Runs after readiness and executor
2161
2921
  * topology are resolved and BEFORE the run is created, dispatched, or given an
@@ -2169,8 +2929,12 @@ async function launchCapabilityGate(ctx, readiness, topology, outcome = "Nothing
2169
2929
  const { deps, epicKey, options } = ctx;
2170
2930
  if (!isUnattendedLaunch(options))
2171
2931
  return null;
2932
+ // BAPI-1593 — no report, no rows: the server's create and approve enforce what
2933
+ // these rows mirror. BAPI-1595 — the local PROVEN refusals (merge credential,
2934
+ // worktree) still run from the preview's snapshot when the launch holds one.
2935
+ if (readiness === null)
2936
+ return await snapshotLaunchEvidenceGate(ctx, topology, outcome);
2172
2937
  const evidence = await collectLaunchEvidence(deps, readiness, topology, ctx.launchCredential);
2173
- (deps.launchReadinessLog ?? deps.errorLog)(formatLaunchReadinessSummary(buildLaunchReadinessChecks(readiness, { launchEvidence: evidence }), { all: ctx.options.all, isProduction: readiness.is_production, prerequisites: readiness.prerequisites }).join("\n"));
2174
2938
  const classification = classifyV2Readiness(readiness, { attended: false, intoBase: false, effectivePolicy: ctx.handoff?.selection }, evidence);
2175
2939
  if (classification.kind !== "operator_blocked" || !LAUNCH_REFUSAL_IDS.includes(classification.id)) {
2176
2940
  return null;
@@ -2210,6 +2974,8 @@ async function previewLaunchCapability(ctx, readiness, topology) {
2210
2974
  return { checks, refusal: null };
2211
2975
  }
2212
2976
  function durableActorAdmissionDenied(readiness) {
2977
+ if (readiness === null)
2978
+ return false;
2213
2979
  const evidence = readiness.admission_evidence;
2214
2980
  return evidence?.schema_version === 1 &&
2215
2981
  evidence.records.some((record) => record.predicate === "durable_actor" && record.verdict === "denied");
@@ -2247,7 +3013,18 @@ const LAUNCHED_PLANE_LEFT_RUNNING = [
2247
3013
  * rebuilt from the manifest, sent as a query parameter, and never rendered.
2248
3014
  */
2249
3015
  async function checkPlaneAdmission(ctx, readiness, manifest) {
2250
- const bringUpRefusal = firstBringUpRefusal(readiness.bring_up ?? null);
3016
+ // BAPI-1593 — an unknown report proves no bring-up fact; the plane's own
3017
+ // reconciler is still confirmed below, from its own read. BAPI-1595 — only a
3018
+ // PROVEN-bad fact refuses (a second reconciler, a database behind head, a missing
3019
+ // worker). The facts come from the full report when one is held, otherwise from
3020
+ // the preview's validated snapshot; unreadable or unreported ones are unknown.
3021
+ const snapshotReadiness = ctx.launchSnapshot?.context.readiness;
3022
+ const bringUpFacts = readiness !== null
3023
+ ? (readiness.bring_up ?? null)
3024
+ : snapshotReadiness !== undefined && snapshotReadiness.state === "known"
3025
+ ? snapshotReadiness.value.bring_up
3026
+ : null;
3027
+ const bringUpRefusal = firstProvenBringUpRefusal(bringUpFacts);
2251
3028
  if (bringUpRefusal !== null) {
2252
3029
  return [
2253
3030
  `${ctx.epicKey}: REFUSED (${bringUpRefusal}) — ${BRING_UP_REFUSAL_MESSAGES[bringUpRefusal]}`,
@@ -2375,7 +3152,12 @@ function assessPlaneFreshness(reports, sleep, mode, allowStalePlane,
2375
3152
  * remedy, which never advises `plane down` for a run that is not finished.
2376
3153
  * Absent keeps `PLANE_SNAPSHOT_STALE_REMEDY` byte for byte.
2377
3154
  */
2378
- boundRun, cleanupPreview = false) {
3155
+ boundRun,
3156
+ /**
3157
+ * A create preview only: the plane server's other live runs (BAPI-1651).
3158
+ * The stale refusal becomes a cleanup warning only when this is `none`.
3159
+ */
3160
+ cleanupPreview = null) {
2379
3161
  const rows = [];
2380
3162
  const blockers = [];
2381
3163
  let overridden = false;
@@ -2409,7 +3191,7 @@ boundRun, cleanupPreview = false) {
2409
3191
  remedy: refusal.remedy,
2410
3192
  });
2411
3193
  }
2412
- else if (verdict === "refuse" && mode === "create" && !allowStalePlane && cleanupPreview &&
3194
+ else if (verdict === "refuse" && mode === "create" && !allowStalePlane && cleanupPreview?.kind === "none" &&
2413
3195
  id === PLANE_SNAPSHOT_FRESHNESS_ID && isTerminalRunCleanupStatus(boundRun?.status)) {
2414
3196
  rows.push({
2415
3197
  duration_ms, id, label, status: "warn", blocking: false,
@@ -2445,7 +3227,11 @@ boundRun, cleanupPreview = false) {
2445
3227
  if (reports !== null) {
2446
3228
  project(PLANE_SNAPSHOT_FRESHNESS_ID, "Plane snapshot freshness", reports.snapshot, {
2447
3229
  reasonId: "plane-snapshot-stale",
2448
- remedy: boundRun !== undefined ? formatBoundPlaneStaleRemedy(boundRun) : PLANE_SNAPSHOT_STALE_REMEDY,
3230
+ remedy: boundRun === undefined
3231
+ ? PLANE_SNAPSHOT_STALE_REMEDY
3232
+ : cleanupPreview !== null && cleanupPreview.kind !== "none" && isTerminalRunCleanupStatus(boundRun.status)
3233
+ ? formatSharedPlaneStaleRemedy(boundRun, cleanupPreview.kind === "live" ? cleanupPreview.epicRunId : null)
3234
+ : formatBoundPlaneStaleRemedy(boundRun),
2449
3235
  });
2450
3236
  project(PLANE_DATABASE_HEAD_ID, "Plane database head", reports.database, {
2451
3237
  reasonId: "plane-database-head-mismatch",
@@ -2515,6 +3301,13 @@ function renderFreshnessRows(rows, heading = 'Plane freshness:') {
2515
3301
  * it is never proof of staleness and never permission to skip another safeguard.
2516
3302
  */
2517
3303
  async function planeFreshnessCreateGuard(ctx, own, trailer = []) {
3304
+ // BAPI-1595 — plane freshness and the plane database head are Bridge-only. A
3305
+ // verified non-Bridge checkout skips both, with its fixed tally line; a Bridge,
3306
+ // a partial checkout, and an unestablished identity keep them.
3307
+ if (isConfirmedNonBridge(ctx)) {
3308
+ tallyBridgeOnlySkip(ctx, BRIDGE_ONLY_SKIPS.planeDatabaseHead);
3309
+ return null;
3310
+ }
2518
3311
  try {
2519
3312
  const reports = await collectFreshnessObservations(ctx, own);
2520
3313
  if (reports === null)
@@ -2525,9 +3318,7 @@ async function planeFreshnessCreateGuard(ctx, own, trailer = []) {
2525
3318
  // setup-epic REUSES the epic's live run instead of creating one, and a reuse
2526
3319
  // is an attachment: it is warned about, never refused. Asked only when a
2527
3320
  // confirmed finding would otherwise block, so the common path reads nothing.
2528
- const live = await ctx.deps
2529
- .readLiveEpicRun(ctx.access, ctx.epicKey)
2530
- .catch(() => ({ kind: "unknown" }));
3321
+ const live = await acquireObservedLive(ctx).catch(() => ({ kind: "unknown" }));
2531
3322
  if (live.kind === "live") {
2532
3323
  assessment = assessPlaneFreshness(reports, null, "attach", ctx.options.allowStalePlane === true, boundRun);
2533
3324
  }
@@ -2562,6 +3353,10 @@ async function planeFreshnessCreateGuard(ctx, own, trailer = []) {
2562
3353
  }
2563
3354
  /** The warning-only counterpart for an existing run. Never refuses, never throws. */
2564
3355
  async function surfacePlaneFreshnessForExistingRun(ctx, own) {
3356
+ if (isConfirmedNonBridge(ctx)) {
3357
+ tallyBridgeOnlySkip(ctx, BRIDGE_ONLY_SKIPS.planeDatabaseHead);
3358
+ return;
3359
+ }
2565
3360
  try {
2566
3361
  const reports = await collectFreshnessObservations(ctx, own);
2567
3362
  if (reports === null)
@@ -2581,19 +3376,60 @@ async function surfacePlaneFreshnessForExistingRun(ctx, own) {
2581
3376
  // Advisory only.
2582
3377
  }
2583
3378
  }
2584
- // ---------------------------------------------------------------------------
2585
- // BAPI-1496 — worker-database advisories on a LOCAL launch
2586
- // ---------------------------------------------------------------------------
3379
+ export const WORKER_DATABASE_UNPROVEN_REASON_CODE = "worker_database_configuration_unproven";
3380
+ export const WORKER_DATABASE_UNPROVEN_LINE = "worker database boundary: not checked (the project's database configuration was not reported)";
3381
+ export const WORKER_DATABASE_FALLBACK_REASON_CODE = "worker_database_configuration_defaulted";
3382
+ export const WORKER_DATABASE_FALLBACK_LINE = "worker database boundary: configuration not reported; checked with Bridge's own database names";
3383
+ export function resolveWorkerDatabaseApplicability(input) {
3384
+ const declared = input.declaration;
3385
+ if (declared !== null && declared !== undefined) {
3386
+ if (declared.mode === "none")
3387
+ return { kind: "skip", reason: "mode_none" };
3388
+ return {
3389
+ kind: "inspect",
3390
+ fallback: false,
3391
+ config: {
3392
+ status: "configured",
3393
+ mode: "disposable_postgres",
3394
+ ...(declared.worker_role !== null ? { workerRole: declared.worker_role } : {}),
3395
+ protectedDatabases: [...declared.protected_databases],
3396
+ envNames: [],
3397
+ },
3398
+ };
3399
+ }
3400
+ if (input.validContext && input.isBridge === true)
3401
+ return { kind: "inspect", config: undefined, fallback: true };
3402
+ return { kind: "unproven" };
3403
+ }
3404
+ /** The applicability for a real launch, from its validated snapshot and verified identity. */
3405
+ function launchWorkerDatabaseApplicability(ctx) {
3406
+ const readiness = ctx.launchSnapshot?.context.readiness;
3407
+ return resolveWorkerDatabaseApplicability({
3408
+ declaration: readiness?.state === "known" ? readiness.value.worker_database : null,
3409
+ validContext: ctx.launchSnapshot !== undefined && ctx.launchSnapshot !== null,
3410
+ isBridge: ctx.previewRepository?.isBridge,
3411
+ });
3412
+ }
3413
+ /** Copy the typed worker state onto its row so a consumer never reads `detail` prose. */
3414
+ function stampWorkerState(rows, section) {
3415
+ return rows.map((row) => {
3416
+ const source = section.rows.find((entry) => entry.id === row.id);
3417
+ return source !== undefined && (source.state === "unsafe" || source.state === "unknown")
3418
+ ? { ...row, worker_state: source.state }
3419
+ : row;
3420
+ });
3421
+ }
2587
3422
  /**
2588
3423
  * Run the worker-database inspection for a local-plane target, once.
2589
3424
  *
2590
3425
  * `null` when nothing applies: a target that is not this machine's plane never
2591
3426
  * runs the inspector, so a remote launch's requests and output are unchanged.
2592
3427
  * An inspector that throws or times out prints one fixed line naming only the
2593
- * closed classification, then yields the doctor's all-unknown section — whose
2594
- * `worker-db-unverifiable` row is a warning, never a refusal.
3428
+ * closed classification, then yields a section with NO rows: a launch shows no
3429
+ * advisory row for an inspection it could not make (BAPI-1594), and the
3430
+ * missing role row still resolves the role need to `unverifiable`.
2595
3431
  */
2596
- async function collectWorkerDatabaseAdvisory(deps, baseUrl, cache) {
3432
+ async function collectWorkerDatabaseAdvisory(deps, baseUrl, cache, config) {
2597
3433
  if (baseUrl === null || planeEndpointForBaseUrl(deps, baseUrl) === null)
2598
3434
  return null;
2599
3435
  const inspect = deps.inspectWorkerDatabase;
@@ -2601,16 +3437,12 @@ async function collectWorkerDatabaseAdvisory(deps, baseUrl, cache) {
2601
3437
  return null;
2602
3438
  const run = async () => {
2603
3439
  let failed = false;
2604
- const section = await collectWorkerDatabaseDoctorSection(() => inspect(deps.cwd()), WORKER_DATABASE_DOCTOR_TIMEOUT_MS, (failure) => {
3440
+ const section = await collectWorkerDatabaseDoctorSection(() => inspect(deps.cwd(), config), WORKER_DATABASE_DOCTOR_TIMEOUT_MS, (failure) => {
2605
3441
  failed = true;
2606
3442
  deps.errorLog(`worker-db inspection failed: ${failure}`);
2607
3443
  }).catch(() => null);
2608
- // A failed or timed-out inspection is ONE fact — the evidence is unverifiable —
2609
- // so a launch shows only the `worker-db-unverifiable` warning, not six unknown
2610
- // rows. The doctor's own all-unknown section is left as it is.
2611
- if (section !== null && failed) {
2612
- return { ...section, rows: section.rows.filter((row) => row.id === "worker-db-unverifiable") };
2613
- }
3444
+ if (section !== null && failed)
3445
+ return { ...section, rows: [] };
2614
3446
  return section;
2615
3447
  };
2616
3448
  if (cache === undefined)
@@ -2618,9 +3450,9 @@ async function collectWorkerDatabaseAdvisory(deps, baseUrl, cache) {
2618
3450
  cache.workerDatabase ??= run();
2619
3451
  return cache.workerDatabase;
2620
3452
  }
2621
- /** The advisory rows for a local launch: non-healthy `worker-db-*` warnings only. */
2622
- async function workerDatabaseAdvisoryRows(deps, baseUrl, cache) {
2623
- const section = await collectWorkerDatabaseAdvisory(deps, baseUrl, cache);
3453
+ /** The advisory rows for a local launch: non-healthy `worker-db-role` and `worker-db-boundary` warnings only. */
3454
+ async function workerDatabaseAdvisoryRows(deps, baseUrl, cache, config) {
3455
+ const section = await collectWorkerDatabaseAdvisory(deps, baseUrl, cache, config);
2624
3456
  return section === null ? [] : previewLaunchRows(workerDatabaseReadinessChecks(section));
2625
3457
  }
2626
3458
  /**
@@ -2631,8 +3463,24 @@ async function workerDatabaseAdvisoryRows(deps, baseUrl, cache) {
2631
3463
  * an unexpected failure prints nothing.
2632
3464
  */
2633
3465
  async function surfaceWorkerDatabaseAdvisory(ctx) {
3466
+ // BAPI-1596 — the configured mode decides, not the checkout's identity. A verified
3467
+ // non-Bridge checkout that declares no database skips with its one fixed tally line;
3468
+ // a configuration that was not reported is tallied and never inspected.
3469
+ const applicability = launchWorkerDatabaseApplicability(ctx);
3470
+ if (applicability.kind === "skip") {
3471
+ if (isConfirmedNonBridge(ctx))
3472
+ tallyBridgeOnlySkip(ctx, BRIDGE_ONLY_SKIPS.workerDatabase);
3473
+ return;
3474
+ }
3475
+ if (applicability.kind === "unproven") {
3476
+ tallyOnce(ctx, WORKER_DATABASE_UNPROVEN_REASON_CODE, WORKER_DATABASE_UNPROVEN_LINE, false);
3477
+ return;
3478
+ }
3479
+ if (applicability.fallback) {
3480
+ tallyOnce(ctx, WORKER_DATABASE_FALLBACK_REASON_CODE, WORKER_DATABASE_FALLBACK_LINE, false);
3481
+ }
2634
3482
  try {
2635
- const rows = await workerDatabaseAdvisoryRows(ctx.deps, ctx.access.baseUrl, ctx.freshness);
3483
+ const rows = await workerDatabaseAdvisoryRows(ctx.deps, ctx.access.baseUrl, ctx.freshness, applicability.config);
2636
3484
  if (rows.length === 0)
2637
3485
  return;
2638
3486
  const log = ctx.deps.launchReadinessLog ?? ctx.deps.errorLog;
@@ -2652,11 +3500,21 @@ async function surfaceWorkerDatabaseAdvisory(ctx) {
2652
3500
  * inspector and its JSON is unchanged. Never changes the decision, a refusal,
2653
3501
  * readiness, or the exit code.
2654
3502
  */
2655
- async function appendWorkerDatabaseAdvisoryRows(deps, preview, repository) {
2656
- if (repository?.isBridge === false) {
2657
- preview.launch_checks = [...(preview.launch_checks ?? []), ...nonBridgeRows(WORKER_DATABASE_PREVIEW_IDS)];
3503
+ async function appendWorkerDatabaseAdvisoryRows(deps, preview, repository, applicability) {
3504
+ // BAPI-1596 — gated on the configured mode, not on checkout identity. A verified
3505
+ // non-Bridge checkout keeps its two fixed `not_bridge_repository` skip rows.
3506
+ if (applicability.kind !== "inspect") {
3507
+ if (repository?.isBridge === false) {
3508
+ preview.launch_checks = [...(preview.launch_checks ?? []), ...nonBridgeRows(WORKER_DATABASE_PREVIEW_IDS)];
3509
+ }
3510
+ if (applicability.kind === "unproven") {
3511
+ (preview.tally_lines ??= []).push({ code: WORKER_DATABASE_UNPROVEN_REASON_CODE, line: WORKER_DATABASE_UNPROVEN_LINE });
3512
+ }
2658
3513
  return null;
2659
3514
  }
3515
+ if (applicability.fallback) {
3516
+ (preview.tally_lines ??= []).push({ code: WORKER_DATABASE_FALLBACK_REASON_CODE, line: WORKER_DATABASE_FALLBACK_LINE });
3517
+ }
2660
3518
  if (repository === undefined)
2661
3519
  return null;
2662
3520
  if (preview.target.kind !== "local_plane")
@@ -2664,8 +3522,8 @@ async function appendWorkerDatabaseAdvisoryRows(deps, preview, repository) {
2664
3522
  try {
2665
3523
  // BAPI-1506: the section is returned so the launch-need step reuses this one
2666
3524
  // inspection instead of running a second.
2667
- const section = await collectWorkerDatabaseAdvisory(deps, preview.target.base_url);
2668
- const rows = section === null ? [] : previewLaunchRows(workerDatabaseReadinessChecks(section));
3525
+ const section = await collectWorkerDatabaseAdvisory(deps, preview.target.base_url, undefined, applicability.config);
3526
+ const rows = section === null ? [] : stampWorkerState(previewLaunchRows(workerDatabaseReadinessChecks(section)), section);
2669
3527
  if (rows.length > 0)
2670
3528
  preview.launch_checks = [...(preview.launch_checks ?? []), ...rows];
2671
3529
  return section;
@@ -2741,11 +3599,6 @@ async function coldStartPlane(ctx) {
2741
3599
  ]);
2742
3600
  }
2743
3601
  }
2744
- // The cold start leaves the readiness `catch` before the ordinary advisory
2745
- // read is reached, so it surfaces the BAPI-1022 containment advisory itself —
2746
- // before anything is started, exactly as every other plan-file route does.
2747
- if (ctx.options.planFile)
2748
- await surfaceContainmentAdvisory(deps, ctx.options.planFile);
2749
3602
  deps.log(`${epicKey}: nothing is listening on the plane endpoint; cold-starting the local plane.`);
2750
3603
  const repoRoot = deps.cwd();
2751
3604
  // BAPI-1496: a plane bound to a finished run is torn down before preflight.
@@ -2760,28 +3613,23 @@ async function coldStartPlane(ctx) {
2760
3613
  "Nothing was started. Fix the item above and run drive-epic again.",
2761
3614
  ]);
2762
3615
  }
2763
- const controlPlane = await deps.launchControlPlane({ preflight, executors: 1 });
3616
+ const parallelColdRefusal = await parallelCreationCandidateRefusal(ctx);
3617
+ if (parallelColdRefusal !== null) {
3618
+ deps.errorLog(`${epicKey}: ${parallelColdRefusal}\nNothing was started.`);
3619
+ return 1;
3620
+ }
3621
+ const coldLanes = parallelLimitToExecutorLanes(ctx.options.parallel ?? DEFAULT_RUN_PARALLEL_LIMIT);
3622
+ const controlPlane = await deps.launchControlPlane({ preflight, executors: coldLanes });
2764
3623
  if (!controlPlane.ok) {
2765
3624
  return reportControlPlaneLaunchFailure(ctx, controlPlane);
2766
3625
  }
2767
3626
  void controlPlane.lifetime.catch(() => undefined);
2768
- // Read ONCE, for route selection only — the pre-launch read had no server to
2769
- // answer it. Not a runtime gate: runtime facts are not consulted here beyond
2770
- // the classification, which treats them as repairable.
2771
- let readiness;
2772
- try {
2773
- readiness = await deps.readReadiness(ctx.access);
2774
- }
2775
- catch (err) {
2776
- if (isSchemaIncompatibleError(err)) {
2777
- return refuse(deps, [...formatSchemaIncompatibleRefusal(epicKey, err), ...LAUNCHED_PLANE_LEFT_RUNNING]);
2778
- }
2779
- return refuse(deps, [
2780
- `${epicKey}: the plane came up, but its Epic Implementer readiness could not be read: ` +
2781
- safeDiagnosticMessage(err, "readiness request failed"),
2782
- ...LAUNCHED_PLANE_LEFT_RUNNING,
2783
- ]);
2784
- }
3627
+ // BAPI-1595 — a launch reads no readiness report, a cold start included. This
3628
+ // plane is a fresh server, so no stored snapshot describes it: say so once and
3629
+ // carry on with every evaluator on its unknown (warn) path. The server's create
3630
+ // and approve decide; the plane's own reconciler is still confirmed below.
3631
+ tallyOnce(ctx, SNAPSHOT_EXPIRED_REASON_CODE, SNAPSHOT_EXPIRED_WARNING);
3632
+ const readiness = launchFullReadiness();
2785
3633
  const prepared = await prepareSetupSelection(ctx);
2786
3634
  if (!prepared.ok) {
2787
3635
  return refuse(deps, [
@@ -2790,11 +3638,13 @@ async function coldStartPlane(ctx) {
2790
3638
  ]);
2791
3639
  }
2792
3640
  ctx = { ...ctx, handoff: prepared.handoff };
2793
- const classification = classifyV2Readiness(readiness, {
2794
- attended: ctx.options.attended === true,
2795
- intoBase: ctx.options.intoBase === true,
2796
- effectivePolicy: ctx.handoff?.selection,
2797
- });
3641
+ const classification = readiness === null
3642
+ ? classifySnapshotDiagnostics(ctx)
3643
+ : classifyV2Readiness(readiness, {
3644
+ attended: ctx.options.attended === true,
3645
+ intoBase: ctx.options.intoBase === true,
3646
+ effectivePolicy: ctx.handoff?.selection,
3647
+ });
2798
3648
  if (classification.kind === "operator_blocked") {
2799
3649
  return refuse(deps, [
2800
3650
  `${epicKey}: the engine path still needs ${classification.describe}.`,
@@ -2824,6 +3674,7 @@ async function coldStartPlane(ctx) {
2824
3674
  repoRoot,
2825
3675
  planeId: controlPlane.planeId,
2826
3676
  awaitPlaneReady: controlPlane.awaitPlaneReady,
3677
+ laneCount: coldLanes,
2827
3678
  }, readiness);
2828
3679
  }
2829
3680
  /**
@@ -2906,8 +3757,66 @@ async function attachToPlane(ctx, manifest, readiness) {
2906
3757
  repoRoot: manifest.repoRoot,
2907
3758
  planeId: manifest.planeId,
2908
3759
  ...(manifest.epicRunId !== undefined ? { boundRunId: manifest.epicRunId } : {}),
3760
+ laneCount: attachedPlaneLaneCount(manifest),
2909
3761
  }, readiness);
2910
3762
  }
3763
+ /**
3764
+ * The first lines of a setup refusal's follow-up text: the outcome first. A proven
3765
+ * pre-create refusal leads with "No run was created."; a confirmed branch move is
3766
+ * always named, so nothing ever claims "no branch changed" after one. Anything not
3767
+ * proven keeps today's text (no lead at all).
3768
+ */
3769
+ function refusalLeadLines(setup) {
3770
+ const lines = [];
3771
+ if (setup.refusedBeforeCreate === true)
3772
+ lines.push("", "No run was created.");
3773
+ if (setup.branchMove !== undefined) {
3774
+ const { branch, from, to } = setup.branchMove;
3775
+ lines.push(`Branch origin/${branch} was moved from ${from} to ${to} before this refusal.`);
3776
+ }
3777
+ return lines;
3778
+ }
3779
+ /**
3780
+ * Wind down the plane THIS invocation launched, but only when a leftover plane is
3781
+ * proven to hold no run: setup refused before any create request, no run id was
3782
+ * resolved, the plane was launched here (not attached), and a fresh manifest read
3783
+ * names the same plane with no bound run. Everything else returns
3784
+ * `not_applicable` and starts no shutdown.
3785
+ *
3786
+ * The outcome record is written (and awaited) as `pending` BEFORE `plane down`, and
3787
+ * rewritten as `completed` or `failed` after. A failed record write never blocks the
3788
+ * shutdown (the record is best-effort), and a failed shutdown never changes the
3789
+ * setup failure's exit code. `plane down` keeps enforcing its own ownership checks;
3790
+ * no retry, lifecycle state, or supervisor change is added here.
3791
+ */
3792
+ async function windDownProvenUnboundPlane(ctx, plane, setup) {
3793
+ if (setup.refusedBeforeCreate !== true || plane.origin !== "launched" || setup.epicRunId !== undefined) {
3794
+ return "not_applicable";
3795
+ }
3796
+ let unbound = false;
3797
+ try {
3798
+ const read = await ctx.deps.readPlaneManifest(plane.repoRoot);
3799
+ unbound = read.kind === "valid" && read.manifest.planeId === plane.planeId && read.manifest.epicRunId === undefined;
3800
+ }
3801
+ catch {
3802
+ unbound = false;
3803
+ }
3804
+ if (!unbound)
3805
+ return "not_applicable";
3806
+ const last = ctx.launchOutcomeState?.last ?? { outcome: "refused", observations: [] };
3807
+ const record = { ...last, refusedBeforeCreate: true };
3808
+ await writeLaunchOutcomeRecord(ctx, record, "pending");
3809
+ let confirmed = false;
3810
+ try {
3811
+ confirmed = (await ctx.deps.runPlane(["down"], { cwd: plane.repoRoot })) === 0;
3812
+ }
3813
+ catch {
3814
+ confirmed = false;
3815
+ }
3816
+ const finalState = confirmed ? "completed" : "failed";
3817
+ await writeLaunchOutcomeRecord(ctx, record, finalState);
3818
+ return finalState;
3819
+ }
2911
3820
  /**
2912
3821
  * The shared tail: create/approve/cut through `setup-epic`, then request lanes
2913
3822
  * scoped to exactly that run.
@@ -2922,33 +3831,53 @@ async function createRunAndRequestLanes(ctx, plane, readiness) {
2922
3831
  const launched = plane.origin === "launched";
2923
3832
  // BAPI-1452: a plane lane owns this run's executor, so the launch evidence
2924
3833
  // can only warn here; printed before the run exists.
2925
- if (readiness !== undefined) {
3834
+ if (readiness !== undefined && readiness !== null) {
2926
3835
  const gate = await launchCapabilityGate(ctx, readiness, { kind: "plane_lane" });
2927
3836
  if (gate !== null)
2928
3837
  return gate;
2929
3838
  }
2930
3839
  // ---- PHASE TWO, part one: create the run ------------------------------
2931
3840
  const setup = await runSelectedSetupEpic(ctx);
3841
+ if (setup.launchHandled === true)
3842
+ return setup.exitCode;
2932
3843
  if (setup.exitCode !== 0) {
2933
- // The control plane is deliberately LEFT RUNNING, and NO EXECUTOR LANE
2934
- // was spawned — there is nothing to claim a job that may not exist.
2935
- // Winding down automatically would stop the very run `setup-epic` may
2936
- // have just created, because `plane down` stops the manifest-bound run
2937
- // before terminating processes.
2938
- deps.errorLog((launched
2939
- ? [
2940
- "",
2941
- `${epicKey}: the Epic Implementer CONTROL PLANE was started by this invocation and is STILL RUNNING.`,
2942
- "No executor lane was spawned, so nothing is claiming jobs.",
2943
- "It was not wound down automatically, because doing so would stop a run that may",
2944
- "already have been created and approved. Inspect it with `plane status`, and wind it",
2945
- "down with `plane down` once you have decided what to do with the run.",
2946
- ]
2947
- : [
2948
- "",
2949
- `${epicKey}: the plane this invocation attached to was left running exactly as it was.`,
2950
- "No executor lane was requested. Inspect it with `plane status`.",
2951
- ]).join("\n"));
3844
+ // The control plane is LEFT RUNNING unless a narrow case is PROVEN safe, and NO
3845
+ // EXECUTOR LANE was spawned — there is nothing to claim a job that may not exist.
3846
+ // Winding down in general would stop the very run `setup-epic` may have just
3847
+ // created, because `plane down` stops the manifest-bound run before terminating
3848
+ // processes. The one exception is below: setup proved (by control flow, never by
3849
+ // text or exit code) that it refused BEFORE any create request, this invocation
3850
+ // started the plane, no run id was resolved, and the plane's manifest still names
3851
+ // this plane with no bound run. Then no run exists for `plane down` to stop.
3852
+ const windDown = await windDownProvenUnboundPlane(ctx, plane, setup);
3853
+ const lead = refusalLeadLines(setup);
3854
+ if (windDown === "completed") {
3855
+ deps.errorLog([...lead, `${epicKey}: the control plane this invocation started was shut down automatically.`].join("\n"));
3856
+ return setup.exitCode;
3857
+ }
3858
+ deps.errorLog([
3859
+ ...lead,
3860
+ ...(windDown === "failed"
3861
+ ? [
3862
+ "",
3863
+ `${epicKey}: Automatic shutdown could not be confirmed. Check the plane with \`plane status\`,`,
3864
+ "and wind it down with `plane down` if it is still running.",
3865
+ ]
3866
+ : launched
3867
+ ? [
3868
+ "",
3869
+ `${epicKey}: the Epic Implementer CONTROL PLANE was started by this invocation and is STILL RUNNING.`,
3870
+ "No executor lane was spawned, so nothing is claiming jobs.",
3871
+ "It was not wound down automatically, because doing so would stop a run that may",
3872
+ "already have been created and approved. Inspect it with `plane status`, and wind it",
3873
+ "down with `plane down` once you have decided what to do with the run.",
3874
+ ]
3875
+ : [
3876
+ "",
3877
+ `${epicKey}: the plane this invocation attached to was left running exactly as it was.`,
3878
+ "No executor lane was requested. Inspect it with `plane status`.",
3879
+ ]),
3880
+ ].join("\n"));
2952
3881
  return setup.exitCode;
2953
3882
  }
2954
3883
  if (setup.epicRunId === undefined) {
@@ -2997,6 +3926,7 @@ async function createRunAndRequestLanes(ctx, plane, readiness) {
2997
3926
  ].join("\n"));
2998
3927
  return 1;
2999
3928
  }
3929
+ reportPlaneCapacity(ctx, plane.laneCount, setup.parallelLimit, setup.runPosture);
3000
3930
  if (plane.awaitPlaneReady === undefined) {
3001
3931
  // Attached: the plane's own detached runtime performs the spawn and the
3002
3932
  // per-lane readiness gating, and this process may exit first. Its progress
@@ -3006,6 +3936,7 @@ async function createRunAndRequestLanes(ctx, plane, readiness) {
3006
3936
  `${epicKey}: attached — executor lane(s) scoped to run ${setup.epicRunId} were requested`,
3007
3937
  "from the running plane, whose runtime starts them and then the dead-man observer.",
3008
3938
  "`plane status` reports their progress; the run's own status reports dispatch.",
3939
+ KEEP_TERMINAL_OPEN_LINE,
3009
3940
  ].join("\n"));
3010
3941
  return 0;
3011
3942
  }
@@ -3041,6 +3972,7 @@ async function createRunAndRequestLanes(ctx, plane, readiness) {
3041
3972
  "That reports PROCESSES. If this run cuts an epic branch, the reconciler holds ticket",
3042
3973
  "dispatch until its index scope finishes preparing; `plane status` and the run's own",
3043
3974
  "status report that separately.",
3975
+ KEEP_TERMINAL_OPEN_LINE,
3044
3976
  ].join("\n"));
3045
3977
  return 0;
3046
3978
  }
@@ -3147,6 +4079,22 @@ function durableCoverageRefusal(epicKey, access, profile, coverage, outcome) {
3147
4079
  ],
3148
4080
  };
3149
4081
  }
4082
+ /**
4083
+ * BAPI-1595 — the durable-host coverage a launch may refuse on. The launch holds the
4084
+ * preview's snapshot rather than a report, so coverage refuses only when the snapshot
4085
+ * PROVES it absent (`false`); an unreported or unreadable value is unknown and the
4086
+ * server's create decides. A full report, when one is held, keeps its strict reading.
4087
+ */
4088
+ function durableCoverageOf(ctx, readiness) {
4089
+ if (readiness !== null)
4090
+ return readiness.executor.repo_wide_executor_live;
4091
+ const snapshotReadiness = ctx.launchSnapshot?.context.readiness;
4092
+ return snapshotReadiness !== undefined &&
4093
+ snapshotReadiness.state === "known" &&
4094
+ snapshotReadiness.value.repo_wide_executor_live === false
4095
+ ? false
4096
+ : true;
4097
+ }
3150
4098
  /** The pre-create refusal when no executor could ever be started from this checkout. */
3151
4099
  function executorPreconditionRefusal(epicKey, message, outcome) {
3152
4100
  return {
@@ -3188,21 +4136,6 @@ function liveRunAmbiguousRefusal(epicKey) {
3188
4136
  ],
3189
4137
  };
3190
4138
  }
3191
- /** BAPI-1285 — the epic's run state could not be read, so nothing may be assumed. */
3192
- function liveRunUnknownRefusal(epicKey, reason) {
3193
- const remedy = "Restore Bridge API access, then run drive-epic again. Creating a run without knowing " +
3194
- "whether one exists could mint a duplicate, which wedges the epic permanently.";
3195
- return {
3196
- reasonId: "live-run-unknown",
3197
- remedy,
3198
- lines: [
3199
- `${epicKey}: REFUSED (live-run-unknown) — the epic's run state could not be read (${reason}).`,
3200
- remedy,
3201
- "",
3202
- "Nothing was created and nothing was started.",
3203
- ],
3204
- };
3205
- }
3206
4139
  /**
3207
4140
  * Create the run, then make sure an executor will claim its jobs — the path for
3208
4141
  * every launch that does not request a plane lane.
@@ -3225,7 +4158,8 @@ async function createRunWithRunExecutor(ctx, readiness) {
3225
4158
  "No run was created and no local executor was started.",
3226
4159
  ]);
3227
4160
  }
3228
- const coverage = readiness.executor.repo_wide_executor_live;
4161
+ // BAPI-1593 — unknown readiness: the server's create and approve decide.
4162
+ const coverage = durableCoverageOf(ctx, readiness);
3229
4163
  if (coverage !== true) {
3230
4164
  return refuse(deps, durableCoverageRefusal(epicKey, access, profile, coverage, "No run was created").lines);
3231
4165
  }
@@ -3235,11 +4169,16 @@ async function createRunWithRunExecutor(ctx, readiness) {
3235
4169
  if (gate !== null)
3236
4170
  return gate;
3237
4171
  const setup = await runSelectedSetupEpic(ctx);
4172
+ if (setup.launchHandled === true)
4173
+ return setup.exitCode;
3238
4174
  if (setup.exitCode === 0) {
3239
4175
  deps.log([
3240
4176
  "",
3241
4177
  `${epicKey}: run ${setup.epicRunId ?? "(id not reported)"} created on ${access.baseUrl}.`,
3242
4178
  "The durable host's repo-wide executor claims its jobs; no local executor was started.",
4179
+ ...(setup.parallelLimit !== undefined && setup.runPosture === "unattended"
4180
+ ? [durableCapacityLine(setup.parallelLimit)]
4181
+ : []),
3243
4182
  ].join("\n"));
3244
4183
  }
3245
4184
  return setup.exitCode;
@@ -3255,9 +4194,11 @@ async function createRunWithRunExecutor(ctx, readiness) {
3255
4194
  if (gate !== null)
3256
4195
  return gate;
3257
4196
  const setup = await runSelectedSetupEpic(ctx);
4197
+ if (setup.launchHandled === true)
4198
+ return setup.exitCode;
3258
4199
  if (setup.exitCode !== 0) {
3259
4200
  // setup-epic already said why. Nothing was started for a run that may not exist.
3260
- deps.errorLog(`\n${epicKey}: no executor was started.`);
4201
+ deps.errorLog([...refusalLeadLines(setup), `\n${epicKey}: no executor was started.`].join("\n"));
3261
4202
  return setup.exitCode;
3262
4203
  }
3263
4204
  if (setup.epicRunId === undefined) {
@@ -3280,6 +4221,10 @@ async function createRunWithRunExecutor(ctx, readiness) {
3280
4221
  access,
3281
4222
  profile,
3282
4223
  mergeCredential: await launchCredentialForExecutor(ctx, readiness),
4224
+ // BAPI-1581 — the SERVER-stored limit, and only for a stored unattended run.
4225
+ ...(setup.runPosture === "unattended" && setup.parallelLimit !== undefined
4226
+ ? { maxConcurrent: setup.parallelLimit }
4227
+ : {}),
3283
4228
  });
3284
4229
  return reportExecutorOutcome(ctx, ensured, setup.epicRunId, "created");
3285
4230
  }
@@ -3328,12 +4273,17 @@ function reportExecutorOutcome(ctx, ensured, epicRunId, framing) {
3328
4273
  ? `${epicKey}: run ${epicRunId} is created on ${access.baseUrl}.`
3329
4274
  : `${epicKey}: run ${epicRunId} is already live on ${access.baseUrl}; nothing was created.`,
3330
4275
  started,
4276
+ ...(ensured.maxConcurrent !== undefined && ensured.maxConcurrent > 1
4277
+ ? [`It serves ${ensured.maxConcurrent} jobs at a time.`]
4278
+ : []),
4279
+ ...(ensured.capacityNotice !== undefined ? [ensured.capacityNotice] : []),
3331
4280
  "It claims only this run's jobs, and exits on its own once the run is done or abandoned.",
3332
4281
  ` Log: ${ensured.logPath}`,
3333
4282
  ` Record: ${ensured.recordPath}`,
3334
4283
  "It runs on THIS machine: sleep is held off while it runs, but a closed lid, a logout, or a",
3335
4284
  "shutdown stops it. The run stays server-side either way; restart the executor, or use a",
3336
4285
  "durable launch profile for long runs.",
4286
+ KEEP_TERMINAL_OPEN_LINE,
3337
4287
  ].join("\n"));
3338
4288
  return 0;
3339
4289
  }
@@ -3372,11 +4322,14 @@ async function planeServesLiveRun(ctx, live) {
3372
4322
  */
3373
4323
  async function attachToLiveRun(ctx, readiness, live, unusedDiscoveredPlan) {
3374
4324
  const { deps, epicKey, access, profile } = ctx;
3375
- const classification = classifyV2Readiness(readiness, {
3376
- attended: ctx.options.attended === true,
3377
- intoBase: ctx.options.intoBase === true,
3378
- approvedStoredPolicy: true,
3379
- });
4325
+ // BAPI-1593 — an unknown report proves nothing to refuse on: attach.
4326
+ const classification = readiness === null
4327
+ ? { kind: "green" }
4328
+ : classifyV2Readiness(readiness, {
4329
+ attended: ctx.options.attended === true,
4330
+ intoBase: ctx.options.intoBase === true,
4331
+ approvedStoredPolicy: true,
4332
+ });
3380
4333
  if (classification.kind === "operator_blocked") {
3381
4334
  return refuse(deps, [
3382
4335
  `${epicKey}: the engine path still needs ${classification.describe}.`,
@@ -3386,11 +4339,15 @@ async function attachToLiveRun(ctx, readiness, live, unusedDiscoveredPlan) {
3386
4339
  ]);
3387
4340
  }
3388
4341
  const planeTarget = planeEndpointForBaseUrl(deps, access.baseUrl) !== null;
3389
- if (classification.kind === "runtime_only") {
4342
+ if (classification.kind === "runtime_only" && readiness !== null) {
3390
4343
  if (!planeTarget)
3391
4344
  return refuseRemoteRuntime(ctx, readiness);
3392
4345
  return refuse(deps, localReconcilerRefusal(epicKey, readiness).lines);
3393
4346
  }
4347
+ await reportLaunchOutcome(ctx, live.status === "active" ? "active" : "pending_activation", {
4348
+ epicRunId: live.epicRunId,
4349
+ runStatus: live.status,
4350
+ });
3394
4351
  if (planeTarget) {
3395
4352
  const manifest = await findAttachablePlane(ctx).catch(() => null);
3396
4353
  if (manifest?.epicRunId === live.epicRunId) {
@@ -3414,8 +4371,15 @@ async function attachToLiveRun(ctx, readiness, live, unusedDiscoveredPlan) {
3414
4371
  "found, so nothing will be created; making sure it has an executor."
3415
4372
  : `${epicKey}: run ${live.epicRunId} is already live (${live.status}); the plan found by epic key ` +
3416
4373
  `(${unusedDiscoveredPlan}) is not used, so nothing will be created; making sure it has an executor.`);
4374
+ // BAPI-1581 — the limit and posture that GOVERN this run come from its stored
4375
+ // policy; launch flags never decide them. A missing stored policy reads as no
4376
+ // known limit and adds no executor concurrency.
4377
+ const storedParallel = live.effectivePolicy !== undefined && typeof live.effectivePolicy.parallel_limit === "number"
4378
+ ? live.effectivePolicy.parallel_limit
4379
+ : undefined;
4380
+ const storedUnattended = live.effectivePolicy?.posture === "unattended";
3417
4381
  if (live.effectivePolicy) {
3418
- deps.log(`Effective policy: stored; serial execution; caps ${live.effectivePolicy.caps ? JSON.stringify(live.effectivePolicy.caps) : "unavailable"}; ` +
4382
+ deps.log(`Effective policy: stored; parallel limit ${live.effectivePolicy.parallel_limit}; caps ${live.effectivePolicy.caps ? JSON.stringify(live.effectivePolicy.caps) : "unavailable"}; ` +
3419
4383
  `timeouts ${live.effectivePolicy.job_timeouts ? JSON.stringify(live.effectivePolicy.job_timeouts) : "unavailable"}; ` +
3420
4384
  `channel ${live.effectivePolicy.escalation_channel}.`);
3421
4385
  }
@@ -3426,7 +4390,9 @@ async function attachToLiveRun(ctx, readiness, live, unusedDiscoveredPlan) {
3426
4390
  "No run was changed and no local executor was started.",
3427
4391
  ]);
3428
4392
  }
3429
- const coverage = readiness.executor.repo_wide_executor_live;
4393
+ // BAPI-1593 — unknown readiness says nothing about coverage; the warning
4394
+ // already printed, and the run is left as it is.
4395
+ const coverage = durableCoverageOf(ctx, readiness);
3430
4396
  if (coverage !== true) {
3431
4397
  return refuse(deps, durableCoverageRefusal(epicKey, access, profile, coverage, "No run was changed").lines);
3432
4398
  }
@@ -3434,15 +4400,32 @@ async function attachToLiveRun(ctx, readiness, live, unusedDiscoveredPlan) {
3434
4400
  "",
3435
4401
  `${epicKey}: run ${live.epicRunId} is served by the durable host's confirmed repo-wide executor.`,
3436
4402
  "No local executor was started.",
4403
+ ...(storedParallel !== undefined && storedUnattended ? [durableCapacityLine(storedParallel)] : []),
3437
4404
  ].join("\n"));
3438
4405
  return 0;
3439
4406
  }
4407
+ // BAPI-1581 — one informational notice, never a refusal or a policy change.
4408
+ if (ctx.options.parallel !== undefined) {
4409
+ if (!storedUnattended) {
4410
+ deps.log(`${epicKey}: --parallel ${ctx.options.parallel} was not applied: run ${live.epicRunId} is not ` +
4411
+ "unattended, and the limit applies only to unattended runs. Nothing was changed.");
4412
+ }
4413
+ else if (storedParallel !== undefined) {
4414
+ const retained = retainedParallelLimitNotice(ctx.options.parallel, storedParallel);
4415
+ if (retained !== null)
4416
+ deps.log(retained);
4417
+ }
4418
+ }
3440
4419
  if (planeTarget && (await planeServesLiveRun(ctx, live))) {
3441
4420
  deps.log([
3442
4421
  "",
3443
4422
  `${epicKey}: this checkout's plane is bound to run ${live.epicRunId}; its executor lanes serve it.`,
3444
4423
  "No run-scoped executor was started beside them.",
3445
4424
  ].join("\n"));
4425
+ const servingManifest = await findAttachablePlane(ctx).catch(() => null);
4426
+ if (servingManifest !== null) {
4427
+ reportPlaneCapacity(ctx, attachedPlaneLaneCount(servingManifest), storedParallel, storedUnattended ? "unattended" : "attended");
4428
+ }
3446
4429
  return 0;
3447
4430
  }
3448
4431
  const prepared = await deps.prepareRunExecutor(deps.cwd());
@@ -3456,6 +4439,7 @@ async function attachToLiveRun(ctx, readiness, live, unusedDiscoveredPlan) {
3456
4439
  access,
3457
4440
  profile,
3458
4441
  mergeCredential: await launchCredentialForExecutor(ctx, readiness),
4442
+ ...(storedUnattended && storedParallel !== undefined ? { maxConcurrent: storedParallel } : {}),
3459
4443
  });
3460
4444
  return reportExecutorOutcome(ctx, ensured, live.epicRunId, "attached");
3461
4445
  }
@@ -3511,6 +4495,100 @@ function reportControlPlaneLaunchFailure(ctx, controlPlane) {
3511
4495
  "No run was created.",
3512
4496
  ]);
3513
4497
  }
4498
+ // ---------------------------------------------------------------------------
4499
+ // BAPI-1285 — the read-only launch preview (`--dry-run [--json]`)
4500
+ // ---------------------------------------------------------------------------
4501
+ //
4502
+ // The preview answers "what would a real invocation do?" and changes nothing. It
4503
+ // resolves the target, reads readiness and the epic's live run, discovers the
4504
+ // plan, and — when a plan is available — runs setup-epic's OWN dry run so the
4505
+ // server's real plan validator speaks. It never calls `adoptLaunchTarget`, a
4506
+ // non-dry `runSetupEpic`, `prepareRunExecutor`, `ensureRunExecutor`,
4507
+ // `launchControlPlane`, `runPlane`, or `requestScopedLanes`, and it never mutates
4508
+ // `process.env`.
4509
+ //
4510
+ // Output discipline: with `--json` stdout carries exactly ONE single-line JSON
4511
+ // document and nothing else, even on refusal. Nothing captured from setup-epic is
4512
+ // replayed, and no error text, credential, webhook URL, or policy content is ever
4513
+ // put into the document. The narrow exception is the production epic-launch
4514
+ // resolver's fixed sentences: they may name a store target key, store/profile
4515
+ // path, profile name, or validated safe binding target URL, never a credential
4516
+ // value or entry contents. Readiness, live-run, setup, and thrown errors remain
4517
+ // excluded.
4518
+ //
4519
+ // Known limits, stated plainly: the preview probes a port in exactly two narrow
4520
+ // cases, both after a local readiness read failed at the transport — a supplied
4521
+ // or discovered plan (to preview the guarded cold start), and no usable plan (the
4522
+ // plane-down stop, whose text is a verbatim part of the real launch's output).
4523
+ // Any other local plane that is not listening reads as unknown readiness; and a
4524
+ // local-plane target with only the reconciler missing previews as if the runtime
4525
+ // could be brought up, as a real launch with a plan composes.
4526
+ // BAPI-1594 — the engine's own paths live in their own module (they are Bridge repository
4527
+ // paths, not owner-facing text); re-exported here beside the preview definitions.
4528
+ export { ENGINE_PATHS };
4529
+ /** Bound for the one engine-path `git status`. */
4530
+ const ENGINE_STATUS_TIMEOUT_MS = 10_000;
4531
+ /** One porcelain-v1 `-z` record: two status columns, a space, then a path. */
4532
+ const PORCELAIN_RECORD = /^[ MTADRCU?!][ MTADRCU?!] [^\0]+$/;
4533
+ /**
4534
+ * Classify the NUL-delimited porcelain-v1 output of the engine-path status.
4535
+ * `clean` only for explicitly empty output. A rename or copy record is followed
4536
+ * by its origin path as a separate NUL-terminated field; a path-filtered rename
4537
+ * into or out of an engine path can legally appear as just the engine-side
4538
+ * addition or deletion. Anything that does not parse is `unreadable`, never clean.
4539
+ */
4540
+ function classifyEngineStatus(stdout) {
4541
+ if (typeof stdout !== "string")
4542
+ return "unreadable";
4543
+ if (stdout === "")
4544
+ return "clean";
4545
+ if (!stdout.endsWith("\0"))
4546
+ return "unreadable";
4547
+ const fields = stdout.slice(0, -1).split("\0");
4548
+ let records = 0;
4549
+ for (let i = 0; i < fields.length; i += 1) {
4550
+ const field = fields[i];
4551
+ if (!PORCELAIN_RECORD.test(field))
4552
+ return "unreadable";
4553
+ records += 1;
4554
+ if (/^[RC]/.test(field) || /^.[RC]/.test(field)) {
4555
+ // The rename/copy origin path follows as its own field.
4556
+ i += 1;
4557
+ if (i >= fields.length || fields[i] === "")
4558
+ return "unreadable";
4559
+ }
4560
+ }
4561
+ return records > 0 ? "dirty" : "unreadable";
4562
+ }
4563
+ /**
4564
+ * Collect the health-check fact for a verified Bridge LOCAL-plane create preview
4565
+ * (BAPI-1594). Advisory by construction: it never changes the decision, a
4566
+ * refusal, or the exit code, and nothing it saw (a filename, raw porcelain, an
4567
+ * error) reaches the document. Any uncertainty asks for the check.
4568
+ */
4569
+ async function appendHealthCheckFact(deps, preview, repository) {
4570
+ if (repository?.isBridge !== true || preview.target.kind !== "local_plane" || preview.decision !== "create")
4571
+ return;
4572
+ const exec = deps.execEngineStatus;
4573
+ if (exec === undefined)
4574
+ return;
4575
+ let outcome = "unreadable";
4576
+ try {
4577
+ const result = await exec("git", ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--", ...ENGINE_PATHS], { cwd: repository.repoRoot, timeoutMs: ENGINE_STATUS_TIMEOUT_MS });
4578
+ if (result !== null && typeof result === "object" && result.ok === true)
4579
+ outcome = classifyEngineStatus(result.stdout);
4580
+ }
4581
+ catch {
4582
+ outcome = "unreadable";
4583
+ }
4584
+ if (outcome === "clean") {
4585
+ preview.health_check_needed = false;
4586
+ }
4587
+ else {
4588
+ preview.health_check_needed = true;
4589
+ preview.health_check_reason = outcome === "dirty" ? "engine_paths_changed" : "git_status_unreadable";
4590
+ }
4591
+ }
3514
4592
  export const DRIVE_EPIC_ACCESS_REFUSAL_REASON_IDS = {
3515
4593
  "profile-unusable": "access-profile-unusable",
3516
4594
  "target-missing": "access-target-missing",
@@ -3521,7 +4599,7 @@ export const DRIVE_EPIC_ACCESS_REFUSAL_REASON_IDS = {
3521
4599
  "credentials-unavailable": "access-credentials-unavailable",
3522
4600
  "credential-unbound": "access-credential-unbound",
3523
4601
  };
3524
- const WORKER_DATABASE_PREVIEW_IDS = ["worker-db-role", "worker-db-boundary", "worker-db-alembic", "worker-db-leftovers", "worker-db-unverifiable", "worker-db-harness"];
4602
+ const WORKER_DATABASE_PREVIEW_IDS = ["worker-db-role", "worker-db-boundary"];
3525
4603
  function nonBridgeRows(ids) {
3526
4604
  return ids.map((id) => {
3527
4605
  const started = monotonicNow();
@@ -3541,24 +4619,32 @@ export function previewLaunchRows(checks) {
3541
4619
  blocking: check.blocking,
3542
4620
  ...(check.detail ? { detail: check.detail } : {}),
3543
4621
  ...(check.remediation ? { remedy: check.remediation } : {}),
3544
- ...harnessOwnerMetadata(check),
3545
4622
  };
3546
4623
  });
3547
4624
  }
3548
- /** BAPI-1558 — carry typed owner roles through the allowlist, for the harness row only, revalidated. */
3549
- function harnessOwnerMetadata(check) {
3550
- if (check.id !== "worker-db-harness")
3551
- return {};
3552
- const roles = sanitizeOwnerRoles(check.owner_roles);
3553
- const coverage = sanitizeHarnessCoverage(check.harness_coverage);
3554
- return {
3555
- ...(roles.length > 0 ? { owner_roles: roles, owner_role_total: sanitizeOwnerRoleTotal(check.owner_role_total, roles.length) } : {}),
3556
- ...(coverage ? { harness_coverage: coverage } : {}),
3557
- };
3558
- }
3559
4625
  /** The readiness reason a preview reports for a generic not-ready engine. */
3560
4626
  const ENGINE_NOT_READY_REASON_ID = "engine-not-ready";
3561
4627
  const ENGINE_NOT_READY_REMEDY = `Resolve Epic Implementer readiness (\`${PRINTED_CONDUCTOR_INSTALL_COMMAND}\`, then \`${PRINTED_DOCTOR_COMMAND}\`) and run drive-epic again. ${PRINTED_CHECK_NAME_INSTRUCTION} See ${CONSUMER_GUIDE_POINTER}.`;
4628
+ const CREATE_POLICY_PROJECTION_KEYS = [
4629
+ "posture",
4630
+ "v2_auto_merge_enabled",
4631
+ "merge_execution_mode",
4632
+ "integration_preparation",
4633
+ ];
4634
+ /** Structural check only: an object carrying exactly the four projection keys. */
4635
+ function readCreatePolicyEnvelope(value) {
4636
+ if (value === undefined)
4637
+ return { kind: "absent" };
4638
+ if (value === null || typeof value !== "object" || Array.isArray(value))
4639
+ return { kind: "malformed" };
4640
+ const record = value;
4641
+ const keys = Object.keys(record);
4642
+ if (keys.length !== CREATE_POLICY_PROJECTION_KEYS.length ||
4643
+ !CREATE_POLICY_PROJECTION_KEYS.every((key) => Object.prototype.hasOwnProperty.call(record, key))) {
4644
+ return { kind: "malformed" };
4645
+ }
4646
+ return { kind: "present", policy: record };
4647
+ }
3562
4648
  /**
3563
4649
  * Read exactly one well-shaped setup-epic dry-run JSON document out of captured
3564
4650
  * `log` output. Anything else — none, several, or one with the wrong shape — is
@@ -3615,7 +4701,15 @@ function readSetupPreviewPayload(stdout) {
3615
4701
  const jobTimeouts = numericMap(facts.job_timeouts);
3616
4702
  if (caps === undefined || jobTimeouts === undefined)
3617
4703
  return null;
4704
+ // BAPI-1581 — strict when present (an integer 1-4 or "server_default"); an
4705
+ // absent field is older setup output and stays absent.
4706
+ const rawParallel = facts.parallel_limit;
4707
+ if (rawParallel !== undefined &&
4708
+ rawParallel !== "server_default" &&
4709
+ !(typeof rawParallel === "number" && Number.isInteger(rawParallel) && rawParallel >= 1 && rawParallel <= 4))
4710
+ return null;
3618
4711
  effectivePolicy = {
4712
+ ...(rawParallel !== undefined ? { parallel_limit: rawParallel } : {}),
3619
4713
  source: facts.source,
3620
4714
  serial_execution: "serial",
3621
4715
  posture: facts.posture,
@@ -3640,21 +4734,126 @@ function readSetupPreviewPayload(stdout) {
3640
4734
  catch {
3641
4735
  return null;
3642
4736
  } })(),
4737
+ serverPlanHash: typeof doc.server_plan_hash === "string" && /^[A-Za-z0-9:_-]{8,128}$/.test(doc.server_plan_hash)
4738
+ ? doc.server_plan_hash
4739
+ : null,
4740
+ createPolicy: readCreatePolicyEnvelope(doc.create_policy),
3643
4741
  };
3644
4742
  }
3645
- /** The plan DAG's node count, or `null` unless it parses to `{ nodes: [...] }`. */
3646
- async function readPlanChildCount(deps, planPath) {
4743
+ /** The node count and the valid ticket keys in file order, or `null` unless the DAG has `{ nodes: [...] }`. */
4744
+ async function readPlanDagChildren(deps, planPath) {
3647
4745
  try {
3648
4746
  const parsed = JSON.parse(await deps.readPlanDag(planPath));
3649
4747
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
3650
4748
  return null;
3651
4749
  const nodes = parsed.nodes;
3652
- return Array.isArray(nodes) ? nodes.length : null;
4750
+ if (!Array.isArray(nodes))
4751
+ return null;
4752
+ const keys = [];
4753
+ for (const node of nodes) {
4754
+ const key = node !== null && typeof node === "object" ? node.ticket_key : undefined;
4755
+ if (typeof key === "string" && EPIC_KEY_PATTERN.test(key))
4756
+ keys.push(key);
4757
+ }
4758
+ return { count: nodes.length, keys };
3653
4759
  }
3654
4760
  catch {
3655
4761
  return null;
3656
4762
  }
3657
4763
  }
4764
+ /**
4765
+ * BAPI-1621 — serve a generated preview's plan from memory.
4766
+ *
4767
+ * Every preview read of the plan goes through `readPlanDag`, setup-epic's dry
4768
+ * run, or `withPlanPath` (the trimmed copy when merged children are skipped).
4769
+ * This overlay answers all three for `planPath` without touching the disk, so a
4770
+ * generated preview stays completely read-only. Every other path reads as before.
4771
+ */
4772
+ function withInlinePlan(deps, planPath, json) {
4773
+ const files = new Map([[planPath, json]]);
4774
+ const inner = deps.withPlanPath ?? withPlanPath;
4775
+ const inMemoryWithPlanPath = async (options, callback) => {
4776
+ if (!options.skipped || options.originalPath !== planPath)
4777
+ return inner(options, callback);
4778
+ const trimmedPath = planPath.replace(/\.json$/, ".trimmed.json");
4779
+ files.set(trimmedPath, options.trimmedJson);
4780
+ try {
4781
+ return await callback(trimmedPath);
4782
+ }
4783
+ finally {
4784
+ files.delete(trimmedPath);
4785
+ }
4786
+ };
4787
+ return {
4788
+ ...deps,
4789
+ readPlanDag: (filePath) => {
4790
+ const inline = files.get(filePath);
4791
+ return inline !== undefined ? Promise.resolve(inline) : deps.readPlanDag(filePath);
4792
+ },
4793
+ previewSetupEpic: (args) => deps.previewSetupEpic({ ...args, planContents: files }),
4794
+ withPlanPath: inMemoryWithPlanPath,
4795
+ };
4796
+ }
4797
+ /**
4798
+ * BAPI-1621 — a found generated plan's nodes for the launch screen, read from the
4799
+ * DAG on disk. Null when the file cannot be read or is not a node list; the
4800
+ * preview's own validation stays the authority on the plan.
4801
+ */
4802
+ async function readGeneratedPlanNodes(deps, planPath) {
4803
+ try {
4804
+ const parsed = JSON.parse(await deps.readPlanDag(planPath));
4805
+ const nodes = parsed?.nodes;
4806
+ if (!Array.isArray(nodes))
4807
+ return null;
4808
+ const result = [];
4809
+ for (const raw of nodes) {
4810
+ const node = raw;
4811
+ if (typeof node?.ticket_key !== "string" || !EPIC_KEY_PATTERN.test(node.ticket_key))
4812
+ return null;
4813
+ if (node.status !== "planned" && node.status !== "done")
4814
+ return null;
4815
+ const dependsOn = Array.isArray(node.depends_on) ? node.depends_on : [];
4816
+ if (!dependsOn.every((dep) => typeof dep === "string" && EPIC_KEY_PATTERN.test(dep)))
4817
+ return null;
4818
+ result.push({
4819
+ ticket_key: node.ticket_key,
4820
+ status: node.status,
4821
+ depends_on: dependsOn,
4822
+ ...(Array.isArray(node.touched_files) ? { touched_files: node.touched_files.filter((f) => typeof f === "string") } : {}),
4823
+ });
4824
+ }
4825
+ return result;
4826
+ }
4827
+ catch {
4828
+ return null;
4829
+ }
4830
+ }
4831
+ /**
4832
+ * BAPI-1648 — the names of approved credential references whose source is
4833
+ * missing or unreadable. The repository name is the verified Bridge name the
4834
+ * preview already resolved, never a folder or remote name. Every failure, and an
4835
+ * absent or unusable record, yields an empty list: this is a display aid and
4836
+ * must not reach launch control flow.
4837
+ */
4838
+ async function collectMissingCredentialNames(deps, observed) {
4839
+ const repoName = observed.repoName ?? observed.access?.repoName ?? observed.contextAccess?.repoName;
4840
+ if (repoName === undefined || deps.readCredentialReferenceStatus === undefined)
4841
+ return [];
4842
+ try {
4843
+ const result = await deps.readCredentialReferenceStatus(repoName);
4844
+ if (result.state !== "ok")
4845
+ return [];
4846
+ const names = new Set();
4847
+ for (const status of result.statuses) {
4848
+ if (status.state === "missing" || status.state === "unreadable")
4849
+ names.add(status.name);
4850
+ }
4851
+ return [...names].sort();
4852
+ }
4853
+ catch {
4854
+ return [];
4855
+ }
4856
+ }
3658
4857
  /**
3659
4858
  * Run the read-only preview. Returns `0` for a `create` or `attach` decision and
3660
4859
  * `1` for `refuse` or `stop`. Never throws: an unexpected failure becomes one
@@ -3704,12 +4903,21 @@ async function runDriveEpicPreview(deps, options) {
3704
4903
  */
3705
4904
  const refuseWithReadiness = (kind, named, _alsoTopLevel = false) => {
3706
4905
  preview.readiness = { kind, reason_id: named.reasonId, remedy: named.remedy };
3707
- preview.refusal = { reason_id: named.reasonId, remedy: named.remedy };
4906
+ // BAPI-1596: `operator_blocked` is the classification that rests on proven evidence.
4907
+ preview.refusal = {
4908
+ reason_id: named.reasonId,
4909
+ remedy: named.remedy,
4910
+ ...(kind === "operator_blocked" ? { authoritative: true } : {}),
4911
+ };
3708
4912
  preview.decision = "refuse";
3709
4913
  };
3710
4914
  /** A refusal that is not about readiness: only the top-level block carries it. */
3711
4915
  const refuseTopLevel = (named) => {
3712
- preview.refusal = { reason_id: named.reasonId, remedy: named.remedy };
4916
+ preview.refusal = {
4917
+ reason_id: named.reasonId,
4918
+ remedy: named.remedy,
4919
+ ...(named.authoritative === true ? { authoritative: true } : {}),
4920
+ };
3713
4921
  preview.decision = "refuse";
3714
4922
  };
3715
4923
  // The readiness read previewDecision observed, for the reachability row. It stays
@@ -3728,10 +4936,14 @@ async function runDriveEpicPreview(deps, options) {
3728
4936
  });
3729
4937
  }
3730
4938
  ensureRefusalExplained(preview);
4939
+ preview.credentials_missing = await collectMissingCredentialNames(deps, observed);
4940
+ await writePreviewLaunchContext(deps, options, preview, observed);
3731
4941
  if (observed.repository?.isBridge === false && !preview.launch_checks?.some((row) => row.id === "plane-snapshot-freshness")) {
3732
4942
  preview.launch_checks = [...(preview.launch_checks ?? []), ...nonBridgeRows(["plane-snapshot-freshness", "plane-database-head"])];
3733
4943
  }
3734
- const isolated = () => ({ ...preview, launch_checks: [] });
4944
+ // Each probe writes to a private copy. `tally_lines` and `warnings` start empty on a copy
4945
+ // (a shared array would double-count; an absent one would be lost) and are merged back below.
4946
+ const isolated = () => ({ ...preview, launch_checks: [], tally_lines: undefined, warnings: undefined });
3735
4947
  const worker = isolated();
3736
4948
  const escalation = isolated();
3737
4949
  const executor = isolated();
@@ -3740,15 +4952,23 @@ async function runDriveEpicPreview(deps, options) {
3740
4952
  if (scopeBase)
3741
4953
  previewScopeBaseBranch.set(needs, scopeBase);
3742
4954
  // Collect into private arrays; only launch-needs waits for the worker result.
3743
- const workerTask = timed("worker_database_ms", () => appendWorkerDatabaseAdvisoryRows(deps, worker, observed.repository));
4955
+ // BAPI-1596 — the boundary follows the configured mode, from the readiness this preview
4956
+ // already holds (the same projection the launch-context file stores). No extra read.
4957
+ const applicability = resolveWorkerDatabaseApplicability({
4958
+ declaration: projectWorkerDatabase(observed.readiness?.gate_profile?.worker_database),
4959
+ validContext: observed.readiness !== null,
4960
+ isBridge: observed.repository?.isBridge,
4961
+ });
4962
+ const workerTask = timed("worker_database_ms", () => appendWorkerDatabaseAdvisoryRows(deps, worker, observed.repository, applicability));
3744
4963
  const needsTask = workerTask.then((section) => {
3745
4964
  needs.launch_checks = [...(worker.launch_checks ?? [])];
3746
- return timed("launch_needs_ms", () => appendLaunchNeedRows(deps, needs, observed, section));
4965
+ return timed("launch_needs_ms", () => appendLaunchNeedRows(deps, needs, observed, section, applicability));
3747
4966
  });
3748
4967
  await Promise.all([
3749
4968
  needsTask,
4969
+ timed("health_status_ms", () => appendHealthCheckFact(deps, preview, observed.repository)),
3750
4970
  timed("escalation_ms", async () => { appendEscalationReachabilityRow(escalation, observed.readiness); }),
3751
- timed("executor_build_ms", () => appendExecutorBuildFreshnessWarning(deps, executor)),
4971
+ timed("executor_build_ms", () => appendExecutorBuildFreshnessWarning(deps, executor, observed.repository)),
3752
4972
  ]);
3753
4973
  const workerIds = new Set(worker.launch_checks?.map((row) => row.id));
3754
4974
  const needRows = needs.launch_checks ?? [];
@@ -3757,14 +4977,21 @@ async function runDriveEpicPreview(deps, options) {
3757
4977
  ...(escalation.launch_checks ?? []), ...(executor.launch_checks ?? []),
3758
4978
  ...needRows.filter((row) => !workerIds.has(row.id)),
3759
4979
  ];
3760
- if (preview.decision === "create") {
4980
+ mergeIsolatedObservations(preview, escalation, [worker, escalation, executor, needs]);
4981
+ // BAPI-1596 — the plan is built once, from the finished preview, and only for a create
4982
+ // or a refusal the preview selected as authoritative. A failure leaves no plan; the
4983
+ // session then shows the plain older-CLI screen and computes nothing.
4984
+ if (preview.decision === "create" || (preview.decision === "refuse" && preview.refusal?.authoritative === true)) {
3761
4985
  try {
3762
- const result = (deps.buildLaunchPlan ?? buildLaunchPlan)(preview);
4986
+ const collected = await collectLaunchPlanFacts(deps, options, preview, observed);
4987
+ // The tally lines do not depend on the builder succeeding.
4988
+ recordLaunchPlanObservations(preview, collected.tally);
4989
+ const result = (deps.buildLaunchPlan ?? buildLaunchPlan)(preview, collected.facts);
3763
4990
  if (result)
3764
4991
  preview.launch_plan = result.launch_plan;
3765
4992
  }
3766
4993
  catch {
3767
- deps.errorLog("Launch plan unavailable; the driving session will compute it.");
4994
+ deps.errorLog("Launch plan unavailable; the preview carries no plan.");
3768
4995
  }
3769
4996
  }
3770
4997
  timings.total_ms = elapsedMs(started);
@@ -3775,6 +5002,160 @@ async function runDriveEpicPreview(deps, options) {
3775
5002
  return 1;
3776
5003
  return preview.decision === "create" || preview.decision === "attach" ? 0 : 1;
3777
5004
  }
5005
+ /** The plan's child keys per preview, in file order. Kept off the document. */
5006
+ const previewPlanChildKeys = new WeakMap();
5007
+ /** The most time a launch preview spends reading the prerequisite cache before it carries on without it. */
5008
+ const PREREQUISITE_CACHE_READ_TIMEOUT_MS = 10_000;
5009
+ const PREREQUISITE_ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
5010
+ function handoffValueText(value) {
5011
+ return value === "unknown" ? "unknown (today's default: proceed)" : value;
5012
+ }
5013
+ /**
5014
+ * BAPI-1596 — collect the launch plan's facts ONCE, from evidence the preview already
5015
+ * holds. The only new reads are the injected cache read and a boolean-only presence
5016
+ * check per distinct core variable name. Nothing here reads an environment value,
5017
+ * refuses, or changes a decision; unavailable evidence is tallied and the launch goes on.
5018
+ */
5019
+ async function collectLaunchPlanFacts(deps, options, preview, observed) {
5020
+ const tally = [];
5021
+ // The hand-off policy this launch will stamp, and the project default beside it.
5022
+ const reported = observed.readiness?.gate_profile?.verification_handoff_default;
5023
+ const projectDefault = reported === "proceed" || reported === "block" ? reported : "unknown";
5024
+ const explicit = options.verificationHandoff === "proceed" || options.verificationHandoff === "block"
5025
+ ? options.verificationHandoff
5026
+ : null;
5027
+ const handoff = { explicit, projectDefault };
5028
+ const effective = explicit ?? projectDefault;
5029
+ const source = explicit !== null ? "explicit choice"
5030
+ : projectDefault !== "unknown" ? "project default"
5031
+ : observed.readiness === null ? "readiness not read" : "older server, no default reported";
5032
+ tally.push({
5033
+ code: "verification_handoff_policy",
5034
+ line: `verification hand-off: ${handoffValueText(effective)} (${source}); project default ${handoffValueText(projectDefault)}`,
5035
+ });
5036
+ // Child 5's cache, for the children this launch will actually run.
5037
+ let prerequisites = { status: "not_collected" };
5038
+ const keys = previewPlanChildKeys.get(preview);
5039
+ if (deps.readPrerequisiteCache !== undefined && keys !== undefined) {
5040
+ const skipped = new Set();
5041
+ const merged = preview.already_done_children;
5042
+ if (merged !== undefined && merged.status === "checked") {
5043
+ for (const child of merged.children)
5044
+ if (child.will_skip === true)
5045
+ skipped.add(child.ticket_key);
5046
+ }
5047
+ const members = new Set(keys.filter((key) => !skipped.has(key)));
5048
+ let read;
5049
+ try {
5050
+ read = observed.contextAccess === undefined
5051
+ ? { kind: "unavailable" }
5052
+ : await deps.readPrerequisiteCache({ epicKey: options.epicKey, children: keys, access: observed.contextAccess });
5053
+ }
5054
+ catch {
5055
+ read = { kind: "unavailable" };
5056
+ }
5057
+ if (read.kind === "unavailable") {
5058
+ tally.push({ code: "prerequisite_cache_unavailable", line: "prerequisite scan: cache not read at preview" });
5059
+ }
5060
+ else {
5061
+ const hasEnv = deps.hasEnvName ?? ((name) => Object.hasOwn(process.env, name));
5062
+ const presence = new Map();
5063
+ const missing = new Map();
5064
+ const runtimeChildren = new Set();
5065
+ const kept = { minor: 0, "observed present": 0, "worker runtime": 0, "not measurable": 0, skipped: 0 };
5066
+ for (const entry of read.entries) {
5067
+ if (!members.has(entry.child)) {
5068
+ kept.skipped += entry.items.length;
5069
+ continue;
5070
+ }
5071
+ for (const item of entry.items) {
5072
+ if ("category" in item) {
5073
+ kept["worker runtime"] += 1;
5074
+ runtimeChildren.add(entry.child);
5075
+ continue;
5076
+ }
5077
+ if ("measurable" in item) {
5078
+ kept["not measurable"] += 1;
5079
+ continue;
5080
+ }
5081
+ if (item.class !== "core") {
5082
+ kept.minor += 1;
5083
+ continue;
5084
+ }
5085
+ if (!PREREQUISITE_ENV_NAME.test(item.env)) {
5086
+ kept["not measurable"] += 1;
5087
+ continue;
5088
+ }
5089
+ if (!presence.has(item.env))
5090
+ presence.set(item.env, hasEnv(item.env));
5091
+ if (presence.get(item.env) === true) {
5092
+ kept["observed present"] += 1;
5093
+ continue;
5094
+ }
5095
+ const mapKey = `${item.env}:${item.uncertain}`;
5096
+ const prior = missing.get(mapKey);
5097
+ missing.set(mapKey, prior === undefined
5098
+ ? { name: item.env, requirement: item.requirement, dependents: item.dependents, uncertain: item.uncertain === "yes" }
5099
+ : { ...prior, dependents: prior.dependents.split(", ").includes(item.dependents) ? prior.dependents : `${prior.dependents}, ${item.dependents}` });
5100
+ }
5101
+ }
5102
+ for (const [category, count] of Object.entries(kept)) {
5103
+ if (count > 0)
5104
+ tally.push({ code: "prerequisite_kept_off_screen", line: `prerequisite scan: kept off the screen: ${category} ${count}` });
5105
+ }
5106
+ prerequisites = {
5107
+ status: "collected",
5108
+ missingCore: [...missing.values()],
5109
+ workerRuntimeChildren: [...runtimeChildren],
5110
+ };
5111
+ }
5112
+ }
5113
+ // Launch rows the screen leaves out, so nothing is silent.
5114
+ const suppressed = [];
5115
+ // Server rows that only warn (for example an unset integration branch) never reach the screen;
5116
+ // the webhook row is the one warning the plan presents.
5117
+ for (const row of preview.prerequisites ?? []) {
5118
+ if (row.impact === "warning" && row.check_status === "not_met" && row.id !== SERVER_WEBHOOK_ROW_ID) {
5119
+ suppressed.push(row.id.replace(/^server\./, ""));
5120
+ }
5121
+ }
5122
+ // Rows the plan presents are the three launch needs and the proven boundary; any other
5123
+ // warning or failing launch row stays in the preview's rows and is named here.
5124
+ const PRESENTED_ROWS = new Set([...Object.values(LAUNCH_NEED_ROW_IDS), "worker-db-boundary"]);
5125
+ for (const row of preview.launch_checks ?? []) {
5126
+ if ((row.status === "warn" || row.status === "fail") && !PRESENTED_ROWS.has(row.id) &&
5127
+ row.id !== ESCALATION_REACHABILITY_CHECK_ID) {
5128
+ suppressed.push(row.id);
5129
+ }
5130
+ }
5131
+ if (suppressed.length > 0) {
5132
+ tally.push({ code: "launch_rows_kept_off_screen", line: `launch rows kept off the screen: ${[...new Set(suppressed)].join(", ")}` });
5133
+ }
5134
+ return { facts: { prerequisites, handoff }, tally };
5135
+ }
5136
+ /** Append the collected fixed lines to the preview's tally lines, once each. */
5137
+ function recordLaunchPlanObservations(preview, lines) {
5138
+ if (lines.length === 0)
5139
+ return;
5140
+ const seen = new Set((preview.tally_lines ?? []).map((entry) => `${entry.code}\u0000${entry.line}`));
5141
+ const fresh = lines.filter((entry) => !seen.has(`${entry.code}\u0000${entry.line}`));
5142
+ if (fresh.length > 0)
5143
+ preview.tally_lines = [...(preview.tally_lines ?? []), ...fresh];
5144
+ }
5145
+ /** Fold the private copies' tally lines, warnings, and escalation presentation back into the preview. */
5146
+ function mergeIsolatedObservations(preview, escalation, parts) {
5147
+ for (const part of parts) {
5148
+ if (part.tally_lines !== undefined && part.tally_lines.length > 0) {
5149
+ preview.tally_lines = [...(preview.tally_lines ?? []), ...part.tally_lines];
5150
+ }
5151
+ if (part.warnings !== undefined && part.warnings.length > 0) {
5152
+ preview.warnings = [...(preview.warnings ?? []), ...part.warnings];
5153
+ }
5154
+ }
5155
+ const presentation = previewEscalationPresentation.get(escalation);
5156
+ if (presentation !== undefined)
5157
+ previewEscalationPresentation.set(preview, presentation);
5158
+ }
3778
5159
  /**
3779
5160
  * Give every `create` or `attach` preview exactly one non-blocking
3780
5161
  * `escalation-reachability` row (BAPI-1490).
@@ -3785,13 +5166,40 @@ async function runDriveEpicPreview(deps, options) {
3785
5166
  * read failure) is passed as unavailable, so the row warns rather than vanishing.
3786
5167
  * A refused or stopped preview describes no launch, so it gets none.
3787
5168
  */
5169
+ /** BAPI-1595 — what each preview's reachability output may claim. Kept off the JSON document. */
5170
+ const previewEscalationPresentation = new WeakMap();
3788
5171
  function appendEscalationReachabilityRow(preview, readiness) {
3789
5172
  const started = monotonicNow();
3790
5173
  if (preview.decision !== "create" && preview.decision !== "attach")
3791
5174
  return;
5175
+ // BAPI-1598 — fixed tally lines for the worker-database and hand-off settings the
5176
+ // readiness already reported. An older server reports neither, so nothing is added.
5177
+ for (const entry of workerSetupTallyEntries(readiness?.gate_profile)) {
5178
+ (preview.tally_lines ??= []).push({ code: entry.code, line: entry.message });
5179
+ }
3792
5180
  const [row] = previewLaunchRows([
3793
5181
  buildEscalationReachabilityCheck(readiness, preview.summary.escalation_channel),
3794
5182
  ]);
5183
+ // BAPI-1595 — decide what the output may SAY. The JSON row stays (an older reader
5184
+ // and the launch plan treat an absent row as "unconfirmed"); the human line is
5185
+ // shown only when it is true, and a left-out line is written to the tally once.
5186
+ const presentation = classifyEscalationReachabilityPresentation(readiness, preview.summary.escalation_channel);
5187
+ previewEscalationPresentation.set(preview, presentation);
5188
+ if (presentation === "uncertain") {
5189
+ (preview.warnings ??= []).push(ESCALATION_CHANNEL_UNCERTAIN_WARNING);
5190
+ }
5191
+ if (presentation === "uncertain" || presentation === "omitted") {
5192
+ (preview.tally_lines ??= []).push({
5193
+ code: ESCALATION_LINE_SUPPRESSED_REASON_CODE,
5194
+ line: ESCALATION_LINE_SUPPRESSED_LINE,
5195
+ });
5196
+ }
5197
+ if (presentation === "uncertain") {
5198
+ (preview.tally_lines ??= []).push({
5199
+ code: ESCALATION_CHANNEL_UNCERTAIN_REASON_CODE,
5200
+ line: ESCALATION_CHANNEL_UNCERTAIN_WARNING,
5201
+ });
5202
+ }
3795
5203
  preview.launch_checks = [
3796
5204
  ...(preview.launch_checks ?? []).filter((existing) => existing.id !== ESCALATION_REACHABILITY_CHECK_ID),
3797
5205
  { ...row, duration_ms: elapsedMs(started) },
@@ -3805,7 +5213,7 @@ function appendEscalationReachabilityRow(preview, readiness) {
3805
5213
  * missing dependency leaves `launch_checks` untouched. A thrown check prints one
3806
5214
  * fixed line and nothing from the exception.
3807
5215
  */
3808
- async function appendExecutorBuildFreshnessWarning(deps, preview) {
5216
+ async function appendExecutorBuildFreshnessWarning(deps, preview, repository) {
3809
5217
  const started = monotonicNow();
3810
5218
  const override = process.env[BRIDGE_LAUNCHER_ENV];
3811
5219
  if (override === undefined || override.trim() === "")
@@ -3813,7 +5221,7 @@ async function appendExecutorBuildFreshnessWarning(deps, preview) {
3813
5221
  if (deps.checkExecutorBuildFreshness === undefined)
3814
5222
  return;
3815
5223
  try {
3816
- const report = await deps.checkExecutorBuildFreshness(deps.cwd());
5224
+ const report = await deps.checkExecutorBuildFreshness(deps.cwd(), repository?.isBridge === false ? { isBridge: false } : undefined);
3817
5225
  if (report.diagnostic === null)
3818
5226
  return;
3819
5227
  const outcome = report.outcomes.find((entry) => entry.status === "warn" || entry.status === "fail") ?? report.outcomes[0];
@@ -3837,6 +5245,70 @@ async function appendExecutorBuildFreshnessWarning(deps, preview) {
3837
5245
  * preview document so its JSON shape is unchanged.
3838
5246
  */
3839
5247
  const previewScopeBaseBranch = new WeakMap();
5248
+ /** BAPI-1601 — why an `unavailable` auto-merge intent has nothing to show. Print-only. */
5249
+ const previewAutoMergeUnavailableReason = new WeakMap();
5250
+ /** The one human auto-merge line, worded exactly as setup-epic words it. */
5251
+ function autoMergeLine(preview) {
5252
+ const merge = preview.summary.auto_merge;
5253
+ if (merge === undefined)
5254
+ return " Auto-merge: n/a";
5255
+ if (merge.state === "unavailable") {
5256
+ return previewAutoMergeUnavailableReason.get(preview) === "invalid"
5257
+ ? " Auto-merge: unavailable (the policy does not declare a valid auto-merge setting)"
5258
+ : " Auto-merge: unavailable (older setup-epic output)";
5259
+ }
5260
+ const intent = merge.state === "on" ? { state: "on" } : { state: "off", reason: merge.reason ?? "" };
5261
+ return ` ${formatSetupEpicAutoMergeIntent(intent, preview.summary.branch ?? undefined)}`;
5262
+ }
5263
+ /** BAPI-1593 — the plan digest setup-epic's dry run says the SERVER validated, per preview. */
5264
+ const previewServerPlanDigest = new WeakMap();
5265
+ /**
5266
+ * BAPI-1593 — write the launch-context file from what the preview already
5267
+ * established. It issues no request: the readiness result is the acquisition's
5268
+ * latest completed attempt, read without spending a retry. A failure is one
5269
+ * warning and a `launch_context_write_failed` observation, never a refusal.
5270
+ */
5271
+ async function writePreviewLaunchContext(deps, options, preview, observed) {
5272
+ if (deps.writeLaunchContext === undefined || observed.acquisition === undefined)
5273
+ return;
5274
+ const readiness = observed.acquisition.peek();
5275
+ // BAPI-1595 — the base branch the launch will bind to. Setup's dry run reports it for
5276
+ // a branch-bearing run; for any other run (for example `--into-base`) it reports
5277
+ // none, so the same resolution the launch uses fills it in. Without a base on the
5278
+ // stored file the launch could never match it.
5279
+ let baseBranch = previewScopeBaseBranch.get(preview) ?? null;
5280
+ if (baseBranch === null && observed.contextAccess !== undefined && deps.readScopeBaseBranch !== undefined) {
5281
+ try {
5282
+ baseBranch = (await deps.readScopeBaseBranch(observed.contextAccess)) ?? null;
5283
+ }
5284
+ catch {
5285
+ baseBranch = null;
5286
+ }
5287
+ }
5288
+ const context = buildEpicLaunchContext({
5289
+ epicKey: options.epicKey,
5290
+ baseBranch,
5291
+ targetBaseUrl: preview.target.base_url,
5292
+ writtenAt: new Date((deps.now ?? Date.now)()),
5293
+ readiness,
5294
+ // BAPI-1595 — the VERIFIED local identity only. A report's own repo_name is never
5295
+ // substituted when the local identity is unavailable.
5296
+ repoName: observed.repoName ?? null,
5297
+ isBridge: observed.repository?.isBridge ?? null,
5298
+ serverPlanDigest: previewServerPlanDigest.get(preview) ?? null,
5299
+ });
5300
+ let written;
5301
+ try {
5302
+ written = await deps.writeLaunchContext(context);
5303
+ }
5304
+ catch {
5305
+ written = { ok: false, reason: "write_failed" };
5306
+ }
5307
+ if (!written.ok) {
5308
+ deps.errorLog(`${options.epicKey}: [warn] launch_context_write_failed — the launch-context file could not be ` +
5309
+ `written (${written.reason}); the preview is unaffected and no current context was claimed.`);
5310
+ }
5311
+ }
3840
5312
  /** Run one probe; a missing boundary or any rejection becomes the fallback fact. */
3841
5313
  async function guardedProbe(run, fallback) {
3842
5314
  if (run === undefined)
@@ -3864,29 +5336,29 @@ async function collectHostPowerFact(deps, topology) {
3864
5336
  return hostPowerFactFromReport(report);
3865
5337
  }
3866
5338
  /**
3867
- * Append the five launch-need rows to a `create` preview (BAPI-1506): worker DB
3868
- * role, self-hosted runner, host power (`host-sleep`), usage reset after the
3869
- * run, and the information-only epic branch behind base.
5339
+ * Append the three launch-need rows to a `create` preview (BAPI-1506, narrowed by
5340
+ * BAPI-1596): worker DB role, self-hosted runner, and host power (`host-sleep`).
5341
+ * The usage-reset and epic-branch-behind-base needs are gone: a launch neither
5342
+ * probes nor shows them.
3870
5343
  *
3871
- * Every probe runs concurrently and is guarded on its own, so a missing
3872
- * boundary, a rejection or a timeout is an `unverifiable` warning row. Rows
3873
- * are `blocking: false` and NEVER change the decision, a refusal, readiness or
3874
- * the exit code. An `attach`, refused or stopped preview gets none of them.
3875
- * The merged `worker-db-role` warning row is decorated in place rather than
3876
- * duplicated.
5344
+ * Each probe runs concurrently and is guarded on its own, so a missing boundary, a
5345
+ * rejection or a timeout is an `unverifiable` warning row. Rows are
5346
+ * `blocking: false` and NEVER change the decision, a refusal, readiness or the
5347
+ * exit code. An `attach`, refused or stopped preview gets none of them. The merged
5348
+ * `worker-db-role` warning row is decorated in place rather than duplicated. When
5349
+ * the project's configuration says the database does not apply (or was not
5350
+ * reported), the role row is `not_applicable`: the same rule as the boundary row.
3877
5351
  */
3878
- async function appendLaunchNeedRows(deps, preview, observed, workerDatabase) {
5352
+ async function appendLaunchNeedRows(deps, preview, observed, workerDatabase, applicability) {
3879
5353
  if (preview.decision !== "create")
3880
5354
  return;
3881
5355
  try {
3882
5356
  const repoRoot = observed.repository?.repoRoot ?? deps.cwd();
3883
5357
  const local = preview.target.kind === "local_plane";
3884
5358
  const readiness = observed.readiness;
3885
- const access = observed.access;
3886
- const nowMs = (deps.now ?? Date.now)();
3887
5359
  const durations = [];
3888
5360
  const measured = (index, work) => measurePrecheck(work, (duration) => { durations[index] = duration; });
3889
- const [runner, power, usage, branch] = await Promise.all([
5361
+ const [runner, power] = await Promise.all([
3890
5362
  measured(0, () => guardedProbe(deps.inspectRequiredRunners === undefined
3891
5363
  ? undefined
3892
5364
  : () => deps.inspectRequiredRunners({
@@ -3895,32 +5367,18 @@ async function appendLaunchNeedRows(deps, preview, observed, workerDatabase) {
3895
5367
  gateProfile: readiness?.gate_profile,
3896
5368
  }), { state: "unverifiable", reason: "probe_failed" })),
3897
5369
  measured(1, () => guardedProbe(() => collectHostPowerFact(deps, observed.launchTopology), { state: "unverifiable", reason: "probe_failed" })),
3898
- measured(2, () => guardedProbe(deps.fetchUsageAdvisory === undefined || access === undefined
3899
- ? undefined
3900
- : () => deps.fetchUsageAdvisory(access), null)),
3901
- measured(3, () => guardedProbe(deps.inspectEpicBranchBehind === undefined
3902
- ? undefined
3903
- : () => deps.inspectEpicBranchBehind({
3904
- repoRoot,
3905
- branch: preview.summary.branch,
3906
- baseBranch: previewScopeBaseBranch.get(preview) ?? null,
3907
- }), preview.summary.branch === null
3908
- ? { state: "not_applicable", reason: "no_epic_branch" }
3909
- : { state: "unverifiable", reason: "git_failed" })),
3910
5370
  ]);
3911
- const workerRow = observed.repository?.isBridge === false
3912
- ? { ...nonBridgeRows(["worker-db-role"])[0], launch_need: { need: "worker_db_role", state: "not_applicable", asked: false } }
5371
+ // BAPI-1613 R6: a cold start has no readiness yet; that is not a non-Bridge checkout.
5372
+ const skipRow = applicability.kind === "unproven" && observed.repository?.isBridge !== false
5373
+ ? { ...nonBridgeRows(["worker-db-role"])[0], reason: "readiness_unknown", detail: "readiness_unknown" }
5374
+ : nonBridgeRows(["worker-db-role"])[0];
5375
+ const workerRow = applicability.kind !== "inspect"
5376
+ ? { ...skipRow, launch_need: { need: "worker_db_role", state: "not_applicable", asked: false } }
3913
5377
  : { ...buildWorkerDbRoleLaunchRow(workerDatabase, local),
3914
5378
  duration_ms: workerDatabase?.rows.find((row) => row.id === "worker-db-role")?.duration_ms ?? elapsedMs(monotonicNow()) };
3915
5379
  const rows = [
3916
5380
  buildSelfHostedRunnerLaunchRow(runner),
3917
5381
  buildHostPowerLaunchRow(power),
3918
- buildUsageResetAfterRunLaunchRow({
3919
- advisory: usage ?? REPOSITORY_USAGE_ADVISORY_UNAVAILABLE,
3920
- childCount: preview.summary.child_count,
3921
- nowMs,
3922
- }),
3923
- buildEpicBranchBehindBaseLaunchRow(branch),
3924
5382
  ].map((row, index) => ({ ...row, duration_ms: durations[index] }));
3925
5383
  const existing = preview.launch_checks ?? [];
3926
5384
  const roleIndex = existing.findIndex((row) => row.id === workerRow.id);
@@ -4001,6 +5459,8 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
4001
5459
  return;
4002
5460
  }
4003
5461
  const access = accessResult.access;
5462
+ observed.repoName = access.repoName;
5463
+ observed.contextAccess = access;
4004
5464
  const profile = accessResult.profile ?? null;
4005
5465
  const endpoint = planeEndpointForBaseUrl(deps, access.baseUrl);
4006
5466
  const planeTarget = endpoint !== null;
@@ -4011,7 +5471,7 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
4011
5471
  ? { source: accessResult.targetSource }
4012
5472
  : {}),
4013
5473
  };
4014
- const ctx = {
5474
+ let ctx = {
4015
5475
  deps,
4016
5476
  epicKey,
4017
5477
  options,
@@ -4021,6 +5481,7 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
4021
5481
  targetSource: accessResult.targetSource ?? "default",
4022
5482
  freshness: createPlaneFreshnessCache(),
4023
5483
  launchCredential: {},
5484
+ liveObservation: {},
4024
5485
  };
4025
5486
  // Discover before readiness so a selected local plane can preview its guarded
4026
5487
  // cold start. Keep the candidate out of ordinary failure documents.
@@ -4028,6 +5489,9 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
4028
5489
  let plan = { status: "not_found" };
4029
5490
  // The full discovery result, kept for the guarded plane-down stop below.
4030
5491
  let discovery = null;
5492
+ // BAPI-1621 — why automatic generation stopped, and whether it read "no live run".
5493
+ let generationReason;
5494
+ let generatedLiveRunChecked = false;
4031
5495
  let docsRootUnresolved = false;
4032
5496
  if (planPath !== undefined) {
4033
5497
  plan = { status: "supplied", path: planPath };
@@ -4049,16 +5513,69 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
4049
5513
  : {}),
4050
5514
  epic_plans_dir: discovered.epic_plans_dir,
4051
5515
  };
4052
- if (discovered.status === "found")
5516
+ if (discovered.status === "found") {
4053
5517
  planPath = discovered.path;
5518
+ // BAPI-1621 — a found GENERATED plan shows its provenance from the files
5519
+ // already on disk; an authored plan's preview is unchanged.
5520
+ if (discovered.generated !== undefined) {
5521
+ plan.generated = true;
5522
+ const nodes = await readGeneratedPlanNodes(deps, discovered.path);
5523
+ if (nodes !== null)
5524
+ plan.generation = { nodes, summary: discovered.generated.summary };
5525
+ }
5526
+ }
5527
+ else if (discovered.status === "plan_not_found" && deps.attemptPlanGeneration !== undefined) {
5528
+ // BAPI-1621 — build in memory only. The preview writes no folder, staging
5529
+ // directory, temporary file, metadata, or DAG.
5530
+ if (!(await planGenerationAllowed(deps.discoveryFs, epicKey, discovered))) {
5531
+ generationReason = "discovery_blocked";
5532
+ }
5533
+ else {
5534
+ const attempt = await deps.attemptPlanGeneration(epicKey).catch(() => ({ kind: "failed", reason: "children_unreadable" }));
5535
+ if (attempt.kind === "failed") {
5536
+ generationReason = attempt.reason;
5537
+ }
5538
+ else if (attempt.kind === "generated" &&
5539
+ !(await planGenerationAllowed(deps.discoveryFs, epicKey, discovered, attempt))) {
5540
+ generationReason = "discovery_blocked";
5541
+ }
5542
+ else if (attempt.kind === "generated") {
5543
+ const folder = generatedPlanFolder(docs.docsDir, epicKey);
5544
+ planPath = path.join(folder, "epic-plan.dag.json");
5545
+ plan = {
5546
+ status: "generated",
5547
+ generated: true,
5548
+ inline: { nodes: attempt.dag.nodes, summary: attempt.summary },
5549
+ would_write: folder,
5550
+ ...(plan.skipped !== undefined ? { skipped: plan.skipped } : {}),
5551
+ epic_plans_dir: discovered.epic_plans_dir,
5552
+ };
5553
+ generatedLiveRunChecked = true;
5554
+ ctx = { ...ctx, deps: withInlinePlan(ctx.deps, planPath, JSON.stringify(attempt.dag, null, 2) + "\n") };
5555
+ }
5556
+ }
5557
+ if (generationReason !== undefined)
5558
+ plan.generation_failure = generationReason;
5559
+ }
4054
5560
  }
4055
5561
  }
4056
5562
  // Every later exit, refusal or not, reports the plan state as discovered.
4057
5563
  preview.plan = plan;
4058
5564
  // --- Readiness. -----------------------------------------------------------
4059
- let readiness;
5565
+ // BAPI-1593 — ONE acquisition for this preview: at most two full reads. The
5566
+ // first failure is inspected on its own (a refused plane port is a cold start);
5567
+ // anything else spends the one retry, and a second uncertain read warns and
5568
+ // continues rather than refusing.
5569
+ const previewAcquisition = createReadinessAcquisition(() => deps.readReadiness(access), {
5570
+ ...(deps.launchSleep !== undefined ? { sleep: deps.launchSleep } : {}),
5571
+ });
5572
+ observed.acquisition = previewAcquisition;
5573
+ let readiness = null;
4060
5574
  try {
4061
- readiness = await deps.readReadiness(access);
5575
+ const first = await previewAcquisition.firstAttempt();
5576
+ if (first.kind !== "ready")
5577
+ throw first.error;
5578
+ readiness = first.readiness;
4062
5579
  }
4063
5580
  catch (err) {
4064
5581
  if (isSchemaIncompatibleError(err)) {
@@ -4097,7 +5614,11 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
4097
5614
  preview.readiness = { kind: "cold_start" };
4098
5615
  await finalizeCreatePreview(ctx, preview, planPath, true, refuseTopLevel);
4099
5616
  if (preview.decision === "create") {
4100
- preview.cold_start = { plane_endpoint: access.baseUrl, will_start_plane: true, live_run_checked: false };
5617
+ preview.cold_start = {
5618
+ plane_endpoint: access.baseUrl,
5619
+ will_start_plane: true,
5620
+ live_run_checked: generatedLiveRunChecked,
5621
+ };
4101
5622
  }
4102
5623
  // No plane exists yet, so there is no snapshot or database to compare;
4103
5624
  // the host-sleep advisory still applies to the plane about to start.
@@ -4122,27 +5643,62 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
4122
5643
  if (probe.kind === "refused") {
4123
5644
  preview.readiness = {
4124
5645
  kind: "unknown",
4125
- remedy: planeDownNoPlanStopText(epicKey, { profile, options }, discovery),
5646
+ remedy: planeDownNoPlanStopText(epicKey, { profile, options }, discovery, generationReason),
4126
5647
  };
4127
5648
  preview.refusal = null;
4128
5649
  preview.decision = "stop";
4129
5650
  return;
4130
5651
  }
4131
5652
  }
4132
- return unknownReadiness();
5653
+ const settled = await previewAcquisition.result();
5654
+ if (settled.kind === "refused") {
5655
+ return refuseTopLevel({
5656
+ reasonId: "schema-incompatible",
5657
+ remedy: "Local schema incompatible: launch-critical schema objects are missing. " +
5658
+ `${SCHEMA_INCOMPATIBLE_REPAIR_ROUTE} Nothing was created or started.`,
5659
+ });
5660
+ }
5661
+ if (settled.kind === "ready")
5662
+ readiness = settled.readiness;
5663
+ }
5664
+ if (readiness === null) {
5665
+ // BAPI-1593 — unknown readiness is a warning, not a refusal: the launch would
5666
+ // continue to the server's create and approve. Only the decisions that need
5667
+ // no readiness report are previewed: the live-run read, and setup's own dry run.
5668
+ preview.readiness = { kind: "unknown", warning: READINESS_UNKNOWN_CONTINUING_WARNING };
5669
+ if (docsRootUnresolved)
5670
+ return refuseTopLevel(docsRootRefusal(epicKey));
5671
+ const unknownLive = await acquireObservedLive(ctx);
5672
+ if (unknownLive.kind === "conflict")
5673
+ return refuseTopLevel(liveRunAmbiguousRefusal(epicKey));
5674
+ if (unknownLive.kind === "unknown")
5675
+ (preview.warnings ??= []).push(LIVE_RUN_UNKNOWN_WARNING);
5676
+ if (unknownLive.kind === "live") {
5677
+ preview.live_run = { epic_run_id: unknownLive.epicRunId, status: unknownLive.status };
5678
+ if (options.planFile === undefined) {
5679
+ preview.decision = "attach";
5680
+ return;
5681
+ }
5682
+ }
5683
+ if (planPath === undefined) {
5684
+ preview.decision = "stop";
5685
+ return;
5686
+ }
5687
+ await finalizeCreatePreview(ctx, preview, planPath, false, refuseTopLevel, true);
5688
+ return;
4133
5689
  }
4134
5690
  observed.readiness = readiness;
4135
5691
  if (docsRootUnresolved)
4136
5692
  return refuseTopLevel(docsRootRefusal(epicKey));
4137
- const live = await deps.readLiveEpicRun(access, epicKey);
5693
+ const live = await acquireObservedLive(ctx);
4138
5694
  if (live.kind === "conflict")
4139
5695
  return refuseTopLevel(liveRunAmbiguousRefusal(epicKey));
4140
5696
  if (live.kind === "unknown")
4141
- return refuseTopLevel(liveRunUnknownRefusal(epicKey, live.reason));
5697
+ (preview.warnings ??= []).push(LIVE_RUN_UNKNOWN_WARNING);
4142
5698
  // BAPI-1532 — a DISCOVERED plan beside a live run is unused: the launch attaches,
4143
5699
  // so the effective plan path is cleared while the preview still reports the plan
4144
5700
  // as found. An explicit --plan-file keeps its create-path behavior unchanged.
4145
- const attachingDiscoveredPlan = options.planFile === undefined && plan.status === "found" && live.kind === "live";
5701
+ const attachingDiscoveredPlan = options.planFile === undefined && (plan.status === "found" || plan.status === "generated") && live.kind === "live";
4146
5702
  const effectivePlanPath = attachingDiscoveredPlan ? undefined : planPath;
4147
5703
  const previewCtx = { ...ctx, options: { ...options, ...(effectivePlanPath ? { planFile: effectivePlanPath } : {}) } };
4148
5704
  const observations = {
@@ -4165,6 +5721,9 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
4165
5721
  approvedStoredPolicy: live.kind === "live" && !effectivePlanPath,
4166
5722
  });
4167
5723
  preview.readiness = { kind: classification.kind };
5724
+ if (mandatoryDiagnosticsUncertain(readiness.diagnostics)) {
5725
+ (preview.warnings ??= []).push(MANDATORY_DIAGNOSTIC_UNKNOWN_WARNING);
5726
+ }
4168
5727
  if (classification.kind === 'operator_blocked') {
4169
5728
  const requirement = V2_READINESS_REQUIREMENTS.find(req => req.id === classification.id);
4170
5729
  if (requirement)
@@ -4178,6 +5737,7 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
4178
5737
  if (live.effectivePolicy) {
4179
5738
  preview.summary.policy_source = live.effectivePolicy.source;
4180
5739
  preview.summary.serial_execution = live.effectivePolicy.serial_execution;
5740
+ preview.summary.parallel_limit = live.effectivePolicy.parallel_limit;
4181
5741
  preview.summary.caps = live.effectivePolicy.caps;
4182
5742
  preview.summary.job_timeouts = live.effectivePolicy.job_timeouts;
4183
5743
  preview.summary.escalation_channel_label = live.effectivePolicy.escalation_channel;
@@ -4247,6 +5807,91 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
4247
5807
  await finalizeCreatePreview(prepared?.ok ? { ...previewCtx, handoff: prepared.handoff, previewObservations: observations, previewMergedEvaluation: mergedEvaluation } : { ...previewCtx, previewObservations: observations, previewMergedEvaluation: mergedEvaluation }, preview, planPathForCreate, false, refuseTopLevel, live.kind === "live");
4248
5808
  await applyPreviewFreshness(ctx, preview, topology, false);
4249
5809
  }
5810
+ /** The `git ls-remote --symref origin HEAD` answer: the default branch and its commit. */
5811
+ function parseRemoteDefaultHead(stdout) {
5812
+ let branch = null;
5813
+ let sha = null;
5814
+ for (const line of stdout.split("\n")) {
5815
+ const symref = /^ref:\s+refs\/heads\/(\S+)\s+HEAD\s*$/.exec(line.trim());
5816
+ if (symref)
5817
+ branch = symref[1];
5818
+ const direct = /^([0-9a-fA-F]{40})\s+HEAD\s*$/.exec(line.trim());
5819
+ if (direct)
5820
+ sha = normalizeCommitSha(direct[1]);
5821
+ }
5822
+ return branch !== null && sha !== null ? { branch, sha } : null;
5823
+ }
5824
+ /**
5825
+ * Preview-time check of the epic branch a new run would cut.
5826
+ *
5827
+ * Returns a refusal ONLY for a proven conflict (`has_own_commits`). Anything it
5828
+ * cannot establish (no target, an unreadable remote, an exception) emits one fixed
5829
+ * warning and returns null: the real launch decides. Read-only: the shared
5830
+ * classifier never updates a branch, and nothing here trusts a local tracking ref.
5831
+ */
5832
+ async function previewEpicBranchConflict(ctx, input) {
5833
+ const { deps } = ctx;
5834
+ const skipped = () => {
5835
+ deps.errorLog("[warn] The epic branch could not be checked during preview; the launch will check it.");
5836
+ return null;
5837
+ };
5838
+ try {
5839
+ const gitDeps = {
5840
+ runCommand: deps.runCommand ?? createExecFileRunCommand(),
5841
+ cwd: deps.cwd(),
5842
+ fetchImpl: globalThis.fetch,
5843
+ errorLog: () => undefined,
5844
+ };
5845
+ const readRemote = async (args) => Promise.resolve(gitDeps.runCommand("git", args, { cwd: gitDeps.cwd }));
5846
+ // No remote branch means nothing can conflict: no target is needed.
5847
+ const branchHead = await readRemote(["ls-remote", "--heads", "origin", `refs/heads/${input.branch}`]);
5848
+ if (branchHead.exitCode === 0 && branchHead.stdout.trim() === "")
5849
+ return null;
5850
+ let target = input.cutCommitSha === null ? null : normalizeCommitSha(input.cutCommitSha);
5851
+ let base = input.configuredBase;
5852
+ let defaultAssumed = null;
5853
+ if (target === null && base !== null) {
5854
+ const head = await readRemote(["ls-remote", "--heads", "origin", `refs/heads/${base}`]);
5855
+ const sha = head.exitCode === 0 ? normalizeCommitSha(head.stdout.trim().split(/\s+/)[0]) : null;
5856
+ target = sha;
5857
+ }
5858
+ if (target === null || base === null) {
5859
+ if (base === null) {
5860
+ // Cold preview with no configured-base evidence: the remote's default branch.
5861
+ const symref = await readRemote(["ls-remote", "--symref", "origin", "HEAD"]);
5862
+ const parsed = symref.exitCode === 0 ? parseRemoteDefaultHead(symref.stdout) : null;
5863
+ if (parsed === null)
5864
+ return skipped();
5865
+ base = parsed.branch;
5866
+ defaultAssumed = parsed.branch;
5867
+ if (target === null)
5868
+ target = parsed.sha;
5869
+ }
5870
+ }
5871
+ if (target === null || base === null)
5872
+ return skipped();
5873
+ const classified = await classifyRemoteEpicBranch(gitDeps, input.branch, target);
5874
+ if (classified.status === "unknown")
5875
+ return skipped();
5876
+ if (classified.status !== "has_own_commits")
5877
+ return null;
5878
+ const lines = [
5879
+ `origin/${input.branch} already holds commits that are not on the commit this run would start from.`,
5880
+ "Inspect them:",
5881
+ `git log origin/${base}..origin/${input.branch}`,
5882
+ "Then finish that work, or delete the branch:",
5883
+ `git push origin --delete ${input.branch}`,
5884
+ "Then preview again. Nothing was created.",
5885
+ ];
5886
+ if (defaultAssumed !== null) {
5887
+ lines.push(`If this repository's base is not ${defaultAssumed}, bring its plane up and preview again.`);
5888
+ }
5889
+ return { reasonId: "epic-branch-has-own-commits", remedy: lines.join("\n") };
5890
+ }
5891
+ catch {
5892
+ return skipped();
5893
+ }
5894
+ }
4250
5895
  async function finalizeCreatePreview(ctx, preview, planPath, coldStart, refuseTopLevel, liveRunKnown = false) {
4251
5896
  const { deps, options, access } = ctx;
4252
5897
  const prepared = ctx.handoff
@@ -4266,12 +5911,13 @@ async function finalizeCreatePreview(ctx, preview, planPath, coldStart, refuseTo
4266
5911
  ? "webhook"
4267
5912
  : prepared.handoff.selection.escalationChannel === "account email" ? "email" : null;
4268
5913
  }
4269
- // Compatibility path when no trusted repository-applicability fact is supplied.
4270
- // Unknown is advisory, not a prerequisite on the sibling identity gate. Neither
4271
- // declared paths nor target topology can establish repository identity.
4272
- preview.plan_database_relevance = "unknown";
4273
- preview.summary.child_count = await readPlanChildCount(deps, planPath);
5914
+ const planChildren = await readPlanDagChildren(deps, planPath);
5915
+ preview.summary.child_count = planChildren?.count ?? null;
4274
5916
  preview.summary.children_to_run = preview.summary.child_count;
5917
+ // A key list is trusted only when it names every node; a partial list would shrink membership.
5918
+ if (planChildren !== null && planChildren.keys.length === planChildren.count) {
5919
+ previewPlanChildKeys.set(preview, planChildren.keys);
5920
+ }
4275
5921
  // BAPI-1510 — the already-merged check, after plan discovery and BEFORE the
4276
5922
  // setup dry run, so the dry run validates the plan a real create would submit.
4277
5923
  // An attach, a disabled check, and a cold start (no plane to ask yet) classify
@@ -4346,18 +5992,34 @@ async function finalizeCreatePreview(ctx, preview, planPath, coldStart, refuseTo
4346
5992
  preview.summary.branch = payload.featureBranch;
4347
5993
  if (payload.scopeBaseBranch !== null)
4348
5994
  previewScopeBaseBranch.set(preview, payload.scopeBaseBranch);
5995
+ // A leftover epic branch with its own commits would refuse the real launch after a
5996
+ // plane had started. Say so now. Outside the setup dry run on purpose, so the
5997
+ // generic `setup-preview-failed` remedy cannot replace these exact instructions.
5998
+ if (!liveRunKnown && payload.featureBranch !== null && payload.existingRunId === null) {
5999
+ const conflict = await previewEpicBranchConflict(ctx, {
6000
+ branch: payload.featureBranch,
6001
+ configuredBase: payload.scopeBaseBranch,
6002
+ cutCommitSha: evaluation?.cutCommitSha ?? null,
6003
+ });
6004
+ if (conflict !== null)
6005
+ return refuseTopLevel(conflict);
6006
+ }
6007
+ if (payload.serverPlanHash !== null)
6008
+ previewServerPlanDigest.set(preview, payload.serverPlanHash);
4349
6009
  preview.summary.ticket_review = payload.ticketReview;
4350
6010
  if (payload.launchReadiness) {
4351
6011
  preview.prerequisites = payload.launchReadiness.prerequisites;
4352
6012
  preview.is_production = payload.launchReadiness.is_production;
4353
6013
  const launch = classifyV2Readiness(payload.launchReadiness, { attended: options.attended, intoBase: options.intoBase });
4354
6014
  if (launch.kind === 'operator_blocked')
4355
- return refuseTopLevel({ reasonId: launch.id, remedy: launch.remedy ?? 'Retry readiness.' });
6015
+ return refuseTopLevel({ reasonId: launch.id, remedy: launch.remedy ?? 'Retry readiness.', authoritative: true });
4356
6016
  }
4357
6017
  if (payload.effectivePolicy) {
4358
6018
  const facts = payload.effectivePolicy;
4359
6019
  preview.summary.policy_source = facts.source;
4360
6020
  preview.summary.serial_execution = facts.serial_execution;
6021
+ if (facts.parallel_limit !== undefined)
6022
+ preview.summary.parallel_limit = facts.parallel_limit;
4361
6023
  preview.summary.caps = facts.caps;
4362
6024
  preview.summary.job_timeouts = facts.job_timeouts;
4363
6025
  preview.summary.escalation_channel_label = facts.escalation_channel;
@@ -4366,8 +6028,27 @@ async function finalizeCreatePreview(ctx, preview, planPath, coldStart, refuseTo
4366
6028
  preview.summary.escalation_channel = facts.escalation_channel === "configured webhook"
4367
6029
  ? "webhook" : facts.escalation_channel === "account email" ? "email" : null;
4368
6030
  }
4369
- preview.summary.auto_merge_scope =
4370
- preview.summary.posture === "unattended" ? payload.featureBranch : null;
6031
+ // BAPI-1601 — one intent result drives the summary, the printed line, and the
6032
+ // compatibility scope, so they cannot disagree. An absent or unusable
6033
+ // `create_policy` is `unavailable` — never `off`, and never an invented scope.
6034
+ const epicBranch = payload.featureBranch ?? undefined;
6035
+ let intent;
6036
+ if (payload.createPolicy.kind === "present") {
6037
+ intent = resolveSetupEpicAutoMergeIntent(payload.createPolicy.policy, {
6038
+ epicBranch,
6039
+ attended: options.attended === true,
6040
+ });
6041
+ // A present envelope with no usable boolean is not "older output".
6042
+ if (intent.state === "unavailable")
6043
+ previewAutoMergeUnavailableReason.set(preview, "invalid");
6044
+ }
6045
+ else {
6046
+ intent = { state: "unavailable" };
6047
+ previewAutoMergeUnavailableReason.set(preview, payload.createPolicy.kind === "absent" ? "older" : "invalid");
6048
+ }
6049
+ preview.summary.auto_merge =
6050
+ intent.state === "off" ? { state: "off", reason: intent.reason } : { state: intent.state };
6051
+ preview.summary.auto_merge_scope = intent.state === "on" ? payload.featureBranch : null;
4371
6052
  // The bootstrap reusing a run IS an attach: it reports the run's id.
4372
6053
  if (payload.existingRunId !== null) {
4373
6054
  // Existing runs are never trimmed: report the check as not applied.
@@ -4435,14 +6116,20 @@ async function applyPreviewFreshness(ctx, preview, topology, coldStart) {
4435
6116
  const sleep = preview.decision === "attach" ? await collectHostSleep(ctx, own.repoRoot) : null;
4436
6117
  // Read-only: one run-state read, local plane only, and only for a bound plane.
4437
6118
  const boundRun = await boundRunForStaleRemedy(ctx, own, reports);
4438
- const assessment = assessPlaneFreshness(reports, sleep, preview.decision === "create" ? "create" : "attach", ctx.options.allowStalePlane === true, boundRun, true);
6119
+ // BAPI-1651: create's cleanup also refuses while another run is live on the
6120
+ // plane, so ask the same read-only question before promising it.
6121
+ const otherLive = preview.decision === "create" && boundRun !== undefined && isTerminalRunCleanupStatus(boundRun.status)
6122
+ ? await readOtherLiveRun(deps.listLiveRunIds ?? (async () => null), ctx.access, boundRun.epicRunId)
6123
+ : null;
6124
+ const assessment = assessPlaneFreshness(reports, sleep, preview.decision === "create" ? "create" : "attach", ctx.options.allowStalePlane === true, boundRun, otherLive);
4439
6125
  if (assessment.rows.length > 0) {
4440
6126
  preview.launch_checks = [...(preview.launch_checks ?? []), ...assessment.rows];
4441
6127
  }
4442
6128
  const refusal = freshnessRefusalOf(assessment.blockers);
4443
6129
  if (refusal !== null) {
4444
6130
  preview.decision = "refuse";
4445
- preview.refusal = { reason_id: refusal.reasonId, remedy: refusal.remedy };
6131
+ // BAPI-1596: a freshness blocker is proven (a stale plane or a database behind head).
6132
+ preview.refusal = { reason_id: refusal.reasonId, remedy: refusal.remedy, authoritative: true };
4446
6133
  }
4447
6134
  }
4448
6135
  catch {
@@ -4533,6 +6220,15 @@ function reachabilityLines(preview) {
4533
6220
  const row = preview.launch_checks?.find((entry) => entry.id === ESCALATION_REACHABILITY_CHECK_ID);
4534
6221
  if (row === undefined)
4535
6222
  return [];
6223
+ // BAPI-1595 — the confirmed "no reachable channel" line appears only when both
6224
+ // facts are established. An unestablished one shows the fixed uncertainty warning
6225
+ // instead, and an unremarkable one shows nothing.
6226
+ const presentation = previewEscalationPresentation.get(preview);
6227
+ if (presentation === "uncertain") {
6228
+ return [` WARN ${ESCALATION_REACHABILITY_CHECK_ID}`, ` ${ESCALATION_CHANNEL_UNCERTAIN_WARNING}`];
6229
+ }
6230
+ if (presentation === "omitted")
6231
+ return [];
4536
6232
  return [
4537
6233
  ` ${row.status === "pass" ? "PASS" : "WARN"} ${ESCALATION_REACHABILITY_CHECK_ID}`,
4538
6234
  ...(row.detail ? [` ${row.detail}`] : []),
@@ -4631,6 +6327,32 @@ export function alreadyDoneLines(preview) {
4631
6327
  }
4632
6328
  return lines;
4633
6329
  }
6330
+ /** The v2 plan as plain lines: the same document the session renders, never recomputed here. */
6331
+ function launchPlanLines(plan) {
6332
+ const lines = [" Launch plan:", ` ${plan.summary}`, ` Recommended: ${plan.recommendation}`, ` Why: ${plan.reason}`];
6333
+ const groups = [
6334
+ ["Blocks the launch", plan.items.blocks_launch],
6335
+ ["Needs your choice", plan.items.needs_choice],
6336
+ ["Worth knowing", plan.items.worth_knowing],
6337
+ ];
6338
+ for (const [title, entries] of groups) {
6339
+ if (entries.length === 0)
6340
+ continue;
6341
+ lines.push(` ${title}:`);
6342
+ for (const entry of entries) {
6343
+ lines.push(` - ${entry.summary}`, ` ${entry.reason}`);
6344
+ if (entry.remedy)
6345
+ lines.push(` Fix: ${entry.remedy}`);
6346
+ }
6347
+ }
6348
+ lines.push(" Your options:");
6349
+ for (const option of plan.options) {
6350
+ lines.push(` ${option.number}. ${option.label}${option.recommended ? " (as recommended)" : ""}. ${option.description} ${option.duration}`);
6351
+ }
6352
+ if (plan.local_handoff)
6353
+ lines.push(` ${plan.local_handoff}`);
6354
+ return lines;
6355
+ }
4634
6356
  /**
4635
6357
  * Print the preview: one JSON line with `--json`, short readable lines otherwise.
4636
6358
  *
@@ -4660,22 +6382,24 @@ async function emitPreview(deps, options, preview) {
4660
6382
  ? "Found, unused"
4661
6383
  : preview.plan.status}${preview.plan.path ? ` — ${preview.plan.path}` : ""}`,
4662
6384
  ];
6385
+ // BAPI-1621 — generated provenance and a stopped generation, in plain words.
6386
+ if (preview.plan.generated === true) {
6387
+ lines.push(preview.plan.status === "generated"
6388
+ ? ` GENERATED — built from current epic children; not written by this preview. A launch saves it to ${preview.plan.would_write ?? "the generated plan folder"}.`
6389
+ : " GENERATED — built from epic children by drive-epic.");
6390
+ }
6391
+ if (preview.plan.generation_failure !== undefined) {
6392
+ lines.push(` generation: stopped (${preview.plan.generation_failure}) — ${PLAN_GENERATION_FAILURE_TEXT[preview.plan.generation_failure]}`);
6393
+ }
4663
6394
  for (const candidate of preview.plan.candidates ?? [])
4664
6395
  lines.push(` candidate: ${candidate}`);
4665
6396
  for (const skipped of preview.plan.skipped ?? []) {
4666
6397
  lines.push(` skipped: ${skipped.path} (${skipped.reason})`);
4667
6398
  }
4668
6399
  const s = preview.summary;
4669
- lines.push(` Ticket review: ${s.ticket_review ?? "on"}`, ` Posture: ${s.posture ?? "n/a"}`, ` Children: ${s.child_count ?? "n/a"}`, ...alreadyDoneLines(preview), ` Branch: ${s.branch ?? "n/a"}`, ` Auto-merge: ${s.auto_merge_scope ?? "n/a"}`, ` Escalation: ${s.escalation_channel ?? "n/a"}`, ...reachabilityLines(preview), ...(preview.launch_plan ? [
4670
- " Launch plan (advisory):",
4671
- ...(preview.launch_plan.items.length === 0 ? [" There are no pending decisions"] :
4672
- preview.launch_plan.items.flatMap((item) => [
4673
- ` ${item.summary} (${item.id}): ${item.recommendation}`,
4674
- ` ${item.reason}`,
4675
- ...(item.remedy ? [` Remedy: ${item.remedy}`] : []),
4676
- ...(item.recommendation === "fix first" ? [" Launch anyway accepts the unresolved risk; no remediation is performed."] : []),
4677
- ])),
4678
- ] : []), ` Validation: ${preview.cold_start ? "Partial — plane is not yet running" : s.server_validation ?? "n/a"}`, ` Decision: ${preview.decision}`);
6400
+ lines.push(` Ticket review: ${s.ticket_review ?? "on"}`, ` Posture: ${s.posture ?? "n/a"}`, ` Parallel limit: ${s.parallel_limit === undefined ? "unavailable" : s.parallel_limit === "server_default" ? "server default" : s.parallel_limit}`, ` ${PARALLEL_LIMIT_MEANING_COPY}`, ` ${PARALLEL_LIMIT_CHANGE_ADVISORY}`, ` Children: ${s.child_count ?? "n/a"}`, ...alreadyDoneLines(preview), ` Branch: ${s.branch ?? "n/a"}`, autoMergeLine(preview), ` Escalation: ${s.escalation_channel ?? "n/a"}`, ...(preview.credentials_missing && preview.credentials_missing.length > 0
6401
+ ? [` Credentials: advisory — not available on this machine: ${preview.credentials_missing.join(", ")}`]
6402
+ : []), ...reachabilityLines(preview), ...(preview.launch_plan ? launchPlanLines(preview.launch_plan) : []), ` Validation: ${preview.cold_start ? "Partial — plane is not yet running" : s.server_validation ?? "n/a"}`, ` Decision: ${preview.decision}`);
4679
6403
  if (isPlaneDownStop(preview)) {
4680
6404
  // The shared stop text, verbatim and unindented, so it reads exactly as the
4681
6405
  // real launch prints it. It is a stop, not a refusal.
@@ -4689,13 +6413,9 @@ async function emitPreview(deps, options, preview) {
4689
6413
  if (preview.refusal && preview.refusal.reason_id !== EPIC_ALREADY_COMPLETE_REASON_ID) {
4690
6414
  lines.push(` Refusal: ${preview.refusal.reason_id} — ${preview.refusal.remedy}`);
4691
6415
  }
6416
+ // BAPI-1596 — no "Not ready: N blocking" summary on the launch preview: the plan above
6417
+ // carries the verdict. The readiness command keeps its own text report.
4692
6418
  const summaryRows = (preview.launch_checks ?? []).filter(row => row.id !== ESCALATION_REACHABILITY_CHECK_ID);
4693
- lines.unshift(...formatLaunchReadinessSummary(summaryRows.map(row => ({
4694
- id: row.id, source: row.id.startsWith('server.') ? 'server' : 'conductor',
4695
- label: row.label, status: row.status, blocking: row.blocking,
4696
- ...(row.detail ? { detail: row.detail } : {}),
4697
- ...(row.remedy ? { remediation: row.remedy } : {}),
4698
- })), { all: options.all, isProduction: preview.is_production, prerequisites: preview.prerequisites }));
4699
6419
  const localRows = summaryRows.filter(row => !READINESS_PREREQUISITE_BY_ID.has(READINESS_LEGACY_IDS[row.id] ?? row.id));
4700
6420
  // BAPI-1506: launch-need rows get their own heading; they are not plane freshness.
4701
6421
  const freshnessRows = localRows.filter(row => row.launch_need === undefined);