@bridge_gpt/mcp-server 0.2.75 → 0.2.77

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 (94) hide show
  1. package/README.md +8 -6
  2. package/build/agents.generated.js +5 -5
  3. package/build/cli-dispatch.js +333 -0
  4. package/build/codex-auto-recovery.js +25 -7
  5. package/build/commands.generated.js +8 -8
  6. package/build/conductor/bridge-api-client.js +193 -13
  7. package/build/conductor/declare-blocked.js +146 -7
  8. package/build/conductor/driver-pass.js +8 -0
  9. package/build/conductor/driver-register.js +8 -2
  10. package/build/conductor/epic-implementer-cli.js +15 -10
  11. package/build/conductor/epic-server-journal.js +52 -22
  12. package/build/conductor/epic-server-recipe.js +15 -5
  13. package/build/conductor/epic-server-runtime.js +163 -45
  14. package/build/conductor/epic-server.js +13 -6
  15. package/build/conductor/install-doctor.js +30 -2
  16. package/build/conductor/launch-plan.js +28 -7
  17. package/build/conductor/local-merge.js +55 -13
  18. package/build/conductor/pr-ci-producer.js +12 -3
  19. package/build/conductor/readiness-prerequisites.js +89 -2
  20. package/build/conductor/readiness-sections.js +46 -13
  21. package/build/conductor/readiness.js +3 -40
  22. package/build/conductor/recovery-cli.js +14 -12
  23. package/build/conductor/repository-workflow-remedy.js +147 -7
  24. package/build/conductor/ui-readiness.js +224 -0
  25. package/build/conductor/wait-run-attention.js +9 -4
  26. package/build/conductor/wait-run-cli.js +9 -2
  27. package/build/docs.generated.js +67 -4
  28. package/build/doctor.js +97 -1
  29. package/build/drive-epic.js +625 -33
  30. package/build/engine-paths.js +10 -0
  31. package/build/epic-coherence-input-cli.js +105 -10
  32. package/build/epic-coherence-input.js +877 -4
  33. package/build/epic-coherence-input.test-fixtures.js +117 -0
  34. package/build/epic-implementer-bin.js +947 -120
  35. package/build/epic-implementer-env.js +2 -2
  36. package/build/epic-launch-context.js +8 -1
  37. package/build/epic-shared/cut-protocol.js +55 -3
  38. package/build/executor/completion-contract.js +14 -1
  39. package/build/executor/failure-reason-codes.js +2 -0
  40. package/build/executor/guarded-fast-forward-push.js +25 -2
  41. package/build/executor/integration-job.js +56 -2
  42. package/build/executor/job-runner.js +87 -28
  43. package/build/executor/likely-tests.js +78 -6
  44. package/build/executor/merge-job.js +45 -1
  45. package/build/executor/permissions.js +187 -2
  46. package/build/executor/provider-checks.js +101 -5
  47. package/build/executor/rebase-finalization.js +29 -27
  48. package/build/executor/reconcile-overlap-job.js +70 -17
  49. package/build/executor/rename-aside.js +265 -0
  50. package/build/executor/required-work-ledger.js +89 -6
  51. package/build/executor/resume-pre-spawn.js +32 -8
  52. package/build/executor/runner.js +26 -4
  53. package/build/executor/types.js +121 -0
  54. package/build/executor/worktree.js +39 -2
  55. package/build/index.js +2500 -495
  56. package/build/init.js +16 -0
  57. package/build/install-bridge-conductor-answers.js +4 -0
  58. package/build/install-bridge-conductor-apply.js +10 -0
  59. package/build/install-bridge-conductor-assessment.js +84 -0
  60. package/build/install-bridge-conductor-contracts.js +9 -1
  61. package/build/install-bridge-conductor-setup.js +103 -3
  62. package/build/install-bridge-conductor.js +440 -812
  63. package/build/install-bridge.js +4 -11
  64. package/build/language-catalog.generated.js +2649 -0
  65. package/build/mcp-host-config.js +54 -37
  66. package/build/phase-context-git-probe.js +16 -0
  67. package/build/pipelines.generated.js +47 -19
  68. package/build/plan-execution-ledger.js +35 -0
  69. package/build/plan-generation.js +34 -0
  70. package/build/plane/build-freshness.js +6 -0
  71. package/build/plane/cli.js +12 -5
  72. package/build/plane/plane-freshness.js +43 -26
  73. package/build/printed-remedy-commands.js +17 -0
  74. package/build/readiness-prerequisites.generated.js +28 -0
  75. package/build/readme.generated.js +1 -1
  76. package/build/run-unit-tests-launcher.js +3 -1
  77. package/build/secret-redaction.js +3 -0
  78. package/build/server.js +7946 -0
  79. package/build/setup-epic.js +41 -8
  80. package/build/start-tickets-prereqs.js +3 -6
  81. package/build/test-support/console-guard.js +30 -0
  82. package/build/test-support/create-preview-world.js +232 -0
  83. package/build/test-support/module-imports.js +155 -0
  84. package/build/test-support/server-client.js +96 -0
  85. package/build/test-support/stdio-server.js +146 -0
  86. package/build/ticket-delivery.js +65 -0
  87. package/build/v2-readiness-requirements.js +39 -5
  88. package/build/version.generated.js +3 -3
  89. package/build/worktree-core.js +51 -7
  90. package/docs/EPIC-IMPLEMENTER.md +150 -2
  91. package/docs/epic-implementer/getting-started.md +5 -1
  92. package/package.json +3 -3
  93. package/pipelines/implement-ticket.json +2 -2
  94. package/pipelines/learn-repository.json +19 -1
@@ -62,10 +62,13 @@ import { READINESS_PRE_CREATE_CODES, READINESS_PREREQUISITE_BY_ID, READINESS_LEG
62
62
  * ratcheted down, and a tool would be useless in a bare-chat session anyway,
63
63
  * where the model has no tool call to make.
64
64
  */
65
- import { access as fsAccess, readdir, readFile, realpath, stat as fsStat } from "node:fs/promises";
65
+ import { access as fsAccess, lstat as fsLstat, readdir, readFile, realpath, stat as fsStat } from "node:fs/promises";
66
66
  import { constants as fsConstants } from "node:fs";
67
67
  import path, { dirname, join } from "node:path";
68
- import { tmpdir } from "node:os";
68
+ import { homedir, tmpdir } from "node:os";
69
+ import { readMcpGrant } from "./mcp-grant.js";
70
+ import { readEpicServerRecord } from "./epic-server-record.js";
71
+ import { buildUiReadiness, classifyPlaywrightGrant, classifyUiVerification, classifyUiWork, } from "./conductor/ui-readiness.js";
69
72
  import { ConductorBridgeApiError, createReadinessAcquisition, resolveEpicLaunchBridgeApiAccess, fetchConductorReadiness, isSchemaIncompatibleError, SCHEMA_INCOMPATIBLE_REPAIR_ROUTE, fetchEpicRunState, isProviderRepositoryIdentity, safeDiagnosticMessage, classifyChildMergeStatus as classifyChildMergeStatusClient, recordSkippedChildren as recordSkippedChildrenClient, fetchEpicChildren, fetchStoredTicketDescription, resolveConductorBridgeApiAccess, validateEpicPlan, } from "./conductor/bridge-api-client.js";
70
73
  import { CHILD_MERGE_STATUS_BATCH_SIZE, buildAlreadyDoneEntries, classifyPlanChildren, selectSkips, } from "./conductor/merged-child-check.js";
71
74
  import { trimDonePlanNodes } from "./conductor/plan-trim.js";
@@ -84,12 +87,12 @@ import { collectWorkerDatabaseDoctorSection, WORKER_DATABASE_DOCTOR_TIMEOUT_MS,
84
87
  import { buildHostPowerLaunchRow, buildSelfHostedRunnerLaunchRow, buildWorkerDbRoleLaunchRow, hostPowerFactFromReport, LAUNCH_NEED_ROW_IDS, workerDatabaseReadinessChecks, } from "./conductor/readiness-sections.js";
85
88
  import { createWorkflowSource, inspectRequiredSelfHostedRunners, } from "./conductor/launch-need-probes.js";
86
89
  import { createWorkerDatabaseDoctorInspector } from "./conductor/worker-database-doctor-inspector.js";
87
- import { ENGINE_PATHS } from "./engine-paths.js";
88
- import { policyDeclaresNotifyWebhook, policyNotifyDestinationsConflict, notifyDestinationsConflictMessage, effectivePolicyFacts, evaluateParallelPolicyPreflight, parseParallelLimit, readSetupEpicPolicyFile, retainedParallelLimitNotice, resolveFeatureBranchSelection, readCanonicalParseTruth as readSetupCanonicalParseTruth, runSetupEpicWorkflow, launchReconnectCommand, READINESS_UNKNOWN_CONTINUING_WARNING, RUN_WAITING_FOR_APPROVAL_PHRASE, classifyRemoteEpicBranch, formatSetupEpicAutoMergeIntent, resolveSetupEpicAutoMergeIntent, readinessSnapshotFromLaunchContext, } from "./setup-epic.js";
90
+ import { ENGINE_PATHS, isEngineTestFile } from "./engine-paths.js";
91
+ import { policyDeclaresNotifyWebhook, policyNotifyDestinationsConflict, notifyDestinationsConflictMessage, effectivePolicyFacts, evaluateParallelPolicyPreflight, parseParallelLimit, readSetupEpicPolicyFile, retainedParallelLimitNotice, resolveFeatureBranchSelection, readCanonicalParseTruth as readSetupCanonicalParseTruth, runSetupEpicWorkflow, launchReconnectCommand, READINESS_UNKNOWN_CONTINUING_WARNING, RUN_WAITING_FOR_APPROVAL_PHRASE, classifyRemoteEpicBranch, formatSetupEpicAutoMergeIntent, resolveSetupEpicAutoMergeIntent, readinessSnapshotFromLaunchContext, validateEpicPlanSidecar, } from "./setup-epic.js";
89
92
  import { getConfigFieldBaseBranch } from "./epic-shared/bridge-client.js";
90
93
  import { createExecFileRunCommand, normalizeCommitSha } from "./epic-shared/cut-protocol.js";
91
94
  import { EPIC_KEY_PATTERN } from "./drive-epic-key.js";
92
- import { AUTHORED_PLAN_SERVER_TOO_OLD_NOTICE, AUTHORED_PLAN_UNKNOWN_REASON_ID, AUTHORED_PLAN_UPLOAD_FAILED_REASON_ID, authoredPlanUnknownRemedy, authoredPlanUploadFailedRemedy, createDefaultAuthoredPlanSaveDeps, explainRunPlanHash, lookupAuthoredPlanForLaunch, materializeAuthoredPlanSnapshot, resolveAuthoredPlanAccess, nonServerPlanProvenance, renderPlanProvenanceLine, saveLocalAuthoredPlan, serverPlanProvenance, } from "./authored-plan.js";
95
+ import { AUTHORED_PLAN_DAG_FILE, AUTHORED_PLAN_META_FILE, AUTHORED_PLAN_SERVER_TOO_OLD_NOTICE, AUTHORED_PLAN_UNKNOWN_REASON_ID, AUTHORED_PLAN_UPLOAD_FAILED_REASON_ID, authoredPlanUnknownRemedy, authoredPlanUploadFailedRemedy, createDefaultAuthoredPlanSaveDeps, explainRunPlanHash, lookupAuthoredPlanForLaunch, materializeAuthoredPlanSnapshot, resolveAuthoredPlanAccess, nonServerPlanProvenance, renderPlanProvenanceLine, saveLocalAuthoredPlan, serverPlanProvenance, } from "./authored-plan.js";
93
96
  import { hashPlan } from "./conductor/plan.js";
94
97
  import { buildEpicLaunchContext, projectWorkerDatabase, readEpicLaunchContext, writeEpicLaunchContext, writeEpicLaunchOutcome, } from "./epic-launch-context.js";
95
98
  import { flushProcessStdout, writeJsonDocument } from "./conductor/json-output.js";
@@ -97,7 +100,7 @@ import { BRIDGE_LAUNCHER_ENV } from "./bridge-permissions.js";
97
100
  import { checkPlaneBuildFreshness, PLANE_BUILD_FIX_REMEDIATION } from "./plane/build-freshness.js";
98
101
  import { discoverEpicPlan, isPlanGenerationEligible, unrelatedMissingMetaPaths, } from "./plan-discovery.js";
99
102
  import { attemptPlanGeneration, createDefaultPlanPublicationFs, generatedPlanFolder, listTrackedFilesWithGit, publishGeneratedPlan, validateGeneratedPlan, } from "./plan-generation-io.js";
100
- import { PLAN_GENERATION_FAILURE_TEXT, } from "./plan-generation.js";
103
+ import { PLAN_GENERATION_FAILURE_TEXT, PLAN_ORDER_NEEDED_REASON_ID, PLAN_ORDER_NEEDED_REMEDY, needsPlanOrder, } from "./plan-generation.js";
101
104
  import { DEFAULT_RUN_PARALLEL_LIMIT, formatPlaneDiagnostic, isPlaneExecutorLaneMember, launchPlaneControlPlane, parallelLimitToExecutorLanes, requestPlaneScopedLanes, runDefaultPlanePreflight, runPlaneCli, } from "./plane/cli.js";
102
105
  import { PLANE_PORT_PROBE_TIMEOUT_MS, describePlanePortOccupant, classifyBridgeCheckout, } from "./plane/preflight.js";
103
106
  import { createPlaneExecFile, createPlaneFsDeps, probeAutomationHealth, probeTcpPort, resolveHostname, } from "./plane/defaults.js";
@@ -110,6 +113,9 @@ import { resolveMemberInstanceId } from "./plane/supervisor.js";
110
113
  import { validateBranchName } from "./base-ref.js";
111
114
  import { createDefaultRunExecutorLaunchDeps, ensureRunExecutor as ensureRunExecutorDefault, prepareRunExecutor as prepareRunExecutorDefault, } from "./executor-launch.js";
112
115
  import { isTerminalEpicRunStatus } from "./epic-run-status.js";
116
+ import { repositoryReadinessVerdict, requiredChecksAdmissionRemedy, requiredChecksAdmissionVerdict, requiredChecksDeniedRecord, } from "./conductor/repository-workflow-remedy.js";
117
+ /** BAPI-1526 — the existing catalog row id for a denied required-checks admission. */
118
+ const REQUIRED_CHECKS_ADMISSION_REASON_ID = "server.admission-required-checks";
113
119
  // BAPI-806: mcp-identity.ts is the SOLE source of the package-name literal, so
114
120
  // the printed invocation interpolates it rather than repeating it.
115
121
  import { MCP_PACKAGE_NAME } from "./mcp-identity.js";
@@ -220,10 +226,18 @@ launchEvidence) {
220
226
  // which reads the policy and refuses if it declares none. Nothing is weakened:
221
227
  // `setup-epic` gates before the create, and the server re-checks the predicate
222
228
  // at approval and probes the URL there.
223
- const deferred = options.approvedStoredPolicy ||
229
+ const notifyDeferred = options.approvedStoredPolicy ||
224
230
  options.effectivePolicy?.escalationChannel === "configured webhook" ||
225
- (options.effectivePolicy === undefined && options.hasPolicyFile)
226
- ? V2_READINESS_REQUIREMENTS.filter((req) => req.id !== "server.unattended-notify-default")
231
+ (options.effectivePolicy === undefined && options.hasPolicyFile);
232
+ // BAPI-1714 — a genuine attach to a live run has already been through first
233
+ // approval, which owns the repository-workflow decision for that run, so it is
234
+ // not re-judged from the repository report. Notify-only deferral (a configured
235
+ // webhook or `--policy-file`) deliberately does NOT exempt it: neither option
236
+ // says anything about the repository's workflows.
237
+ const workflowExempt = options.approvedStoredPolicy === true;
238
+ const deferred = notifyDeferred || workflowExempt
239
+ ? V2_READINESS_REQUIREMENTS.filter((req) => !(notifyDeferred && req.id === "server.unattended-notify-default") &&
240
+ !(workflowExempt && req.id === "server.repository-workflow-readiness"))
227
241
  : V2_READINESS_REQUIREMENTS;
228
242
  // `--into-base` is the second opt-out, and it is structural rather than
229
243
  // declared: it selects the branch-silent composition, whose policy carries no
@@ -350,6 +364,17 @@ function indexedWorkflowsRemedy(readiness) {
350
364
  return INDEXED_WORKFLOWS_UNCLASSIFIED;
351
365
  }
352
366
  const INDEXED_WORKFLOWS_UNCLASSIFIED = "The state blocking the indexed workflows could not be established; run readiness again to read it.";
367
+ /**
368
+ * BAPI-1714 — a live run that is still `planning` while the server holds its
369
+ * authored plan is an UNFINISHED SETUP, not a run to attach to: approval has not
370
+ * happened, so there is nothing to attach an executor to. It routes through the
371
+ * setup path, which reuses the planning run. Every other live status, a planning
372
+ * run with no stored server plan, and the separate discovered-local-plan path all
373
+ * keep attaching. Pure: it reads only the two values it is given.
374
+ */
375
+ function isPlanningSetupToFinish(live, serverPlan) {
376
+ return live.kind === "live" && live.status === "planning" && serverPlan !== null;
377
+ }
353
378
  /**
354
379
  * Parse argv. Rejects malformed input BEFORE any side effect — no readiness
355
380
  * read, no credential resolution, no delegation.
@@ -1280,12 +1305,16 @@ export function createDefaultDriveEpicDeps() {
1280
1305
  fs: createPlaneFsDeps(),
1281
1306
  ...(applicability?.isBridge === false ? { isBridge: false } : {}),
1282
1307
  }),
1283
- collectPlaneFreshness: ({ repoRoot, ownsManifest, expectedPlaneId }) => checkPlaneFreshness(repoRoot, {
1308
+ collectPlaneFreshness: ({ repoRoot, ownsManifest, expectedPlaneId, snapshotFromCheckoutHead }) => checkPlaneFreshness(repoRoot, {
1284
1309
  execFile: createPlaneExecFile(),
1285
1310
  fileExists: (filePath) => fsStat(filePath).then((entry) => entry.isFile(), () => false),
1286
1311
  platform: process.platform,
1287
1312
  readPlaneManifest: (root) => readPlaneManifest(root, createPlaneFsDeps()),
1288
- }, repoRoot, { ownsManifest, ...(expectedPlaneId !== undefined ? { expectedPlaneId } : {}) }),
1313
+ }, repoRoot, {
1314
+ ownsManifest,
1315
+ ...(expectedPlaneId !== undefined ? { expectedPlaneId } : {}),
1316
+ ...(snapshotFromCheckoutHead === true ? { snapshotFromCheckoutHead: true } : {}),
1317
+ }),
1289
1318
  inspectHostSleep: (repoRoot) => inspectHostSleep(repoRoot, { execFile: createPlaneExecFile(), platform: process.platform }),
1290
1319
  inspectRequiredRunners: ({ repoRoot, providerRepository, gateProfile }) => inspectRequiredSelfHostedRunners({
1291
1320
  repoRoot,
@@ -1315,6 +1344,12 @@ export function createDefaultDriveEpicDeps() {
1315
1344
  clearTimeout(timer);
1316
1345
  }
1317
1346
  },
1347
+ // BAPI-1718 — the advisory UI-readiness reads delegate to the existing readers.
1348
+ // The captured environment keeps them off any later launch-target adoption.
1349
+ readUiTicketDescription: (access, ticketKey) => fetchStoredTicketDescription(access, ticketKey),
1350
+ listUiTrackedFiles: () => listTrackedFilesWithGit(process.cwd()),
1351
+ readUiMcpGrant: (repoName) => readMcpGrant(repoName, { env: normalServerEnv, homedir, readFile: (p) => readFile(p, "utf8") }),
1352
+ readUiEpicServerRecord: (repoName) => readEpicServerRecord(repoName, { env: normalServerEnv, homedir, readFile: (p) => readFile(p, "utf8"), lstat: (p) => fsLstat(p) }),
1318
1353
  execEngineStatus: createPlaneExecFile(),
1319
1354
  cleanupTerminalRunPlane: (input) => cleanupTerminalRunPlane(input, createTerminalRunCleanupDeps(process.env)),
1320
1355
  listLiveRunIds: (access) => createTerminalRunCleanupDeps(process.env).listLiveRunIds(access),
@@ -1541,6 +1576,20 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1541
1576
  // plan: it stops when (and only when) the launch would create a run.
1542
1577
  let serverPlan = null;
1543
1578
  let authoredLookup = null;
1579
+ // BAPI-1782 — an explicit `--plan-file` in the authored-plan folder shape (the
1580
+ // canonical DAG name beside metadata naming this epic) may be stored as the
1581
+ // epic's authored plan on a real create. It stays the selected plan whatever
1582
+ // the lookup answers; only a definite `not_stored` uploads it, later, on a
1583
+ // create path. Any other file keeps its existing behavior and makes no lookup.
1584
+ const explicitUpload = planFile !== undefined && deps.lookupAuthoredPlan !== undefined
1585
+ ? await explicitPlanUploadCandidate(deps, epicKey, planFile)
1586
+ : null;
1587
+ let explicitLookup = null;
1588
+ if (explicitUpload !== null && deps.lookupAuthoredPlan !== undefined) {
1589
+ explicitLookup = await deps
1590
+ .lookupAuthoredPlan(epicKey, repo)
1591
+ .catch(() => ({ lookup: { kind: "unknown", reason: "network" }, endpoint: null }));
1592
+ }
1544
1593
  if (planFile === undefined && deps.lookupAuthoredPlan !== undefined) {
1545
1594
  authoredLookup = await deps
1546
1595
  .lookupAuthoredPlan(epicKey, repo)
@@ -1566,6 +1615,11 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1566
1615
  discovered = await discoverEpicPlan(epicKey, docs.docsDir, deps.discoveryFs);
1567
1616
  if (discovered.status === "plan_not_found") {
1568
1617
  const generated = await generateMissingPlanForLaunch(ctx, docs.docsDir, discovered);
1618
+ // BAPI-1782 — a freshly built plan whose order fails launch admission is
1619
+ // refused before anything is published. Generation only reaches a built
1620
+ // plan after reading "no live run", so no attach is skipped here.
1621
+ if (generated.planOrderNeeded === true)
1622
+ return refuse(deps, [planOrderNeededRefusalLine(epicKey)]);
1569
1623
  discovered = generated.discovery;
1570
1624
  generationReason = generated.reason;
1571
1625
  }
@@ -1596,6 +1650,47 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1596
1650
  * its own, or a concurrent writer's. A generated plan is never uploaded.
1597
1651
  */
1598
1652
  const uploadLocalPlanIfNeeded = async () => {
1653
+ // BAPI-1782 — an eligible explicit `--plan-file` after a definite "no plan
1654
+ // stored". The run starts from the returned snapshot only when it is the
1655
+ // same plan as the file; a different stored plan was never shown, so refuse.
1656
+ if (explicitUpload !== null) {
1657
+ if (serverPlan !== null ||
1658
+ explicitLookup?.lookup.kind !== "not_stored" ||
1659
+ deps.uploadAuthoredPlan === undefined) {
1660
+ return { ok: true };
1661
+ }
1662
+ const uploaded = await deps
1663
+ .uploadAuthoredPlan({ epicKey, planDir: dirname(explicitUpload.planFile), repo })
1664
+ .catch(() => null);
1665
+ if (uploaded === null || !uploaded.ok) {
1666
+ const retry = uploaded !== null && !uploaded.ok
1667
+ ? uploaded.retryCommand
1668
+ : `npx -y ${MCP_PACKAGE_NAME} epic-plan save --epic-key ${epicKey}`;
1669
+ return {
1670
+ ok: false,
1671
+ code: refuse(deps, [
1672
+ `${epicKey}: REFUSED (${AUTHORED_PLAN_UPLOAD_FAILED_REASON_ID}) — ${authoredPlanUploadFailedRemedy(retry)}`,
1673
+ ]),
1674
+ };
1675
+ }
1676
+ if (uploaded.result.snapshot.plan_hash !== explicitUpload.planHash) {
1677
+ return {
1678
+ ok: false,
1679
+ code: refuse(deps, [
1680
+ `${epicKey}: REFUSED (${AUTHORED_PLAN_UPLOAD_FAILED_REASON_ID}) — ${explicitPlanStoredDiffersRemedy(epicKey)}`,
1681
+ ]),
1682
+ };
1683
+ }
1684
+ serverPlan = uploaded.result.snapshot;
1685
+ deps.log(`${epicKey}: saved the plan file to the Bridge server as authored version ` +
1686
+ `${serverPlan.authored_version}${uploaded.created ? "" : " (the same plan was already stored; using it)"}.`);
1687
+ const provenance = serverPlanProvenance(serverPlan, uploaded.endpoint);
1688
+ if (ctx.planProvenance !== undefined)
1689
+ Object.assign(ctx.planProvenance, provenance);
1690
+ else
1691
+ ctx = { ...ctx, planProvenance: provenance, planHashEvidence: {} };
1692
+ return { ok: true };
1693
+ }
1599
1694
  if (serverPlan !== null ||
1600
1695
  authoredLookup?.lookup.kind !== "not_stored" ||
1601
1696
  discovered?.status !== "found" ||
@@ -1686,6 +1781,11 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1686
1781
  return escalate(deps, epicKey, `launch profile '${launchProfile.name}' selects durable execution, and its control plane is ` +
1687
1782
  "not answering; no local replacement was started");
1688
1783
  }
1784
+ // BAPI-1782 — never cold-start a plane for a generated plan whose order
1785
+ // fails launch admission. Checked before any upload or plane start.
1786
+ if (await foundGeneratedPlanNeedsOrder(deps, discovered)) {
1787
+ return refuse(deps, [planOrderNeededRefusalLine(epicKey)]);
1788
+ }
1689
1789
  // BAPI-1706 — a cold start creates a run, so a local-only plan is uploaded
1690
1790
  // first and the server snapshot is what the new plane receives.
1691
1791
  const upload = await uploadLocalPlanIfNeeded();
@@ -1727,6 +1827,18 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1727
1827
  // run only on the create path, after the live-run read below, so attaching to a
1728
1828
  // live run never depends on them.
1729
1829
  if (ctx.options.planFile !== undefined && !planWasDiscovered) {
1830
+ // BAPI-1782 — store an eligible explicit plan only when the launch's one
1831
+ // live-run observation (the same cached read setup selection uses) shows no
1832
+ // run to reuse. A live or uncertain read keeps today's explicit behavior.
1833
+ if (explicitUpload !== null && explicitLookup?.lookup.kind === "not_stored") {
1834
+ const live = await acquireObservedLive(ctx);
1835
+ if (live.kind === "none") {
1836
+ const upload = await uploadLocalPlanIfNeeded();
1837
+ if (!upload.ok)
1838
+ return upload.code;
1839
+ await selectServerPlanFile();
1840
+ }
1841
+ }
1730
1842
  const prepared = await prepareSetupSelection(ctx);
1731
1843
  if (!prepared.ok) {
1732
1844
  return refuse(deps, [
@@ -1754,7 +1866,11 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1754
1866
  const live = await acquireObservedLive(ctx);
1755
1867
  if (live.kind === "conflict")
1756
1868
  return refuse(deps, liveRunAmbiguousRefusal(epicKey).lines);
1757
- if (live.kind === "live") {
1869
+ // BAPI-1714 — a `planning` run with a stored server plan is an INCOMPLETE
1870
+ // setup, not a live run to attach to: it has not been approved yet. It
1871
+ // falls through to the setup path below, which reuses the planning run.
1872
+ // Every other live status keeps attaching.
1873
+ if (live.kind === "live" && !isPlanningSetupToFinish(live, serverPlan)) {
1758
1874
  if (serverPlan !== null) {
1759
1875
  deps.log(`${epicKey}: a run is already live; it keeps the plan it was created with.`);
1760
1876
  }
@@ -1797,6 +1913,11 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1797
1913
  const { planFile: _unusedDiscoveredPlan, ...attachOptions } = ctx.options;
1798
1914
  return await attachToLiveRun({ ...ctx, options: attachOptions }, readiness, live, discovered.path);
1799
1915
  }
1916
+ // BAPI-1782 — the selected plan (after any publication-collision
1917
+ // rediscovery) is checked here, before upload, setup selection, or create.
1918
+ if (await foundGeneratedPlanNeedsOrder(deps, discovered)) {
1919
+ return refuse(deps, [planOrderNeededRefusalLine(epicKey)]);
1920
+ }
1800
1921
  // BAPI-1706 — the first real create from a local-only authored plan uploads
1801
1922
  // it, then runs the server-confirmed snapshot.
1802
1923
  const upload = await uploadLocalPlanIfNeeded();
@@ -2084,8 +2205,17 @@ function escalate(deps, epicKey, reason) {
2084
2205
  deps.errorLog(text);
2085
2206
  return 1;
2086
2207
  }
2087
- /** BAPI-1686 — said on every healthy-launch success output. */
2208
+ /**
2209
+ * BAPI-1686 — said on the healthy plane-launch and plane-attach success paths,
2210
+ * where the plane's processes belong to this terminal. A run-scoped executor
2211
+ * prints {@link RUN_EXECUTOR_DETACHED_LINE} instead.
2212
+ */
2088
2213
  export const KEEP_TERMINAL_OPEN_LINE = "Keep this terminal open and this machine awake. If the run stops moving, re-run this command: it attaches to the live run.";
2214
+ /**
2215
+ * BAPI-1725 — said once after a run-scoped executor outcome. That executor is
2216
+ * started detached, so closing the terminal or session does not stop it.
2217
+ */
2218
+ export const RUN_EXECUTOR_DETACHED_LINE = "Closing this terminal or session does not stop it. If the run stops moving, re-run this command: it attaches to the live run.";
2089
2219
  /** The prefix of the default launch-report line. */
2090
2220
  export const LAUNCH_REPORT_PREFIX = "Launch report: ";
2091
2221
  /** How long drive-epic watches a planning run for activation after an uncertain approve. */
@@ -2139,6 +2269,10 @@ async function generateMissingPlanForLaunch(ctx, docsDir, discovery) {
2139
2269
  if (!(await planGenerationAllowed(deps.discoveryFs, epicKey, discovery, attempt))) {
2140
2270
  return { discovery, reason: "discovery_blocked" };
2141
2271
  }
2272
+ // BAPI-1782 — launch admission, before anything is written: a built plan that
2273
+ // runs more than one planned child in key order is never published.
2274
+ if (needsPlanOrder(attempt.dag.nodes, attempt.summary))
2275
+ return { discovery, planOrderNeeded: true };
2142
2276
  let published;
2143
2277
  try {
2144
2278
  published = await deps.publishGeneratedPlan({
@@ -2162,6 +2296,54 @@ async function generateMissingPlanForLaunch(ctx, docsDir, discovery) {
2162
2296
  const after = await discoverEpicPlan(epicKey, docsDir, deps.discoveryFs);
2163
2297
  return after.status === "plan_not_found" ? { discovery: after, reason: "publish_failed" } : { discovery: after };
2164
2298
  }
2299
+ /** BAPI-1782 — the one-line real-launch refusal for an untrustworthy generated order. */
2300
+ function planOrderNeededRefusalLine(epicKey) {
2301
+ return `${epicKey}: REFUSED (${PLAN_ORDER_NEEDED_REASON_ID}) — ${PLAN_ORDER_NEEDED_REMEDY}`;
2302
+ }
2303
+ /**
2304
+ * BAPI-1782 — whether the SELECTED found plan is a generated plan that fails
2305
+ * launch admission. Reads the same nodes the preview reads; an authored plan, or
2306
+ * a generated DAG whose nodes cannot be read, is left to the existing checks.
2307
+ */
2308
+ async function foundGeneratedPlanNeedsOrder(deps, discovered) {
2309
+ if (discovered?.status !== "found" || discovered.generated === undefined)
2310
+ return false;
2311
+ const nodes = await readGeneratedPlanNodes(deps, discovered.path);
2312
+ return nodes !== null && needsPlanOrder(nodes, discovered.generated.summary);
2313
+ }
2314
+ /**
2315
+ * BAPI-1782 — an explicit `--plan-file` is eligible for upload only in the
2316
+ * authored-plan folder shape: the exact canonical DAG name, a sibling metadata
2317
+ * file that names this epic (the authored-plan reader's own identity rule), and
2318
+ * a DAG that passes the same sidecar validation. Anything else returns null and
2319
+ * keeps the explicit file's existing launch behavior, with no new refusal.
2320
+ */
2321
+ async function explicitPlanUploadCandidate(deps, epicKey, planFile) {
2322
+ if (path.basename(planFile) !== AUTHORED_PLAN_DAG_FILE)
2323
+ return null;
2324
+ try {
2325
+ const meta = JSON.parse(await deps.readPlanDag(path.join(dirname(planFile), AUTHORED_PLAN_META_FILE)));
2326
+ if (meta === null || typeof meta !== "object" || Array.isArray(meta))
2327
+ return null;
2328
+ const metaKey = meta.epic_key;
2329
+ if (typeof metaKey !== "string" || metaKey.trim() !== epicKey)
2330
+ return null;
2331
+ const validation = validateEpicPlanSidecar(JSON.parse(await deps.readPlanDag(planFile)));
2332
+ if (!validation.ok)
2333
+ return null;
2334
+ return { planFile, planHash: hashPlan(validation.plan) };
2335
+ }
2336
+ catch {
2337
+ return null;
2338
+ }
2339
+ }
2340
+ /** BAPI-1782 — the remedy when the server already stores a different plan than the explicit file. */
2341
+ function explicitPlanStoredDiffersRemedy(epicKey) {
2342
+ return ("No run was created; the Bridge server already stores a different plan for this epic than the " +
2343
+ "file passed with --plan-file, and a run never starts from a plan nobody was shown. Run the " +
2344
+ `preview again (\`drive-epic ${epicKey} --dry-run\`) to see the stored plan, then launch. ` +
2345
+ "Nothing was created or started.");
2346
+ }
2165
2347
  /**
2166
2348
  * Whether discovery's skipped entries allow generation. A DAG with no metadata
2167
2349
  * blocks only when it names the epic or one of its children, or can't be read.
@@ -2254,6 +2436,14 @@ export const LIVE_RUN_UNKNOWN_REASON_CODE = "live_run_unknown_continued";
2254
2436
  /** A mandatory diagnostic whose verdict or classification was not established. */
2255
2437
  export const MANDATORY_DIAGNOSTIC_UNKNOWN_WARNING = "mandatory diagnostic: unknown, continuing; server create and approve decide";
2256
2438
  export const MANDATORY_DIAGNOSTIC_UNKNOWN_REASON_CODE = "mandatory_diagnostic_unknown_continued";
2439
+ /**
2440
+ * BAPI-1714 — the repository's review and CI workflows could not be verified.
2441
+ * Preview continues (an unverifiable read is not a proven deficiency), but first
2442
+ * approval re-checks them and may still refuse, so the preview does not promise
2443
+ * approval.
2444
+ */
2445
+ export const REPOSITORY_WORKFLOWS_UNVERIFIABLE_WARNING = "Repository workflows could not be verified. Preview continues; first approval " +
2446
+ "will re-check them and may refuse if they remain unverifiable.";
2257
2447
  /** The escalation channel evidence was not established, so no "no channel" claim is made. */
2258
2448
  export const ESCALATION_CHANNEL_UNCERTAIN_WARNING = "escalation channel: unconfirmed, continuing; server create and approve decide";
2259
2449
  export const ESCALATION_CHANNEL_UNCERTAIN_REASON_CODE = "escalation_channel_unconfirmed_continued";
@@ -3343,6 +3533,42 @@ async function collectFreshnessObservations(ctx, own) {
3343
3533
  }
3344
3534
  return pending;
3345
3535
  }
3536
+ /**
3537
+ * BAPI-1725 — the cold-start observation: the CURRENT checkout's `HEAD` against
3538
+ * `origin/main`, before any plane exists. Snapshot only: it reads no manifest and
3539
+ * no database, so a stale or absent manifest can never redirect or hide it, and
3540
+ * no database row is ever fabricated. `null` when nothing applies (a non-plane
3541
+ * target, a missing collector, or a collector that fails): unproven evidence is
3542
+ * never a refusal.
3543
+ *
3544
+ * The preview shares one read per invocation (`cached`); a launch reads fresh, so
3545
+ * it never reuses an earlier preview's result.
3546
+ */
3547
+ async function collectCheckoutHeadFreshness(ctx, repoRoot, cached) {
3548
+ const { deps } = ctx;
3549
+ if (planeEndpointForBaseUrl(deps, ctx.access.baseUrl) === null)
3550
+ return null;
3551
+ const collect = deps.collectPlaneFreshness;
3552
+ if (collect === undefined)
3553
+ return null;
3554
+ const read = () => collect({ repoRoot, ownsManifest: false, snapshotFromCheckoutHead: true }).catch(() => null);
3555
+ let observed;
3556
+ if (cached) {
3557
+ const cache = ctx.freshness ?? createPlaneFreshnessCache();
3558
+ const key = `${repoRoot}\u0000checkout-head`;
3559
+ let pending = cache.observations.get(key);
3560
+ if (pending === undefined) {
3561
+ pending = read();
3562
+ cache.observations.set(key, pending);
3563
+ }
3564
+ observed = await pending;
3565
+ }
3566
+ else {
3567
+ observed = await read();
3568
+ }
3569
+ // Only the snapshot report is used, whatever else a collector returned.
3570
+ return observed === null ? null : { snapshot: observed.snapshot };
3571
+ }
3346
3572
  async function collectHostSleep(ctx, repoRoot) {
3347
3573
  const { deps } = ctx;
3348
3574
  if (planeEndpointForBaseUrl(deps, ctx.access.baseUrl) === null)
@@ -3485,10 +3711,13 @@ cleanupPreview = null) {
3485
3711
  ? formatSharedPlaneStaleRemedy(boundRun, cleanupPreview.kind === "live" ? cleanupPreview.epicRunId : null)
3486
3712
  : formatBoundPlaneStaleRemedy(boundRun),
3487
3713
  });
3488
- project(PLANE_DATABASE_HEAD_ID, "Plane database head", reports.database, {
3489
- reasonId: "plane-database-head-mismatch",
3490
- remedy: PLANE_DATABASE_HEAD_REMEDY,
3491
- });
3714
+ // A snapshot-only observation (BAPI-1725) carries no database report; none is invented.
3715
+ if ("database" in reports) {
3716
+ project(PLANE_DATABASE_HEAD_ID, "Plane database head", reports.database, {
3717
+ reasonId: "plane-database-head-mismatch",
3718
+ remedy: PLANE_DATABASE_HEAD_REMEDY,
3719
+ });
3720
+ }
3492
3721
  }
3493
3722
  if (sleep !== null) {
3494
3723
  const duration_ms = sleep.duration_ms ?? elapsedMs(monotonicNow());
@@ -3603,6 +3832,52 @@ async function planeFreshnessCreateGuard(ctx, own, trailer = []) {
3603
3832
  return null;
3604
3833
  }
3605
3834
  }
3835
+ /**
3836
+ * BAPI-1725 — the pre-launch freshness guard for a cold start. It reads the
3837
+ * current checkout's `HEAD` against `origin/main` (a fresh read, never the
3838
+ * preview's), runs the observation through {@link assessPlaneFreshness}
3839
+ * unchanged, and refuses only a confirmed, non-overridden stale result.
3840
+ *
3841
+ * Nothing has started when this refuses, so the output ends with `Nothing was
3842
+ * started.` and carries no running-plane trailer. Unverified evidence logs the
3843
+ * existing warning and the launch continues; an unexpected failure of this
3844
+ * advisory read never stops a launch. A confirmed non-Bridge checkout skips it.
3845
+ */
3846
+ async function coldStartCheckoutHeadGuard(ctx, repoRoot) {
3847
+ if (isConfirmedNonBridge(ctx))
3848
+ return null;
3849
+ try {
3850
+ const reports = await collectCheckoutHeadFreshness(ctx, repoRoot, false);
3851
+ if (reports === null)
3852
+ return null;
3853
+ const assessment = assessPlaneFreshness(reports, null, "create", ctx.options.allowStalePlane === true);
3854
+ const refusal = freshnessRefusalOf(assessment.blockers);
3855
+ const adverse = adverseFreshnessRows(assessment.rows);
3856
+ if (refusal !== null) {
3857
+ return refuse(ctx.deps, [
3858
+ `${ctx.epicKey}: REFUSED (${refusal.reasonId}) — the local plane is not current enough to ` +
3859
+ "create a run against.",
3860
+ ...renderFreshnessRows(adverse),
3861
+ "",
3862
+ "Nothing was started.",
3863
+ ]);
3864
+ }
3865
+ if (adverse.length > 0) {
3866
+ const log = ctx.deps.launchReadinessLog ?? ctx.deps.errorLog;
3867
+ log([
3868
+ assessment.overridden
3869
+ ? `${ctx.epicKey}: plane freshness — proceeding; a confirmed refusal was overridden for this invocation.`
3870
+ : `${ctx.epicKey}: plane freshness — proceeding; some evidence could not be verified.`,
3871
+ ...renderFreshnessRows(adverse),
3872
+ ].join("\n"));
3873
+ }
3874
+ return null;
3875
+ }
3876
+ catch {
3877
+ // An unexpected failure of an advisory read never stops a launch.
3878
+ return null;
3879
+ }
3880
+ }
3606
3881
  /** The warning-only counterpart for an existing run. Never refuses, never throws. */
3607
3882
  async function surfacePlaneFreshnessForExistingRun(ctx, own) {
3608
3883
  if (isConfirmedNonBridge(ctx)) {
@@ -3870,6 +4145,11 @@ async function coldStartPlane(ctx) {
3870
4145
  deps.errorLog(`${epicKey}: ${parallelColdRefusal}\nNothing was started.`);
3871
4146
  return 1;
3872
4147
  }
4148
+ // BAPI-1725: refuse a proven-stale checkout BEFORE anything is launched. The
4149
+ // post-launch guard below stays as the backstop.
4150
+ const staleHead = await coldStartCheckoutHeadGuard(ctx, repoRoot);
4151
+ if (staleHead !== null)
4152
+ return staleHead;
3873
4153
  const coldLanes = parallelLimitToExecutorLanes(ctx.options.parallel ?? DEFAULT_RUN_PARALLEL_LIMIT);
3874
4154
  const controlPlane = await deps.launchControlPlane({ preflight, executors: coldLanes });
3875
4155
  if (!controlPlane.ok) {
@@ -4372,6 +4652,41 @@ function docsRootRefusal(epicKey) {
4372
4652
  ],
4373
4653
  };
4374
4654
  }
4655
+ /**
4656
+ * BAPI-1781 — the epic's live run is explicitly STOPPED: `blocked` with a stored
4657
+ * `run_control` whose state is `stopped` (what `stop-run` writes). A stopped run
4658
+ * never resumes on its own, so attaching a new launch to it would drive nothing.
4659
+ * Returns the run id, or `null` for any other live run — another blocked state
4660
+ * (paused, quarantined, a preflight block with no record), an unreadable or
4661
+ * missing control, or an unknown read all keep their existing outcomes. Pure.
4662
+ */
4663
+ export function stoppedLiveRunId(live) {
4664
+ if (live.kind !== "live" || live.status !== "blocked")
4665
+ return null;
4666
+ const run = live.state?.epic_run;
4667
+ const control = run?.run_control;
4668
+ if (control === null || typeof control !== "object" || Array.isArray(control))
4669
+ return null;
4670
+ return control.state === "stopped" ? live.epicRunId : null;
4671
+ }
4672
+ export const LIVE_RUN_STOPPED_REASON_ID = "live-run-stopped";
4673
+ /** BAPI-1781 — a stopped live run is ended, not attached to: name the one-step verb. */
4674
+ function liveRunStoppedRefusal(epicKey, epicRunId) {
4675
+ const remedy = `The live run ${epicRunId} is stopped; stop-run pauses a run but does not end it. ` +
4676
+ `End it in one step with \`epic-implementer abandon-run --epic-run-id ${epicRunId}\`, ` +
4677
+ "then run drive-epic again.";
4678
+ return {
4679
+ reasonId: LIVE_RUN_STOPPED_REASON_ID,
4680
+ remedy,
4681
+ lines: [
4682
+ `${epicKey}: REFUSED (${LIVE_RUN_STOPPED_REASON_ID}) — this epic's live run ${epicRunId} is stopped, ` +
4683
+ "so drive-epic will not attach a new launch to it.",
4684
+ remedy,
4685
+ "",
4686
+ "Nothing was created and nothing was started.",
4687
+ ],
4688
+ };
4689
+ }
4375
4690
  /** BAPI-1285 — several active runs for one epic: it is wedged. */
4376
4691
  function liveRunAmbiguousRefusal(epicKey) {
4377
4692
  const remedy = "Abandon the duplicate run with `epic-implementer abandon-run --epic-run-id " +
@@ -4535,7 +4850,7 @@ function reportExecutorOutcome(ctx, ensured, epicRunId, framing) {
4535
4850
  "It runs on THIS machine: sleep is held off while it runs, but a closed lid, a logout, or a",
4536
4851
  "shutdown stops it. The run stays server-side either way; restart the executor, or use a",
4537
4852
  "durable launch profile for long runs.",
4538
- KEEP_TERMINAL_OPEN_LINE,
4853
+ RUN_EXECUTOR_DETACHED_LINE,
4539
4854
  ].join("\n"));
4540
4855
  return 0;
4541
4856
  }
@@ -4564,6 +4879,10 @@ async function planeServesLiveRun(ctx, live) {
4564
4879
  /**
4565
4880
  * BAPI-1285 — a live run and no usable plan: make sure the run has an executor.
4566
4881
  *
4882
+ * BAPI-1714 — this ATTACHES; it does not finish setup. A `planning` run whose
4883
+ * authored plan the server holds is routed to the setup path instead (see
4884
+ * {@link isPlanningSetupToFinish}), so only an approved or later run reaches here.
4885
+ *
4567
4886
  * It creates nothing and never calls `setup-epic`, which hard-requires a plan
4568
4887
  * file. Readiness gates it exactly as it gates a create (only green proceeds),
4569
4888
  * because starting an executor for a run nothing can drive is not attaching to it.
@@ -4574,6 +4893,12 @@ async function planeServesLiveRun(ctx, live) {
4574
4893
  */
4575
4894
  async function attachToLiveRun(ctx, readiness, live, unusedDiscoveredPlan) {
4576
4895
  const { deps, epicKey, access, profile } = ctx;
4896
+ // BAPI-1781 — a stopped run never resumes on its own, so a real launch must not
4897
+ // attach to it either (the preview already refuses the same way). Checked first,
4898
+ // at the one choke point every attach path goes through.
4899
+ const stoppedRunId = stoppedLiveRunId(live);
4900
+ if (stoppedRunId !== null)
4901
+ return refuse(deps, liveRunStoppedRefusal(epicKey, stoppedRunId).lines);
4577
4902
  // BAPI-1593 — an unknown report proves nothing to refuse on: attach.
4578
4903
  const classification = readiness === null
4579
4904
  ? { kind: "green" }
@@ -4798,19 +5123,28 @@ function classifyEngineStatus(stdout) {
4798
5123
  return "unreadable";
4799
5124
  const fields = stdout.slice(0, -1).split("\0");
4800
5125
  let records = 0;
5126
+ // BAPI-1782 — records that touch only engine test files are counted (so the
5127
+ // output still parses as status) but do not make the checkout dirty.
5128
+ let runtimeRecords = 0;
4801
5129
  for (let i = 0; i < fields.length; i += 1) {
4802
5130
  const field = fields[i];
4803
5131
  if (!PORCELAIN_RECORD.test(field))
4804
5132
  return "unreadable";
4805
5133
  records += 1;
5134
+ let testOnly = isEngineTestFile(field.slice(3));
4806
5135
  if (/^[RC]/.test(field) || /^.[RC]/.test(field)) {
4807
5136
  // The rename/copy origin path follows as its own field.
4808
5137
  i += 1;
4809
5138
  if (i >= fields.length || fields[i] === "")
4810
5139
  return "unreadable";
5140
+ testOnly = testOnly && isEngineTestFile(fields[i]);
4811
5141
  }
5142
+ if (!testOnly)
5143
+ runtimeRecords += 1;
4812
5144
  }
4813
- return records > 0 ? "dirty" : "unreadable";
5145
+ if (records === 0)
5146
+ return "unreadable";
5147
+ return runtimeRecords > 0 ? "dirty" : "clean";
4814
5148
  }
4815
5149
  /**
4816
5150
  * Collect the health-check fact for a verified Bridge LOCAL-plane create preview
@@ -5169,6 +5503,7 @@ async function runDriveEpicPreview(deps, options) {
5169
5503
  reason_id: named.reasonId,
5170
5504
  remedy: named.remedy,
5171
5505
  ...(named.authoritative === true ? { authoritative: true } : {}),
5506
+ ...(named.reasonCode !== undefined ? { reason_code: named.reasonCode } : {}),
5172
5507
  };
5173
5508
  preview.decision = "refuse";
5174
5509
  };
@@ -5220,7 +5555,7 @@ async function runDriveEpicPreview(deps, options) {
5220
5555
  needsTask,
5221
5556
  timed("health_status_ms", () => appendHealthCheckFact(deps, preview, observed.repository)),
5222
5557
  timed("escalation_ms", async () => { appendEscalationReachabilityRow(escalation, observed.readiness); }),
5223
- timed("executor_build_ms", () => appendExecutorBuildFreshnessWarning(deps, executor, observed.repository)),
5558
+ timed("executor_build_ms", () => appendExecutorBuildFreshnessWarning(deps, executor)),
5224
5559
  ]);
5225
5560
  const workerIds = new Set(worker.launch_checks?.map((row) => row.id));
5226
5561
  const needRows = needs.launch_checks ?? [];
@@ -5238,6 +5573,8 @@ async function runDriveEpicPreview(deps, options) {
5238
5573
  const collected = await collectLaunchPlanFacts(deps, options, preview, observed);
5239
5574
  // The tally lines do not depend on the builder succeeding.
5240
5575
  recordLaunchPlanObservations(preview, collected.tally);
5576
+ if (collected.uiReadiness !== undefined)
5577
+ preview.ui_readiness = collected.uiReadiness;
5241
5578
  const result = (deps.buildLaunchPlan ?? buildLaunchPlan)(preview, collected.facts);
5242
5579
  if (result)
5243
5580
  preview.launch_plan = result.launch_plan;
@@ -5259,6 +5596,130 @@ const previewPlanChildKeys = new WeakMap();
5259
5596
  /** The most time a launch preview spends reading the prerequisite cache before it carries on without it. */
5260
5597
  const PREREQUISITE_CACHE_READ_TIMEOUT_MS = 10_000;
5261
5598
  const PREREQUISITE_ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
5599
+ /** BAPI-1718 — the most time a create preview spends on ALL its advisory UI reads, shared. */
5600
+ const UI_READINESS_READ_TIMEOUT_MS = 10_000;
5601
+ /**
5602
+ * BAPI-1718 — start independent advisory reads together and finish under ONE
5603
+ * shared deadline. A `null` read was never available (a missing seam or access) and
5604
+ * stays failed. A read that throws, rejects, or has not finished when the deadline
5605
+ * passes is failed too; every read that completed keeps its value. The timer is
5606
+ * always cleared, a late completion is ignored, and nothing is retried.
5607
+ */
5608
+ async function collectAdvisoryReads(reads, timeoutMs) {
5609
+ const results = reads.map(() => ({ state: "failed" }));
5610
+ let closed = false;
5611
+ const settled = reads.map((run, index) => {
5612
+ if (run === null)
5613
+ return Promise.resolve();
5614
+ let pending;
5615
+ try {
5616
+ pending = Promise.resolve(run());
5617
+ }
5618
+ catch {
5619
+ return Promise.resolve();
5620
+ }
5621
+ return pending.then((value) => {
5622
+ if (!closed)
5623
+ results[index] = { state: "ok", value };
5624
+ }, () => undefined);
5625
+ });
5626
+ let timer;
5627
+ const deadline = new Promise((resolve) => {
5628
+ timer = setTimeout(resolve, timeoutMs);
5629
+ });
5630
+ try {
5631
+ await Promise.race([Promise.all(settled), deadline]);
5632
+ }
5633
+ finally {
5634
+ closed = true;
5635
+ if (timer !== undefined)
5636
+ clearTimeout(timer);
5637
+ }
5638
+ return [...results];
5639
+ }
5640
+ const UI_EPIC_SERVER_MODES = ["none", "local", "sfcc_shared_active"];
5641
+ /**
5642
+ * BAPI-1718 — the advisory UI readiness for a `create` preview. It reuses the plan
5643
+ * nodes and child set the preview already holds and reads only what is missing:
5644
+ * the epic and running-child descriptions, the tracked-file list, the worker grant,
5645
+ * and the epic-server record. It never throws and never changes anything the
5646
+ * preview decided; an unexpected failure simply yields no readiness.
5647
+ */
5648
+ async function collectUiReadiness(deps, options, preview, observed, handoff) {
5649
+ try {
5650
+ const access = observed.contextAccess;
5651
+ const repoName = observed.repoName ?? observed.access?.repoName ?? access?.repoName;
5652
+ // The children this launch will run: the plan's keys minus the already-done skips.
5653
+ const skipped = new Set();
5654
+ const merged = preview.already_done_children;
5655
+ if (merged !== undefined && merged.status === "checked") {
5656
+ for (const child of merged.children)
5657
+ if (child.will_skip === true)
5658
+ skipped.add(child.ticket_key);
5659
+ }
5660
+ const running = [...new Set((previewPlanChildKeys.get(preview) ?? []).filter((key) => !skipped.has(key)))];
5661
+ const readDescription = deps.readUiTicketDescription;
5662
+ const describe = (key) => readDescription === undefined || access === undefined ? null : () => readDescription(access, key);
5663
+ const readTracked = deps.listUiTrackedFiles;
5664
+ const readGrant = deps.readUiMcpGrant;
5665
+ const readRecord = deps.readUiEpicServerRecord;
5666
+ const results = await collectAdvisoryReads([
5667
+ describe(options.epicKey),
5668
+ ...running.map(describe),
5669
+ readTracked === undefined ? null : () => readTracked(),
5670
+ readGrant === undefined || repoName === undefined ? null : () => readGrant(repoName),
5671
+ readRecord === undefined || repoName === undefined ? null : () => readRecord(repoName),
5672
+ ], UI_READINESS_READ_TIMEOUT_MS);
5673
+ const asDescription = (read) => read.state === "ok" && typeof read.value === "string" ? { state: "ok", value: read.value } : { state: "failed" };
5674
+ const [epicRead, ...rest] = results;
5675
+ const childReads = rest.slice(0, running.length);
5676
+ const [trackedRead, grantRead, recordRead] = rest.slice(running.length);
5677
+ const tracked = trackedRead.state === "ok" && Array.isArray(trackedRead.value) &&
5678
+ trackedRead.value.every((entry) => typeof entry === "string")
5679
+ ? { state: "ok", value: trackedRead.value }
5680
+ : { state: "failed" };
5681
+ let grant = { state: "failed" };
5682
+ if (grantRead.state === "ok" && grantRead.value !== null && typeof grantRead.value === "object") {
5683
+ const value = grantRead.value;
5684
+ if (value.state === "absent")
5685
+ grant = { state: "absent" };
5686
+ else if (value.state === "unusable")
5687
+ grant = { state: "unusable", reason: "" };
5688
+ else if (value.state === "ok" && Array.isArray(value.grant?.servers))
5689
+ grant = value;
5690
+ }
5691
+ let mode = "unknown";
5692
+ if (recordRead.state === "ok" && recordRead.value !== null && typeof recordRead.value === "object") {
5693
+ const value = recordRead.value;
5694
+ if (value.state === "absent")
5695
+ mode = "none";
5696
+ else if (value.state === "ok" && typeof value.record?.mode === "string" && UI_EPIC_SERVER_MODES.includes(value.record.mode)) {
5697
+ mode = value.record.mode;
5698
+ }
5699
+ }
5700
+ const work = classifyUiWork({
5701
+ epicKey: options.epicKey,
5702
+ epicDescription: asDescription(epicRead),
5703
+ runningChildren: running.map((key, index) => ({ key, description: asDescription(childReads[index]) })),
5704
+ nodes: (preview.plan.generation?.nodes ?? preview.plan.inline?.nodes ?? []).map((node) => ({
5705
+ ticket_key: node.ticket_key,
5706
+ ...(node.touched_files !== undefined ? { touched_files: node.touched_files } : {}),
5707
+ })),
5708
+ trackedFiles: tracked,
5709
+ });
5710
+ return buildUiReadiness({
5711
+ work,
5712
+ verification: classifyUiVerification(grant, mode),
5713
+ mode,
5714
+ playwrightGrant: classifyPlaywrightGrant(grant),
5715
+ handoff,
5716
+ });
5717
+ }
5718
+ catch {
5719
+ // Advisory only: nothing from the failure is shown, and the preview is unchanged.
5720
+ return undefined;
5721
+ }
5722
+ }
5262
5723
  function handoffValueText(value) {
5263
5724
  return value === "unknown" ? "unknown (today's default: proceed)" : value;
5264
5725
  }
@@ -5403,7 +5864,15 @@ async function collectLaunchPlanFacts(deps, options, preview, observed) {
5403
5864
  if (suppressed.length > 0) {
5404
5865
  tally.push({ code: "launch_rows_kept_off_screen", line: `launch rows kept off the screen: ${[...new Set(suppressed)].join(", ")}` });
5405
5866
  }
5406
- return { facts: { prerequisites, handoff }, tally };
5867
+ // BAPI-1718 — the UI advisory is computed for a `create` decision only. It adds no
5868
+ // read for attach or any other decision, and never feeds the launch plan or a check.
5869
+ let uiReadiness;
5870
+ if (preview.decision === "create") {
5871
+ uiReadiness = await collectUiReadiness(deps, options, preview, observed, effective);
5872
+ if (uiReadiness !== undefined)
5873
+ tally.push({ code: "ui_readiness", line: uiReadiness.line });
5874
+ }
5875
+ return { facts: { prerequisites, handoff }, tally, ...(uiReadiness !== undefined ? { uiReadiness } : {}) };
5407
5876
  }
5408
5877
  /** Append the collected fixed lines to the preview's tally lines, once each. */
5409
5878
  function recordLaunchPlanObservations(preview, lines) {
@@ -5477,23 +5946,55 @@ function appendEscalationReachabilityRow(preview, readiness) {
5477
5946
  { ...row, duration_ms: elapsedMs(started) },
5478
5947
  ];
5479
5948
  }
5949
+ /**
5950
+ * The Bridge checkout root a launcher override names (BAPI-1725), or `null`.
5951
+ *
5952
+ * A plain whitespace split of the launcher value; the first absolute-path token
5953
+ * with an exact `mcp_server` path component selects the directory holding that
5954
+ * component. This matches the launcher format `resolvePermissionLauncher`
5955
+ * supports, which refuses quoted values, so there is deliberately no quote-aware
5956
+ * tokenization and no reconstruction of space-bearing paths. `mcp_server_extra`
5957
+ * and other lookalike components never qualify.
5958
+ */
5959
+ function bridgeRootFromLauncher(launcher) {
5960
+ for (const token of launcher.trim().split(/\s+/)) {
5961
+ if (token === "" || !path.isAbsolute(token))
5962
+ continue;
5963
+ let current = token;
5964
+ for (;;) {
5965
+ const parent = dirname(current);
5966
+ if (parent === current)
5967
+ break;
5968
+ if (path.basename(current) === "mcp_server")
5969
+ return parent;
5970
+ current = parent;
5971
+ }
5972
+ }
5973
+ return null;
5974
+ }
5480
5975
  /**
5481
5976
  * Append a non-blocking `executor-build-freshness` warning to the preview when a
5482
- * local CLI override (`BAPI_MCP_CLI`) is set and the executor build is stale or
5483
- * unreadable. Fail-open and read-only: it never changes the decision, a refusal,
5977
+ * local CLI override (`BAPI_MCP_CLI`) is set and the Bridge build it names is
5978
+ * stale or unreadable. Fail-open and read-only: it never changes the decision, a refusal,
5484
5979
  * readiness, or the exit code. A passing check, an unset or blank override, or a
5485
5980
  * missing dependency leaves `launch_checks` untouched. A thrown check prints one
5486
5981
  * fixed line and nothing from the exception.
5487
5982
  */
5488
- async function appendExecutorBuildFreshnessWarning(deps, preview, repository) {
5983
+ async function appendExecutorBuildFreshnessWarning(deps, preview) {
5489
5984
  const started = monotonicNow();
5490
5985
  const override = process.env[BRIDGE_LAUNCHER_ENV];
5491
5986
  if (override === undefined || override.trim() === "")
5492
5987
  return;
5493
5988
  if (deps.checkExecutorBuildFreshness === undefined)
5494
5989
  return;
5990
+ // BAPI-1725: the executor runs the Bridge build the launcher names, not the
5991
+ // consumer checkout. No qualifying launcher path means nothing to check; it
5992
+ // never falls back to the consumer's cwd.
5993
+ const bridgeRoot = bridgeRootFromLauncher(override);
5994
+ if (bridgeRoot === null)
5995
+ return;
5495
5996
  try {
5496
- const report = await deps.checkExecutorBuildFreshness(deps.cwd(), repository?.isBridge === false ? { isBridge: false } : undefined);
5997
+ const report = await deps.checkExecutorBuildFreshness(bridgeRoot);
5497
5998
  if (report.diagnostic === null)
5498
5999
  return;
5499
6000
  const outcome = report.outcomes.find((entry) => entry.status === "warn" || entry.status === "fail") ?? report.outcomes[0];
@@ -5530,7 +6031,24 @@ function autoMergeLine(preview) {
5530
6031
  : " Auto-merge: unavailable (older setup-epic output)";
5531
6032
  }
5532
6033
  const intent = merge.state === "on" ? { state: "on" } : { state: "off", reason: merge.reason ?? "" };
5533
- return ` ${formatSetupEpicAutoMergeIntent(intent, preview.summary.branch ?? undefined)}`;
6034
+ return ` ${formatSetupEpicAutoMergeIntent(intent, preview.summary.branch ?? undefined)}${autoMergeForecastSuffix(merge)}`;
6035
+ }
6036
+ /**
6037
+ * BAPI-1526 — the advisory suffix for the one "Auto-merge:" line. Empty for an
6038
+ * `off` intent, `unknown`, `not_requested`, or an absent forecast, so those lines
6039
+ * stay byte-identical. Reason ids are closed tokens, already validated by the parser.
6040
+ */
6041
+ function autoMergeForecastSuffix(merge) {
6042
+ const forecast = merge.forecast;
6043
+ if (merge.state !== "on" || forecast === undefined)
6044
+ return "";
6045
+ const ids = forecast.reason_ids.join(", ");
6046
+ if (forecast.outcome === "merge_approval_required") {
6047
+ return `; first approval will require merge approval${ids === "" ? "" : ` (${ids})`}`;
6048
+ }
6049
+ if (forecast.outcome === "auto_merge_kept" && ids !== "")
6050
+ return `; kept at first approval (${ids})`;
6051
+ return "";
5534
6052
  }
5535
6053
  /** BAPI-1593 — the plan digest setup-epic's dry run says the SERVER validated, per preview. */
5536
6054
  const previewServerPlanDigest = new WeakMap();
@@ -5764,6 +6282,10 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5764
6282
  // BAPI-1621 — why automatic generation stopped, and whether it read "no live run".
5765
6283
  let generationReason;
5766
6284
  let generatedLiveRunChecked = false;
6285
+ // BAPI-1782 — a generated plan (in memory or found) whose order fails launch
6286
+ // admission. Applied only where this preview would create a run; the plan block
6287
+ // is kept as it is so the driver can read the child keys from it.
6288
+ let planOrderNeeded = false;
5767
6289
  let docsRootUnresolved = false;
5768
6290
  // BAPI-1706 — the same server-first precedence the launch uses, read once and
5769
6291
  // written nowhere: no upload, no temporary folder, no local file.
@@ -5839,8 +6361,10 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5839
6361
  if (discovered.generated !== undefined) {
5840
6362
  plan.generated = true;
5841
6363
  const nodes = await readGeneratedPlanNodes(deps, discovered.path);
5842
- if (nodes !== null)
6364
+ if (nodes !== null) {
5843
6365
  plan.generation = { nodes, summary: discovered.generated.summary };
6366
+ planOrderNeeded = needsPlanOrder(nodes, discovered.generated.summary);
6367
+ }
5844
6368
  }
5845
6369
  }
5846
6370
  else if (discovered.status === "plan_not_found" && deps.attemptPlanGeneration !== undefined) {
@@ -5870,6 +6394,7 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5870
6394
  epic_plans_dir: discovered.epic_plans_dir,
5871
6395
  };
5872
6396
  generatedLiveRunChecked = true;
6397
+ planOrderNeeded = needsPlanOrder(attempt.dag.nodes, attempt.summary);
5873
6398
  ctx = { ...ctx, deps: withInlinePlan(ctx.deps, planPath, JSON.stringify(attempt.dag, null, 2) + "\n") };
5874
6399
  }
5875
6400
  }
@@ -5896,6 +6421,18 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5896
6421
  const authoredPlanUnknown = authoredLookupKind === "unknown";
5897
6422
  // Every later exit, refusal or not, reports the plan state as discovered.
5898
6423
  preview.plan = plan;
6424
+ /**
6425
+ * BAPI-1782 — the launch-admission refusal for an untrustworthy generated order.
6426
+ * Called only on a path that would create a run, after the existing gates, so
6427
+ * a live run is still attached to and earlier refusals keep their precedence.
6428
+ * Returns true when it refused.
6429
+ */
6430
+ const refusePlanOrderNeeded = () => {
6431
+ if (!planOrderNeeded)
6432
+ return false;
6433
+ refuseTopLevel({ reasonId: PLAN_ORDER_NEEDED_REASON_ID, remedy: PLAN_ORDER_NEEDED_REMEDY, authoritative: true });
6434
+ return true;
6435
+ };
5899
6436
  // --- Readiness. -----------------------------------------------------------
5900
6437
  // BAPI-1593 — ONE acquisition for this preview: at most two full reads. The
5901
6438
  // first failure is inspected on its own (a refused plane port is a cold start);
@@ -5947,6 +6484,8 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5947
6484
  });
5948
6485
  }
5949
6486
  preview.readiness = { kind: "cold_start" };
6487
+ if (refusePlanOrderNeeded())
6488
+ return;
5950
6489
  await finalizeCreatePreview(ctx, preview, planPath, true, refuseTopLevel);
5951
6490
  if (preview.decision === "create") {
5952
6491
  preview.cold_start = {
@@ -5955,8 +6494,9 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5955
6494
  live_run_checked: generatedLiveRunChecked,
5956
6495
  };
5957
6496
  }
5958
- // No plane exists yet, so there is no snapshot or database to compare;
5959
- // the host-sleep advisory still applies to the plane about to start.
6497
+ // No plane exists yet, so there is no plane snapshot or database to compare.
6498
+ // The checkout's HEAD is compared with origin/main instead (BAPI-1725); the
6499
+ // host-sleep advisory still applies to the plane about to start.
5960
6500
  observed.access = access;
5961
6501
  observed.launchTopology = { kind: "local", repoRoot: null };
5962
6502
  await applyPreviewFreshness(ctx, preview, {}, true);
@@ -6010,7 +6550,11 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
6010
6550
  (preview.warnings ??= []).push(LIVE_RUN_UNKNOWN_WARNING);
6011
6551
  if (unknownLive.kind === "live") {
6012
6552
  preview.live_run = { epic_run_id: unknownLive.epicRunId, status: unknownLive.status };
6013
- if (options.planFile === undefined) {
6553
+ if (options.planFile === undefined && !isPlanningSetupToFinish(unknownLive, previewServerPlan)) {
6554
+ // BAPI-1781 — a stopped live run is reported with its one-step exit, not attached to.
6555
+ const stoppedRunId = stoppedLiveRunId(unknownLive);
6556
+ if (stoppedRunId !== null)
6557
+ return refuseTopLevel(liveRunStoppedRefusal(epicKey, stoppedRunId));
6014
6558
  preview.decision = "attach";
6015
6559
  return;
6016
6560
  }
@@ -6022,6 +6566,8 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
6022
6566
  preview.decision = "stop";
6023
6567
  return;
6024
6568
  }
6569
+ if (refusePlanOrderNeeded())
6570
+ return;
6025
6571
  await finalizeCreatePreview(ctx, preview, planPath, false, refuseTopLevel, true);
6026
6572
  return;
6027
6573
  }
@@ -6036,7 +6582,11 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
6036
6582
  // BAPI-1532 — a DISCOVERED plan beside a live run is unused: the launch attaches,
6037
6583
  // so the effective plan path is cleared while the preview still reports the plan
6038
6584
  // as found. An explicit --plan-file keeps its create-path behavior unchanged.
6039
- const attachingDiscoveredPlan = options.planFile === undefined && (plan.status === "found" || plan.status === "generated") && live.kind === "live";
6585
+ const attachingDiscoveredPlan = options.planFile === undefined &&
6586
+ (plan.status === "found" || plan.status === "generated") &&
6587
+ live.kind === "live" &&
6588
+ // BAPI-1714 — finishing setup for a planning run keeps the stored server plan.
6589
+ !isPlanningSetupToFinish(live, previewServerPlan);
6040
6590
  const effectivePlanPath = attachingDiscoveredPlan ? undefined : planPath;
6041
6591
  const previewCtx = { ...ctx, options: { ...options, ...(effectivePlanPath ? { planFile: effectivePlanPath } : {}) } };
6042
6592
  const observations = {
@@ -6062,6 +6612,18 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
6062
6612
  if (mandatoryDiagnosticsUncertain(readiness.diagnostics)) {
6063
6613
  (preview.warnings ??= []).push(MANDATORY_DIAGNOSTIC_UNKNOWN_WARNING);
6064
6614
  }
6615
+ // BAPI-1714 — an unverifiable workflow read warns once, on an applicable
6616
+ // unattended create or setup path. A genuine live-run attach (a live run with no
6617
+ // plan to set up) is excluded: first approval already decided it.
6618
+ const genuineAttach = live.kind === "live" && effectivePlanPath === undefined;
6619
+ if (options.attended !== true &&
6620
+ options.intoBase !== true &&
6621
+ !genuineAttach &&
6622
+ readiness.unattended?.repository_readiness_confirmed === false &&
6623
+ repositoryReadinessVerdict(readiness) === "unknown" &&
6624
+ !(preview.warnings ?? []).includes(REPOSITORY_WORKFLOWS_UNVERIFIABLE_WARNING)) {
6625
+ (preview.warnings ??= []).push(REPOSITORY_WORKFLOWS_UNVERIFIABLE_WARNING);
6626
+ }
6065
6627
  if (classification.kind === 'operator_blocked') {
6066
6628
  const requirement = V2_READINESS_REQUIREMENTS.find(req => req.id === classification.id);
6067
6629
  if (requirement)
@@ -6103,6 +6665,10 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
6103
6665
  preview.decision = "stop";
6104
6666
  return;
6105
6667
  }
6668
+ // BAPI-1781 — a stopped live run is reported with its one-step exit, not attached to.
6669
+ const stoppedRunId = stoppedLiveRunId(live);
6670
+ if (stoppedRunId !== null)
6671
+ return refuseTopLevel(liveRunStoppedRefusal(epicKey, stoppedRunId));
6106
6672
  const blocked = previewReadinessRefusal(ctx, classification, readiness, planeTarget, "attach");
6107
6673
  if (blocked !== null)
6108
6674
  return refuseWithReadiness(classification.kind, blocked);
@@ -6147,6 +6713,8 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
6147
6713
  return refuseWithReadiness("operator_blocked", launch.refusal);
6148
6714
  observed.access = access;
6149
6715
  observed.launchTopology = launchTopology;
6716
+ if (refusePlanOrderNeeded())
6717
+ return;
6150
6718
  await finalizeCreatePreview(prepared?.ok ? { ...previewCtx, handoff: prepared.handoff, previewObservations: observations, previewMergedEvaluation: mergedEvaluation } : { ...previewCtx, previewObservations: observations, previewMergedEvaluation: mergedEvaluation }, preview, planPathForCreate, false, refuseTopLevel, live.kind === "live");
6151
6719
  await applyPreviewFreshness(ctx, preview, topology, false);
6152
6720
  }
@@ -6356,6 +6924,20 @@ async function finalizeCreatePreview(ctx, preview, planPath, coldStart, refuseTo
6356
6924
  const launch = classifyV2Readiness(payload.launchReadiness, { attended: options.attended, intoBase: options.intoBase });
6357
6925
  if (launch.kind === 'operator_blocked')
6358
6926
  return refuseTopLevel({ reasonId: launch.id, remedy: launch.remedy ?? 'Retry readiness.', authoritative: true });
6927
+ // BAPI-1526 — first approval would refuse this create's required checks. Read
6928
+ // ONLY on this policy-aware launch report (the actual create policy), and only
6929
+ // before a run exists: re-attaching to a live run is the recovery path, and an
6930
+ // approved run carries its own bound evidence. Anything but a proven denial
6931
+ // continues; approval stays the authority.
6932
+ if (payload.existingRunId === null && requiredChecksAdmissionVerdict(payload.launchReadiness) === "denied") {
6933
+ const denied = requiredChecksDeniedRecord(payload.launchReadiness);
6934
+ return refuseTopLevel({
6935
+ reasonId: REQUIRED_CHECKS_ADMISSION_REASON_ID,
6936
+ remedy: `${requiredChecksAdmissionRemedy(payload.launchReadiness)} Nothing was created.`,
6937
+ authoritative: true,
6938
+ ...(denied?.reason ? { reasonCode: denied.reason } : {}),
6939
+ });
6940
+ }
6359
6941
  }
6360
6942
  if (payload.effectivePolicy) {
6361
6943
  const facts = payload.effectivePolicy;
@@ -6391,6 +6973,11 @@ async function finalizeCreatePreview(ctx, preview, planPath, coldStart, refuseTo
6391
6973
  }
6392
6974
  preview.summary.auto_merge =
6393
6975
  intent.state === "off" ? { state: "off", reason: intent.reason } : { state: intent.state };
6976
+ // BAPI-1526 — the server's advisory forecast for THIS create policy (the
6977
+ // launch report). Absent on an older server; never changes the decision.
6978
+ const forecast = payload.launchReadiness?.merge_forecast;
6979
+ if (forecast !== undefined)
6980
+ preview.summary.auto_merge.forecast = forecast;
6394
6981
  preview.summary.auto_merge_scope = intent.state === "on" ? payload.featureBranch : null;
6395
6982
  // The bootstrap reusing a run IS an attach: it reports the run's id.
6396
6983
  if (payload.existingRunId !== null) {
@@ -6444,7 +7031,7 @@ async function applyPreviewFreshness(ctx, preview, topology, coldStart) {
6444
7031
  if (planeEndpointForBaseUrl(deps, ctx.access.baseUrl) === null)
6445
7032
  return;
6446
7033
  try {
6447
- const manifest = topology.manifest ?? null;
7034
+ const manifest = coldStart ? null : topology.manifest ?? null;
6448
7035
  const own = manifest !== null
6449
7036
  ? {
6450
7037
  repoRoot: manifest.repoRoot,
@@ -6453,7 +7040,12 @@ async function applyPreviewFreshness(ctx, preview, topology, coldStart) {
6453
7040
  ...(manifest.epicRunId ? { epicRunId: manifest.epicRunId } : {}),
6454
7041
  }
6455
7042
  : { repoRoot: deps.cwd(), ownsManifest: false };
6456
- const reports = coldStart ? null : await collectFreshnessObservations(ctx, own);
7043
+ // BAPI-1725: a cold start has no plane, so compare the CURRENT checkout's HEAD
7044
+ // (never a manifest's snapshot path) with origin/main; this feeds the same
7045
+ // assessor, override, and refusal as every other freshness observation.
7046
+ const reports = coldStart
7047
+ ? await collectCheckoutHeadFreshness(ctx, deps.cwd(), true)
7048
+ : await collectFreshnessObservations(ctx, own);
6457
7049
  // BAPI-1506: a `create` preview reports host sleep as a launch need on every
6458
7050
  // target (see appendLaunchNeedRows); only `attach` keeps it here.
6459
7051
  const sleep = preview.decision === "attach" ? await collectHostSleep(ctx, own.repoRoot) : null;