@bridge_gpt/mcp-server 0.2.69 → 0.2.71

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 (164) hide show
  1. package/README.md +140 -292
  2. package/build/agent-launchers/claude-executor-adapter.js +27 -5
  3. package/build/agent-registry.js +5 -5
  4. package/build/agents.generated.js +15 -5
  5. package/build/artifact-diff.js +110 -0
  6. package/build/bin-entrypoint.js +36 -0
  7. package/build/bounded-wait.js +9 -1
  8. package/build/bridge-permissions.js +36 -9
  9. package/build/claude-review-workflow-drift.js +3 -3
  10. package/build/codex-bridge-profile.js +1 -1
  11. package/build/commands.generated.js +6 -6
  12. package/build/conductor/bridge-api-client.js +858 -21
  13. package/build/conductor/bring-up-facts.js +9 -9
  14. package/build/conductor/command-drift-production.js +7 -2
  15. package/build/conductor/doctor.js +472 -18
  16. package/build/conductor/epic-child-continuation.js +54 -3
  17. package/build/conductor/epic-implementer-cli.js +136 -34
  18. package/build/conductor/epic-runtime.js +2 -2
  19. package/build/conductor/epic-state.js +1 -1
  20. package/build/conductor/gate-discovery.js +524 -10
  21. package/build/conductor/gate-settings-review.js +451 -0
  22. package/build/conductor/hook-runtime-qualification.js +1 -1
  23. package/build/conductor/install-doctor.js +4 -2
  24. package/build/conductor/launch-need-probes.js +342 -0
  25. package/build/conductor/launch-plan.js +145 -0
  26. package/build/conductor/local-merge.js +241 -56
  27. package/build/conductor/merge-credential.js +172 -0
  28. package/build/conductor/merge-execution-eligibility.js +1 -1
  29. package/build/conductor/merged-child-check.js +95 -0
  30. package/build/conductor/plan-trim.js +30 -0
  31. package/build/conductor/pr-ci-producer.js +1 -1
  32. package/build/conductor/precheck-timings.js +14 -0
  33. package/build/conductor/preview-observations.js +10 -0
  34. package/build/conductor/readiness-cli.js +11 -6
  35. package/build/conductor/readiness-prerequisites.js +41 -0
  36. package/build/conductor/readiness-sections.js +348 -55
  37. package/build/conductor/readiness.js +99 -87
  38. package/build/conductor/recovery-cli.js +665 -23
  39. package/build/conductor/recovery-operations.js +350 -8
  40. package/build/conductor/repair-contract.js +47 -2
  41. package/build/conductor/repository-workflow-remedy.js +8 -6
  42. package/build/conductor/stored-merge-credential.js +76 -0
  43. package/build/conductor/stored-merge-token-probe.js +28 -0
  44. package/build/conductor/temporary-plan.js +50 -0
  45. package/build/conductor/wait-run-cli.js +759 -0
  46. package/build/conductor/worker-database-doctor-inspector.js +49 -0
  47. package/build/conductor-bin.js +2 -2
  48. package/build/conductor-claude-hook-bin.js +2 -2
  49. package/build/conductor-claude-hook-removed-stub-bin.js +2 -5
  50. package/build/conductor-removed-stub-bin.js +2 -5
  51. package/build/credential-store.js +356 -13
  52. package/build/docs.generated.js +26 -13
  53. package/build/doctor.js +94 -32
  54. package/build/drive-epic-help.js +212 -0
  55. package/build/drive-epic.js +1989 -379
  56. package/build/epic-ci-workflow-drift.js +125 -0
  57. package/build/epic-ci-workflow-install.js +240 -0
  58. package/build/epic-ci-workflow-v1.js +132 -0
  59. package/build/epic-ci-workflow.js +318 -0
  60. package/build/epic-contract-context.js +326 -0
  61. package/build/epic-implementer-bin.js +58 -42
  62. package/build/epic-implementer-claude-hook-bin.js +2 -2
  63. package/build/escalation-reachability.js +134 -0
  64. package/build/executor/ci-rerun-job.js +220 -14
  65. package/build/executor/cleanup-report.js +99 -0
  66. package/build/executor/cli.js +12 -1
  67. package/build/executor/completion-contract.js +66 -11
  68. package/build/executor/completion-supervision.js +99 -0
  69. package/build/executor/delivery-outcome.js +179 -0
  70. package/build/executor/deps.js +3 -0
  71. package/build/executor/env.js +276 -1
  72. package/build/executor/failure-reason-codes.js +126 -0
  73. package/build/executor/gate-qualification-job.js +20 -5
  74. package/build/executor/heartbeat.js +38 -0
  75. package/build/executor/http-client.js +72 -0
  76. package/build/executor/integration-job.js +298 -5
  77. package/build/executor/job-errors.js +36 -6
  78. package/build/executor/job-runner.js +830 -45
  79. package/build/executor/likely-tests.js +42 -3
  80. package/build/executor/merge-job.js +145 -2
  81. package/build/executor/observation.js +73 -4
  82. package/build/executor/permissions.js +193 -97
  83. package/build/executor/preflight.js +19 -3
  84. package/build/executor/process-containment.js +46 -2
  85. package/build/executor/prompt-spec.js +113 -9
  86. package/build/executor/rebase-finalization.js +38 -3
  87. package/build/executor/reconcile-overlap-job.js +41 -8
  88. package/build/executor/required-work-ledger.js +236 -81
  89. package/build/executor/resume-pre-spawn.js +38 -1
  90. package/build/executor/runner.js +91 -3
  91. package/build/executor/test-clock.js +8 -0
  92. package/build/executor/types.js +37 -2
  93. package/build/executor/worker-cli-launcher.js +259 -0
  94. package/build/executor/worker-command.js +177 -5
  95. package/build/executor/worker-database-target.js +91 -0
  96. package/build/executor/worker-database.js +927 -0
  97. package/build/executor/worker-finalization.js +106 -0
  98. package/build/executor/worker-guard-hook.js +203 -0
  99. package/build/executor/worker-resources.js +58 -0
  100. package/build/executor/worker-verification-guidance.js +44 -2
  101. package/build/executor/worktree.js +303 -15
  102. package/build/executor-launch.js +11 -1
  103. package/build/generated-assets-doctor.js +9 -1
  104. package/build/generated-assets-health.js +13 -4
  105. package/build/generated-assets-legacy.js +39 -0
  106. package/build/generated-assets-paths.js +12 -1
  107. package/build/generated-assets-repair.js +4 -1
  108. package/build/generated-assets-test-support.js +12 -0
  109. package/build/github-remote.js +33 -0
  110. package/build/github-sign-in.js +62 -0
  111. package/build/index.js +1133 -546
  112. package/build/init.js +39 -1
  113. package/build/install-bridge-conductor-gate.js +270 -11
  114. package/build/install-bridge-conductor-setup.js +427 -0
  115. package/build/install-bridge-conductor.js +1545 -268
  116. package/build/install-bridge.js +376 -60
  117. package/build/mcp-install-state.js +8 -2
  118. package/build/merge-pull-request.js +6 -0
  119. package/build/merge-workflow-install.js +782 -344
  120. package/build/phase-result-artifacts.js +75 -20
  121. package/build/pipeline-orchestrator.js +247 -4
  122. package/build/pipelines.generated.js +35 -35
  123. package/build/plan-discovery.js +15 -2
  124. package/build/plan-execution-ledger.js +321 -17
  125. package/build/plan-phase-routing.js +48 -13
  126. package/build/plane/cli.js +105 -51
  127. package/build/plane/defaults.js +3 -0
  128. package/build/plane/plane-freshness.js +298 -0
  129. package/build/plane/preflight.js +19 -0
  130. package/build/plane/schema-compatibility.js +137 -0
  131. package/build/plane/shutdown-deps.js +38 -0
  132. package/build/plane/shutdown.js +83 -8
  133. package/build/plane/terminal-run-cleanup.js +303 -0
  134. package/build/printed-remedy-commands.js +33 -4
  135. package/build/readiness-check.js +6 -2
  136. package/build/readiness-prerequisites.generated.js +532 -0
  137. package/build/readme.generated.js +1 -1
  138. package/build/repository-toolchains.js +581 -0
  139. package/build/setup-epic.js +421 -34
  140. package/build/shared-resources.generated.js +5 -0
  141. package/build/start-tickets.js +28 -15
  142. package/build/test-command-detection.js +284 -0
  143. package/build/test-command-validation.js +73 -0
  144. package/build/testing-config-client.js +150 -0
  145. package/build/ticket-delivery-artifacts.js +265 -0
  146. package/build/ticket-delivery-enrollment.js +369 -0
  147. package/build/ticket-delivery.js +205 -0
  148. package/build/ticket-review-summary.js +14 -0
  149. package/build/upgrade-cli.js +13 -0
  150. package/build/v2-readiness-requirements.js +552 -0
  151. package/build/version.generated.js +3 -3
  152. package/build/worker-guard-hook-bin.js +2 -2
  153. package/build/worktree-core.js +22 -7
  154. package/docs/BRIDGE-DIRECTORY-README.md +48 -0
  155. package/docs/EPIC-IMPLEMENTER-INSTALL.md +12 -867
  156. package/docs/EPIC-IMPLEMENTER.md +142 -63
  157. package/docs/epic-implementer/getting-started.md +187 -0
  158. package/docs/epic-implementer/self-hosting.md +133 -0
  159. package/package.json +4 -4
  160. package/pipelines/idea-to-ticket.json +1 -1
  161. package/pipelines/implement-ticket.json +8 -8
  162. package/pipelines/review-ticket.json +2 -2
  163. package/design-assets/favicon/favicon-32x32.png +0 -0
  164. package/design-assets/just-logo-rough-draft.png +0 -0
@@ -1,3 +1,8 @@
1
+ import { monotonicNow, elapsedMs, measurePrecheck } from "./conductor/precheck-timings.js";
2
+ import { buildLaunchPlan } from "./conductor/launch-plan.js";
3
+ import { ticketReviewSummary } from "./ticket-review-summary.js";
4
+ import { parseConductorReadinessResponse } from "./conductor/bridge-api-client.js";
5
+ import { READINESS_PRE_CREATE_CODES, READINESS_PREREQUISITE_BY_ID, READINESS_LEGACY_IDS } from "./readiness-prerequisites.generated.js";
1
6
  /**
2
7
  * `drive-epic` — the one universal conductor entry point (BAPI-887).
3
8
  *
@@ -53,32 +58,49 @@
53
58
  * ratcheted down, and a tool would be useless in a bare-chat session anyway,
54
59
  * where the model has no tool call to make.
55
60
  */
56
- import { readdir, readFile } from "node:fs/promises";
61
+ import { access as fsAccess, readdir, readFile, realpath, stat as fsStat } from "node:fs/promises";
62
+ import { constants as fsConstants } from "node:fs";
57
63
  import path, { dirname, join } from "node:path";
58
- import { CONDUCTOR_DEFAULT_BASE_URL, ConductorBridgeApiError, resolveEpicLaunchBridgeApiAccess, fetchConductorReadiness, fetchEpicRunState, gateProfileWaivesCiWorkflow, safeDiagnosticMessage, } from "./conductor/bridge-api-client.js";
64
+ 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";
65
+ import { CHILD_MERGE_STATUS_BATCH_SIZE, buildAlreadyDoneEntries, classifyPlanChildren, selectSkips, } from "./conductor/merged-child-check.js";
66
+ import { trimDonePlanNodes } from "./conductor/plan-trim.js";
67
+ import { withPlanPath } from "./conductor/temporary-plan.js";
68
+ import { ESCALATION_REACHABILITY_CHECK_ID, buildEscalationReachabilityCheck, } from "./escalation-reachability.js";
59
69
  import { EPIC_LAUNCH_PROFILE_NAME_PATTERN, epicLaunchPolicyDigest, pinEpicLaunchPolicy, renderEpicLaunchCommand, resolveEpicLaunchSelection, shellQuote, } from "./epic-launch-profile.js";
60
70
  import { validateHttpBaseUrl, describeBaseUrlRejection } from "./base-url.js";
61
71
  import { BRING_UP_REFUSAL_MESSAGES, BRING_UP_RUNBOOK, firstBringUpRefusal, } from "./conductor/bring-up-facts.js";
62
- import { repositoryWorkflowRemedy } from "./conductor/repository-workflow-remedy.js";
63
- import { policyDeclaresNotifyWebhook, policyNotifyDestinationsConflict, notifyDestinationsConflictMessage, effectivePolicyFacts, readSetupEpicPolicyFile, runSetupEpicWorkflow, } from "./setup-epic.js";
72
+ import { V2_READINESS_REQUIREMENTS, buildLaunchReadinessChecks, firstLaunchEvidenceBlocker, formatLaunchReadinessSummary, projectReadinessRowBlocking, unattendedPostureCheck, } from "./v2-readiness-requirements.js";
73
+ import { classifyLocalGhPreflight, probeLocalMergeCapability, } from "./conductor/local-merge.js";
74
+ import { nodeGithubMergeCredentialReadDeps, resolveMergeCredentialAtAction, } from "./conductor/stored-merge-credential.js";
75
+ import { resolveWorktreeSettingsExclude, } from "./executor/permissions.js";
76
+ import { collectWorkerDatabaseDoctorSection, WORKER_DATABASE_DOCTOR_TIMEOUT_MS, } from "./conductor/doctor.js";
77
+ import { buildEpicBranchBehindBaseLaunchRow, buildHostPowerLaunchRow, buildSelfHostedRunnerLaunchRow, buildUsageResetAfterRunLaunchRow, buildWorkerDbRoleLaunchRow, hostPowerFactFromReport, workerDatabaseReadinessChecks, } from "./conductor/readiness-sections.js";
78
+ import { createWorkflowSource, inspectEpicBranchBehindBase, inspectRequiredSelfHostedRunners, } from "./conductor/launch-need-probes.js";
79
+ import { createWorkerDatabaseDoctorInspector } from "./conductor/worker-database-doctor-inspector.js";
80
+ import { policyDeclaresNotifyWebhook, policyNotifyDestinationsConflict, notifyDestinationsConflictMessage, effectivePolicyFacts, readSetupEpicPolicyFile, readCanonicalParseTruth as readSetupCanonicalParseTruth, runSetupEpicWorkflow, } from "./setup-epic.js";
64
81
  import { EPIC_KEY_PATTERN } from "./drive-epic-key.js";
65
82
  import { flushProcessStdout, writeJsonDocument } from "./conductor/json-output.js";
83
+ import { BRIDGE_LAUNCHER_ENV } from "./bridge-permissions.js";
84
+ import { checkPlaneBuildFreshness, PLANE_BUILD_FIX_REMEDIATION } from "./plane/build-freshness.js";
66
85
  import { discoverEpicPlan, } from "./plan-discovery.js";
67
86
  import { formatPlaneDiagnostic, launchPlaneControlPlane, requestPlaneScopedLanes, runDefaultPlanePreflight, runPlaneCli, } from "./plane/cli.js";
68
- import { PLANE_PORT_PROBE_TIMEOUT_MS, describePlanePortOccupant, } from "./plane/preflight.js";
69
- import { createPlaneFsDeps, probeAutomationHealth, probeTcpPort, resolveHostname, } from "./plane/defaults.js";
87
+ import { PLANE_PORT_PROBE_TIMEOUT_MS, describePlanePortOccupant, isBridgeEngineRepository, } from "./plane/preflight.js";
88
+ import { createPlaneExecFile, createPlaneFsDeps, probeAutomationHealth, probeTcpPort, resolveHostname, } from "./plane/defaults.js";
70
89
  import { readPlaneManifest } from "./plane/manifest.js";
90
+ import { cleanupTerminalRunPlane, createTerminalRunCleanupDeps, terminalRunCleanupStderrLine, } from "./plane/terminal-run-cleanup.js";
91
+ 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";
71
92
  import { baseUrlNamesPlaneEndpoint, planeEndpointForTarget } from "./plane/endpoint.js";
72
93
  import { resolvePlaneServerEndpoint, } from "./plane/member-roster.js";
73
94
  import { resolveMemberInstanceId } from "./plane/supervisor.js";
74
- import { PLANE_SERVER_PORT_ENV_VAR, } from "./plane/types.js";
75
95
  import { validateBranchName } from "./base-ref.js";
76
96
  import { createDefaultRunExecutorLaunchDeps, ensureRunExecutor as ensureRunExecutorDefault, prepareRunExecutor as prepareRunExecutorDefault, } from "./executor-launch.js";
77
97
  import { isTerminalEpicRunStatus } from "./epic-run-status.js";
78
98
  // BAPI-806: mcp-identity.ts is the SOLE source of the package-name literal, so
79
99
  // the printed invocation interpolates it rather than repeating it.
80
100
  import { MCP_PACKAGE_NAME } from "./mcp-identity.js";
81
- import { PRINTED_CHECK_NAME_INSTRUCTION, PRINTED_CONDUCTOR_INSTALL_COMMAND, PRINTED_DOCTOR_COMMAND, } from "./printed-remedy-commands.js";
101
+ import { getDriveEpicAdvancedUsage, getDriveEpicUsage } from "./drive-epic-help.js";
102
+ export { getDriveEpicUsage };
103
+ import { CONSUMER_GUIDE_POINTER, PRINTED_CHECK_NAME_INSTRUCTION, PRINTED_CONDUCTOR_INSTALL_COMMAND, PRINTED_DOCTOR_COMMAND, } from "./printed-remedy-commands.js";
82
104
  /** The conductor paths. Derived types below come from this constant. */
83
105
  export const DRIVE_EPIC_CONDUCTORS = ["v2"];
84
106
  /**
@@ -89,135 +111,12 @@ export const DRIVE_EPIC_CONDUCTORS = ["v2"];
89
111
  * one named constant rather than branching scattered through the routing logic.
90
112
  */
91
113
  export const DRIVE_EPIC_PREFERRED_CONDUCTOR = "v2";
92
- /**
93
- * The v2 readiness predicate, as a list so a failure can name what is missing.
94
- *
95
- * These are the facts v2 actually needs to drive an epic: a stored supervisor
96
- * posture, a reconciler that is ticking, a provisioned and live executor, and
97
- * complete GitHub App credentials. Each is read from the SERVER's report and
98
- * never re-derived locally — two implementations of one classification drift,
99
- * and a CLI that disagreed with the server about whether v2 can run would be
100
- * worse than no check at all.
101
- */
102
- export const V2_READINESS_REQUIREMENTS = [
103
- {
104
- id: "supervisor_setup",
105
- describe: "supervisor setup stored for this repository",
106
- satisfied: (r) => r.supervisor.setup_present,
107
- },
108
- {
109
- id: "supervisor_config",
110
- describe: "supervisor configuration stored for this repository",
111
- satisfied: (r) => r.supervisor.config_present,
112
- },
113
- {
114
- id: "github_credentials",
115
- describe: "GitHub App credentials that resolve completely",
116
- satisfied: (r) => r.github.credentials_complete,
117
- },
118
- {
119
- id: "reconciler_live",
120
- describe: "a reconciler that is ticking and not stale",
121
- // BAPI-1279 — launch liveness is a DEPLOYMENT fact. The `bring_up` block
122
- // reads the reconciler's process heartbeat deployment-wide, so a repository
123
- // that has never run an epic still reads live when the worker is healthy.
124
- // The repository-scoped `reconciler` section ("is this repository's work
125
- // moving?", from `epic_runs.last_tick_at`) is only the fallback for a server
126
- // too old to report `bring_up`.
127
- satisfied: (r) => r.bring_up
128
- ? r.bring_up.heartbeat_readable && r.bring_up.worker_present &&
129
- r.bring_up.single_transition_authority
130
- : r.reconciler.liveness_readable && !r.reconciler.stale,
131
- },
132
- {
133
- id: "executor_live",
134
- describe: "an executor provisioned and reporting ready",
135
- // BAPI-1279 — diagnostic only. drive-epic starts (or, for a durable profile,
136
- // verifies) the run's executor itself once the run exists.
137
- advisoryOnly: true,
138
- satisfied: (r) => r.executor.liveness_readable && r.executor.ready === true,
139
- },
140
- // BAPI-1102 — the three unattended prerequisites, in the order `setup-epic`
141
- // refuses them, so readiness and the refusal name the same first blocker.
142
- //
143
- // Each reads the SERVER's `unattended` block and re-derives nothing. A server
144
- // that does not report the block (older than BAPI-1102) leaves every one of
145
- // them UNSATISFIED: "could not be read" is not "holds", and these authorize an
146
- // unattended merge.
147
- //
148
- // The FIRST of them therefore carries the older-server remedy too, because it
149
- // is the one an unreported block always blocks on, and telling that operator
150
- // to set a consent flag would send them to fix something that may already be
151
- // set — the server simply never said (BAPI-1102 review).
152
- {
153
- id: "unattended_consent",
154
- describe: "repository consent to unattended Epic Implementer runs",
155
- unattendedOnly: true,
156
- // No fixed `remedy`: this requirement's action always depends on WHY.
157
- remedyFor: (r) => r.unattended === null || r.unattended === undefined
158
- ? "This Bridge API deploy does not report a repository's unattended " +
159
- "prerequisites at all, so none of them could be confirmed. Upgrade the " +
160
- "deploy, or pass --attended."
161
- : "Unattended runs are off for this repository. Turn on 'Allow unattended " +
162
- "Epic Implementer runs' on the repository's Setup page in the Bridge " +
163
- "admin panel, or pass --attended. If it is already on, contact Bridge support.",
164
- satisfied: (r) => r.unattended?.conductor_allowed === true,
165
- },
166
- {
167
- id: "unattended_notify_default",
168
- describe: "an escalation channel (a verified notify webhook or the account email)",
169
- unattendedOnly: true,
170
- remedy: "Supply a --policy-file declaring notify.webhook_url, or add an email address " +
171
- "to the account so escalation alerts can be emailed, or pass --attended. " +
172
- "notify.local_sink does not satisfy this.",
173
- // BAPI-1274 — the account's email address is an escalation channel when no
174
- // webhook is declared; the server reports its presence, never the address.
175
- satisfied: (r) => r.unattended?.notify_webhook_default_declared === true ||
176
- r.unattended?.escalation_email_available === true,
177
- },
178
- {
179
- id: "repository_readiness",
180
- describe: "confirmed review and epic-implementer-ci workflows on the default branch",
181
- unattendedOnly: true,
182
- // BAPI-1359 (Miss 38): the remedy names the SPECIFIC missing item, from the
183
- // same shared formatter the readiness row and the setup-epic refusal use. The
184
- // fixed install-command sentence that stood here could never clear a missing
185
- // migration-guard job — no install step creates one — so it is gone from this
186
- // refusal.
187
- //
188
- // BAPI-1390: the server decides which files are required (the review file
189
- // only for a `verdict_protocol` run; the CI lane file only for a repository
190
- // with no STORED gate profile and no `no_ci_gate`), and `satisfied` reads that
191
- // decision as given. The remedy waives the CI file the same way, so a stored
192
- // profile is never told to add a file it does not need. Gate-profile WARNINGS
193
- // (epic-branch rows) are not requirements and are never read here.
194
- remedyFor: (r) => repositoryWorkflowRemedy(gateProfileWaivesCiWorkflow(r) ? { ...r, conductor_ci_workflow: null } : r),
195
- satisfied: (r) => r.unattended?.repository_readiness_confirmed === true,
196
- },
197
- // BAPI-1135 — merge-execution eligibility is deliberately NOT a requirement here.
198
- //
199
- // It was one, and it made `drive-epic` refuse EVERY repository the moment it
200
- // shipped. The requirement could only be keyed on repository facts, because
201
- // this layer keeps the composed run policy opaque to itself — and no
202
- // repository carries the merge workflow until epic child 4 lands it. So both
203
- // states resolved the same way: an upgraded server reported
204
- // `merge_workflow_present: false` (`not_eligible`), an older one reported no
205
- // block at all (`could_not_verify`), and either made `selectConductor` return
206
- // `not_ready` and `classifyV2Readiness` return `operator_blocked` — for
207
- // `--attended`, `--into-base` and `local`-mode runs alike, with a remedy
208
- // naming a flag that does not exist yet.
209
- //
210
- // That is exactly the failure `selectConductor`'s own docstring warns about,
211
- // and it contradicts the compatibility guarantee the rest of this slice keeps:
212
- // nothing changes for a run that does not declare `github_actions`.
213
- //
214
- // Eligibility is still enforced, at the three layers that can actually see the
215
- // declared mode: `setup-epic`'s pre-create refusal (which reads the composed
216
- // policy), the approval route's server-side gate, and — authoritatively — the
217
- // before-merge preflight. Readiness still REPORTS the facts as diagnostic
218
- // rows, which inform without blocking. Reinstating a requirement here belongs
219
- // with child 4, once a repository can actually satisfy it.
220
- ];
114
+ // BAPI-1452: `V2_READINESS_REQUIREMENTS` moved to `./v2-readiness-requirements.ts`
115
+ // with an explicit governed row-ID list on every requirement, so readiness rows
116
+ // derive `blocking` from requirement applicability alone. It is re-exported
117
+ // here for existing consumers; classification and conductor selection stay in
118
+ // this module.
119
+ export { V2_READINESS_REQUIREMENTS };
221
120
  /**
222
121
  * The readiness facts a `plane up` can actually repair (BAPI-1054).
223
122
  *
@@ -237,7 +136,9 @@ export const V2_READINESS_REQUIREMENTS = [
237
136
  * running plane behind and change nothing — which is the precise failure the
238
137
  * classification exists to prevent.
239
138
  */
240
- export const V2_RUNTIME_READINESS_IDS = ["reconciler_live"];
139
+ export const V2_RUNTIME_READINESS_IDS = ["server.worker-present"];
140
+ /** BAPI-1452 — the credential capability row id, for naming its refusal. */
141
+ const MERGE_CREDENTIAL_ROW = "conductor.merge-credential-capability";
241
142
  /**
242
143
  * Classify the SERVER's readiness report into the composition's three cases.
243
144
  *
@@ -250,13 +151,22 @@ export const V2_RUNTIME_READINESS_IDS = ["reconciler_live"];
250
151
  * three competing actions has to work out which to do first, and the order here
251
152
  * already encodes that (setup, then config, then credentials).
252
153
  */
253
- export function classifyV2Readiness(readiness, options = {}) {
154
+ export function classifyV2Readiness(readiness, options = {},
155
+ /**
156
+ * BAPI-1452 — the value-free launch evidence (credential probe verdict and
157
+ * worktree-preparation result) collected locally before run creation. A
158
+ * separate input rather than a new option, so the server report and the
159
+ * local evidence stay visibly distinct. Absent: no evidence was collected,
160
+ * and the classification is exactly the pre-BAPI-1452 one. The unattended
161
+ * posture is never read from here — only from the server report.
162
+ */
163
+ launchEvidence) {
254
164
  for (const diagnostic of readiness.diagnostics ?? []) {
255
165
  if (diagnostic.severity === null || diagnostic.applicability === null) {
256
166
  return {
257
167
  kind: "operator_blocked",
258
168
  id: "diagnostic-metadata-unknown",
259
- describe: "declared diagnostic severity and applicability",
169
+ describe: "Additional readiness diagnostics",
260
170
  remedy: "Upgrade or repair the readiness producer, then retry the selected target.",
261
171
  };
262
172
  }
@@ -264,7 +174,7 @@ export function classifyV2Readiness(readiness, options = {}) {
264
174
  return {
265
175
  kind: "operator_blocked",
266
176
  id: "mandatory-diagnostic-unverified",
267
- describe: `mandatory diagnostic ${diagnostic.id}`,
177
+ describe: "Additional readiness diagnostics",
268
178
  remedy: "Resolve the mandatory diagnostic at the selected Bridge API target and retry.",
269
179
  };
270
180
  }
@@ -287,7 +197,7 @@ export function classifyV2Readiness(readiness, options = {}) {
287
197
  const deferred = options.approvedStoredPolicy ||
288
198
  options.effectivePolicy?.escalationChannel === "configured webhook" ||
289
199
  (options.effectivePolicy === undefined && options.hasPolicyFile)
290
- ? V2_READINESS_REQUIREMENTS.filter((req) => req.id !== "unattended_notify_default")
200
+ ? V2_READINESS_REQUIREMENTS.filter((req) => req.id !== "server.unattended-notify-default")
291
201
  : V2_READINESS_REQUIREMENTS;
292
202
  // `--into-base` is the second opt-out, and it is structural rather than
293
203
  // declared: it selects the branch-silent composition, whose policy carries no
@@ -303,6 +213,30 @@ export function classifyV2Readiness(readiness, options = {}) {
303
213
  ? gating.filter((req) => req.unattendedOnly !== true)
304
214
  : gating;
305
215
  const unmet = applicable.filter((req) => !req.satisfied(readiness));
216
+ // BAPI-1452 — launch evidence. Only a PROVEN gap (missing or invalid
217
+ // credential, proven no access, proven worktree impossibility) refuses;
218
+ // unverified evidence is a warning and never a pass. Server-fact blockers
219
+ // keep priority, so a disabled posture is still named first.
220
+ const launchChecks = launchEvidence !== undefined && !optedOut
221
+ ? buildLaunchReadinessChecks(readiness, {
222
+ attended: options.attended,
223
+ intoBase: options.intoBase,
224
+ launchEvidence,
225
+ })
226
+ : [];
227
+ const launchBlocker = firstLaunchEvidenceBlocker(launchChecks);
228
+ const serverBlocker = unmet.find((req) => !(V2_RUNTIME_READINESS_IDS.includes(req.id) || V2_RUNTIME_READINESS_IDS.some(id => READINESS_LEGACY_IDS[id] === req.id)));
229
+ if (launchBlocker !== null && serverBlocker === undefined) {
230
+ return {
231
+ kind: "operator_blocked",
232
+ id: launchBlocker.id.slice(launchBlocker.id.indexOf(".") + 1),
233
+ describe: launchBlocker.id === MERGE_CREDENTIAL_ROW
234
+ ? "a merge credential that has push and can read pull requests"
235
+ : "an executor clone whose shared git exclude can be prepared",
236
+ remedy: `${launchBlocker.detail ?? launchBlocker.label}. ${launchBlocker.remediation}`,
237
+ };
238
+ }
239
+ const launchWarnings = launchChecks.filter((check) => check.status === "warn");
306
240
  if (unmet.length === 0) {
307
241
  // Older deployments have no bring-up block; their existing reconciler
308
242
  // liveness predicate remains the available evidence. For deployments that
@@ -323,13 +257,16 @@ export function classifyV2Readiness(readiness, options = {}) {
323
257
  remedy: "Resolve the missing or duplicate reconciler process before launch.",
324
258
  };
325
259
  }
326
- return { kind: "green" };
260
+ return launchWarnings.length > 0 ? { kind: "green", warnings: launchWarnings } : { kind: "green" };
261
+ }
262
+ if (readiness.is_production && (serverBlocker?.id === 'server.worker-present' || unmet.some(req => req.id === 'server.worker-present'))) {
263
+ return { kind: 'operator_blocked', id: 'service-availability', describe: 'Service availability', remedy: 'Retry readiness before launching.' };
327
264
  }
328
- const blocker = unmet.find((req) => !V2_RUNTIME_READINESS_IDS.includes(req.id));
265
+ const blocker = serverBlocker;
329
266
  if (blocker) {
330
267
  return {
331
268
  kind: "operator_blocked",
332
- id: blocker.id,
269
+ 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,
333
270
  describe: blocker.describe,
334
271
  ...(() => {
335
272
  const remedy = blocker.remedyFor?.(readiness) ?? blocker.remedy;
@@ -339,157 +276,14 @@ export function classifyV2Readiness(readiness, options = {}) {
339
276
  }
340
277
  return { kind: "runtime_only", unmetIds: unmet.map((req) => req.id) };
341
278
  }
342
- export function getDriveEpicUsage() {
343
- return [
344
- "Usage: mcp-server drive-epic [options] <EPIC>",
345
- "",
346
- "Drives one epic with the conductor this project can actually run. Reads",
347
- "conductor readiness from Bridge API and routes to exactly one path — it",
348
- "never asks you to choose.",
349
- "",
350
- "Arguments:",
351
- " <EPIC> Jira epic key, matches [A-Z]+-[0-9]+ (e.g. BAPI-885)",
352
- "",
353
- "Branch strategy (v2): a plan with two or more nodes defaults to a dedicated",
354
- "epic/<KEY> branch — child PRs target it, one draft integration PR targets the",
355
- "repository base branch. Both flags below only override that default; the",
356
- "strategy itself is decided by the bootstrap this command delegates to, never",
357
- "here.",
358
- "",
359
- "Posture (v2, BAPI-1102): a run that selects an epic branch is created",
360
- "UNATTENDED by default — it authorizes automatic merge into the epic branch, and",
361
- "the server stamps its CI gate at first approval. The INTEGRATION PR into the",
362
- "repository base branch stays human-gated. Pass --attended to opt out. An",
363
- "unattended run has three repository prerequisites (consent, which is ON by",
364
- "default and switched on the Bridge admin panel's Setup page; an escalation",
365
- "channel, either a verified notify webhook or the account's email address; and",
366
- "confirmed review and CI workflows on the default branch) that readiness lists",
367
- "with their state and that are refused BY NAME before any run is created.",
368
- "",
369
- "Every run gets an executor (BAPI-1279): with --plan-file, once the run is",
370
- "created drive-epic starts a RUN-SCOPED EXECUTOR for it in the background, from",
371
- "this checkout's Git top level. It claims only that run's jobs, logs to",
372
- ".bridge/executors/<run>.log, and exits on its own when the run is done or",
373
- "abandoned. Re-running for the same live run starts no second one. A durable",
374
- "launch profile starts none: it requires a fresh --repo-wide executor instead.",
375
- "Checks that need no run happen FIRST, so a refusal before the run is created",
376
- "creates nothing; an executor that fails to start after it leaves the run intact",
377
- "and prints the log path and the exact command to start it by hand.",
378
- "",
379
- "Reconciler liveness is read from the deployment's heartbeat. Against a target",
380
- "that is not this machine's plane (production, say), drive-epic never touches a",
381
- "local plane: a target with no live reconciler is refused by name.",
382
- "",
383
- "One command (BAPI-1054, reordered by BAPI-1102): with --plan-file, drive-epic",
384
- "starts the conductor runtime for you against the local plane endpoint, when",
385
- "readiness is missing ONLY the reconciler. It brings up the CONTROL PLANE first",
386
- "(server and reconciler), creates and approves the run, then starts executor lanes",
387
- "SCOPED to that run, and starts the dead-man observer last — one invocation, no",
388
- "manual `plane up` first. A report missing supervisor setup,",
389
- "supervisor configuration, GitHub App credentials, or an unattended prerequisite",
390
- "is NOT started: those are operator-owned, and drive-epic exits with that one",
391
- "named reason instead.",
392
- "",
393
- "The plane port (BAPI-1153): with --plan-file and BAPI_BASE_URL naming the",
394
- `local plane endpoint (127.0.0.1, port ${PLANE_SERVER_PORT_ENV_VAR} or the default),`,
395
- "drive-epic handles the port one of three ways, and never asks you to choose:",
396
- " - cold start: nothing listens there — it brings the plane up, then creates",
397
- " the run;",
398
- " - attach: this repository's own healthy plane is there — it creates the run",
399
- " against that plane and starts NO second server or reconciler;",
400
- " - refusal: anything else holds the port (another listener, a manifest for a",
401
- " different repository, an unreadable manifest, a plane that cannot take a",
402
- " run) — one named reason, and nothing is started.",
403
- "One epic per plane — for its LANES: a plane's lanes serve the one run it is",
404
- "bound to. A second run attaches to the same plane's reconciler and gets its own",
405
- "run-scoped executor instead. A plane whose bound run cannot be read is refused",
406
- "as plane-already-bound. Concurrent planes on one database are not supported.",
407
- "Executor lanes and run-scoped executors are always scoped to the one run with",
408
- "--epic-run-id, on every path.",
409
- "",
410
- "Finding the plan (BAPI-1285): without --plan-file, drive-epic searches",
411
- "{docs_dir}/epic-plans/*/epic-plan.meta.json for a file naming this epic",
412
- "({\"epic_key\": \"<KEY>\"}), where docs_dir is BAPI_DOCS_DIR or docs/tmp",
413
- "resolved against the Git top level. Exactly one match with a sibling",
414
- "epic-plan.dag.json is used as if you had passed --plan-file, and its path is",
415
- "printed before anything is created. It never guesses: no match, two or more",
416
- "matches, or an unusable meta file stops with the paths it found and creates",
417
- "nothing. It never matches by folder name, child ticket key, or manifest. A",
418
- "supplied --plan-file always wins, and discovery does not run. The meta file is",
419
- "written by `emit-epic-implementer-bundle finalize`; a plan finalized before",
420
- "that has none, so pass its DAG with --plan-file.",
421
- "",
422
- "A live run with no plan: when the epic already has a live run and no plan was",
423
- "supplied or found, drive-epic does not create anything. It makes sure that run",
424
- "has an executor (reusing a live one, never starting a second) and reports it. A",
425
- "durable launch profile starts none and relies on its host's confirmed repo-wide",
426
- "executor; a plane already bound to the run needs none. An epic with several active runs, or",
427
- "a run that cannot be read, is refused by name.",
428
- "",
429
- "Preconditions are validated, never repaired: the current directory must be a Git",
430
- "work tree inside the target repository, because the run's executor starts there.",
431
- "No worktree is created for you and no replacement port is chosen for you — each",
432
- "failure names the fix. Fix it and rerun.",
433
- "",
434
- "Options:",
435
- " --plan-file <path> Plan DAG sidecar. Optional: without it, drive-epic finds",
436
- " the plan by epic key (see above). A supplied path always",
437
- " wins, and when the v2 path is selected drive-epic runs",
438
- " the bootstrap directly with it.",
439
- " --repo <name> Repo name (default: BAPI_REPO_NAME or .bridge/config)",
440
- " --feature-branch <name> Override the derived epic/<KEY> name. Forwarded",
441
- " verbatim, never interpreted here.",
442
- " --into-base OPT OUT of the epic-branch default: children target the",
443
- " repository base branch (the pre-BAPI-1009 behavior).",
444
- " Contradictory with --feature-branch; passing both is a",
445
- " parse error.",
446
- " --attended OPT OUT of the unattended default. Forwarded verbatim to",
447
- " the bootstrap, which owns what it composes; drive-epic",
448
- " reads it only to skip the unattended prerequisites.",
449
- "",
450
- "Policy (forwarded verbatim; drive-epic interprets none of it):",
451
- " --policy-file <path> JSON file holding the COMPLETE run policy.",
452
- " --review-policy <src> PER-RUN review policy source.",
453
- " --replace-policy Authorize replacing a LIVE run's stored policy.",
454
- "",
455
- "Launch target (BAPI-1260) — decided BEFORE any authenticated request:",
456
- " --launch-profile <name> Select the host-local launch profile guided setup",
457
- " approved (`install conductor --launch-profile <name>`):",
458
- " target, repository, mode, runtime, and policy and",
459
- " credential references. Useful for a local or other",
460
- " non-production server and for durable hosts.",
461
- " --base-url <url> Explicit Bridge API target. With a profile it must",
462
- " agree with it — an override never rebinds a profile.",
463
- "BAPI_EPIC_LAUNCH_PROFILE selects a host-local launch profile for epic",
464
- "launches. --launch-profile takes precedence. For an environment-selected",
465
- "profile, BAPI_BASE_URL remains the general CLI endpoint and does not",
466
- "conflict with the epic launch target; --base-url still must agree.",
467
- "Without either, BAPI_BASE_URL is used. With none of the three, drive-epic",
468
- `targets production (${CONDUCTOR_DEFAULT_BASE_URL}) and uses the`,
469
- "stored bapi:<repo> key when one is available. A stored key approved for a",
470
- "different endpoint is never sent; an unapproved key is sent only to",
471
- "production.",
472
- "",
473
- "Preview (BAPI-1285):",
474
- " --dry-run Read-only launch preview. Resolves the target, reads",
475
- " readiness and the epic's live run, discovers the plan,",
476
- " and runs the bootstrap's own dry-run validation. It",
477
- " reports what a real run WOULD do (create, attach,",
478
- " refuse, or stop) and never creates a run, cuts a",
479
- " branch, starts a plane, requests a lane, or starts or",
480
- " signals an executor. Exit 0 for create or attach, 1 for",
481
- " refuse or stop.",
482
- " --json With --dry-run only: print exactly one JSON document on",
483
- " stdout and nothing else. Alone, it is a parse error.",
484
- "",
485
- " -h, --help Show this help",
486
- ].join("\n");
487
- }
488
279
  /**
489
280
  * Parse argv. Rejects malformed input BEFORE any side effect — no readiness
490
281
  * read, no credential resolution, no delegation.
491
282
  */
492
283
  export function parseDriveEpicArgs(argv) {
284
+ if (argv.includes("--help-advanced")) {
285
+ return { status: "help", usage: getDriveEpicAdvancedUsage() };
286
+ }
493
287
  if (argv.includes("-h") || argv.includes("--help")) {
494
288
  return { status: "help", usage: getDriveEpicUsage() };
495
289
  }
@@ -528,8 +322,46 @@ export function parseDriveEpicArgs(argv) {
528
322
  // BAPI-1285 preview flags. Valueless; `--json` is meaningless without `--dry-run`.
529
323
  let dryRun = false;
530
324
  let json = false;
325
+ let all = false;
326
+ let allowStalePlane = false;
327
+ // BAPI-1496 — verification hand-off pass-throughs. Captured, never interpreted:
328
+ // setup-epic owns the vocabulary, the pairing rules, and the policy keys.
329
+ let verificationHandoff;
330
+ const verificationHandoffExceptions = [];
331
+ // BAPI-1510 — drive-only already-merged child controls. Never reach setup argv.
332
+ const keepChildren = [];
333
+ const skipChildren = [];
334
+ let noMergedCheck = false;
531
335
  for (let i = 0; i < argv.length; i++) {
532
336
  const arg = argv[i];
337
+ if (arg === "--all") {
338
+ all = true;
339
+ continue;
340
+ }
341
+ if (arg === "--no-merged-check") {
342
+ noMergedCheck = true;
343
+ continue;
344
+ }
345
+ if (arg === "--keep-child" || arg === "--skip-child") {
346
+ const value = argv[i + 1];
347
+ if (value === undefined || value.startsWith("-")) {
348
+ return { status: "error", message: `${arg} requires a ticket key.` };
349
+ }
350
+ if (!EPIC_KEY_PATTERN.test(value)) {
351
+ return { status: "error", message: `${arg} requires a ticket key like PROJ-123, got '${value}'.` };
352
+ }
353
+ (arg === "--keep-child" ? keepChildren : skipChildren).push(value);
354
+ i++;
355
+ continue;
356
+ }
357
+ const childEq = arg.match(/^(--keep-child|--skip-child)=(.*)$/);
358
+ if (childEq) {
359
+ if (!EPIC_KEY_PATTERN.test(childEq[2])) {
360
+ return { status: "error", message: `${childEq[1]} requires a ticket key like PROJ-123, got '${childEq[2]}'.` };
361
+ }
362
+ (childEq[1] === "--keep-child" ? keepChildren : skipChildren).push(childEq[2]);
363
+ continue;
364
+ }
533
365
  if (arg === "--dry-run") {
534
366
  dryRun = true;
535
367
  continue;
@@ -542,6 +374,11 @@ export function parseDriveEpicArgs(argv) {
542
374
  intoBase = true;
543
375
  continue;
544
376
  }
377
+ // BAPI-1476 — valueless, invocation-only, and never forwarded to setup-epic.
378
+ if (arg === "--allow-stale-plane") {
379
+ allowStalePlane = true;
380
+ continue;
381
+ }
545
382
  // BAPI-1102 — valueless, forwarded verbatim, and interpreted here for
546
383
  // exactly one thing: making the unattended readiness prerequisites
547
384
  // inapplicable. drive-epic reads no policy.
@@ -553,6 +390,29 @@ export function parseDriveEpicArgs(argv) {
553
390
  replacePolicy = true;
554
391
  continue;
555
392
  }
393
+ if (arg === "--verification-handoff" || arg === "--verification-handoff-exception") {
394
+ const value = argv[i + 1];
395
+ if (value === undefined || value.startsWith("-")) {
396
+ return { status: "error", message: `${arg} requires a value.` };
397
+ }
398
+ if (arg === "--verification-handoff")
399
+ verificationHandoff = value;
400
+ else
401
+ verificationHandoffExceptions.push(value);
402
+ i++;
403
+ continue;
404
+ }
405
+ const handoffEq = arg.match(/^(--verification-handoff|--verification-handoff-exception)=(.*)$/);
406
+ if (handoffEq) {
407
+ if (handoffEq[2].trim().length === 0) {
408
+ return { status: "error", message: `${handoffEq[1]} requires a value.` };
409
+ }
410
+ if (handoffEq[1] === "--verification-handoff")
411
+ verificationHandoff = handoffEq[2];
412
+ else
413
+ verificationHandoffExceptions.push(handoffEq[2]);
414
+ continue;
415
+ }
556
416
  if (arg === "--plan-file" ||
557
417
  arg === "--repo" ||
558
418
  arg === "--feature-branch" ||
@@ -628,6 +488,22 @@ export function parseDriveEpicArgs(argv) {
628
488
  "form of the read-only launch preview, and a real launch has no JSON output.",
629
489
  };
630
490
  }
491
+ // BAPI-1510 — contradictory child intent is refused before any file read or launch.
492
+ const overlap = keepChildren.filter((key) => skipChildren.includes(key));
493
+ if (overlap.length > 0) {
494
+ return {
495
+ status: "error",
496
+ message: `${overlap[0]} is named by both --keep-child and --skip-child. ` +
497
+ "Keep it (run it) or skip it, not both.",
498
+ };
499
+ }
500
+ if (noMergedCheck && skipChildren.length > 0) {
501
+ return {
502
+ status: "error",
503
+ message: "--no-merged-check turns off the already-merged check, but --skip-child needs " +
504
+ "that check to confirm the child is merged. Remove one of them.",
505
+ };
506
+ }
631
507
  // BAPI-1009: refused HERE — before access resolution, before the readiness
632
508
  // request, and before any delegation — with the same corrective wording
633
509
  // setup-epic uses, so the two entry points explain one mistake one way.
@@ -670,7 +546,7 @@ export function parseDriveEpicArgs(argv) {
670
546
  }
671
547
  const epicKey = positionals[0];
672
548
  if (!EPIC_KEY_PATTERN.test(epicKey)) {
673
- return { status: "error", message: `Malformed epic key '${epicKey}'. Expected e.g. BAPI-885.` };
549
+ return { status: "error", message: `Malformed epic key '${epicKey}'. Expected e.g. PROJ-885.` };
674
550
  }
675
551
  const options = {
676
552
  epicKey,
@@ -685,8 +561,15 @@ export function parseDriveEpicArgs(argv) {
685
561
  ...(replacePolicy ? { replacePolicy: true } : {}),
686
562
  ...(launchProfile ? { launchProfile } : {}),
687
563
  ...(baseUrl ? { baseUrl } : {}),
564
+ ...(all ? { all: true } : {}),
688
565
  ...(dryRun ? { dryRun: true } : {}),
689
566
  ...(json ? { json: true } : {}),
567
+ ...(allowStalePlane ? { allowStalePlane: true } : {}),
568
+ ...(verificationHandoff !== undefined ? { verificationHandoff } : {}),
569
+ ...(verificationHandoffExceptions.length > 0 ? { verificationHandoffExceptions } : {}),
570
+ ...(keepChildren.length > 0 ? { keepChildren: [...new Set(keepChildren)] } : {}),
571
+ ...(skipChildren.length > 0 ? { skipChildren: [...new Set(skipChildren)] } : {}),
572
+ ...(noMergedCheck ? { noMergedCheck: true } : {}),
690
573
  };
691
574
  return { status: "ok", options };
692
575
  }
@@ -718,7 +601,7 @@ export function selectConductor(readiness) {
718
601
  return {
719
602
  kind: "selected",
720
603
  conductor: DRIVE_EPIC_PREFERRED_CONDUCTOR,
721
- reason: "conductor readiness is green",
604
+ reason: "Epic Implementer readiness is green",
722
605
  };
723
606
  }
724
607
  return {
@@ -739,7 +622,7 @@ export function selectConductor(readiness) {
739
622
  * no quoting to get wrong.
740
623
  */
741
624
  export function buildSetupEpicArgv(options) {
742
- const { epicKey, planFile, repo, featureBranch, intoBase, attended, policyFile, reviewPolicy, replacePolicy, launchProfile, baseUrl, } = options;
625
+ const { epicKey, planFile, repo, featureBranch, intoBase, attended, policyFile, reviewPolicy, replacePolicy, launchProfile, baseUrl, verificationHandoff, verificationHandoffExceptions, } = options;
743
626
  return [
744
627
  "--epic-key",
745
628
  epicKey,
@@ -760,17 +643,26 @@ export function buildSetupEpicArgv(options) {
760
643
  // the adopted BAPI_BASE_URL instead.
761
644
  ...(launchProfile ? ["--launch-profile", launchProfile] : []),
762
645
  ...(baseUrl ? ["--base-url", baseUrl] : []),
646
+ // BAPI-1496 — the owner's verification hand-off choice, verbatim and only
647
+ // when supplied, so every pre-existing argv stays byte-identical.
648
+ ...(verificationHandoff !== undefined ? ["--verification-handoff", verificationHandoff] : []),
649
+ ...(verificationHandoffExceptions ?? []).flatMap((entry) => ["--verification-handoff-exception", entry]),
763
650
  ];
764
651
  }
765
652
  /**
766
653
  * Render the no-plan stop: what discovery found, how to make a plan, and how to
767
654
  * re-run with one.
768
655
  *
769
- * Precondition: the caller has already ruled out delegation, a not-ready result,
770
- * AND a live run. This runs only after plan discovery came back empty or
656
+ * Normal precondition: the caller has already ruled out delegation, a not-ready
657
+ * result, AND a live run. This runs only after plan discovery came back empty or
771
658
  * ambiguous (BAPI-1285), so it never claims "nothing derives a plan from an epic
772
659
  * key" — something does, and it names exactly what it found.
773
660
  *
661
+ * The `plane_not_running` presentation is the exception to that precondition:
662
+ * the local plane refused connections, so readiness was never read and whether a
663
+ * run for this epic is already live is UNCHECKED. It says so, and tells the
664
+ * operator how to attach.
665
+ *
774
666
  * It offers two ways to re-run and only one of them is a runnable `drive-epic`
775
667
  * command: `/drive-epic-run` is a session slash command, not a second conductor.
776
668
  */
@@ -787,7 +679,20 @@ launch = { profile: null },
787
679
  * BAPI-1285 — what discovery found. Absent reads as "no metadata named this
788
680
  * epic", with the searched directory left as its placeholder.
789
681
  */
790
- discovery) {
682
+ discovery, presentation = "default") {
683
+ // BAPI-1496 — an owner's explicit verification hand-off choice survives the
684
+ // re-run command verbatim. Nothing is derived: no flag, no flag added.
685
+ const handoffSuffix = [
686
+ ...(launch.options?.verificationHandoff !== undefined
687
+ ? ["--verification-handoff", launch.options.verificationHandoff]
688
+ : []),
689
+ ...(launch.options?.verificationHandoffExceptions ?? []).flatMap((entry) => [
690
+ "--verification-handoff-exception",
691
+ entry,
692
+ ]),
693
+ ]
694
+ .map((part) => ` ${shellQuote(part)}`)
695
+ .join("");
791
696
  const invocation = launch.profile !== null
792
697
  ? renderEpicLaunchCommand(launch.profile, {
793
698
  epicKey,
@@ -796,8 +701,8 @@ discovery) {
796
701
  ...(launch.options?.attended ? { attended: true } : {}),
797
702
  ...(launch.options?.intoBase ? { intoBase: true } : {}),
798
703
  ...(launch.options?.featureBranch ? { featureBranch: launch.options.featureBranch } : {}),
799
- }).replace(`${shellQuote("<path>")}`, "<path>")
800
- : `npx -y ${MCP_PACKAGE_NAME} drive-epic ${epicKey} --plan-file <path>`;
704
+ }).replace(`${shellQuote("<path>")}`, "<path>") + handoffSuffix
705
+ : `npx -y ${MCP_PACKAGE_NAME} drive-epic ${epicKey} --plan-file <path>${handoffSuffix}`;
801
706
  const plansDir = discovery?.epic_plans_dir ?? "{docs_dir}/epic-plans";
802
707
  const outcome = discovery?.status === "plan_ambiguous"
803
708
  ? [
@@ -809,7 +714,7 @@ discovery) {
809
714
  const skipped = discovery !== undefined && discovery.skipped.length > 0
810
715
  ? [
811
716
  "",
812
- "These metadata files could not be used, so they were not counted:",
717
+ "These plan metadata files were missing or could not be used, so they were not counted:",
813
718
  ...discovery.skipped.map((entry) => ` - ${entry.path} (${entry.reason})`),
814
719
  ]
815
720
  : [];
@@ -817,7 +722,9 @@ discovery) {
817
722
  conductor: "v2",
818
723
  invocation,
819
724
  lines: [
820
- `${epicKey}: ${selection.reason}, but no plan was supplied and none could be selected.`,
725
+ presentation === "plane_not_running"
726
+ ? `${epicKey}: readiness could not be checked because the local plane is not running and no usable plan could be selected.`
727
+ : `${epicKey}: ${selection.reason}, but no plan was supplied and none could be selected.`,
821
728
  "",
822
729
  ...outcome,
823
730
  ...skipped,
@@ -832,19 +739,42 @@ discovery) {
832
739
  "",
833
740
  ` 1. To make one, run /plan-epic ${epicKey} in an interactive session. It writes the`,
834
741
  " sidecar to {docs_dir}/epic-plans/{epic_slug}/epic-plan.dag.json.",
835
- " If the epic's tickets already exist, run emit-epic-implementer-bundle",
836
- " finalize instead — it resolves the placeholder keys in an existing",
837
- " sidecar, attaches touched_files, and writes epic-plan.meta.json so the",
838
- " plan is found next time.",
742
+ " For an existing /plan-epic sidecar that has the required bundle inputs and",
743
+ " whose tickets already exist, run emit-epic-implementer-bundle finalize",
744
+ " instead — it resolves the placeholder keys, attaches touched_files, and",
745
+ " writes epic-plan.meta.json so the plan is found next time.",
746
+ " A folder produced by /define-tickets holds a DAG but no metadata file. Use it",
747
+ " directly with --plan-file <that folder's epic-plan.dag.json>.",
839
748
  "",
840
749
  ` 2. Re-run with the plan, in a session: /drive-epic-run ${epicKey} <plan path>`,
841
750
  ` or from a shell: ${invocation}`,
842
751
  "",
843
752
  `That shell command bootstraps the run for you; ${SETUP_EPIC_SUBCOMMAND} is not`,
844
753
  "something you invoke directly.",
754
+ ...(presentation === "plane_not_running"
755
+ ? ["", PLANE_DOWN_LIVE_RUN_CAVEAT]
756
+ : []),
845
757
  ],
846
758
  };
847
759
  }
760
+ /** Appended to the plane-not-running handoff: live-run existence was not checked. */
761
+ const PLANE_DOWN_LIVE_RUN_CAVEAT = "If a run for this epic is already live, bring its plane up and preview again to attach.";
762
+ /** Placeholder selection for the plane-down stop: readiness was never read. */
763
+ const PLANE_DOWN_SELECTION = {
764
+ kind: "selected",
765
+ conductor: DRIVE_EPIC_PREFERRED_CONDUCTOR,
766
+ reason: "readiness was not checked",
767
+ };
768
+ /**
769
+ * The one text both the preview and a real launch print for the guarded
770
+ * plane-down no-plan stop, so the preview is a verbatim part of the real output.
771
+ */
772
+ function planeDownNoPlanStopText(epicKey, launch, discovery) {
773
+ const text = renderConductorHandoff(PLANE_DOWN_SELECTION, epicKey, launch, discovery, "plane_not_running")
774
+ .lines.join("\n");
775
+ assertSingleConductorInvocation(text);
776
+ return text;
777
+ }
848
778
  /**
849
779
  * Tokens that identify a conductor path in user-facing output. Used by the
850
780
  * output guard and by its test — one list, so a new spelling cannot be added to
@@ -864,7 +794,7 @@ const SETUP_EPIC_SUBCOMMAND = CONDUCTOR_INVOCATION_TOKENS[0];
864
794
  export function assertSingleConductorInvocation(text) {
865
795
  const named = CONDUCTOR_INVOCATION_TOKENS.filter((token) => text.includes(token));
866
796
  if (named.length > 1) {
867
- throw new Error(`drive-epic emitted more than one conductor invocation (${named.join(", ")}). ` +
797
+ throw new Error(`drive-epic emitted more than one launch path (${named.join(", ")}). ` +
868
798
  "Exactly one path may ever be presented.");
869
799
  }
870
800
  // BAPI-1260 — the entry point itself, too. A rendered handoff now carries a
@@ -1120,6 +1050,9 @@ function createDefaultPlanDiscoveryFs() {
1120
1050
  export async function readLiveEpicRunByKey(access, epicKey, fetchImpl = globalThis.fetch) {
1121
1051
  try {
1122
1052
  const state = await fetchEpicRunState(access, epicKey, fetchImpl);
1053
+ // The same response's engine-reported channel facts; read here so attach,
1054
+ // preview and setup never re-derive a channel from the redacted policy.
1055
+ const notificationSink = state?.notification_sink;
1123
1056
  const run = state
1124
1057
  ?.epic_run;
1125
1058
  if (typeof run?.epic_run_id !== "string" ||
@@ -1129,10 +1062,12 @@ export async function readLiveEpicRunByKey(access, epicKey, fetchImpl = globalTh
1129
1062
  }
1130
1063
  return {
1131
1064
  kind: "live",
1065
+ state,
1132
1066
  epicRunId: run.epic_run_id,
1133
1067
  status: run.status,
1068
+ ticketReview: ticketReviewSummary(run.ticket_review),
1134
1069
  ...(run.policy_json !== undefined
1135
- ? { effectivePolicy: effectivePolicyFacts(run.policy_json, "stored") }
1070
+ ? { effectivePolicy: effectivePolicyFacts(run.policy_json, "stored", notificationSink) }
1136
1071
  : {}),
1137
1072
  };
1138
1073
  }
@@ -1152,6 +1087,15 @@ export async function readLiveEpicRunByKey(access, epicKey, fetchImpl = globalTh
1152
1087
  }
1153
1088
  export function createDefaultDriveEpicDeps() {
1154
1089
  return {
1090
+ inspectRepositoryIdentity: async () => {
1091
+ const top = await createPlaneExecFile()("git", ["rev-parse", "--show-toplevel"], {
1092
+ cwd: process.cwd(), timeoutMs: 5000,
1093
+ });
1094
+ if (!top.ok || !path.isAbsolute(top.stdout.trim()))
1095
+ throw new Error("repository_root_unverifiable");
1096
+ const repoRoot = await realpath(top.stdout.trim());
1097
+ return { repoRoot, isBridge: await isBridgeEngineRepository(repoRoot, createPlaneFsDeps()) };
1098
+ },
1155
1099
  resolveAccess: async (repo, cwd, launch) => {
1156
1100
  // BAPI-1260: the target-first launch contract. BAPI-1272: with no target
1157
1101
  // selected it defaults to production, and a stored key is sent there only
@@ -1191,6 +1135,25 @@ export function createDefaultDriveEpicDeps() {
1191
1135
  cwd: () => process.cwd(),
1192
1136
  resolvePlaneEndpoint: () => resolvePlaneServerEndpoint(process.env),
1193
1137
  probePlanePort: (host, port) => probeTcpPort(host, port, PLANE_PORT_PROBE_TIMEOUT_MS),
1138
+ checkExecutorBuildFreshness: (repoRoot) => checkPlaneBuildFreshness(repoRoot, { fs: createPlaneFsDeps() }),
1139
+ collectPlaneFreshness: ({ repoRoot, ownsManifest, expectedPlaneId }) => checkPlaneFreshness(repoRoot, {
1140
+ execFile: createPlaneExecFile(),
1141
+ fileExists: (filePath) => fsStat(filePath).then((entry) => entry.isFile(), () => false),
1142
+ platform: process.platform,
1143
+ readPlaneManifest: (root) => readPlaneManifest(root, createPlaneFsDeps()),
1144
+ }, repoRoot, { ownsManifest, ...(expectedPlaneId !== undefined ? { expectedPlaneId } : {}) }),
1145
+ inspectHostSleep: (repoRoot) => inspectHostSleep(repoRoot, { execFile: createPlaneExecFile(), platform: process.platform }),
1146
+ inspectRequiredRunners: ({ repoRoot, providerRepository, gateProfile }) => inspectRequiredSelfHostedRunners({
1147
+ repoRoot,
1148
+ providerRepository,
1149
+ gateProfile,
1150
+ execFile: createPlaneExecFile(),
1151
+ workflows: createWorkflowSource(),
1152
+ }),
1153
+ inspectEpicBranchBehind: ({ repoRoot, branch, baseBranch }) => inspectEpicBranchBehindBase({ repoRoot, branch, baseBranch, execFile: createPlaneExecFile() }),
1154
+ fetchUsageAdvisory: (access) => fetchRepositoryUsageAdvisory(access),
1155
+ inspectWorkerDatabase: (repoRoot) => createWorkerDatabaseDoctorInspector({ env: process.env, cwd: repoRoot ?? process.cwd() })(),
1156
+ cleanupTerminalRunPlane: (input) => cleanupTerminalRunPlane(input, createTerminalRunCleanupDeps(process.env)),
1194
1157
  readRunState: async (access, epicRunId) => {
1195
1158
  const state = await fetchEpicRunState(access, epicRunId, globalThis.fetch);
1196
1159
  const run = state.epic_run;
@@ -1224,13 +1187,14 @@ export function createDefaultDriveEpicDeps() {
1224
1187
  readPlanDag: (filePath) => readFile(filePath, "utf8"),
1225
1188
  readPolicyFile: (filePath) => readFile(filePath, "utf8"),
1226
1189
  readLiveEpicRun: (access, epicKey) => readLiveEpicRunByKey(access, epicKey),
1227
- previewSetupEpic: async ({ argv, baseUrl, handoff }) => {
1190
+ previewSetupEpic: async ({ argv, baseUrl, handoff, observations }) => {
1228
1191
  const stdout = [];
1229
1192
  const stderr = [];
1230
1193
  const result = await runSetupEpicWorkflow(argv, {
1231
1194
  // A COPY carrying the resolved target: the preview never mutates
1232
1195
  // `process.env`, so a dry run leaves the process exactly as it found it.
1233
1196
  env: { ...process.env, BAPI_BASE_URL: baseUrl },
1197
+ previewObservations: observations,
1234
1198
  log: (message) => stdout.push(message),
1235
1199
  errorLog: (message) => stderr.push(message),
1236
1200
  }, handoff);
@@ -1242,8 +1206,28 @@ export function createDefaultDriveEpicDeps() {
1242
1206
  // preview must not call.
1243
1207
  inspectRunExecutorPrecondition: async (cwd) => {
1244
1208
  const result = await prepareRunExecutorDefault(cwd, createDefaultRunExecutorLaunchDeps());
1245
- return result.ok ? { ok: true } : { ok: false, message: result.message };
1209
+ // BAPI-1452: the Git top level rides along so the dry run can inspect the
1210
+ // same clone a real launch would, without ever preparing it.
1211
+ return result.ok
1212
+ ? { ok: true, repoRoot: result.prepared.repoRoot }
1213
+ : { ok: false, message: result.message };
1246
1214
  },
1215
+ probeLaunchMergeCredential: (args) => probeLocalMergeCapability(args),
1216
+ // BAPI-1461: the local executor this launch starts runs in the person's own
1217
+ // session, so its credential may come from the repository's stored entry.
1218
+ resolveLaunchMergeCredential: ({ kind, repository }) => resolveMergeCredentialAtAction(process.env, kind, {
1219
+ allowStoredEntry: true,
1220
+ providerRepository: repository,
1221
+ storeDeps: nodeGithubMergeCredentialReadDeps(process.env),
1222
+ }),
1223
+ launchReadinessLog: (message) => console.error(message),
1224
+ // Read-only filesystem boundary: `readFile`, `stat`, and a W_OK `access`
1225
+ // check. Nothing here can create or write the exclude.
1226
+ inspectWorktreeExclude: (repoRoot) => resolveWorktreeSettingsExclude(repoRoot, {
1227
+ readFile: (filePath) => readFile(filePath, "utf8"),
1228
+ stat: async (filePath) => ({ mode: (await fsStat(filePath)).mode }),
1229
+ accessWritable: (target) => fsAccess(target, fsConstants.W_OK),
1230
+ }),
1247
1231
  prepareRunExecutor: (cwd) => prepareRunExecutorDefault(cwd, createDefaultRunExecutorLaunchDeps()),
1248
1232
  ensureRunExecutor: (args) => ensureRunExecutorDefault(args, createDefaultRunExecutorLaunchDeps()),
1249
1233
  // stdout is safe here: `drive-epic` is dispatched BEFORE MCP server
@@ -1292,7 +1276,7 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1292
1276
  // child processes' BAPI_BASE_URL.
1293
1277
  const accessResult = await deps.resolveAccess(repo, undefined, launch);
1294
1278
  if (!accessResult.ok) {
1295
- return escalate(deps, epicKey, `conductor readiness could not be read: ${accessResult.error}`);
1279
+ return escalate(deps, epicKey, `Epic Implementer readiness could not be read: ${accessResult.error}`);
1296
1280
  }
1297
1281
  const launchProfile = accessResult.profile ?? null;
1298
1282
  deps.adoptLaunchTarget?.(accessResult.access.baseUrl);
@@ -1310,6 +1294,8 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1310
1294
  access: accessResult.access,
1311
1295
  profile: launchProfile,
1312
1296
  targetSource: accessResult.targetSource ?? "default",
1297
+ freshness: createPlaneFreshnessCache(),
1298
+ launchCredential: {},
1313
1299
  };
1314
1300
  // BAPI-1285 — with no `--plan-file`, look for the plan BEFORE readiness. A
1315
1301
  // discovered plan must count as a supplied one for the BAPI-1153 cold-start
@@ -1320,11 +1306,16 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1320
1306
  // escalates exactly as before, and the live-run read stays after readiness.
1321
1307
  let discovered = null;
1322
1308
  let docsRootUnresolved = false;
1309
+ // BAPI-1532 — whether the effective plan was FOUND rather than supplied. A
1310
+ // discovered plan is a convenience, not approved input: it may still be used to
1311
+ // create a run, but a live run is attached to first and the plan stays unused.
1312
+ let planWasDiscovered = false;
1323
1313
  if (planFile === undefined) {
1324
1314
  const docs = await deps.resolveDocsDir();
1325
1315
  if (docs.ok) {
1326
1316
  discovered = await discoverEpicPlan(epicKey, docs.docsDir, deps.discoveryFs);
1327
1317
  if (discovered.status === "found") {
1318
+ planWasDiscovered = true;
1328
1319
  ctx = { ...ctx, options: { ...ctx.options, planFile: discovered.path } };
1329
1320
  }
1330
1321
  }
@@ -1348,6 +1339,10 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1348
1339
  readiness = await deps.readReadiness(accessResult.access);
1349
1340
  }
1350
1341
  catch (err) {
1342
+ // BAPI-1455 — a proven-incompatible local schema is a terminal refusal,
1343
+ // not an unknown: the server read the catalog and named what is missing.
1344
+ if (isSchemaIncompatibleError(err))
1345
+ return refuse(deps, formatSchemaIncompatibleRefusal(epicKey, err));
1351
1346
  // BAPI-1153 — the cold-start case. With a plan file, a readiness read that
1352
1347
  // failed at the TRANSPORT against the plane's own endpoint, on a port that
1353
1348
  // actively refuses connections, is not "unknown": it is "no server yet".
@@ -1376,9 +1371,33 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1376
1371
  }
1377
1372
  }
1378
1373
  }
1379
- return escalate(deps, epicKey, `conductor readiness could not be read: ${safeDiagnosticMessage(err, "readiness request failed")}`);
1374
+ // The narrow no-plan stop: a local, non-durable plane that refuses
1375
+ // connections, with no usable plan supplied or discovered. Readiness was
1376
+ // never read, so this is the existing stop outcome — not a new refusal.
1377
+ // Nothing is started or created.
1378
+ if (ctx.options.planFile === undefined &&
1379
+ planeTarget &&
1380
+ err instanceof ConductorBridgeApiError &&
1381
+ err.kind === "network" &&
1382
+ launchProfile?.executionMode !== "durable" &&
1383
+ discovered !== null &&
1384
+ (discovered.status === "plan_not_found" || discovered.status === "plan_ambiguous")) {
1385
+ const endpoint = planeEndpointForBaseUrl(deps, accessResult.access.baseUrl);
1386
+ if (endpoint !== null) {
1387
+ const probe = await deps.probePlanePort(endpoint.host, endpoint.port).catch(() => ({ kind: "error" }));
1388
+ if (probe.kind === "refused") {
1389
+ deps.errorLog(planeDownNoPlanStopText(epicKey, { profile: launchProfile, options: parsed.options }, discovered));
1390
+ return 1;
1391
+ }
1392
+ }
1393
+ }
1394
+ return escalate(deps, epicKey, `Epic Implementer readiness could not be read: ${safeDiagnosticMessage(err, "readiness request failed")}`);
1380
1395
  }
1381
- if (ctx.options.planFile !== undefined) {
1396
+ // BAPI-1532 — an EXPLICIT plan selects its setup now. A discovered plan does
1397
+ // not: plan selection, approval, and the create-time escalation-channel checks
1398
+ // run only on the create path, after the live-run read below, so attaching to a
1399
+ // live run never depends on them.
1400
+ if (ctx.options.planFile !== undefined && !planWasDiscovered) {
1382
1401
  const prepared = await prepareSetupSelection(ctx);
1383
1402
  if (!prepared.ok) {
1384
1403
  return refuse(deps, [
@@ -1417,8 +1436,24 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1417
1436
  if (live.kind === "unknown")
1418
1437
  return refuse(deps, liveRunUnknownRefusal(epicKey, live.reason).lines);
1419
1438
  if (discovered.status === "found") {
1420
- // The plan was folded into `ctx.options` before readiness; from here it is
1421
- // indistinguishable from a supplied `--plan-file`.
1439
+ if (live.kind === "live") {
1440
+ // BAPI-1532 — attach FIRST. The discovered plan is dropped from the
1441
+ // effective options, so nothing below can treat it as approved input,
1442
+ // and the local file is left untouched.
1443
+ const { planFile: _unusedDiscoveredPlan, ...attachOptions } = ctx.options;
1444
+ return await attachToLiveRun({ ...ctx, options: attachOptions }, readiness, live, discovered.path);
1445
+ }
1446
+ // The create path: setup selection runs now. The plan was folded into
1447
+ // `ctx.options` before readiness; from here it is indistinguishable from
1448
+ // a supplied `--plan-file`.
1449
+ const prepared = await prepareSetupSelection(ctx);
1450
+ if (!prepared.ok) {
1451
+ return refuse(deps, [
1452
+ `${epicKey}: REFUSED (${prepared.reasonId}) — the selected run or policy could not be verified.`,
1453
+ "Nothing was created or started.",
1454
+ ]);
1455
+ }
1456
+ ctx = { ...ctx, handoff: prepared.handoff };
1422
1457
  await announceFoundPlan();
1423
1458
  }
1424
1459
  else if (live.kind === "live") {
@@ -1461,10 +1496,33 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1461
1496
  // Otherwise — no plane here, or one owned by a sibling worktree — the
1462
1497
  // run gets a run-scoped executor. The preflight runs only when a
1463
1498
  // manifest says there is a plane in this checkout to attach to.
1499
+ // BAPI-1496: a plane bound to a finished run is torn down BEFORE it can
1500
+ // be attached to. Once it is gone, nothing serves this endpoint, so the
1501
+ // launch cold-starts a fresh plane rather than creating against the
1502
+ // stopped API or trusting the readiness read from it.
1503
+ const cleaned = await cleanUpTerminalRunPlane(ctx, deps.cwd());
1504
+ if (cleaned?.kind === "completed") {
1505
+ const endpoint = planeEndpointForBaseUrl(deps, ctx.access.baseUrl);
1506
+ const probe = endpoint
1507
+ ? await deps.probePlanePort(endpoint.host, endpoint.port).catch(() => ({ kind: "error" }))
1508
+ : null;
1509
+ if (probe?.kind === "refused")
1510
+ return await coldStartPlane(ctx);
1511
+ }
1464
1512
  const attachable = await findAttachablePlane(ctx);
1465
1513
  if (attachable !== null) {
1466
1514
  return await attachToPlane(ctx, attachable, readiness);
1467
1515
  }
1516
+ // BAPI-1476: no manifest in this checkout belongs to the plane serving the
1517
+ // endpoint (a sibling worktree's, or none), so the snapshot is unverified
1518
+ // here; the database check still runs. Decided before setup-epic.
1519
+ const staleSibling = await planeFreshnessCreateGuard(ctx, {
1520
+ repoRoot: deps.cwd(),
1521
+ ownsManifest: false,
1522
+ });
1523
+ if (staleSibling !== null)
1524
+ return staleSibling;
1525
+ await surfaceWorkerDatabaseAdvisory(ctx);
1468
1526
  return await createRunWithRunExecutor(ctx, readiness);
1469
1527
  }
1470
1528
  // Operator-blocked: ONE named reason, and nothing is started. `plane up`
@@ -1472,8 +1530,7 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1472
1530
  // so bringing it up would leave a running plane behind and change nothing.
1473
1531
  if (classification.kind === "operator_blocked") {
1474
1532
  const refusal = [
1475
- `${epicKey}: the engine path still needs ${classification.describe} ` +
1476
- `(${classification.id}).`,
1533
+ `${epicKey}: the engine path still needs ${classification.describe}.`,
1477
1534
  "",
1478
1535
  "This is not something starting the runtime can fix, so nothing was started.",
1479
1536
  // The requirement's OWN remedy when it has one. Telling an operator to
@@ -1497,6 +1554,8 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1497
1554
  }
1498
1555
  // Runtime-only: this invocation composes bring-up with run creation.
1499
1556
  const repoRoot = deps.cwd();
1557
+ // BAPI-1496: a plane bound to a finished run is torn down before preflight.
1558
+ await cleanUpTerminalRunPlane(ctx, repoRoot);
1500
1559
  const preflight = await deps.runPlanePreflight(repoRoot);
1501
1560
  // BAPI-1153 — ATTACH. A port serving this repository's own live, healthy
1502
1561
  // plane is not a blocker when the Bridge API this command talks to IS that
@@ -1517,7 +1576,7 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1517
1576
  });
1518
1577
  if (precondition) {
1519
1578
  const lines = [
1520
- `${epicKey}: cannot start the conductor runtime — ${precondition.check} failed.`,
1579
+ `${epicKey}: cannot start the Epic Implementer runtime — ${precondition.check} failed.`,
1521
1580
  formatPlaneDiagnostic(precondition),
1522
1581
  ];
1523
1582
  // BAPI-1153: an occupied port names WHICH kind of occupant it is and its
@@ -1548,7 +1607,7 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1548
1607
  // The new order is the only one that can work: the server has to be up
1549
1608
  // before a run can be created, and the run has to exist before a lane can
1550
1609
  // be scoped to it.
1551
- deps.log(`${epicKey}: the conductor runtime is not live; starting its control plane before creating the run.`);
1610
+ deps.log(`${epicKey}: the Epic Implementer runtime is not live; starting its control plane before creating the run.`);
1552
1611
  // The SAME preflight result is handed to the launch, so the port that was
1553
1612
  // probed is the port that gets launched and the two cannot disagree.
1554
1613
  const controlPlane = await deps.launchControlPlane({ preflight, executors: 1 });
@@ -1562,6 +1621,12 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1562
1621
  // the detached runtime is its own process-group leader and outlives us by
1563
1622
  // design, which is what "the plane is left running" means.
1564
1623
  void controlPlane.lifetime.catch(() => undefined);
1624
+ // BAPI-1476: the plane this invocation just started, checked before any
1625
+ // setup or run-create. A refusal leaves the plane running and says so.
1626
+ const staleLaunched = await planeFreshnessCreateGuard(ctx, { repoRoot, ownsManifest: true, planeId: controlPlane.planeId }, LAUNCHED_PLANE_LEFT_RUNNING);
1627
+ if (staleLaunched !== null)
1628
+ return staleLaunched;
1629
+ await surfaceWorkerDatabaseAdvisory(ctx);
1565
1630
  // Readiness is NOT re-read as a gate here. A successful bring-up IS the
1566
1631
  // runtime fact: the launch already waited for this plane's own reconciler
1567
1632
  // heartbeat. (`reconciler_live` now reads the deployment heartbeat, but the
@@ -1573,7 +1638,7 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1573
1638
  repoRoot,
1574
1639
  planeId: controlPlane.planeId,
1575
1640
  awaitPlaneReady: controlPlane.awaitPlaneReady,
1576
- });
1641
+ }, readiness);
1577
1642
  }
1578
1643
  // No plan file, and readiness is not green: v2 is not ready and there is no
1579
1644
  // second conductor to offer. Report it as a not-ready refusal on stderr with
@@ -1583,8 +1648,9 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1583
1648
  `${epicKey}: ${selection.reason}.`,
1584
1649
  "",
1585
1650
  "The v2 engine is not ready to drive this epic, and there is no alternative",
1586
- "conductor to fall back to. Resolve conductor readiness (`install-bridge",
1587
- "conductor`, then `doctor`) and run drive-epic again.",
1651
+ "engine to fall back to. Resolve Epic Implementer readiness (`install conductor`,",
1652
+ "then `doctor`) and run drive-epic again.",
1653
+ `See ${CONSUMER_GUIDE_POINTER}.`,
1588
1654
  ].join("\n");
1589
1655
  assertSingleConductorInvocation(refusal);
1590
1656
  deps.errorLog(refusal);
@@ -1633,7 +1699,7 @@ async function surfaceContainmentAdvisory(deps, planFile) {
1633
1699
  * A constant so the preview's `readiness.remedy` is the very line the real
1634
1700
  * refusal prints, not a second copy that can drift.
1635
1701
  */
1636
- const ESCALATE_REMEDY = "Restore Bridge API access and run drive-epic again, or ask an operator to resolve conductor readiness.";
1702
+ const ESCALATE_REMEDY = "Restore Bridge API access and run drive-epic again, or ask an operator to resolve Epic Implementer readiness.";
1637
1703
  /** The reason id the preview reports for an unknown readiness read. */
1638
1704
  const READINESS_UNKNOWN_REASON_ID = "readiness-unknown";
1639
1705
  /**
@@ -1642,8 +1708,9 @@ const READINESS_UNKNOWN_REASON_ID = "readiness-unknown";
1642
1708
  * the preview cannot disagree.
1643
1709
  */
1644
1710
  function operatorBlockedRemedy(classification) {
1645
- return (classification.remedy ??
1646
- `Resolve it with \`${PRINTED_CONDUCTOR_INSTALL_COMMAND}\` (${PRINTED_CHECK_NAME_INSTRUCTION}), then run drive-epic again.`);
1711
+ const remedy = classification.remedy ??
1712
+ `Resolve it with \`${PRINTED_CONDUCTOR_INSTALL_COMMAND}\` (${PRINTED_CHECK_NAME_INSTRUCTION}), then run drive-epic again.`;
1713
+ return `${remedy} See ${CONSUMER_GUIDE_POINTER}.`;
1647
1714
  }
1648
1715
  /**
1649
1716
  * The escalation branch. Prints NO conductor invocation at all — naming a
@@ -1652,10 +1719,10 @@ function operatorBlockedRemedy(classification) {
1652
1719
  */
1653
1720
  function escalate(deps, epicKey, reason) {
1654
1721
  const lines = [
1655
- `Cannot determine which conductor owns ${epicKey}: ${reason}`,
1722
+ `Cannot determine which engine owns ${epicKey}: ${reason}`,
1656
1723
  "",
1657
1724
  "This is not a not-ready result — it is an unknown one, and starting the wrong",
1658
- "conductor on an epic wedges it permanently.",
1725
+ "engine on an epic wedges it permanently.",
1659
1726
  ESCALATE_REMEDY,
1660
1727
  ];
1661
1728
  const text = lines.join("\n");
@@ -1664,8 +1731,12 @@ function escalate(deps, epicKey, reason) {
1664
1731
  return 1;
1665
1732
  }
1666
1733
  /** Resolve policy intent once for the setup delegation, after a fresh run read. */
1667
- async function prepareSetupSelection(ctx, coldStart = false) {
1668
- const live = coldStart ? { kind: "none" } : await ctx.deps.readLiveEpicRun(ctx.access, ctx.epicKey);
1734
+ /** Narrow an effective-policy channel label to the closed identity set. */
1735
+ function channelIdentityOf(label) {
1736
+ return label === "configured webhook" || label === "account email" ? label : "unavailable";
1737
+ }
1738
+ async function prepareSetupSelection(ctx, coldStart = false, observedLive) {
1739
+ const live = coldStart ? { kind: "none" } : observedLive ?? await ctx.deps.readLiveEpicRun(ctx.access, ctx.epicKey);
1669
1740
  if (live.kind === "conflict")
1670
1741
  return { ok: false, reasonId: "live-run-ambiguous" };
1671
1742
  if (live.kind === "unknown")
@@ -1701,12 +1772,157 @@ async function prepareSetupSelection(ctx, coldStart = false) {
1701
1772
  policy,
1702
1773
  escalationChannel: pinnedPolicy
1703
1774
  ? policyDeclaresNotifyWebhook(pinnedPolicy) ? "configured webhook" : "account email"
1704
- : live.kind === "live" ? "unavailable" : "account email",
1775
+ : live.kind === "live" ? channelIdentityOf(live.effectivePolicy?.escalation_channel) : "account email",
1705
1776
  });
1706
1777
  if (pinnedPolicy)
1707
1778
  pinEpicLaunchPolicy(selection, pinnedPolicy);
1708
1779
  return { ok: true, handoff: { selection, access: ctx.access, profile: ctx.profile } };
1709
1780
  }
1781
+ // ---------------------------------------------------------------------------
1782
+ // BAPI-1510 — already-merged child detection
1783
+ // ---------------------------------------------------------------------------
1784
+ /** The refusal reason shared by the preview and a real create when nothing is left to run. */
1785
+ export const EPIC_ALREADY_COMPLETE_REASON_ID = "epic-already-complete";
1786
+ const EPIC_ALREADY_COMPLETE_REMEDY = "Every child in this plan is already merged and on the indexed commit, so there is nothing to run. " +
1787
+ "If you still want a child to run, pass --keep-child <KEY> for it.";
1788
+ /** The fixed text a failed explicit skip is refused with. */
1789
+ function skipRefusalRemedy(refusals) {
1790
+ const keys = (reason) => refusals.filter((r) => r.reason === reason).map((r) => r.ticketKey);
1791
+ const parts = [];
1792
+ const notInPlan = keys("not_in_plan");
1793
+ if (notInPlan.length > 0)
1794
+ parts.push(`${notInPlan.join(", ")} not in this plan`);
1795
+ const unavailable = keys("check_unavailable");
1796
+ if (unavailable.length > 0) {
1797
+ parts.push(`${unavailable.join(", ")} could not be confirmed because the already-merged check could not run`);
1798
+ }
1799
+ const weak = keys("not_skippable");
1800
+ if (weak.length > 0) {
1801
+ parts.push(`${weak.join(", ")} not currently shown as merged on the indexed commit`);
1802
+ }
1803
+ return (`--skip-child was refused: ${parts.join("; ")}. ` +
1804
+ "Remove the flag for those children (they will run), or fix the cause and try again.");
1805
+ }
1806
+ /** Parse a plan sidecar into its DAG and child keys, or `null` when it is not usable for the check. */
1807
+ async function readPlanChildren(deps, planPath) {
1808
+ try {
1809
+ const parsed = JSON.parse(await deps.readPlanDag(planPath));
1810
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
1811
+ return null;
1812
+ const nodes = parsed.nodes;
1813
+ if (!Array.isArray(nodes))
1814
+ return null;
1815
+ const keys = [];
1816
+ for (const node of nodes) {
1817
+ const key = node?.ticket_key;
1818
+ if (typeof key !== "string" || !EPIC_KEY_PATTERN.test(key))
1819
+ return null;
1820
+ keys.push(key);
1821
+ }
1822
+ if (new Set(keys).size !== keys.length)
1823
+ return null;
1824
+ return { plan: parsed, keys };
1825
+ }
1826
+ catch {
1827
+ return null;
1828
+ }
1829
+ }
1830
+ function notChecked(reason, base = {}) {
1831
+ return {
1832
+ state: { status: "not_checked", reason, children: [] },
1833
+ childKeys: [],
1834
+ plan: null,
1835
+ cutCommitSha: null,
1836
+ skipKeys: new Set(),
1837
+ confirmedKeys: new Set(),
1838
+ refusals: [],
1839
+ ...base,
1840
+ };
1841
+ }
1842
+ /**
1843
+ * Classify the plan's children against the canonical indexed commit and decide the
1844
+ * skip set. Read-only; every failure degrades to "not checked, keep every child",
1845
+ * except that an explicit `--skip-child` it cannot support becomes a refusal.
1846
+ * Detection that is turned off (`--no-merged-check`) never reads anything.
1847
+ */
1848
+ async function evaluateMergedChildren(ctx, planPath) {
1849
+ const { deps, options, access, epicKey } = ctx;
1850
+ if (options.noMergedCheck === true)
1851
+ return notChecked("disabled");
1852
+ const children = await readPlanChildren(deps, planPath);
1853
+ if (children === null)
1854
+ return notChecked("no_plan");
1855
+ const base = { childKeys: children.keys, plan: children.plan };
1856
+ const skipChildren = options.skipChildren ?? [];
1857
+ const keepChildren = options.keepChildren ?? [];
1858
+ const failed = (reason, cutCommitSha) => ({
1859
+ ...notChecked(reason, base),
1860
+ cutCommitSha,
1861
+ refusals: selectSkips({ planKeys: children.keys, results: null, keepChildren, skipChildren }).refusals,
1862
+ });
1863
+ let cutCommitSha;
1864
+ try {
1865
+ const truth = await (deps.readCanonicalParseTruth
1866
+ ? deps.readCanonicalParseTruth(access)
1867
+ : readSetupCanonicalParseTruth(access, globalThis.fetch));
1868
+ if (!truth.ok)
1869
+ return failed("cut_commit_unavailable", null);
1870
+ cutCommitSha = truth.cutCommitSha;
1871
+ }
1872
+ catch {
1873
+ return failed("cut_commit_unavailable", null);
1874
+ }
1875
+ const classify = deps.classifyChildMergeStatus
1876
+ ? (request) => deps.classifyChildMergeStatus(access, request)
1877
+ : (request) => classifyChildMergeStatusClient(access, request);
1878
+ const checked = await classifyPlanChildren(classify, epicKey, children.keys, cutCommitSha);
1879
+ if (!checked.ok)
1880
+ return failed("check_failed", cutCommitSha);
1881
+ const selection = selectSkips({
1882
+ planKeys: children.keys,
1883
+ results: checked.results,
1884
+ keepChildren,
1885
+ skipChildren,
1886
+ });
1887
+ return {
1888
+ state: { status: "checked", children: buildAlreadyDoneEntries(checked.results, selection.skipKeys) },
1889
+ childKeys: children.keys,
1890
+ plan: children.plan,
1891
+ cutCommitSha,
1892
+ skipKeys: selection.skipKeys,
1893
+ confirmedKeys: selection.confirmedKeys,
1894
+ refusals: selection.refusals,
1895
+ };
1896
+ }
1897
+ /** The PR number for a skipped child, only when it is a valid positive integer. */
1898
+ function skippedChildPr(state, key) {
1899
+ const entry = state.children.find((child) => child.ticket_key === key);
1900
+ return entry !== undefined && entry.pr_number !== null && Number.isSafeInteger(entry.pr_number) && entry.pr_number > 0
1901
+ ? entry.pr_number
1902
+ : null;
1903
+ }
1904
+ /** Post-create audit recording: best effort, one plain warning, never changes the outcome. */
1905
+ async function recordSkippedChildrenBestEffort(ctx, epicRunId, skipped) {
1906
+ const { deps, access } = ctx;
1907
+ const children = skipped.map((s) => ({ ticketKey: s.key, operatorConfirmed: s.confirmed }));
1908
+ let allRecorded = true;
1909
+ try {
1910
+ for (let i = 0; i < children.length; i += CHILD_MERGE_STATUS_BATCH_SIZE) {
1911
+ const batch = children.slice(i, i + CHILD_MERGE_STATUS_BATCH_SIZE);
1912
+ const response = deps.recordSkippedChildren
1913
+ ? await deps.recordSkippedChildren(access, epicRunId, batch)
1914
+ : await recordSkippedChildrenClient(access, epicRunId, batch);
1915
+ if (response.results.some((r) => r.outcome === "refused"))
1916
+ allRecorded = false;
1917
+ }
1918
+ }
1919
+ catch {
1920
+ allRecorded = false;
1921
+ }
1922
+ if (!allRecorded) {
1923
+ deps.errorLog("The run was created, but the skipped-child record could not be saved.");
1924
+ }
1925
+ }
1710
1926
  async function runSelectedSetupEpic(ctx) {
1711
1927
  const prepared = ctx.handoff
1712
1928
  ? { ok: true, handoff: ctx.handoff }
@@ -1715,7 +1931,61 @@ async function runSelectedSetupEpic(ctx) {
1715
1931
  ctx.deps.errorLog(`${ctx.epicKey}: REFUSED (${prepared.reasonId}) — the selected run or policy could not be verified.`);
1716
1932
  return { exitCode: 1 };
1717
1933
  }
1718
- const result = await ctx.deps.runSetupEpic(buildSetupEpicArgv(ctx.options), prepared.handoff);
1934
+ const { deps, options, epicKey } = ctx;
1935
+ // BAPI-1510 — fresh classification immediately before setup. Preview verdicts are
1936
+ // never consumed: each create starts from the ORIGINAL plan and re-checks.
1937
+ const planPath = options.planFile;
1938
+ if (planPath === undefined || options.noMergedCheck === true) {
1939
+ return await deps.runSetupEpic(buildSetupEpicArgv(options), prepared.handoff);
1940
+ }
1941
+ const evaluation = await evaluateMergedChildren(ctx, planPath);
1942
+ if (evaluation.refusals.length > 0) {
1943
+ deps.errorLog(`${epicKey}: REFUSED (skip-child-refused) — ${skipRefusalRemedy(evaluation.refusals)}`);
1944
+ deps.errorLog("No run was created.");
1945
+ return { exitCode: 1 };
1946
+ }
1947
+ if (evaluation.state.status === "not_checked") {
1948
+ if (evaluation.state.reason === "cut_commit_unavailable" || evaluation.state.reason === "check_failed") {
1949
+ deps.errorLog(`${epicKey}: could not check for already-merged children; every child stays in the plan.`);
1950
+ }
1951
+ return await deps.runSetupEpic(buildSetupEpicArgv(options), prepared.handoff);
1952
+ }
1953
+ if (evaluation.skipKeys.size === 0 || evaluation.plan === null || evaluation.cutCommitSha === null) {
1954
+ return await deps.runSetupEpic(buildSetupEpicArgv(options), prepared.handoff);
1955
+ }
1956
+ if (evaluation.skipKeys.size >= evaluation.childKeys.length) {
1957
+ deps.errorLog(`${epicKey}: REFUSED (${EPIC_ALREADY_COMPLETE_REASON_ID}) — ${EPIC_ALREADY_COMPLETE_REMEDY}`);
1958
+ deps.errorLog("No run was created.");
1959
+ return { exitCode: 1 };
1960
+ }
1961
+ const skipped = evaluation.childKeys
1962
+ .filter((key) => evaluation.skipKeys.has(key))
1963
+ .map((key) => ({ key, confirmed: evaluation.confirmedKeys.has(key) }));
1964
+ for (const { key, confirmed } of skipped) {
1965
+ const pr = skippedChildPr(evaluation.state, key);
1966
+ deps.log(`${epicKey}: ${confirmed ? "skipping (confirmed by you)" : "skipping already-merged child"} ${key}` +
1967
+ `${pr !== null ? ` (#${pr})` : ""}`);
1968
+ }
1969
+ const trimmed = trimDonePlanNodes(evaluation.plan, evaluation.skipKeys);
1970
+ const withPath = deps.withPlanPath ?? withPlanPath;
1971
+ const result = await withPath({
1972
+ originalPath: planPath,
1973
+ trimmedJson: JSON.stringify(trimmed, null, 2),
1974
+ skipped: true,
1975
+ warn: (message) => deps.errorLog(message),
1976
+ }, (trimmedPath) => deps.runSetupEpic(buildSetupEpicArgv({ ...options, planFile: trimmedPath }), {
1977
+ ...prepared.handoff,
1978
+ expectedCutCommitSha: evaluation.cutCommitSha,
1979
+ attachOnlyOnReuse: true,
1980
+ }));
1981
+ if (result.reusedExistingRun === true) {
1982
+ // Reuse or race adoption: the trimmed plan was never applied and nothing is recorded.
1983
+ deps.log(`${epicKey}: an existing run was found; the already-merged check was not applied and existing runs are unchanged.`);
1984
+ return result;
1985
+ }
1986
+ if (result.epicRunId !== undefined && result.runCreated === true && result.planStored === true) {
1987
+ await recordSkippedChildrenBestEffort(ctx, result.epicRunId, skipped);
1988
+ }
1719
1989
  return result;
1720
1990
  }
1721
1991
  /** Emit one refusal, guarded so it can never name a second conductor. */
@@ -1725,6 +1995,205 @@ function refuse(deps, lines) {
1725
1995
  deps.errorLog(text);
1726
1996
  return 1;
1727
1997
  }
1998
+ /** The launch evidence rows exist only for an unattended launch. */
1999
+ function isUnattendedLaunch(options) {
2000
+ return options.attended !== true && options.intoBase !== true;
2001
+ }
2002
+ /** The launch row ids a launch can be refused on, without their namespace. */
2003
+ const LAUNCH_REFUSAL_IDS = ["merge-credential-capability", "worktree-preparation", ...Object.values(READINESS_PRE_CREATE_CODES)];
2004
+ /**
2005
+ * The credential evidence. Probes ONLY a locally owned executor's credential in
2006
+ * `local` / `machine_token` mode, against the server's explicit `owner/name`;
2007
+ * never the launcher's unrelated credential for an external executor, and never
2008
+ * anything for `github_actions`. Every gap is a value-free warning reason.
2009
+ */
2010
+ async function collectCredentialEvidence(deps, readiness, topology, box) {
2011
+ const mode = readiness.resolved_merge_execution_mode;
2012
+ if (mode === undefined)
2013
+ return { kind: "unverified", reason: "server_fields_missing" };
2014
+ if (mode === null)
2015
+ return { kind: "unverified", reason: "mode_unresolved" };
2016
+ if (mode === "github_actions")
2017
+ return { kind: "github_actions" };
2018
+ if (topology.kind === "plane_lane")
2019
+ return { kind: "unverified", reason: "external_executor_plane", mode };
2020
+ if (topology.kind === "durable_profile") {
2021
+ return { kind: "unverified", reason: "external_executor_durable", mode };
2022
+ }
2023
+ const repository = readiness.provider_repository;
2024
+ if (repository === undefined)
2025
+ return { kind: "unverified", reason: "server_fields_missing", mode };
2026
+ if (!isProviderRepositoryIdentity(repository)) {
2027
+ return { kind: "unverified", reason: "repository_unresolved", mode };
2028
+ }
2029
+ if (deps.probeLaunchMergeCredential === undefined) {
2030
+ return { kind: "unverified", reason: "probe_unavailable", mode };
2031
+ }
2032
+ // BAPI-1461: resolve once, with the stored-entry fallback, and probe exactly
2033
+ // the credential the executor will be handed — never a second env lookup.
2034
+ const resolved = await resolveLaunchCredentialOnce(deps, mode, repository, box);
2035
+ let verdict;
2036
+ try {
2037
+ verdict = classifyLocalGhPreflight(await deps.probeLaunchMergeCredential({
2038
+ kind: mode,
2039
+ repository,
2040
+ // A store-sourced credential is handed over explicitly; an env one is the
2041
+ // same value the probe resolves itself, so its call is unchanged.
2042
+ ...(resolved !== undefined && resolved.fromStore
2043
+ ? { resolved: { credential: resolved.credential, invalid: resolved.invalid } }
2044
+ : {}),
2045
+ }));
2046
+ }
2047
+ catch {
2048
+ // Nothing from the thrown value is kept: an unexpected probe failure is
2049
+ // simply unavailable evidence.
2050
+ return { kind: "unverified", reason: "probe_unavailable", mode };
2051
+ }
2052
+ switch (verdict) {
2053
+ case "passed":
2054
+ return { kind: "verified", mode, repository };
2055
+ case "credential_missing":
2056
+ return { kind: "credential_missing", mode };
2057
+ case "credential_invalid":
2058
+ return { kind: "credential_invalid", mode };
2059
+ case "no_access":
2060
+ return { kind: "no_access", mode, repository };
2061
+ case "gh_unavailable":
2062
+ return { kind: "unverified", reason: "gh_unavailable", mode };
2063
+ case "probe_unavailable":
2064
+ return { kind: "unverified", reason: "probe_unavailable", mode };
2065
+ }
2066
+ }
2067
+ /**
2068
+ * BAPI-1461 — resolve the launch's merge credential once and remember it in the
2069
+ * launch's box. `undefined` means no resolver was supplied (or it failed), so the
2070
+ * probe falls back to its own environment lookup and nothing is handed over.
2071
+ */
2072
+ async function resolveLaunchCredentialOnce(deps, kind, repository, box) {
2073
+ if (deps.resolveLaunchMergeCredential === undefined)
2074
+ return undefined;
2075
+ let resolution;
2076
+ try {
2077
+ resolution = await deps.resolveLaunchMergeCredential({ kind, repository });
2078
+ }
2079
+ catch {
2080
+ return undefined;
2081
+ }
2082
+ const credential = resolution.status === "resolved" ? resolution.credential : null;
2083
+ if (box !== undefined)
2084
+ box.resolved = credential;
2085
+ return {
2086
+ credential,
2087
+ invalid: resolution.status === "invalid",
2088
+ fromStore: (resolution.status === "resolved" || resolution.status === "invalid") && resolution.source === "store",
2089
+ };
2090
+ }
2091
+ /**
2092
+ * BAPI-1461 — the credential to hand a run-scoped executor: the one this launch
2093
+ * already resolved, or (on the live-run attach path, which runs no launch gate)
2094
+ * a fresh resolution for a locally owned, `local`-mode executor. Only the local
2095
+ * kind is ever handed over; nothing for machine-user or GitHub Actions mode.
2096
+ */
2097
+ async function launchCredentialForExecutor(ctx, readiness) {
2098
+ const box = ctx.launchCredential;
2099
+ if (box !== undefined && box.resolved !== undefined) {
2100
+ return box.resolved?.kind === "local" ? box.resolved : null;
2101
+ }
2102
+ if (readiness.resolved_merge_execution_mode !== "local")
2103
+ return null;
2104
+ const repository = readiness.provider_repository;
2105
+ if (typeof repository !== "string" || !isProviderRepositoryIdentity(repository))
2106
+ return null;
2107
+ const resolved = await resolveLaunchCredentialOnce(ctx.deps, "local", repository, box);
2108
+ return resolved?.credential ?? null;
2109
+ }
2110
+ /**
2111
+ * The worktree evidence, from Child 1's NON-WRITING resolver against the clone
2112
+ * the executor will own. Blocks only when the exclude is proven neither present
2113
+ * nor writable; anything the resolver cannot establish is a warning. The
2114
+ * absolute exclude path never leaves this function.
2115
+ */
2116
+ async function collectWorktreeEvidence(deps, topology) {
2117
+ if (topology.kind === "plane_lane")
2118
+ return { kind: "unverified", reason: "external_executor_plane" };
2119
+ if (topology.kind === "durable_profile")
2120
+ return { kind: "unverified", reason: "external_executor_durable" };
2121
+ if (topology.repoRoot === null || deps.inspectWorktreeExclude === undefined) {
2122
+ return { kind: "unverified", reason: "inspection_unavailable" };
2123
+ }
2124
+ let resolution;
2125
+ try {
2126
+ resolution = await deps.inspectWorktreeExclude(topology.repoRoot);
2127
+ }
2128
+ catch {
2129
+ return { kind: "unverified", reason: "inspection_unavailable" };
2130
+ }
2131
+ if (resolution.kind !== "resolved")
2132
+ return { kind: "unverified", reason: "inspection_unavailable" };
2133
+ if (resolution.present || resolution.writable)
2134
+ return { kind: "ready", present: resolution.present };
2135
+ return { kind: "blocked" };
2136
+ }
2137
+ /** Collect both halves of the launch evidence. */
2138
+ async function collectLaunchEvidence(deps, readiness, topology, box) {
2139
+ return {
2140
+ credential: await collectCredentialEvidence(deps, readiness, topology, box),
2141
+ worktree: await collectWorktreeEvidence(deps, topology),
2142
+ };
2143
+ }
2144
+ /**
2145
+ * The launch capability gate (BAPI-1452). Runs after readiness and executor
2146
+ * topology are resolved and BEFORE the run is created, dispatched, or given an
2147
+ * executor. Prints the compact launch summary, then refuses (exit 1) only on a
2148
+ * proven blocker; `null` means continue.
2149
+ *
2150
+ * Attended and `--into-base` launches skip it: the unattended requirements do
2151
+ * not apply there, so there is nothing for the evidence to refuse.
2152
+ */
2153
+ async function launchCapabilityGate(ctx, readiness, topology, outcome = "Nothing was created or started.") {
2154
+ const { deps, epicKey, options } = ctx;
2155
+ if (!isUnattendedLaunch(options))
2156
+ return null;
2157
+ const evidence = await collectLaunchEvidence(deps, readiness, topology, ctx.launchCredential);
2158
+ (deps.launchReadinessLog ?? deps.errorLog)(formatLaunchReadinessSummary(buildLaunchReadinessChecks(readiness, { launchEvidence: evidence }), { all: ctx.options.all, isProduction: readiness.is_production, prerequisites: readiness.prerequisites }).join("\n"));
2159
+ const classification = classifyV2Readiness(readiness, { attended: false, intoBase: false, effectivePolicy: ctx.handoff?.selection }, evidence);
2160
+ if (classification.kind !== "operator_blocked" || !LAUNCH_REFUSAL_IDS.includes(classification.id)) {
2161
+ return null;
2162
+ }
2163
+ return refuse(deps, [
2164
+ `${epicKey}: REFUSED (${classification.id}) — the launch still needs ${classification.describe}.`,
2165
+ operatorBlockedRemedy(classification),
2166
+ outcome,
2167
+ ]);
2168
+ }
2169
+ /**
2170
+ * The launch rows a preview reports, and the refusal they imply (BAPI-1452).
2171
+ * Uses the SAME evidence collection and classification as a real launch; the
2172
+ * worktree check reads the clone the read-only inspection names and never
2173
+ * prepares or writes it.
2174
+ */
2175
+ async function previewLaunchCapability(ctx, readiness, topology) {
2176
+ const { deps, options } = ctx;
2177
+ const context = { attended: options.attended === true, intoBase: options.intoBase === true };
2178
+ if (!isUnattendedLaunch(options)) {
2179
+ return { checks: buildLaunchReadinessChecks(readiness, context), refusal: null };
2180
+ }
2181
+ const durations = {};
2182
+ const [credential, worktree] = await Promise.all([
2183
+ measurePrecheck(() => collectCredentialEvidence(deps, readiness, topology), (ms) => { durations["conductor.merge-credential-capability"] = ms; }),
2184
+ measurePrecheck(() => collectWorktreeEvidence(deps, topology), (ms) => { durations["conductor.worktree-preparation"] = ms; }),
2185
+ ]);
2186
+ const evidence = { credential, worktree };
2187
+ const checks = buildLaunchReadinessChecks(readiness, { ...context, launchEvidence: evidence }).map((row) => ({ ...row, duration_ms: durations[row.id] ?? elapsedMs(monotonicNow()) }));
2188
+ const classification = classifyV2Readiness(readiness, { ...context, effectivePolicy: ctx.handoff?.selection }, evidence);
2189
+ if (classification.kind === "operator_blocked" && LAUNCH_REFUSAL_IDS.includes(classification.id)) {
2190
+ return {
2191
+ checks,
2192
+ refusal: { reasonId: classification.id, remedy: operatorBlockedRemedy(classification) },
2193
+ };
2194
+ }
2195
+ return { checks, refusal: null };
2196
+ }
1728
2197
  function durableActorAdmissionDenied(readiness) {
1729
2198
  const evidence = readiness.admission_evidence;
1730
2199
  return evidence?.schema_version === 1 &&
@@ -1743,7 +2212,7 @@ function planeEndpointForBaseUrl(deps, baseUrl) {
1743
2212
  /** What to tell the operator about a plane THIS invocation started and left up. */
1744
2213
  const LAUNCHED_PLANE_LEFT_RUNNING = [
1745
2214
  "",
1746
- "The conductor CONTROL PLANE was started by this invocation and is STILL RUNNING.",
2215
+ "The Epic Implementer CONTROL PLANE was started by this invocation and is STILL RUNNING.",
1747
2216
  "No run was created and no executor lane was spawned. Inspect it with `plane status`,",
1748
2217
  "and wind it down with `plane down` once the item above is fixed.",
1749
2218
  ];
@@ -1782,10 +2251,448 @@ async function checkPlaneAdmission(ctx, readiness, manifest) {
1782
2251
  `${ctx.epicKey}: REFUSED (plane-reconciler-unconfirmed) — the plane's own reconciler could ` +
1783
2252
  `not be confirmed as the live transition authority (its heartbeat reads: ${state}).`,
1784
2253
  "Another reconciler may be standing in for this plane — often a reparented worker.py from an",
1785
- `earlier plane. Check \`ps aux | grep worker.py\` (${BRING_UP_RUNBOOK} §6), stop any`,
2254
+ `earlier plane. Check \`ps aux | grep worker.py\` (see ${BRING_UP_RUNBOOK}), stop any`,
1786
2255
  "survivor, and run drive-epic again.",
1787
2256
  ];
1788
2257
  }
2258
+ // ---------------------------------------------------------------------------
2259
+ // BAPI-1476 — local-plane freshness: one evidence collection, one policy
2260
+ // ---------------------------------------------------------------------------
2261
+ //
2262
+ // `plane/plane-freshness.ts` OBSERVES. This section DECIDES, and the decision
2263
+ // differs by mode: a launch that would CREATE a run refuses on a confirmed stale
2264
+ // snapshot or database head; a launch that only ATTACHES to a run that already
2265
+ // exists never stops mid-run on freshness — it warns. `--allow-stale-plane`
2266
+ // downgrades the creation refusals for one invocation and nothing else.
2267
+ /** Refusal names for a confirmed freshness problem. Unique to this check. */
2268
+ export const DRIVE_EPIC_FRESHNESS_REFUSALS = [
2269
+ /** The plane's pinned snapshot is behind `origin/main`. */
2270
+ "plane-snapshot-stale",
2271
+ /** The database revision set differs from the repository migration head. */
2272
+ "plane-database-head-mismatch",
2273
+ ];
2274
+ function createPlaneFreshnessCache() {
2275
+ return { observations: new Map() };
2276
+ }
2277
+ /**
2278
+ * Collect snapshot and database evidence ONCE per (checkout, ownership) for this
2279
+ * invocation. `null` when nothing applies: a non-plane target gets no reads at
2280
+ * all, so a production launch's output is byte-for-byte unchanged.
2281
+ */
2282
+ async function collectFreshnessObservations(ctx, own) {
2283
+ const { deps } = ctx;
2284
+ if (planeEndpointForBaseUrl(deps, ctx.access.baseUrl) === null)
2285
+ return null;
2286
+ const collect = deps.collectPlaneFreshness;
2287
+ if (collect === undefined)
2288
+ return null;
2289
+ const cache = ctx.freshness ?? createPlaneFreshnessCache();
2290
+ const key = `${own.repoRoot}\u0000${own.ownsManifest ? own.planeId ?? "" : "-"}`;
2291
+ let pending = cache.observations.get(key);
2292
+ if (pending === undefined) {
2293
+ pending = collect({
2294
+ repoRoot: own.repoRoot,
2295
+ ownsManifest: own.ownsManifest,
2296
+ ...(own.planeId !== undefined ? { expectedPlaneId: own.planeId } : {}),
2297
+ }).catch(() => null);
2298
+ cache.observations.set(key, pending);
2299
+ }
2300
+ return pending;
2301
+ }
2302
+ async function collectHostSleep(ctx, repoRoot) {
2303
+ const { deps } = ctx;
2304
+ if (planeEndpointForBaseUrl(deps, ctx.access.baseUrl) === null)
2305
+ return null;
2306
+ const inspect = deps.inspectHostSleep;
2307
+ if (inspect === undefined)
2308
+ return null;
2309
+ const cache = ctx.freshness ?? createPlaneFreshnessCache();
2310
+ cache.sleep ??= (async () => {
2311
+ const started = monotonicNow();
2312
+ const report = await inspect(repoRoot).catch(() => null);
2313
+ return report === null ? null : { ...report, duration_ms: elapsedMs(started) };
2314
+ })();
2315
+ return cache.sleep;
2316
+ }
2317
+ /**
2318
+ * BAPI-1496 — the bound run a stale-snapshot remedy should name, or `undefined`
2319
+ * for an unbound plane. Read only when the plane is this checkout's own, bound,
2320
+ * local, and its snapshot is confirmed stale, so the common path issues no
2321
+ * request. A failed read is an UNKNOWN status, never assumed terminal.
2322
+ */
2323
+ async function boundRunForStaleRemedy(ctx, own, reports) {
2324
+ if (!own.ownsManifest || own.epicRunId === undefined || reports === null)
2325
+ return undefined;
2326
+ // The bound remedy is shown only on a confirmed stale refusal, so only that reads.
2327
+ if (freshnessVerdictOf(reports.snapshot).verdict !== "refuse")
2328
+ return undefined;
2329
+ if (planeEndpointForBaseUrl(ctx.deps, ctx.access.baseUrl) === null)
2330
+ return undefined;
2331
+ const state = await ctx.deps.readRunState(ctx.access, own.epicRunId).catch(() => null);
2332
+ return { epicRunId: own.epicRunId, status: state?.status ?? null };
2333
+ }
2334
+ function freshnessVerdictOf(report) {
2335
+ const outcome = report.outcomes[0];
2336
+ const detail = outcome?.detail ?? "";
2337
+ switch (outcome?.status) {
2338
+ case "pass":
2339
+ return { verdict: "pass", detail };
2340
+ case "fail":
2341
+ return { verdict: "refuse", detail };
2342
+ case "skip":
2343
+ return { verdict: "skip", detail };
2344
+ default:
2345
+ return { verdict: "unverified", detail };
2346
+ }
2347
+ }
2348
+ /**
2349
+ * Project the observations into launch rows and the creation blockers.
2350
+ *
2351
+ * Row `status` stays in the existing four-state vocabulary (`fail` for a
2352
+ * confirmed refusal, `warn` for unverified evidence); the verdict word — `pass`,
2353
+ * `refuse`, `unverified` — leads the row's detail so human and JSON output carry
2354
+ * the same meaning.
2355
+ */
2356
+ function assessPlaneFreshness(reports, sleep, mode, allowStalePlane,
2357
+ /**
2358
+ * BAPI-1496 — the stale plane's bound run and its read-only server status.
2359
+ * Present only for a plane bound to a run; it selects the ownership-specific
2360
+ * remedy, which never advises `plane down` for a run that is not finished.
2361
+ * Absent keeps `PLANE_SNAPSHOT_STALE_REMEDY` byte for byte.
2362
+ */
2363
+ boundRun) {
2364
+ const rows = [];
2365
+ const blockers = [];
2366
+ let overridden = false;
2367
+ const flagNote = allowStalePlane ? "; overridden for this invocation by --allow-stale-plane" : "";
2368
+ const project = (id, label, report, refusal) => {
2369
+ const duration_ms = report.duration_ms ?? elapsedMs(monotonicNow());
2370
+ const { verdict, detail } = freshnessVerdictOf(report);
2371
+ if (verdict === "pass") {
2372
+ rows.push({ duration_ms, id, label, status: "pass", blocking: false, detail: `pass — ${detail}` });
2373
+ }
2374
+ else if (verdict === "unverified") {
2375
+ rows.push({
2376
+ duration_ms,
2377
+ id,
2378
+ label,
2379
+ status: "warn",
2380
+ blocking: false,
2381
+ detail: `unverified — ${detail}`,
2382
+ remedy: PLANE_FRESHNESS_UNVERIFIED_REMEDY,
2383
+ });
2384
+ }
2385
+ else if (verdict === "refuse" && mode === "attach") {
2386
+ // Warning-only: an existing run is never stopped for freshness.
2387
+ rows.push({
2388
+ duration_ms,
2389
+ id,
2390
+ label,
2391
+ status: "warn",
2392
+ blocking: false,
2393
+ detail: `refuse (warning only; attachment proceeds) — ${detail}${flagNote}`,
2394
+ remedy: refusal.remedy,
2395
+ });
2396
+ }
2397
+ else if (verdict === "refuse" && allowStalePlane) {
2398
+ overridden = true;
2399
+ rows.push({
2400
+ duration_ms,
2401
+ id,
2402
+ label,
2403
+ status: "fail",
2404
+ blocking: false,
2405
+ detail: `refuse (overridden for this invocation) — ${detail}`,
2406
+ remedy: refusal.remedy,
2407
+ });
2408
+ }
2409
+ else if (verdict === "refuse") {
2410
+ blockers.push(refusal);
2411
+ rows.push({
2412
+ duration_ms,
2413
+ id,
2414
+ label,
2415
+ status: "fail",
2416
+ blocking: true,
2417
+ detail: `refuse — ${detail}`,
2418
+ remedy: refusal.remedy,
2419
+ });
2420
+ }
2421
+ };
2422
+ if (reports !== null) {
2423
+ project(PLANE_SNAPSHOT_FRESHNESS_ID, "Plane snapshot freshness", reports.snapshot, {
2424
+ reasonId: "plane-snapshot-stale",
2425
+ remedy: boundRun !== undefined ? formatBoundPlaneStaleRemedy(boundRun) : PLANE_SNAPSHOT_STALE_REMEDY,
2426
+ });
2427
+ project(PLANE_DATABASE_HEAD_ID, "Plane database head", reports.database, {
2428
+ reasonId: "plane-database-head-mismatch",
2429
+ remedy: PLANE_DATABASE_HEAD_REMEDY,
2430
+ });
2431
+ }
2432
+ if (sleep !== null) {
2433
+ const duration_ms = sleep.duration_ms ?? elapsedMs(monotonicNow());
2434
+ const { verdict, detail } = freshnessVerdictOf(sleep);
2435
+ if (verdict === "skip") {
2436
+ rows.push({ duration_ms, id: PLANE_HOST_SLEEP_ID, label: "Host sleep", status: "skip", blocking: false, detail: `not applicable — ${detail}` });
2437
+ }
2438
+ else if (verdict === "unverified") {
2439
+ rows.push({
2440
+ duration_ms,
2441
+ id: PLANE_HOST_SLEEP_ID,
2442
+ label: "Host sleep",
2443
+ status: "warn",
2444
+ blocking: false,
2445
+ detail: `unverified — ${detail}`,
2446
+ remedy: PLANE_FRESHNESS_UNVERIFIED_REMEDY,
2447
+ });
2448
+ }
2449
+ else if (hostPowerFactFromReport(sleep).state === "present") {
2450
+ // BAPI-1506: a battery or lid advisory is a warning with its remedy, not
2451
+ // a pass. It still never blocks.
2452
+ rows.push({
2453
+ duration_ms,
2454
+ id: PLANE_HOST_SLEEP_ID,
2455
+ label: "Host sleep",
2456
+ status: "warn",
2457
+ blocking: false,
2458
+ detail: `present — ${detail}`,
2459
+ remedy: PLANE_SLEEP_REMEDY,
2460
+ });
2461
+ }
2462
+ else {
2463
+ // Readable evidence never blocks setup. "pass" means exactly that.
2464
+ rows.push({ duration_ms, id: PLANE_HOST_SLEEP_ID, label: "Host sleep", status: "pass", blocking: false, detail: `pass — ${detail}` });
2465
+ }
2466
+ }
2467
+ return { rows, blockers, overridden };
2468
+ }
2469
+ /** Rows worth printing on a real launch: everything except a plain pass. */
2470
+ function adverseFreshnessRows(rows) {
2471
+ return rows.filter((row) => row.status !== "pass");
2472
+ }
2473
+ /** The blockers as one named refusal; both remedies are kept, in fixed order. */
2474
+ function freshnessRefusalOf(blockers) {
2475
+ const first = blockers[0];
2476
+ if (first === undefined)
2477
+ return null;
2478
+ return { reasonId: first.reasonId, remedy: blockers.map((blocker) => blocker.remedy).join(" ") };
2479
+ }
2480
+ function renderFreshnessRows(rows, heading = 'Plane freshness:') {
2481
+ return [heading, ...rows.flatMap(row => [
2482
+ ` [${row.status === 'fail' && row.blocking ? 'Blocking' : row.status === 'warn' ? 'Warning' : 'Informational'}] ${row.label}${row.detail ? ` — ${row.detail}` : ''}`,
2483
+ ...(row.remedy ? [` → ${row.remedy}`] : []),
2484
+ ])];
2485
+ }
2486
+ /**
2487
+ * The guard for a CREATING launch, placed beside `checkPlaneAdmission` and before
2488
+ * the first setup or run-create side effect. Returns an exit code only when it
2489
+ * refuses; otherwise it prints any non-blocking finding and returns `null`.
2490
+ *
2491
+ * Fail-open on missing evidence: unreadable or absent evidence is a warning, so
2492
+ * it is never proof of staleness and never permission to skip another safeguard.
2493
+ */
2494
+ async function planeFreshnessCreateGuard(ctx, own, trailer = []) {
2495
+ try {
2496
+ const reports = await collectFreshnessObservations(ctx, own);
2497
+ if (reports === null)
2498
+ return null;
2499
+ const boundRun = await boundRunForStaleRemedy(ctx, own, reports);
2500
+ let assessment = assessPlaneFreshness(reports, null, "create", ctx.options.allowStalePlane === true, boundRun);
2501
+ if (assessment.blockers.length > 0) {
2502
+ // setup-epic REUSES the epic's live run instead of creating one, and a reuse
2503
+ // is an attachment: it is warned about, never refused. Asked only when a
2504
+ // confirmed finding would otherwise block, so the common path reads nothing.
2505
+ const live = await ctx.deps
2506
+ .readLiveEpicRun(ctx.access, ctx.epicKey)
2507
+ .catch(() => ({ kind: "unknown" }));
2508
+ if (live.kind === "live") {
2509
+ assessment = assessPlaneFreshness(reports, null, "attach", ctx.options.allowStalePlane === true, boundRun);
2510
+ }
2511
+ }
2512
+ const refusal = freshnessRefusalOf(assessment.blockers);
2513
+ const adverse = adverseFreshnessRows(assessment.rows);
2514
+ if (refusal !== null) {
2515
+ return refuse(ctx.deps, [
2516
+ `${ctx.epicKey}: REFUSED (${refusal.reasonId}) — the local plane is not current enough to ` +
2517
+ "create a run against.",
2518
+ ...renderFreshnessRows(adverse),
2519
+ "",
2520
+ "Nothing was created.",
2521
+ ...trailer,
2522
+ ]);
2523
+ }
2524
+ if (adverse.length > 0) {
2525
+ const log = ctx.deps.launchReadinessLog ?? ctx.deps.errorLog;
2526
+ log([
2527
+ assessment.overridden
2528
+ ? `${ctx.epicKey}: plane freshness — proceeding; a confirmed refusal was overridden for this invocation.`
2529
+ : `${ctx.epicKey}: plane freshness — proceeding; some evidence could not be verified.`,
2530
+ ...renderFreshnessRows(adverse),
2531
+ ].join("\n"));
2532
+ }
2533
+ return null;
2534
+ }
2535
+ catch {
2536
+ // An unexpected failure of an advisory read never stops a launch.
2537
+ return null;
2538
+ }
2539
+ }
2540
+ /** The warning-only counterpart for an existing run. Never refuses, never throws. */
2541
+ async function surfacePlaneFreshnessForExistingRun(ctx, own) {
2542
+ try {
2543
+ const reports = await collectFreshnessObservations(ctx, own);
2544
+ if (reports === null)
2545
+ return;
2546
+ const boundRun = await boundRunForStaleRemedy(ctx, own, reports);
2547
+ const assessment = assessPlaneFreshness(reports, null, "attach", ctx.options.allowStalePlane === true, boundRun);
2548
+ const adverse = adverseFreshnessRows(assessment.rows);
2549
+ if (adverse.length === 0)
2550
+ return;
2551
+ const log = ctx.deps.launchReadinessLog ?? ctx.deps.errorLog;
2552
+ log([
2553
+ `${ctx.epicKey}: plane freshness — attaching to the existing run; findings below are warnings only.`,
2554
+ ...renderFreshnessRows(adverse),
2555
+ ].join("\n"));
2556
+ }
2557
+ catch {
2558
+ // Advisory only.
2559
+ }
2560
+ }
2561
+ // ---------------------------------------------------------------------------
2562
+ // BAPI-1496 — worker-database advisories on a LOCAL launch
2563
+ // ---------------------------------------------------------------------------
2564
+ /**
2565
+ * Run the worker-database inspection for a local-plane target, once.
2566
+ *
2567
+ * `null` when nothing applies: a target that is not this machine's plane never
2568
+ * runs the inspector, so a remote launch's requests and output are unchanged.
2569
+ * An inspector that throws or times out prints one fixed line naming only the
2570
+ * closed classification, then yields the doctor's all-unknown section — whose
2571
+ * `worker-db-unverifiable` row is a warning, never a refusal.
2572
+ */
2573
+ async function collectWorkerDatabaseAdvisory(deps, baseUrl, cache) {
2574
+ if (baseUrl === null || planeEndpointForBaseUrl(deps, baseUrl) === null)
2575
+ return null;
2576
+ const inspect = deps.inspectWorkerDatabase;
2577
+ if (inspect === undefined)
2578
+ return null;
2579
+ const run = async () => {
2580
+ let failed = false;
2581
+ const section = await collectWorkerDatabaseDoctorSection(() => inspect(deps.cwd()), WORKER_DATABASE_DOCTOR_TIMEOUT_MS, (failure) => {
2582
+ failed = true;
2583
+ deps.errorLog(`worker-db inspection failed: ${failure}`);
2584
+ }).catch(() => null);
2585
+ // A failed or timed-out inspection is ONE fact — the evidence is unverifiable —
2586
+ // so a launch shows only the `worker-db-unverifiable` warning, not six unknown
2587
+ // rows. The doctor's own all-unknown section is left as it is.
2588
+ if (section !== null && failed) {
2589
+ return { ...section, rows: section.rows.filter((row) => row.id === "worker-db-unverifiable") };
2590
+ }
2591
+ return section;
2592
+ };
2593
+ if (cache === undefined)
2594
+ return run();
2595
+ cache.workerDatabase ??= run();
2596
+ return cache.workerDatabase;
2597
+ }
2598
+ /** The advisory rows for a local launch: non-healthy `worker-db-*` warnings only. */
2599
+ async function workerDatabaseAdvisoryRows(deps, baseUrl, cache) {
2600
+ const section = await collectWorkerDatabaseAdvisory(deps, baseUrl, cache);
2601
+ return section === null ? [] : previewLaunchRows(workerDatabaseReadinessChecks(section));
2602
+ }
2603
+ /**
2604
+ * Print the worker-database warnings on a real local launch, beside the other
2605
+ * launch readiness output. Called after the creating launch's freshness guard
2606
+ * on every local creating path, attended and `--into-base` included. Advisory by
2607
+ * construction: it never refuses, never changes a decision or an exit code, and
2608
+ * an unexpected failure prints nothing.
2609
+ */
2610
+ async function surfaceWorkerDatabaseAdvisory(ctx) {
2611
+ try {
2612
+ const rows = await workerDatabaseAdvisoryRows(ctx.deps, ctx.access.baseUrl, ctx.freshness);
2613
+ if (rows.length === 0)
2614
+ return;
2615
+ const log = ctx.deps.launchReadinessLog ?? ctx.deps.errorLog;
2616
+ log([
2617
+ `${ctx.epicKey}: worker databases — warnings only; they never block a launch.`,
2618
+ ...renderFreshnessRows(rows).map((line, index) => (index === 0 ? "Worker databases (advisory):" : line)),
2619
+ ].join("\n"));
2620
+ }
2621
+ catch {
2622
+ // Advisory only.
2623
+ }
2624
+ }
2625
+ /**
2626
+ * Append the worker-database warnings to a LOCAL-plane preview's
2627
+ * `launch_checks`, modeled on {@link appendExecutorBuildFreshnessWarning}.
2628
+ * Gated on the preview's own `target.kind`, so a remote preview never runs the
2629
+ * inspector and its JSON is unchanged. Never changes the decision, a refusal,
2630
+ * readiness, or the exit code.
2631
+ */
2632
+ async function appendWorkerDatabaseAdvisoryRows(deps, preview, repository) {
2633
+ if (repository?.isBridge === false) {
2634
+ preview.launch_checks = [...(preview.launch_checks ?? []), ...nonBridgeRows(WORKER_DATABASE_PREVIEW_IDS)];
2635
+ return null;
2636
+ }
2637
+ if (repository === undefined)
2638
+ return null;
2639
+ if (preview.target.kind !== "local_plane")
2640
+ return null;
2641
+ try {
2642
+ // BAPI-1506: the section is returned so the launch-need step reuses this one
2643
+ // inspection instead of running a second.
2644
+ const section = await collectWorkerDatabaseAdvisory(deps, preview.target.base_url);
2645
+ const rows = section === null ? [] : previewLaunchRows(workerDatabaseReadinessChecks(section));
2646
+ if (rows.length > 0)
2647
+ preview.launch_checks = [...(preview.launch_checks ?? []), ...rows];
2648
+ return section;
2649
+ }
2650
+ catch {
2651
+ // Leave the preview as it was.
2652
+ return null;
2653
+ }
2654
+ }
2655
+ // ---------------------------------------------------------------------------
2656
+ // BAPI-1496 — terminal-run plane cleanup before a LOCAL creating launch
2657
+ // ---------------------------------------------------------------------------
2658
+ /**
2659
+ * Tear down this checkout's plane when it serves a finished run, before the
2660
+ * launch can attach to it or its preflight can refuse on it.
2661
+ *
2662
+ * `null` when nothing applies: a target that is not this machine's plane never
2663
+ * reaches the cleanup, so a remote launch makes no new call and sends no
2664
+ * signal. Eligibility, ownership re-validation, and the guarded teardown all
2665
+ * live in `plane/terminal-run-cleanup.ts`; this only routes. An incomplete or
2666
+ * aborted cleanup prints its one line and the launch continues into ordinary
2667
+ * preflight, whose `existing-plane` refusal still applies. A completed cleanup
2668
+ * drops every cached freshness observation, because they described the plane
2669
+ * that is now gone.
2670
+ */
2671
+ async function cleanUpTerminalRunPlane(ctx, repoRoot) {
2672
+ const { deps } = ctx;
2673
+ const cleanup = deps.cleanupTerminalRunPlane;
2674
+ if (cleanup === undefined)
2675
+ return null;
2676
+ const endpoint = planeEndpointForBaseUrl(deps, ctx.access.baseUrl);
2677
+ if (endpoint === null)
2678
+ return null;
2679
+ let result;
2680
+ try {
2681
+ result = await cleanup({ repoRoot, endpoint });
2682
+ }
2683
+ catch {
2684
+ deps.errorLog("terminal-run plane cleanup could not run; inspect `plane status`.");
2685
+ return null;
2686
+ }
2687
+ const line = terminalRunCleanupStderrLine(result);
2688
+ if (line !== null)
2689
+ deps.errorLog(line);
2690
+ if (result.kind === "completed" && ctx.freshness !== undefined) {
2691
+ ctx.freshness.observations.clear();
2692
+ ctx.freshness.sleep = undefined;
2693
+ }
2694
+ return result;
2695
+ }
1789
2696
  /**
1790
2697
  * COLD START: nothing is listening on the plane endpoint, so bring the control
1791
2698
  * plane up and compose the run against it.
@@ -1816,13 +2723,15 @@ async function coldStartPlane(ctx) {
1816
2723
  // before anything is started, exactly as every other plan-file route does.
1817
2724
  if (ctx.options.planFile)
1818
2725
  await surfaceContainmentAdvisory(deps, ctx.options.planFile);
1819
- deps.log(`${epicKey}: nothing is listening on the plane endpoint; cold-starting the conductor plane.`);
2726
+ deps.log(`${epicKey}: nothing is listening on the plane endpoint; cold-starting the local plane.`);
1820
2727
  const repoRoot = deps.cwd();
2728
+ // BAPI-1496: a plane bound to a finished run is torn down before preflight.
2729
+ await cleanUpTerminalRunPlane(ctx, repoRoot);
1821
2730
  const preflight = await deps.runPlanePreflight(repoRoot);
1822
2731
  const precondition = firstPreconditionRefusal(preflight);
1823
2732
  if (precondition) {
1824
2733
  return refuse(deps, [
1825
- `${epicKey}: cannot start the conductor runtime — ${precondition.check} failed.`,
2734
+ `${epicKey}: cannot start the Epic Implementer runtime — ${precondition.check} failed.`,
1826
2735
  formatPlaneDiagnostic(precondition),
1827
2736
  "",
1828
2737
  "Nothing was started. Fix the item above and run drive-epic again.",
@@ -1841,8 +2750,11 @@ async function coldStartPlane(ctx) {
1841
2750
  readiness = await deps.readReadiness(ctx.access);
1842
2751
  }
1843
2752
  catch (err) {
2753
+ if (isSchemaIncompatibleError(err)) {
2754
+ return refuse(deps, [...formatSchemaIncompatibleRefusal(epicKey, err), ...LAUNCHED_PLANE_LEFT_RUNNING]);
2755
+ }
1844
2756
  return refuse(deps, [
1845
- `${epicKey}: the plane came up, but its conductor readiness could not be read: ` +
2757
+ `${epicKey}: the plane came up, but its Epic Implementer readiness could not be read: ` +
1846
2758
  safeDiagnosticMessage(err, "readiness request failed"),
1847
2759
  ...LAUNCHED_PLANE_LEFT_RUNNING,
1848
2760
  ]);
@@ -1862,7 +2774,7 @@ async function coldStartPlane(ctx) {
1862
2774
  });
1863
2775
  if (classification.kind === "operator_blocked") {
1864
2776
  return refuse(deps, [
1865
- `${epicKey}: the engine path still needs ${classification.describe} (${classification.id}).`,
2777
+ `${epicKey}: the engine path still needs ${classification.describe}.`,
1866
2778
  operatorBlockedRemedy(classification),
1867
2779
  ...LAUNCHED_PLANE_LEFT_RUNNING,
1868
2780
  ]);
@@ -1879,12 +2791,17 @@ async function coldStartPlane(ctx) {
1879
2791
  if (admission !== null) {
1880
2792
  return refuse(deps, [...admission, ...LAUNCHED_PLANE_LEFT_RUNNING]);
1881
2793
  }
2794
+ // BAPI-1476: before the first setup/run-create side effect.
2795
+ const staleCold = await planeFreshnessCreateGuard(ctx, { repoRoot, ownsManifest: true, planeId: controlPlane.planeId }, LAUNCHED_PLANE_LEFT_RUNNING);
2796
+ if (staleCold !== null)
2797
+ return staleCold;
2798
+ await surfaceWorkerDatabaseAdvisory(ctx);
1882
2799
  return createRunAndRequestLanes(ctx, {
1883
2800
  origin: "launched",
1884
2801
  repoRoot,
1885
2802
  planeId: controlPlane.planeId,
1886
2803
  awaitPlaneReady: controlPlane.awaitPlaneReady,
1887
- });
2804
+ }, readiness);
1888
2805
  }
1889
2806
  /**
1890
2807
  * ATTACH: the plane endpoint already serves this repository's live plane.
@@ -1945,6 +2862,16 @@ async function attachToPlane(ctx, manifest, readiness) {
1945
2862
  if (admission !== null) {
1946
2863
  return refuse(deps, [...admission, "", "Nothing was started."]);
1947
2864
  }
2865
+ // BAPI-1476: both branches below create a run, so the guard precedes both.
2866
+ const staleAttach = await planeFreshnessCreateGuard(attachCtx, {
2867
+ repoRoot: manifest.repoRoot,
2868
+ ownsManifest: true,
2869
+ planeId: manifest.planeId,
2870
+ ...(manifest.epicRunId ? { epicRunId: manifest.epicRunId } : {}),
2871
+ });
2872
+ if (staleAttach !== null)
2873
+ return staleAttach;
2874
+ await surfaceWorkerDatabaseAdvisory(attachCtx);
1948
2875
  if (dedicatedExecutorReason !== null) {
1949
2876
  deps.log(`${epicKey}: attaching to this repository's running plane (${dedicatedExecutorReason}); ` +
1950
2877
  "its reconciler will drive this run too, and a dedicated executor will be started for it.");
@@ -1956,7 +2883,7 @@ async function attachToPlane(ctx, manifest, readiness) {
1956
2883
  repoRoot: manifest.repoRoot,
1957
2884
  planeId: manifest.planeId,
1958
2885
  ...(manifest.epicRunId !== undefined ? { boundRunId: manifest.epicRunId } : {}),
1959
- });
2886
+ }, readiness);
1960
2887
  }
1961
2888
  /**
1962
2889
  * The shared tail: create/approve/cut through `setup-epic`, then request lanes
@@ -1967,9 +2894,16 @@ async function attachToPlane(ctx, manifest, readiness) {
1967
2894
  * `executorClaimScopeArgs` as `--epic-run-id`, and `--repo-wide` is not
1968
2895
  * constructible here.
1969
2896
  */
1970
- async function createRunAndRequestLanes(ctx, plane) {
2897
+ async function createRunAndRequestLanes(ctx, plane, readiness) {
1971
2898
  const { deps, epicKey } = ctx;
1972
2899
  const launched = plane.origin === "launched";
2900
+ // BAPI-1452: a plane lane owns this run's executor, so the launch evidence
2901
+ // can only warn here; printed before the run exists.
2902
+ if (readiness !== undefined) {
2903
+ const gate = await launchCapabilityGate(ctx, readiness, { kind: "plane_lane" });
2904
+ if (gate !== null)
2905
+ return gate;
2906
+ }
1973
2907
  // ---- PHASE TWO, part one: create the run ------------------------------
1974
2908
  const setup = await runSelectedSetupEpic(ctx);
1975
2909
  if (setup.exitCode !== 0) {
@@ -1981,7 +2915,7 @@ async function createRunAndRequestLanes(ctx, plane) {
1981
2915
  deps.errorLog((launched
1982
2916
  ? [
1983
2917
  "",
1984
- `${epicKey}: the conductor CONTROL PLANE was started by this invocation and is STILL RUNNING.`,
2918
+ `${epicKey}: the Epic Implementer CONTROL PLANE was started by this invocation and is STILL RUNNING.`,
1985
2919
  "No executor lane was spawned, so nothing is claiming jobs.",
1986
2920
  "It was not wound down automatically, because doing so would stop a run that may",
1987
2921
  "already have been created and approved. Inspect it with `plane status`, and wind it",
@@ -2158,7 +3092,7 @@ function remoteRuntimeRefusal(epicKey, access, readiness) {
2158
3092
  const lines = [`${epicKey}: REFUSED (${reasonId}) — ${remedy}`];
2159
3093
  if (bringUp === null) {
2160
3094
  lines.push("This Bridge API version cannot report deployment liveness, so a launch against it cannot " +
2161
- "be confirmed. Upgrade the Bridge API deploy.");
3095
+ "be confirmed. Try again later; if it keeps happening, email info@bridgegpt.ai.");
2162
3096
  }
2163
3097
  lines.push("", "No run was created.", REMOTE_NO_PLANE_LINE);
2164
3098
  return { reasonId, remedy, lines };
@@ -2171,7 +3105,7 @@ function remoteRuntimeRefusal(epicKey, access, readiness) {
2171
3105
  function durableCoverageRefusal(epicKey, access, profile, coverage, outcome) {
2172
3106
  const remedy = [
2173
3107
  "Start the durable host's executor with --repo-wide",
2174
- " (`install conductor --execution-mode durable --executor-id <id> --repo-wide`),",
3108
+ " (`install conductor --execution-mode durable --executor-id <id> --repo-wide`; see `drive-epic --help-advanced`),",
2175
3109
  "or launch without the durable profile.",
2176
3110
  ].join("\n");
2177
3111
  return {
@@ -2272,6 +3206,11 @@ async function createRunWithRunExecutor(ctx, readiness) {
2272
3206
  if (coverage !== true) {
2273
3207
  return refuse(deps, durableCoverageRefusal(epicKey, access, profile, coverage, "No run was created").lines);
2274
3208
  }
3209
+ // BAPI-1452: the durable host owns the executor clone and credential, so
3210
+ // this can only warn — but it says so before the run exists.
3211
+ const gate = await launchCapabilityGate(ctx, readiness, { kind: "durable_profile" }, "No run was created and no local executor was started.");
3212
+ if (gate !== null)
3213
+ return gate;
2275
3214
  const setup = await runSelectedSetupEpic(ctx);
2276
3215
  if (setup.exitCode === 0) {
2277
3216
  deps.log([
@@ -2287,6 +3226,11 @@ async function createRunWithRunExecutor(ctx, readiness) {
2287
3226
  if (!prepared.ok) {
2288
3227
  return refuse(deps, executorPreconditionRefusal(epicKey, prepared.message, "No run was created.").lines);
2289
3228
  }
3229
+ // BAPI-1452: the launch capability gate checks the SAME clone the executor
3230
+ // will own (`prepared.repoRoot`, its cwd) — not a second preparation.
3231
+ const gate = await launchCapabilityGate(ctx, readiness, { kind: "local", repoRoot: prepared.prepared.repoRoot }, "No run was created.");
3232
+ if (gate !== null)
3233
+ return gate;
2290
3234
  const setup = await runSelectedSetupEpic(ctx);
2291
3235
  if (setup.exitCode !== 0) {
2292
3236
  // setup-epic already said why. Nothing was started for a run that may not exist.
@@ -2303,13 +3247,16 @@ async function createRunWithRunExecutor(ctx, readiness) {
2303
3247
  "server-side before retrying; retrying blindly could create a second run.",
2304
3248
  ]);
2305
3249
  }
2306
- // POST-CREATE: start or reuse exactly one executor scoped to this run.
3250
+ // POST-CREATE: start or reuse exactly one executor scoped to this run. It
3251
+ // receives the merge credential this launch resolved (BAPI-1461), so a token
3252
+ // stored once works without exporting it or restarting the editor.
2307
3253
  const ensured = await deps.ensureRunExecutor({
2308
3254
  prepared: prepared.prepared,
2309
3255
  repoName: access.repoName,
2310
3256
  epicRunId: setup.epicRunId,
2311
3257
  access,
2312
3258
  profile,
3259
+ mergeCredential: await launchCredentialForExecutor(ctx, readiness),
2313
3260
  });
2314
3261
  return reportExecutorOutcome(ctx, ensured, setup.epicRunId, "created");
2315
3262
  }
@@ -2400,7 +3347,7 @@ async function planeServesLiveRun(ctx, live) {
2400
3347
  * - this checkout's plane bound to THIS run: its lanes serve it, start nothing;
2401
3348
  * - otherwise: prepare, then ensure a run-scoped executor for the LIVE run's id.
2402
3349
  */
2403
- async function attachToLiveRun(ctx, readiness, live) {
3350
+ async function attachToLiveRun(ctx, readiness, live, unusedDiscoveredPlan) {
2404
3351
  const { deps, epicKey, access, profile } = ctx;
2405
3352
  const classification = classifyV2Readiness(readiness, {
2406
3353
  attended: ctx.options.attended === true,
@@ -2409,7 +3356,7 @@ async function attachToLiveRun(ctx, readiness, live) {
2409
3356
  });
2410
3357
  if (classification.kind === "operator_blocked") {
2411
3358
  return refuse(deps, [
2412
- `${epicKey}: the engine path still needs ${classification.describe} (${classification.id}).`,
3359
+ `${epicKey}: the engine path still needs ${classification.describe}.`,
2413
3360
  "",
2414
3361
  "This is not something starting the runtime can fix, so nothing was started.",
2415
3362
  operatorBlockedRemedy(classification),
@@ -2428,9 +3375,22 @@ async function attachToLiveRun(ctx, readiness, live) {
2428
3375
  if (admission !== null)
2429
3376
  return refuse(deps, admission);
2430
3377
  }
3378
+ // BAPI-1476: warning-only. An existing run is never stopped for freshness,
3379
+ // and the plane is neither repaired nor restarted here.
3380
+ await surfacePlaneFreshnessForExistingRun(ctx, manifest !== null
3381
+ ? {
3382
+ repoRoot: manifest.repoRoot,
3383
+ ownsManifest: true,
3384
+ planeId: manifest.planeId,
3385
+ ...(manifest.epicRunId ? { epicRunId: manifest.epicRunId } : {}),
3386
+ }
3387
+ : { repoRoot: deps.cwd(), ownsManifest: false });
2431
3388
  }
2432
- deps.log(`${epicKey}: run ${live.epicRunId} is already live (${live.status}) and no plan was supplied or ` +
2433
- "found, so nothing will be created; making sure it has an executor.");
3389
+ deps.log(unusedDiscoveredPlan === undefined
3390
+ ? `${epicKey}: run ${live.epicRunId} is already live (${live.status}) and no plan was supplied or ` +
3391
+ "found, so nothing will be created; making sure it has an executor."
3392
+ : `${epicKey}: run ${live.epicRunId} is already live (${live.status}); the plan found by epic key ` +
3393
+ `(${unusedDiscoveredPlan}) is not used, so nothing will be created; making sure it has an executor.`);
2434
3394
  if (live.effectivePolicy) {
2435
3395
  deps.log(`Effective policy: stored; serial execution; caps ${live.effectivePolicy.caps ? JSON.stringify(live.effectivePolicy.caps) : "unavailable"}; ` +
2436
3396
  `timeouts ${live.effectivePolicy.job_timeouts ? JSON.stringify(live.effectivePolicy.job_timeouts) : "unavailable"}; ` +
@@ -2472,6 +3432,7 @@ async function attachToLiveRun(ctx, readiness, live) {
2472
3432
  epicRunId: live.epicRunId,
2473
3433
  access,
2474
3434
  profile,
3435
+ mergeCredential: await launchCredentialForExecutor(ctx, readiness),
2475
3436
  });
2476
3437
  return reportExecutorOutcome(ctx, ensured, live.epicRunId, "attached");
2477
3438
  }
@@ -2486,8 +3447,8 @@ function localReconcilerRefusal(epicKey, readiness) {
2486
3447
  const reasonId = reason ?? "local-reconciler-not-live";
2487
3448
  const remedy = reason !== null
2488
3449
  ? BRING_UP_REFUSAL_MESSAGES[reason]
2489
- : "the local conductor plane reports no live reconciler, so nothing would drive this run. " +
2490
- "Start it with `plane up`, or pass --plan-file so drive-epic can bring the runtime up.";
3450
+ : "the local plane reports no live reconciler, so nothing would drive this run. " +
3451
+ "Start it as `drive-epic --help-advanced` describes, or pass --plan-file so drive-epic can bring the runtime up.";
2491
3452
  return {
2492
3453
  reasonId,
2493
3454
  remedy,
@@ -2537,9 +3498,32 @@ export const DRIVE_EPIC_ACCESS_REFUSAL_REASON_IDS = {
2537
3498
  "credentials-unavailable": "access-credentials-unavailable",
2538
3499
  "credential-unbound": "access-credential-unbound",
2539
3500
  };
3501
+ const WORKER_DATABASE_PREVIEW_IDS = ["worker-db-role", "worker-db-boundary", "worker-db-alembic", "worker-db-leftovers", "worker-db-unverifiable", "worker-db-harness"];
3502
+ function nonBridgeRows(ids) {
3503
+ return ids.map((id) => {
3504
+ const started = monotonicNow();
3505
+ return { id, label: id, status: "skip", blocking: false,
3506
+ reason: "not_bridge_repository", detail: "not_bridge_repository", duration_ms: elapsedMs(started) };
3507
+ });
3508
+ }
3509
+ /** BAPI-1452 — project launch rows into the stable preview shape. */
3510
+ function previewLaunchRows(checks) {
3511
+ return checks.map((check) => {
3512
+ const started = monotonicNow();
3513
+ return {
3514
+ duration_ms: check.duration_ms ?? elapsedMs(started),
3515
+ id: check.id,
3516
+ label: check.label,
3517
+ status: check.status,
3518
+ blocking: check.blocking,
3519
+ ...(check.detail ? { detail: check.detail } : {}),
3520
+ ...(check.remediation ? { remedy: check.remediation } : {}),
3521
+ };
3522
+ });
3523
+ }
2540
3524
  /** The readiness reason a preview reports for a generic not-ready engine. */
2541
3525
  const ENGINE_NOT_READY_REASON_ID = "engine-not-ready";
2542
- const ENGINE_NOT_READY_REMEDY = `Resolve conductor readiness (\`${PRINTED_CONDUCTOR_INSTALL_COMMAND}\`, then \`${PRINTED_DOCTOR_COMMAND}\`) and run drive-epic again. ${PRINTED_CHECK_NAME_INSTRUCTION}`;
3526
+ 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}.`;
2543
3527
  /**
2544
3528
  * Read exactly one well-shaped setup-epic dry-run JSON document out of captured
2545
3529
  * `log` output. Anything else — none, several, or one with the wrong shape — is
@@ -2608,8 +3592,19 @@ function readSetupPreviewPayload(stdout) {
2608
3592
  return {
2609
3593
  existingRunId: typeof existing === "string" && existing !== "" ? existing : null,
2610
3594
  featureBranch: typeof branch === "string" && branch !== "" ? branch : null,
3595
+ // An older bootstrap omits it; anything not a valid branch name is dropped.
3596
+ scopeBaseBranch: typeof doc.scope_base_branch === "string" && validateBranchName(doc.scope_base_branch) === null
3597
+ ? doc.scope_base_branch
3598
+ : null,
2611
3599
  serverValidated: doc.server_validated,
2612
3600
  effectivePolicy,
3601
+ ticketReview: typeof doc.ticket_review === 'string' && /^(on|off \(legacy choice not recorded\)|off requested \(admin key required; choice recorded at create\)|off \(set by actor_[a-z0-9]{4,32} on \d{4}-\d{2}-\d{2}\))$/.test(doc.ticket_review) ? doc.ticket_review : 'on',
3602
+ launchReadiness: (() => { try {
3603
+ return doc.launch_readiness ? parseConductorReadinessResponse(doc.launch_readiness) : null;
3604
+ }
3605
+ catch {
3606
+ return null;
3607
+ } })(),
2613
3608
  };
2614
3609
  }
2615
3610
  /** The plan DAG's node count, or `null` unless it parses to `{ nodes: [...] }`. */
@@ -2631,20 +3626,35 @@ async function readPlanChildCount(deps, planPath) {
2631
3626
  * named refusal in the same document.
2632
3627
  */
2633
3628
  async function runDriveEpicPreview(deps, options) {
3629
+ const started = monotonicNow();
3630
+ const timings = {};
3631
+ const original = deps;
3632
+ const timed = (phase, run) => measurePrecheck(run, (duration) => { timings[phase] = duration; });
3633
+ deps = {
3634
+ ...original,
3635
+ inspectRepositoryIdentity: () => timed("repository_identity_ms", () => original.inspectRepositoryIdentity()),
3636
+ readReadiness: (access) => timed("readiness_ms", () => original.readReadiness(access)),
3637
+ readLiveEpicRun: (access, epic) => timed("live_run_ms", () => original.readLiveEpicRun(access, epic)),
3638
+ previewSetupEpic: (args) => timed("setup_preview_ms", () => original.previewSetupEpic(args)),
3639
+ };
2634
3640
  const { epicKey } = options;
2635
3641
  const posture = options.attended === true || options.intoBase === true ? "attended" : "unattended";
2636
3642
  const preview = {
3643
+ timings,
2637
3644
  epic_key: epicKey,
2638
3645
  target: { base_url: null, kind: null },
2639
3646
  readiness: { kind: "unknown" },
2640
3647
  live_run: null,
2641
3648
  plan: { status: "not_found" },
3649
+ already_done_children: { status: "not_checked", reason: "no_plan", children: [] },
2642
3650
  summary: {
2643
3651
  child_count: null,
3652
+ children_to_run: null,
2644
3653
  branch: null,
2645
3654
  posture,
2646
3655
  auto_merge_scope: null,
2647
3656
  escalation_channel: null,
3657
+ ticket_review: "on",
2648
3658
  server_validation: "not_run",
2649
3659
  },
2650
3660
  decision: "refuse",
@@ -2667,8 +3677,11 @@ async function runDriveEpicPreview(deps, options) {
2667
3677
  preview.refusal = { reason_id: named.reasonId, remedy: named.remedy };
2668
3678
  preview.decision = "refuse";
2669
3679
  };
3680
+ // The readiness read previewDecision observed, for the reachability row. It stays
3681
+ // `null` when no read succeeded, which the row reports as unconfirmed.
3682
+ const observed = { readiness: null };
2670
3683
  try {
2671
- await previewDecision(deps, options, preview, refuseWithReadiness, refuseTopLevel);
3684
+ await timed("decision_ms", () => previewDecision(deps, options, preview, refuseWithReadiness, refuseTopLevel, observed));
2672
3685
  }
2673
3686
  catch {
2674
3687
  // Sanitized on purpose: nothing from the thrown value reaches the document.
@@ -2680,6 +3693,46 @@ async function runDriveEpicPreview(deps, options) {
2680
3693
  });
2681
3694
  }
2682
3695
  ensureRefusalExplained(preview);
3696
+ if (observed.repository?.isBridge === false && !preview.launch_checks?.some((row) => row.id === "plane-snapshot-freshness")) {
3697
+ preview.launch_checks = [...(preview.launch_checks ?? []), ...nonBridgeRows(["plane-snapshot-freshness", "plane-database-head"])];
3698
+ }
3699
+ const isolated = () => ({ ...preview, launch_checks: [] });
3700
+ const worker = isolated();
3701
+ const escalation = isolated();
3702
+ const executor = isolated();
3703
+ const needs = isolated();
3704
+ const scopeBase = previewScopeBaseBranch.get(preview);
3705
+ if (scopeBase)
3706
+ previewScopeBaseBranch.set(needs, scopeBase);
3707
+ // Collect into private arrays; only launch-needs waits for the worker result.
3708
+ const workerTask = timed("worker_database_ms", () => appendWorkerDatabaseAdvisoryRows(deps, worker, observed.repository));
3709
+ const needsTask = workerTask.then((section) => {
3710
+ needs.launch_checks = [...(worker.launch_checks ?? [])];
3711
+ return timed("launch_needs_ms", () => appendLaunchNeedRows(deps, needs, observed, section));
3712
+ });
3713
+ await Promise.all([
3714
+ needsTask,
3715
+ timed("escalation_ms", async () => { appendEscalationReachabilityRow(escalation, observed.readiness); }),
3716
+ timed("executor_build_ms", () => appendExecutorBuildFreshnessWarning(deps, executor)),
3717
+ ]);
3718
+ const workerIds = new Set(worker.launch_checks?.map((row) => row.id));
3719
+ const needRows = needs.launch_checks ?? [];
3720
+ preview.launch_checks = [
3721
+ ...(preview.launch_checks ?? []), ...needRows.filter((row) => workerIds.has(row.id)),
3722
+ ...(escalation.launch_checks ?? []), ...(executor.launch_checks ?? []),
3723
+ ...needRows.filter((row) => !workerIds.has(row.id)),
3724
+ ];
3725
+ if (preview.decision === "create") {
3726
+ try {
3727
+ const result = (deps.buildLaunchPlan ?? buildLaunchPlan)(preview);
3728
+ if (result)
3729
+ preview.launch_plan = result.launch_plan;
3730
+ }
3731
+ catch {
3732
+ deps.errorLog("Launch plan unavailable; the driving session will compute it.");
3733
+ }
3734
+ }
3735
+ timings.total_ms = elapsedMs(started);
2683
3736
  const emitted = await emitPreview(deps, options, preview);
2684
3737
  // BAPI-1397 (F3): a `--json` document that could not reach stdout whole is a
2685
3738
  // failed preview, never a silently truncated one.
@@ -2687,9 +3740,167 @@ async function runDriveEpicPreview(deps, options) {
2687
3740
  return 1;
2688
3741
  return preview.decision === "create" || preview.decision === "attach" ? 0 : 1;
2689
3742
  }
3743
+ /**
3744
+ * Give every `create` or `attach` preview exactly one non-blocking
3745
+ * `escalation-reachability` row (BAPI-1490).
3746
+ *
3747
+ * Built from the readiness the preview already read and the channel the preview
3748
+ * already resolved; it adds no request and never changes the decision, a refusal,
3749
+ * a reason, or the exit code. A readiness that was not read (cold start, remote
3750
+ * read failure) is passed as unavailable, so the row warns rather than vanishing.
3751
+ * A refused or stopped preview describes no launch, so it gets none.
3752
+ */
3753
+ function appendEscalationReachabilityRow(preview, readiness) {
3754
+ const started = monotonicNow();
3755
+ if (preview.decision !== "create" && preview.decision !== "attach")
3756
+ return;
3757
+ const [row] = previewLaunchRows([
3758
+ buildEscalationReachabilityCheck(readiness, preview.summary.escalation_channel),
3759
+ ]);
3760
+ preview.launch_checks = [
3761
+ ...(preview.launch_checks ?? []).filter((existing) => existing.id !== ESCALATION_REACHABILITY_CHECK_ID),
3762
+ { ...row, duration_ms: elapsedMs(started) },
3763
+ ];
3764
+ }
3765
+ /**
3766
+ * Append a non-blocking `executor-build-freshness` warning to the preview when a
3767
+ * local CLI override (`BAPI_MCP_CLI`) is set and the executor build is stale or
3768
+ * unreadable. Fail-open and read-only: it never changes the decision, a refusal,
3769
+ * readiness, or the exit code. A passing check, an unset or blank override, or a
3770
+ * missing dependency leaves `launch_checks` untouched. A thrown check prints one
3771
+ * fixed line and nothing from the exception.
3772
+ */
3773
+ async function appendExecutorBuildFreshnessWarning(deps, preview) {
3774
+ const started = monotonicNow();
3775
+ const override = process.env[BRIDGE_LAUNCHER_ENV];
3776
+ if (override === undefined || override.trim() === "")
3777
+ return;
3778
+ if (deps.checkExecutorBuildFreshness === undefined)
3779
+ return;
3780
+ try {
3781
+ const report = await deps.checkExecutorBuildFreshness(deps.cwd());
3782
+ if (report.diagnostic === null)
3783
+ return;
3784
+ const outcome = report.outcomes.find((entry) => entry.status === "warn" || entry.status === "fail") ?? report.outcomes[0];
3785
+ const row = {
3786
+ id: "executor-build-freshness",
3787
+ duration_ms: elapsedMs(started),
3788
+ label: outcome?.label ?? "Executor build freshness",
3789
+ status: "warn",
3790
+ blocking: false,
3791
+ ...(outcome?.detail ? { detail: outcome.detail } : {}),
3792
+ remedy: PLANE_BUILD_FIX_REMEDIATION,
3793
+ };
3794
+ preview.launch_checks = [...(preview.launch_checks ?? []), row];
3795
+ }
3796
+ catch {
3797
+ deps.errorLog("Executor build freshness check could not run.");
3798
+ }
3799
+ }
3800
+ /**
3801
+ * The base branch setup-epic's dry run reported, per preview. Kept off the
3802
+ * preview document so its JSON shape is unchanged.
3803
+ */
3804
+ const previewScopeBaseBranch = new WeakMap();
3805
+ /** Run one probe; a missing boundary or any rejection becomes the fallback fact. */
3806
+ async function guardedProbe(run, fallback) {
3807
+ if (run === undefined)
3808
+ return fallback;
3809
+ try {
3810
+ return await run();
3811
+ }
3812
+ catch {
3813
+ return fallback;
3814
+ }
3815
+ }
3816
+ /** Power evidence for the host the run's executor will run on. */
3817
+ async function collectHostPowerFact(deps, topology) {
3818
+ // `local` and `plane_lane` executors run on this host (a plane lane is chosen
3819
+ // only for this machine's own plane). Anything else runs elsewhere.
3820
+ if (topology === undefined)
3821
+ return { state: "unverifiable", reason: "unverified" };
3822
+ if (topology.kind === "durable_profile")
3823
+ return { state: "unverifiable", reason: "remote_executor" };
3824
+ const inspect = deps.inspectHostSleep;
3825
+ if (inspect === undefined)
3826
+ return { state: "unverifiable", reason: "probe_failed" };
3827
+ const repoRoot = topology.kind === "local" && topology.repoRoot !== null ? topology.repoRoot : deps.cwd();
3828
+ const report = await inspect(repoRoot).catch(() => null);
3829
+ return hostPowerFactFromReport(report);
3830
+ }
3831
+ /**
3832
+ * Append the five launch-need rows to a `create` preview (BAPI-1506): worker DB
3833
+ * role, self-hosted runner, host power (`host-sleep`), usage reset after the
3834
+ * run, and the information-only epic branch behind base.
3835
+ *
3836
+ * Every probe runs concurrently and is guarded on its own, so a missing
3837
+ * boundary, a rejection or a timeout is an `unverifiable` warning row. Rows
3838
+ * are `blocking: false` and NEVER change the decision, a refusal, readiness or
3839
+ * the exit code. An `attach`, refused or stopped preview gets none of them.
3840
+ * The merged `worker-db-role` warning row is decorated in place rather than
3841
+ * duplicated.
3842
+ */
3843
+ async function appendLaunchNeedRows(deps, preview, observed, workerDatabase) {
3844
+ if (preview.decision !== "create")
3845
+ return;
3846
+ try {
3847
+ const repoRoot = observed.repository?.repoRoot ?? deps.cwd();
3848
+ const local = preview.target.kind === "local_plane";
3849
+ const readiness = observed.readiness;
3850
+ const access = observed.access;
3851
+ const nowMs = (deps.now ?? Date.now)();
3852
+ const durations = [];
3853
+ const measured = (index, work) => measurePrecheck(work, (duration) => { durations[index] = duration; });
3854
+ const [runner, power, usage, branch] = await Promise.all([
3855
+ measured(0, () => guardedProbe(deps.inspectRequiredRunners === undefined
3856
+ ? undefined
3857
+ : () => deps.inspectRequiredRunners({
3858
+ repoRoot,
3859
+ providerRepository: readiness?.provider_repository,
3860
+ gateProfile: readiness?.gate_profile,
3861
+ }), { state: "unverifiable", reason: "probe_failed" })),
3862
+ measured(1, () => guardedProbe(() => collectHostPowerFact(deps, observed.launchTopology), { state: "unverifiable", reason: "probe_failed" })),
3863
+ measured(2, () => guardedProbe(deps.fetchUsageAdvisory === undefined || access === undefined
3864
+ ? undefined
3865
+ : () => deps.fetchUsageAdvisory(access), null)),
3866
+ measured(3, () => guardedProbe(deps.inspectEpicBranchBehind === undefined
3867
+ ? undefined
3868
+ : () => deps.inspectEpicBranchBehind({
3869
+ repoRoot,
3870
+ branch: preview.summary.branch,
3871
+ baseBranch: previewScopeBaseBranch.get(preview) ?? null,
3872
+ }), preview.summary.branch === null
3873
+ ? { state: "not_applicable", reason: "no_epic_branch" }
3874
+ : { state: "unverifiable", reason: "git_failed" })),
3875
+ ]);
3876
+ const workerRow = observed.repository?.isBridge === false
3877
+ ? { ...nonBridgeRows(["worker-db-role"])[0], launch_need: { need: "worker_db_role", state: "not_applicable", asked: false } }
3878
+ : { ...buildWorkerDbRoleLaunchRow(workerDatabase, local),
3879
+ duration_ms: workerDatabase?.rows.find((row) => row.id === "worker-db-role")?.duration_ms ?? elapsedMs(monotonicNow()) };
3880
+ const rows = [
3881
+ buildSelfHostedRunnerLaunchRow(runner),
3882
+ buildHostPowerLaunchRow(power),
3883
+ buildUsageResetAfterRunLaunchRow({
3884
+ advisory: usage ?? REPOSITORY_USAGE_ADVISORY_UNAVAILABLE,
3885
+ childCount: preview.summary.child_count,
3886
+ nowMs,
3887
+ }),
3888
+ buildEpicBranchBehindBaseLaunchRow(branch),
3889
+ ].map((row, index) => ({ ...row, duration_ms: durations[index] }));
3890
+ const existing = preview.launch_checks ?? [];
3891
+ const roleIndex = existing.findIndex((row) => row.id === workerRow.id);
3892
+ const merged = roleIndex >= 0
3893
+ ? existing.map((row, index) => (index === roleIndex ? workerRow : row))
3894
+ : [...existing, workerRow];
3895
+ preview.launch_checks = [...merged, ...rows];
3896
+ }
3897
+ catch {
3898
+ // Advisory only: leave the preview as it was.
3899
+ }
3900
+ }
2690
3901
  /** The fixed explanation used when a refusal reached the end with none of its own. */
2691
3902
  export const PREVIEW_REFUSAL_FALLBACK_REASON_ID = "preview-refused";
2692
- const PREVIEW_REFUSAL_FALLBACK_REMEDY = "The preview refused this launch without naming a specific cause. Resolve conductor readiness and preview again; nothing was created or started.";
3903
+ const PREVIEW_REFUSAL_FALLBACK_REMEDY = `The preview refused this launch without naming a specific cause. Resolve Epic Implementer readiness and preview again; nothing was created or started. See ${CONSUMER_GUIDE_POINTER}.`;
2693
3904
  function isNamedRefusal(value) {
2694
3905
  if (value === null || typeof value !== "object")
2695
3906
  return false;
@@ -2717,12 +3928,24 @@ export function ensureRefusalExplained(preview) {
2717
3928
  : { reason_id: PREVIEW_REFUSAL_FALLBACK_REASON_ID, remedy: PREVIEW_REFUSAL_FALLBACK_REMEDY };
2718
3929
  }
2719
3930
  /** Fill in `preview` by walking the same decisions a real launch makes, read-only. */
2720
- async function previewDecision(deps, options, preview, refuseWithReadiness, refuseTopLevel) {
3931
+ async function previewDecision(deps, options, preview, refuseWithReadiness, refuseTopLevel, observed = { readiness: null }) {
2721
3932
  const { epicKey } = options;
2722
3933
  const unknownReadiness = () => refuseWithReadiness("unknown", {
2723
3934
  reasonId: READINESS_UNKNOWN_REASON_ID,
2724
3935
  remedy: ESCALATE_REMEDY,
2725
3936
  });
3937
+ try {
3938
+ observed.repository = await deps.inspectRepositoryIdentity();
3939
+ // This deps object is invocation-owned; subsequent relative probes use the
3940
+ // verified Git toplevel even when the command started in a subdirectory.
3941
+ deps.cwd = () => observed.repository.repoRoot;
3942
+ }
3943
+ catch {
3944
+ return refuseTopLevel({
3945
+ reasonId: "repository-identity-unverifiable",
3946
+ remedy: "Resolve the invocation Git worktree and its marker-file permissions, then preview again.",
3947
+ });
3948
+ }
2726
3949
  // --- Target: resolved, never adopted. -------------------------------------
2727
3950
  const accessResult = await deps.resolveAccess(options.repo, undefined, launchSelectionOf(options));
2728
3951
  if (!accessResult.ok) {
@@ -2753,11 +3976,23 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
2753
3976
  ? { source: accessResult.targetSource }
2754
3977
  : {}),
2755
3978
  };
2756
- const ctx = { deps, epicKey, options, access, profile, targetSource: accessResult.targetSource ?? "default" };
3979
+ const ctx = {
3980
+ deps,
3981
+ epicKey,
3982
+ options,
3983
+ access,
3984
+ profile,
3985
+ previewRepository: observed.repository,
3986
+ targetSource: accessResult.targetSource ?? "default",
3987
+ freshness: createPlaneFreshnessCache(),
3988
+ launchCredential: {},
3989
+ };
2757
3990
  // Discover before readiness so a selected local plane can preview its guarded
2758
3991
  // cold start. Keep the candidate out of ordinary failure documents.
2759
3992
  let planPath = options.planFile;
2760
3993
  let plan = { status: "not_found" };
3994
+ // The full discovery result, kept for the guarded plane-down stop below.
3995
+ let discovery = null;
2761
3996
  let docsRootUnresolved = false;
2762
3997
  if (planPath !== undefined) {
2763
3998
  plan = { status: "supplied", path: planPath };
@@ -2769,6 +4004,7 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
2769
4004
  }
2770
4005
  else {
2771
4006
  const discovered = await discoverEpicPlan(epicKey, docs.docsDir, deps.discoveryFs);
4007
+ discovery = discovered;
2772
4008
  plan = {
2773
4009
  status: discovered.status === "found" ? "found" : discovered.status === "plan_ambiguous" ? "ambiguous" : "not_found",
2774
4010
  ...(discovered.status === "found" ? { path: discovered.path } : {}),
@@ -2782,24 +4018,39 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
2782
4018
  planPath = discovered.path;
2783
4019
  }
2784
4020
  }
4021
+ // Every later exit, refusal or not, reports the plan state as discovered.
4022
+ preview.plan = plan;
2785
4023
  // --- Readiness. -----------------------------------------------------------
2786
4024
  let readiness;
2787
4025
  try {
2788
4026
  readiness = await deps.readReadiness(access);
2789
4027
  }
2790
4028
  catch (err) {
2791
- if (planPath !== undefined && endpoint !== null && profile?.executionMode !== "durable" &&
4029
+ if (isSchemaIncompatibleError(err)) {
4030
+ return refuseTopLevel({
4031
+ reasonId: "schema-incompatible",
4032
+ remedy: "Local schema incompatible: launch-critical schema objects are missing. " +
4033
+ `${SCHEMA_INCOMPATIBLE_REPAIR_ROUTE} Nothing was created or started.`,
4034
+ });
4035
+ }
4036
+ if (observed.repository.isBridge && planPath !== undefined && endpoint !== null && profile?.executionMode !== "durable" &&
2792
4037
  err instanceof ConductorBridgeApiError && err.kind === "network") {
2793
4038
  const probe = await deps.probePlanePort(endpoint.host, endpoint.port).catch(() => ({ kind: "error" }));
2794
4039
  if (probe.kind === "refused") {
2795
4040
  const preflight = await deps.runPlanePreflight(deps.cwd());
2796
4041
  const blocker = firstPreconditionRefusal(preflight) ??
2797
4042
  preflight.diagnostics.find((diagnostic) => diagnostic.severity === "blocking");
2798
- preview.plan = plan;
2799
4043
  if (blocker) {
4044
+ // Keep the blocker's own evidence (e.g. Alembic revisions) and its
4045
+ // fix. The fixed sentence is only for a blocker that carries neither.
4046
+ const evidence = [blocker.message, blocker.remediation]
4047
+ .filter((part) => typeof part === "string" && part.trim() !== "")
4048
+ .join(" ");
2800
4049
  return refuseTopLevel({
2801
4050
  reasonId: blocker.check,
2802
- remedy: `The local plane preflight refused ${blocker.check}. Fix that condition and preview again.`,
4051
+ remedy: evidence !== ""
4052
+ ? evidence
4053
+ : `The local plane preflight refused ${blocker.check}. Fix that condition and preview again.`,
2803
4054
  });
2804
4055
  }
2805
4056
  if (!preflight.ok) {
@@ -2813,12 +4064,39 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
2813
4064
  if (preview.decision === "create") {
2814
4065
  preview.cold_start = { plane_endpoint: access.baseUrl, will_start_plane: true, live_run_checked: false };
2815
4066
  }
4067
+ // No plane exists yet, so there is no snapshot or database to compare;
4068
+ // the host-sleep advisory still applies to the plane about to start.
4069
+ observed.access = access;
4070
+ observed.launchTopology = { kind: "local", repoRoot: null };
4071
+ await applyPreviewFreshness(ctx, preview, {}, true);
4072
+ return;
4073
+ }
4074
+ }
4075
+ // The narrow no-plan stop. Mirrors the real launch exactly: a local,
4076
+ // non-durable plane that refuses connections, and no usable plan. This is
4077
+ // the pre-existing `stop` outcome with no refusal and no new reason id; the
4078
+ // probe is the only port check the preview makes.
4079
+ if (planPath === undefined &&
4080
+ endpoint !== null &&
4081
+ profile?.executionMode !== "durable" &&
4082
+ err instanceof ConductorBridgeApiError &&
4083
+ err.kind === "network" &&
4084
+ discovery !== null &&
4085
+ (discovery.status === "plan_not_found" || discovery.status === "plan_ambiguous")) {
4086
+ const probe = await deps.probePlanePort(endpoint.host, endpoint.port).catch(() => ({ kind: "error" }));
4087
+ if (probe.kind === "refused") {
4088
+ preview.readiness = {
4089
+ kind: "unknown",
4090
+ remedy: planeDownNoPlanStopText(epicKey, { profile, options }, discovery),
4091
+ };
4092
+ preview.refusal = null;
4093
+ preview.decision = "stop";
2816
4094
  return;
2817
4095
  }
2818
4096
  }
2819
4097
  return unknownReadiness();
2820
4098
  }
2821
- preview.plan = plan;
4099
+ observed.readiness = readiness;
2822
4100
  if (docsRootUnresolved)
2823
4101
  return refuseTopLevel(docsRootRefusal(epicKey));
2824
4102
  const live = await deps.readLiveEpicRun(access, epicKey);
@@ -2826,8 +4104,19 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
2826
4104
  return refuseTopLevel(liveRunAmbiguousRefusal(epicKey));
2827
4105
  if (live.kind === "unknown")
2828
4106
  return refuseTopLevel(liveRunUnknownRefusal(epicKey, live.reason));
2829
- const previewCtx = { ...ctx, options: { ...options, ...(planPath ? { planFile: planPath } : {}) } };
2830
- const prepared = planPath ? await prepareSetupSelection(previewCtx) : null;
4107
+ // BAPI-1532 — a DISCOVERED plan beside a live run is unused: the launch attaches,
4108
+ // so the effective plan path is cleared while the preview still reports the plan
4109
+ // as found. An explicit --plan-file keeps its create-path behavior unchanged.
4110
+ const attachingDiscoveredPlan = options.planFile === undefined && plan.status === "found" && live.kind === "live";
4111
+ const effectivePlanPath = attachingDiscoveredPlan ? undefined : planPath;
4112
+ const previewCtx = { ...ctx, options: { ...options, ...(effectivePlanPath ? { planFile: effectivePlanPath } : {}) } };
4113
+ const observations = {
4114
+ endpoint: access.baseUrl, repository: access.repoName, epic: epicKey,
4115
+ readiness: { state: "supplied", value: readiness },
4116
+ liveRun: live.kind === "none" ? { state: "absent" }
4117
+ : live.kind === "live" && live.state ? { state: "supplied", value: live.state } : { state: "error" },
4118
+ };
4119
+ const prepared = effectivePlanPath ? await prepareSetupSelection(previewCtx, false, live) : null;
2831
4120
  if (prepared !== null && !prepared.ok) {
2832
4121
  return refuseTopLevel({
2833
4122
  reasonId: prepared.reasonId,
@@ -2838,13 +4127,19 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
2838
4127
  attended: options.attended === true,
2839
4128
  intoBase: options.intoBase === true,
2840
4129
  effectivePolicy: prepared?.ok ? prepared.handoff.selection : undefined,
2841
- approvedStoredPolicy: live.kind === "live" && !planPath,
4130
+ approvedStoredPolicy: live.kind === "live" && !effectivePlanPath,
2842
4131
  });
2843
4132
  preview.readiness = { kind: classification.kind };
4133
+ if (classification.kind === 'operator_blocked') {
4134
+ const requirement = V2_READINESS_REQUIREMENTS.find(req => req.id === classification.id);
4135
+ if (requirement)
4136
+ preview.launch_checks = [{ id: requirement.id, label: requirement.describe, status: 'fail', blocking: true, remedy: classification.remedy, duration_ms: elapsedMs(monotonicNow()) }];
4137
+ }
2844
4138
  const selection = selectConductor(readiness);
2845
4139
  // --- The live run. Conflict and unknown refuse whatever the plan says. ------
2846
4140
  if (live.kind === "live") {
2847
4141
  preview.live_run = { epic_run_id: live.epicRunId, status: live.status };
4142
+ preview.summary.ticket_review = live.ticketReview ?? "on";
2848
4143
  if (live.effectivePolicy) {
2849
4144
  preview.summary.policy_source = live.effectivePolicy.source;
2850
4145
  preview.summary.serial_execution = live.effectivePolicy.serial_execution;
@@ -2852,11 +4147,14 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
2852
4147
  preview.summary.job_timeouts = live.effectivePolicy.job_timeouts;
2853
4148
  preview.summary.escalation_channel_label = live.effectivePolicy.escalation_channel;
2854
4149
  preview.summary.posture = live.effectivePolicy.posture;
2855
- preview.summary.escalation_channel = null;
4150
+ preview.summary.escalation_channel =
4151
+ live.effectivePolicy.escalation_channel === "configured webhook"
4152
+ ? "webhook"
4153
+ : live.effectivePolicy.escalation_channel === "account email" ? "email" : null;
2856
4154
  }
2857
4155
  }
2858
4156
  // --- No plan: attach to a live run, or stop. --------------------------------
2859
- if (planPath === undefined) {
4157
+ if (effectivePlanPath === undefined) {
2860
4158
  if (live.kind !== "live") {
2861
4159
  if (selection.kind === "not_ready") {
2862
4160
  return refuseWithReadiness(classification.kind, {
@@ -2870,20 +4168,49 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
2870
4168
  const blocked = previewReadinessRefusal(ctx, classification, readiness, planeTarget, "attach");
2871
4169
  if (blocked !== null)
2872
4170
  return refuseWithReadiness(classification.kind, blocked);
2873
- const facts = await previewExecutorFacts(ctx, readiness, planeTarget, live, "No run was changed");
4171
+ const attachTopology = {};
4172
+ const facts = await previewExecutorFacts(ctx, readiness, planeTarget, live, "No run was changed", attachTopology);
2874
4173
  if (facts !== null)
2875
4174
  return refuseWithReadiness(classification.kind, facts, true);
2876
4175
  preview.decision = "attach";
4176
+ await applyPreviewFreshness(ctx, preview, attachTopology, false);
2877
4177
  return;
2878
4178
  }
4179
+ // The create path below always has a plan.
4180
+ const planPathForCreate = effectivePlanPath;
2879
4181
  // --- A plan is available: the create path's gates, then setup's own dry run. --
2880
4182
  const blocked = previewReadinessRefusal(ctx, classification, readiness, planeTarget, "create");
2881
- if (blocked !== null)
4183
+ if (blocked !== null) {
4184
+ // BAPI-1452: a disabled Setup-page posture keeps its exact control name and
4185
+ // turn-it-back-on remedy in the structured output as well as the refusal.
4186
+ if (classification.kind === "operator_blocked" && classification.id === "unattended_consent") {
4187
+ preview.launch_checks = previewLaunchRows(projectReadinessRowBlocking([unattendedPostureCheck(readiness)], {
4188
+ attended: options.attended === true,
4189
+ intoBase: options.intoBase === true,
4190
+ }));
4191
+ }
2882
4192
  return refuseWithReadiness(classification.kind, blocked);
2883
- const facts = await previewExecutorFacts(ctx, readiness, planeTarget, null, "No run was created");
4193
+ }
4194
+ const topology = {};
4195
+ const facts = await previewExecutorFacts(ctx, readiness, planeTarget, null, "No run was created", topology);
2884
4196
  if (facts !== null)
2885
4197
  return refuseWithReadiness(classification.kind, facts, true);
2886
- await finalizeCreatePreview(prepared?.ok ? { ...previewCtx, handoff: prepared.handoff } : previewCtx, preview, planPath, false, refuseTopLevel, live.kind === "live");
4198
+ // BAPI-1452: the same launch evidence a real launch collects, before any
4199
+ // setup preview. A local plane that still needs its runtime will run this
4200
+ // launch on plane lanes, whose executor this launcher cannot inspect.
4201
+ const launchTopology = planeTarget && classification.kind === "runtime_only"
4202
+ ? { kind: "plane_lane" }
4203
+ : topology.value ?? { kind: "local", repoRoot: null };
4204
+ const mergedEvaluation = live.kind !== "live" && options.noMergedCheck !== true
4205
+ ? evaluateMergedChildren(ctx, planPathForCreate).catch(() => notChecked("check_failed")) : undefined;
4206
+ const launch = await previewLaunchCapability(prepared?.ok ? { ...previewCtx, handoff: prepared.handoff } : previewCtx, readiness, launchTopology);
4207
+ preview.launch_checks = previewLaunchRows(launch.checks);
4208
+ if (launch.refusal !== null)
4209
+ return refuseWithReadiness("operator_blocked", launch.refusal);
4210
+ observed.access = access;
4211
+ observed.launchTopology = launchTopology;
4212
+ await finalizeCreatePreview(prepared?.ok ? { ...previewCtx, handoff: prepared.handoff, previewObservations: observations, previewMergedEvaluation: mergedEvaluation } : { ...previewCtx, previewObservations: observations, previewMergedEvaluation: mergedEvaluation }, preview, planPathForCreate, false, refuseTopLevel, live.kind === "live");
4213
+ await applyPreviewFreshness(ctx, preview, topology, false);
2887
4214
  }
2888
4215
  async function finalizeCreatePreview(ctx, preview, planPath, coldStart, refuseTopLevel, liveRunKnown = false) {
2889
4216
  const { deps, options, access } = ctx;
@@ -2904,12 +4231,65 @@ async function finalizeCreatePreview(ctx, preview, planPath, coldStart, refuseTo
2904
4231
  ? "webhook"
2905
4232
  : prepared.handoff.selection.escalationChannel === "account email" ? "email" : null;
2906
4233
  }
4234
+ // Compatibility path when no trusted repository-applicability fact is supplied.
4235
+ // Unknown is advisory, not a prerequisite on the sibling identity gate. Neither
4236
+ // declared paths nor target topology can establish repository identity.
4237
+ preview.plan_database_relevance = "unknown";
2907
4238
  preview.summary.child_count = await readPlanChildCount(deps, planPath);
2908
- const setup = await deps.previewSetupEpic({
2909
- argv: [...buildSetupEpicArgv({ ...options, planFile: planPath }), ...(coldStart ? ["--local-only"] : []), "--dry-run", "--json"],
4239
+ preview.summary.children_to_run = preview.summary.child_count;
4240
+ // BAPI-1510 — the already-merged check, after plan discovery and BEFORE the
4241
+ // setup dry run, so the dry run validates the plan a real create would submit.
4242
+ // An attach, a disabled check, and a cold start (no plane to ask yet) classify
4243
+ // nothing and keep every child.
4244
+ let evaluation = null;
4245
+ if (liveRunKnown) {
4246
+ preview.already_done_children = { status: "not_checked", reason: "attach", children: [] };
4247
+ }
4248
+ else if (options.noMergedCheck === true) {
4249
+ preview.already_done_children = { status: "not_checked", reason: "disabled", children: [] };
4250
+ }
4251
+ else if (coldStart) {
4252
+ preview.already_done_children = { status: "not_checked", reason: "cold_start", children: [] };
4253
+ }
4254
+ else {
4255
+ evaluation = await (ctx.previewMergedEvaluation ?? evaluateMergedChildren(ctx, planPath));
4256
+ preview.already_done_children = evaluation.state;
4257
+ if (evaluation.refusals.length > 0) {
4258
+ return refuseTopLevel({
4259
+ reasonId: "skip-child-refused",
4260
+ remedy: `${skipRefusalRemedy(evaluation.refusals)} Nothing was created.`,
4261
+ });
4262
+ }
4263
+ if (evaluation.skipKeys.size > 0 && evaluation.skipKeys.size >= evaluation.childKeys.length) {
4264
+ return refuseTopLevel({
4265
+ reasonId: EPIC_ALREADY_COMPLETE_REASON_ID,
4266
+ remedy: EPIC_ALREADY_COMPLETE_REMEDY,
4267
+ });
4268
+ }
4269
+ if (preview.summary.child_count !== null) {
4270
+ preview.summary.children_to_run = preview.summary.child_count - evaluation.skipKeys.size;
4271
+ }
4272
+ }
4273
+ const trim = evaluation !== null &&
4274
+ evaluation.skipKeys.size > 0 &&
4275
+ evaluation.plan !== null &&
4276
+ evaluation.cutCommitSha !== null
4277
+ ? { plan: trimDonePlanNodes(evaluation.plan, evaluation.skipKeys), cut: evaluation.cutCommitSha }
4278
+ : null;
4279
+ const runPreviewSetup = (effectivePlanPath) => deps.previewSetupEpic({
4280
+ argv: [...buildSetupEpicArgv({ ...options, planFile: effectivePlanPath }), ...(coldStart ? ["--local-only"] : []), "--dry-run", "--json"],
2910
4281
  baseUrl: access.baseUrl,
2911
- handoff: prepared.handoff,
4282
+ observations: ctx.previewObservations,
4283
+ handoff: trim !== null ? { ...prepared.handoff, expectedCutCommitSha: trim.cut } : prepared.handoff,
2912
4284
  });
4285
+ const setup = trim !== null
4286
+ ? await (deps.withPlanPath ?? withPlanPath)({
4287
+ originalPath: planPath,
4288
+ trimmedJson: JSON.stringify(trim.plan, null, 2),
4289
+ skipped: true,
4290
+ warn: (message) => deps.errorLog(message),
4291
+ }, runPreviewSetup)
4292
+ : await runPreviewSetup(planPath);
2913
4293
  if (setup.exitCode !== 0) {
2914
4294
  preview.summary.server_validation = "failed";
2915
4295
  return refuseTopLevel({
@@ -2929,6 +4309,16 @@ async function finalizeCreatePreview(ctx, preview, planPath, coldStart, refuseTo
2929
4309
  }
2930
4310
  preview.summary.server_validation = payload.serverValidated ? "passed" : "partial";
2931
4311
  preview.summary.branch = payload.featureBranch;
4312
+ if (payload.scopeBaseBranch !== null)
4313
+ previewScopeBaseBranch.set(preview, payload.scopeBaseBranch);
4314
+ preview.summary.ticket_review = payload.ticketReview;
4315
+ if (payload.launchReadiness) {
4316
+ preview.prerequisites = payload.launchReadiness.prerequisites;
4317
+ preview.is_production = payload.launchReadiness.is_production;
4318
+ const launch = classifyV2Readiness(payload.launchReadiness, { attended: options.attended, intoBase: options.intoBase });
4319
+ if (launch.kind === 'operator_blocked')
4320
+ return refuseTopLevel({ reasonId: launch.id, remedy: launch.remedy ?? 'Retry readiness.' });
4321
+ }
2932
4322
  if (payload.effectivePolicy) {
2933
4323
  const facts = payload.effectivePolicy;
2934
4324
  preview.summary.policy_source = facts.source;
@@ -2945,6 +4335,9 @@ async function finalizeCreatePreview(ctx, preview, planPath, coldStart, refuseTo
2945
4335
  preview.summary.posture === "unattended" ? payload.featureBranch : null;
2946
4336
  // The bootstrap reusing a run IS an attach: it reports the run's id.
2947
4337
  if (payload.existingRunId !== null) {
4338
+ // Existing runs are never trimmed: report the check as not applied.
4339
+ preview.already_done_children = { status: "not_checked", reason: "attach", children: [] };
4340
+ preview.summary.children_to_run = preview.summary.child_count;
2948
4341
  preview.live_run = {
2949
4342
  epic_run_id: payload.existingRunId,
2950
4343
  status: preview.live_run?.epic_run_id === payload.existingRunId ? preview.live_run.status : null,
@@ -2973,15 +4366,71 @@ function previewReadinessRefusal(ctx, classification, readiness, planeTarget, pa
2973
4366
  }
2974
4367
  return null;
2975
4368
  }
4369
+ /**
4370
+ * Append the freshness rows to a preview and, for a decision that would CREATE a
4371
+ * run, apply the creation policy. An `attach` decision (an existing live run, or a
4372
+ * bootstrap that reuses one) only ever warns. Reads nothing for a non-plane target.
4373
+ *
4374
+ * Advisory by construction: an unexpected failure here leaves the preview exactly
4375
+ * as it was.
4376
+ */
4377
+ async function applyPreviewFreshness(ctx, preview, topology, coldStart) {
4378
+ if (preview.decision !== "create" && preview.decision !== "attach")
4379
+ return;
4380
+ if (ctx.previewRepository?.isBridge === false) {
4381
+ preview.launch_checks = [...(preview.launch_checks ?? []), ...nonBridgeRows(["plane-snapshot-freshness", "plane-database-head"])];
4382
+ return;
4383
+ }
4384
+ const { deps } = ctx;
4385
+ if (planeEndpointForBaseUrl(deps, ctx.access.baseUrl) === null)
4386
+ return;
4387
+ try {
4388
+ const manifest = topology.manifest ?? null;
4389
+ const own = manifest !== null
4390
+ ? {
4391
+ repoRoot: manifest.repoRoot,
4392
+ ownsManifest: true,
4393
+ planeId: manifest.planeId,
4394
+ ...(manifest.epicRunId ? { epicRunId: manifest.epicRunId } : {}),
4395
+ }
4396
+ : { repoRoot: deps.cwd(), ownsManifest: false };
4397
+ const reports = coldStart ? null : await collectFreshnessObservations(ctx, own);
4398
+ // BAPI-1506: a `create` preview reports host sleep as a launch need on every
4399
+ // target (see appendLaunchNeedRows); only `attach` keeps it here.
4400
+ const sleep = preview.decision === "attach" ? await collectHostSleep(ctx, own.repoRoot) : null;
4401
+ // Read-only: one run-state read, local plane only, and only for a bound plane.
4402
+ const boundRun = await boundRunForStaleRemedy(ctx, own, reports);
4403
+ const assessment = assessPlaneFreshness(reports, sleep, preview.decision === "create" ? "create" : "attach", ctx.options.allowStalePlane === true, boundRun);
4404
+ if (assessment.rows.length > 0) {
4405
+ preview.launch_checks = [...(preview.launch_checks ?? []), ...assessment.rows];
4406
+ }
4407
+ const refusal = freshnessRefusalOf(assessment.blockers);
4408
+ if (refusal !== null) {
4409
+ preview.decision = "refuse";
4410
+ preview.refusal = { reason_id: refusal.reasonId, remedy: refusal.remedy };
4411
+ }
4412
+ }
4413
+ catch {
4414
+ // Leave the preview as it was; nothing from the failure reaches the document.
4415
+ }
4416
+ }
2976
4417
  /**
2977
4418
  * The executor-side refusals a real launch would hit, decided read-only: the
2978
4419
  * durable profile's coverage check, else whether an executor could be started
2979
4420
  * from this checkout at all. Returns `null` when neither refuses, including when
2980
4421
  * this checkout's plane already serves the live run and needs no executor.
2981
4422
  */
2982
- async function previewExecutorFacts(ctx, readiness, planeTarget, live, outcome) {
4423
+ async function previewExecutorFacts(ctx, readiness, planeTarget, live, outcome,
4424
+ /**
4425
+ * BAPI-1452 — receives the executor topology a real launch would use.
4426
+ * BAPI-1476 — and the attachable plane manifest this checkout owns, if any, so
4427
+ * freshness compares only the selected plane's snapshot.
4428
+ */
4429
+ topologyOut) {
2983
4430
  const { deps, epicKey, access, profile } = ctx;
2984
4431
  if (profile !== null && profile.executionMode === "durable") {
4432
+ if (topologyOut)
4433
+ topologyOut.value = { kind: "durable_profile" };
2985
4434
  if (durableActorAdmissionDenied(readiness)) {
2986
4435
  return {
2987
4436
  reasonId: "actor-admission-denied",
@@ -2993,9 +4442,11 @@ async function previewExecutorFacts(ctx, readiness, planeTarget, live, outcome)
2993
4442
  ? null
2994
4443
  : durableCoverageRefusal(epicKey, access, profile, coverage, outcome);
2995
4444
  }
2996
- if (planeTarget) {
4445
+ if (planeTarget && ctx.previewRepository?.isBridge !== false) {
2997
4446
  if (live !== null) {
2998
4447
  const manifest = await findAttachablePlane(ctx).catch(() => null);
4448
+ if (topologyOut)
4449
+ topologyOut.manifest = manifest;
2999
4450
  if (manifest?.epicRunId === live.epicRunId) {
3000
4451
  const admission = await checkPlaneAdmission(ctx, readiness, manifest);
3001
4452
  if (admission !== null) {
@@ -3005,15 +4456,140 @@ async function previewExecutorFacts(ctx, readiness, planeTarget, live, outcome)
3005
4456
  if (await planeServesLiveRun(ctx, live))
3006
4457
  return null;
3007
4458
  }
3008
- else if ((await findAttachablePlane(ctx).catch(() => null)) !== null) {
3009
- return null;
4459
+ else {
4460
+ const attachable = await findAttachablePlane(ctx).catch(() => null);
4461
+ if (topologyOut)
4462
+ topologyOut.manifest = attachable;
4463
+ if (attachable !== null) {
4464
+ if (topologyOut)
4465
+ topologyOut.value = { kind: "plane_lane" };
4466
+ return null;
4467
+ }
3010
4468
  }
3011
4469
  }
3012
4470
  const inspected = await deps.inspectRunExecutorPrecondition(deps.cwd());
4471
+ // BAPI-1452: the read-only inspection names the clone a run-scoped executor
4472
+ // would own; the preview never calls `prepareRunExecutor` to learn it.
4473
+ if (topologyOut && inspected.ok) {
4474
+ topologyOut.value = { kind: "local", repoRoot: inspected.repoRoot ?? null };
4475
+ }
3013
4476
  return inspected.ok
3014
4477
  ? null
3015
4478
  : executorPreconditionRefusal(epicKey, inspected.message, outcome === "No run was created" ? "No run was created." : "No run was changed.");
3016
4479
  }
4480
+ /**
4481
+ * True for the guarded plane-down no-plan stop: a `stop` that is not a refusal,
4482
+ * with unknown readiness carrying the shared handoff text as its remedy.
4483
+ */
4484
+ function isPlaneDownStop(preview) {
4485
+ return (preview.decision === "stop" &&
4486
+ preview.refusal === null &&
4487
+ preview.readiness.kind === "unknown" &&
4488
+ typeof preview.readiness.remedy === "string" &&
4489
+ preview.readiness.remedy !== "");
4490
+ }
4491
+ /**
4492
+ * The escalation-reachability row as text, directly under the `Escalation:` line.
4493
+ * An explicit `WARN` or `PASS` word carries the meaning (never colour), and the
4494
+ * explanation and fix sit on their own indented lines so a narrow terminal wraps
4495
+ * them beneath the label.
4496
+ */
4497
+ function reachabilityLines(preview) {
4498
+ const row = preview.launch_checks?.find((entry) => entry.id === ESCALATION_REACHABILITY_CHECK_ID);
4499
+ if (row === undefined)
4500
+ return [];
4501
+ return [
4502
+ ` ${row.status === "pass" ? "PASS" : "WARN"} ${ESCALATION_REACHABILITY_CHECK_ID}`,
4503
+ ...(row.detail ? [` ${row.detail}`] : []),
4504
+ ...(row.remedy ? [` Fix: ${row.remedy}`] : []),
4505
+ ];
4506
+ }
4507
+ /** Operator wording for each reason a child that was checked could not be proven merged. */
4508
+ const UNKNOWN_REASON_TEXT = {
4509
+ ancestry_unknown: "its merge could not be compared with the indexed commit",
4510
+ binding_ambiguous: "its delivery records name more than one pull request",
4511
+ provider_unavailable: "the code host could not be read",
4512
+ binding_read_failed: "its delivery records could not be read",
4513
+ merge_sha_unavailable: "its merge commit could not be confirmed",
4514
+ deadline_exceeded: "the check ran out of time",
4515
+ };
4516
+ const NOT_CHECKED_TEXT = {
4517
+ disabled: "Merged check: turned off (--no-merged-check). Every child will run.",
4518
+ attach: "Merged check: not applied; existing runs are unchanged.",
4519
+ cold_start: "Merged check: will be checked at create.",
4520
+ cut_commit_unavailable: "Merged check: the indexed commit could not be read. Every child will run.",
4521
+ check_failed: "Merged check: could not complete. Every child will run.",
4522
+ no_plan: null,
4523
+ };
4524
+ /**
4525
+ * The already-merged summary for the human preview (BAPI-1510). Leads with the
4526
+ * children to run and skipped, then the groups in a fixed order. Meaning is carried
4527
+ * by words, never colour; only customer ticket keys and validated PR numbers appear.
4528
+ */
4529
+ function alreadyDoneLines(preview) {
4530
+ const s = preview.summary;
4531
+ const state = preview.already_done_children ?? { status: "not_checked", reason: "no_plan", children: [] };
4532
+ const lines = [];
4533
+ if (preview.refusal?.reason_id === EPIC_ALREADY_COMPLETE_REASON_ID) {
4534
+ lines.push(" Status: no work to run — every child is already merged", ` ${preview.refusal.remedy}`);
4535
+ return lines;
4536
+ }
4537
+ const skipped = state.children.filter((child) => child.will_skip);
4538
+ if (state.status === "checked" || s.child_count !== null) {
4539
+ if (s.children_to_run !== null && s.children_to_run !== undefined) {
4540
+ lines.push(` To run: ${s.children_to_run}`);
4541
+ }
4542
+ lines.push(` Skipped: ${skipped.length}`);
4543
+ }
4544
+ if (state.status === "not_checked") {
4545
+ const text = NOT_CHECKED_TEXT[state.reason];
4546
+ if (text !== null)
4547
+ lines.push(` ${text}`);
4548
+ return lines;
4549
+ }
4550
+ const pr = (child) => child.pr_number !== null && Number.isSafeInteger(child.pr_number) && child.pr_number > 0
4551
+ ? ` (#${child.pr_number})`
4552
+ : "";
4553
+ if (skipped.length > 0) {
4554
+ lines.push(" Skipped (already merged):");
4555
+ for (const child of skipped) {
4556
+ lines.push(` ${child.ticket_key}${pr(child)} — ${child.classification === "done" ? "already merged" : "confirmed skip"}`);
4557
+ }
4558
+ }
4559
+ const probably = state.children.filter((child) => child.classification === "probably_done" && !child.will_skip);
4560
+ if (probably.length > 0) {
4561
+ lines.push(" Probably done — confirmation needed:");
4562
+ for (const child of probably) {
4563
+ lines.push(` ${child.ticket_key}${pr(child)} — on the indexed commit but has no delivery record; it will run. ` +
4564
+ `To skip it, pass --skip-child ${child.ticket_key}.`);
4565
+ }
4566
+ }
4567
+ const behind = state.children.filter((child) => child.reason === "merged_after_index");
4568
+ for (const child of behind) {
4569
+ lines.push(` ${child.ticket_key}${pr(child)} — merged after the indexed commit; it will run. ` +
4570
+ "Re-index the repository, or promote the branch it merged into, to skip it.");
4571
+ }
4572
+ const unknown = state.children.filter((child) => child.classification === "unknown");
4573
+ if (unknown.some((child) => child.reason === "ancestry_unavailable_for_provider")) {
4574
+ lines.push(" Merged-child detection is not supported for this repository's code host; every child will run.");
4575
+ }
4576
+ const byReason = new Map();
4577
+ for (const child of unknown) {
4578
+ if (child.reason === "ancestry_unavailable_for_provider")
4579
+ continue;
4580
+ byReason.set(child.reason, [...(byReason.get(child.reason) ?? []), child.ticket_key]);
4581
+ }
4582
+ for (const [reason, keys] of byReason) {
4583
+ lines.push(` Could not confirm ${keys.join(", ")}: ${UNKNOWN_REASON_TEXT[reason] ?? "the check was inconclusive"}. ` +
4584
+ `${keys.length === 1 ? "It" : "They"} will run.`);
4585
+ }
4586
+ if (skipped.length > 0 && s.children_to_run === 1) {
4587
+ lines.push(s.branch !== null
4588
+ ? ` Strategy: one child remains and runs on ${s.branch}`
4589
+ : " Strategy: one child remains and runs directly on the repository base branch");
4590
+ }
4591
+ return lines;
4592
+ }
3017
4593
  /**
3018
4594
  * Print the preview: one JSON line with `--json`, short readable lines otherwise.
3019
4595
  *
@@ -3035,8 +4611,13 @@ async function emitPreview(deps, options, preview) {
3035
4611
  ` Readiness: ${preview.readiness.kind}${preview.readiness.reason_id ? ` (${preview.readiness.reason_id})` : ""}`,
3036
4612
  ` Live run: ${preview.live_run
3037
4613
  ? `${preview.live_run.epic_run_id}${preview.live_run.status ? ` (${preview.live_run.status})` : ""}`
3038
- : preview.cold_start ? "unchecked (plane not yet running)" : "none"}`,
3039
- ` Plan: ${preview.plan.status}${preview.plan.path ? ` — ${preview.plan.path}` : ""}`,
4614
+ : preview.cold_start ? "unchecked (plane not yet running)"
4615
+ : isPlaneDownStop(preview) ? "unchecked (plane not running)" : "none"}`,
4616
+ // BAPI-1532 — a plan found beside a live run is "Found, unused": the launch
4617
+ // attaches and the local file is not read as approved input.
4618
+ ` Plan: ${preview.plan.status === "found" && preview.decision === "attach"
4619
+ ? "Found, unused"
4620
+ : preview.plan.status}${preview.plan.path ? ` — ${preview.plan.path}` : ""}`,
3040
4621
  ];
3041
4622
  for (const candidate of preview.plan.candidates ?? [])
3042
4623
  lines.push(` candidate: ${candidate}`);
@@ -3044,15 +4625,44 @@ async function emitPreview(deps, options, preview) {
3044
4625
  lines.push(` skipped: ${skipped.path} (${skipped.reason})`);
3045
4626
  }
3046
4627
  const s = preview.summary;
3047
- lines.push(` Posture: ${s.posture ?? "n/a"}`, ` Children: ${s.child_count ?? "n/a"}`, ` Branch: ${s.branch ?? "n/a"}`, ` Auto-merge: ${s.auto_merge_scope ?? "n/a"}`, ` Escalation: ${s.escalation_channel ?? "n/a"}`, ` Validation: ${preview.cold_start ? "Partial — plane is not yet running" : s.server_validation ?? "n/a"}`, ` Decision: ${preview.decision}`);
3048
- if (preview.readiness.remedy &&
4628
+ 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 ? [
4629
+ " Launch plan (advisory):",
4630
+ ...(preview.launch_plan.items.length === 0 ? [" There are no pending decisions"] :
4631
+ preview.launch_plan.items.flatMap((item) => [
4632
+ ` ${item.summary} (${item.id}): ${item.recommendation}`,
4633
+ ` ${item.reason}`,
4634
+ ...(item.remedy ? [` Remedy: ${item.remedy}`] : []),
4635
+ ...(item.recommendation === "fix first" ? [" Launch anyway accepts the unresolved risk; no remediation is performed."] : []),
4636
+ ])),
4637
+ ] : []), ` Validation: ${preview.cold_start ? "Partial — plane is not yet running" : s.server_validation ?? "n/a"}`, ` Decision: ${preview.decision}`);
4638
+ if (isPlaneDownStop(preview)) {
4639
+ // The shared stop text, verbatim and unindented, so it reads exactly as the
4640
+ // real launch prints it. It is a stop, not a refusal.
4641
+ lines.push("", preview.readiness.remedy);
4642
+ }
4643
+ else if (preview.readiness.remedy &&
3049
4644
  preview.readiness.remedy !== preview.refusal?.remedy &&
3050
4645
  !preview.refusal?.reason_id.startsWith("access-")) {
3051
4646
  lines.push(` Remedy: ${preview.readiness.remedy}`);
3052
4647
  }
3053
- if (preview.refusal) {
4648
+ if (preview.refusal && preview.refusal.reason_id !== EPIC_ALREADY_COMPLETE_REASON_ID) {
3054
4649
  lines.push(` Refusal: ${preview.refusal.reason_id} — ${preview.refusal.remedy}`);
3055
4650
  }
4651
+ const summaryRows = (preview.launch_checks ?? []).filter(row => row.id !== ESCALATION_REACHABILITY_CHECK_ID);
4652
+ lines.unshift(...formatLaunchReadinessSummary(summaryRows.map(row => ({
4653
+ id: row.id, source: row.id.startsWith('server.') ? 'server' : 'conductor',
4654
+ label: row.label, status: row.status, blocking: row.blocking,
4655
+ ...(row.detail ? { detail: row.detail } : {}),
4656
+ ...(row.remedy ? { remediation: row.remedy } : {}),
4657
+ })), { all: options.all, isProduction: preview.is_production, prerequisites: preview.prerequisites }));
4658
+ const localRows = summaryRows.filter(row => !READINESS_PREREQUISITE_BY_ID.has(READINESS_LEGACY_IDS[row.id] ?? row.id));
4659
+ // BAPI-1506: launch-need rows get their own heading; they are not plane freshness.
4660
+ const freshnessRows = localRows.filter(row => row.launch_need === undefined);
4661
+ const launchNeedRows = localRows.filter(row => row.launch_need !== undefined);
4662
+ if (freshnessRows.length)
4663
+ lines.push(...renderFreshnessRows(freshnessRows));
4664
+ if (launchNeedRows.length)
4665
+ lines.push(...renderFreshnessRows(launchNeedRows, 'Launch needs (advisory; never blocks):'));
3056
4666
  deps.log(lines.join("\n"));
3057
4667
  return true;
3058
4668
  }