@bridge_gpt/mcp-server 0.2.74 → 0.2.76

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 (102) hide show
  1. package/README.md +14 -7
  2. package/build/agent-launchers/prompt.js +9 -21
  3. package/build/agents.generated.js +6 -6
  4. package/build/authored-plan.js +542 -0
  5. package/build/bridge-permissions.js +8 -0
  6. package/build/codex-auto-recovery.js +25 -7
  7. package/build/commands.generated.js +7 -7
  8. package/build/conductor/bridge-api-client.js +807 -52
  9. package/build/conductor/declare-blocked.js +4 -0
  10. package/build/conductor/driver-pass.js +8 -0
  11. package/build/conductor/epic-implementer-cli.js +341 -96
  12. package/build/conductor/epic-server-journal.js +13 -0
  13. package/build/conductor/epic-server-recipe.js +15 -5
  14. package/build/conductor/epic-server-runtime.js +163 -45
  15. package/build/conductor/epic-server.js +13 -6
  16. package/build/conductor/gate-discovery.js +209 -9
  17. package/build/conductor/gate-settings-review.js +7 -11
  18. package/build/conductor/install-doctor.js +30 -2
  19. package/build/conductor/launch-plan.js +58 -12
  20. package/build/conductor/local-merge.js +54 -12
  21. package/build/conductor/open-decision-phrases.js +50 -0
  22. package/build/conductor/pr-ci-producer.js +12 -3
  23. package/build/conductor/prerequisite-inputs.js +181 -14
  24. package/build/conductor/readiness-sections.js +46 -13
  25. package/build/conductor/readiness.js +3 -40
  26. package/build/conductor/recovery-cli.js +12 -12
  27. package/build/conductor/repository-workflow-remedy.js +147 -7
  28. package/build/conductor/ui-readiness.js +224 -0
  29. package/build/conductor/wait-run-attention.js +9 -4
  30. package/build/conductor/wait-run-cli.js +9 -2
  31. package/build/connect-github-api.js +18 -0
  32. package/build/connect-github.js +35 -18
  33. package/build/docs.generated.js +3 -3
  34. package/build/drive-epic.js +787 -37
  35. package/build/epic-ci-workflow.js +3 -2
  36. package/build/epic-implementer-bin.js +200 -66
  37. package/build/epic-implementer-bundle-cli.js +61 -0
  38. package/build/epic-implementer-claude-hook-bin.js +1 -1
  39. package/build/epic-implementer-env.js +3 -4
  40. package/build/epic-integration-pr.js +5 -2
  41. package/build/epic-launch-context.js +8 -1
  42. package/build/epic-shared/cut-protocol.js +55 -3
  43. package/build/executor/completion-contract.js +24 -1
  44. package/build/executor/failure-reason-codes.js +2 -0
  45. package/build/executor/gate-qualification-job.js +193 -23
  46. package/build/executor/gate-qualification-tests-ran.js +232 -0
  47. package/build/executor/integration-job.js +56 -2
  48. package/build/executor/job-runner.js +13 -723
  49. package/build/executor/job-type-wrappers.js +734 -0
  50. package/build/executor/merge-job.js +45 -1
  51. package/build/executor/permissions.js +187 -2
  52. package/build/executor/preflight.js +6 -2
  53. package/build/executor/process-containment.js +8 -1
  54. package/build/executor/provider-checks.js +28 -5
  55. package/build/executor/reconcile-overlap-job.js +70 -17
  56. package/build/executor/required-verification.js +28 -2
  57. package/build/executor/required-work-ledger.js +7 -2
  58. package/build/executor/resume-pre-spawn.js +32 -8
  59. package/build/executor/runner.js +30 -5
  60. package/build/executor/types.js +9 -0
  61. package/build/executor/worker-database.js +6 -1
  62. package/build/executor/worker-guard-hook.js +24 -2
  63. package/build/executor/worktree.js +12 -1
  64. package/build/generated/ticket-status.js +20 -0
  65. package/build/index.js +627 -551
  66. package/build/init.js +16 -0
  67. package/build/install-bridge-conductor-answers.js +32 -1
  68. package/build/install-bridge-conductor-apply.js +21 -3
  69. package/build/install-bridge-conductor-assessment.js +185 -12
  70. package/build/install-bridge-conductor-compact.js +2 -0
  71. package/build/install-bridge-conductor-contracts.js +9 -1
  72. package/build/install-bridge-conductor-gate.js +257 -80
  73. package/build/install-bridge-conductor-setup.js +106 -6
  74. package/build/install-bridge-conductor-trial-report.js +170 -0
  75. package/build/install-bridge-conductor.js +740 -124
  76. package/build/mcp-host-config.js +54 -37
  77. package/build/phase-context-git-probe.js +16 -0
  78. package/build/pipelines.generated.js +15 -15
  79. package/build/plan-execution-ledger.js +27 -0
  80. package/build/plan-generation.js +17 -0
  81. package/build/plane/plane-freshness.js +43 -26
  82. package/build/printed-remedy-commands.js +62 -0
  83. package/build/readme.generated.js +1 -1
  84. package/build/repository-toolchains.js +11 -5
  85. package/build/scripts/saved-commands-config-field-driver.js +65 -0
  86. package/build/secret-redaction.js +3 -0
  87. package/build/setup-epic.js +51 -9
  88. package/build/test-support/create-preview-world.js +232 -0
  89. package/build/test-support/executor-source-files.js +1 -1
  90. package/build/ticket-delivery.js +65 -0
  91. package/build/v2-readiness-requirements.js +13 -4
  92. package/build/version.generated.js +3 -3
  93. package/build/worker-guard-hook-bin.js +2 -2
  94. package/build/worktree-core.js +51 -7
  95. package/docs/EPIC-IMPLEMENTER.md +83 -4
  96. package/docs/epic-implementer/getting-started.md +1 -1
  97. package/docs/install/github-app.md +79 -92
  98. package/package.json +1 -1
  99. package/pipelines/implement-ticket.json +2 -2
  100. package/build/conductor/epic-reconcile.js +0 -603
  101. package/build/conductor/epic-runtime.js +0 -2020
  102. package/build/conductor/epic-state.js +0 -774
@@ -1,4 +1,5 @@
1
1
  import { isTerminalRunCleanupStatus } from "./plane/terminal-run-status.js";
2
+ import { redactSecrets } from "./secret-redaction.js";
2
3
  import { resolveDeclaredRunBaseBranch } from "./conductor/run-branch.js";
3
4
  import { monotonicNow, elapsedMs, measurePrecheck } from "./conductor/precheck-timings.js";
4
5
  import { buildLaunchPlan, LAUNCH_PRE_CREATE_CODES, PARALLEL_LIMIT_CHANGE_ADVISORY, PARALLEL_LIMIT_MEANING_COPY, SERVER_WEBHOOK_ROW_ID, } from "./conductor/launch-plan.js";
@@ -61,9 +62,13 @@ import { READINESS_PRE_CREATE_CODES, READINESS_PREREQUISITE_BY_ID, READINESS_LEG
61
62
  * ratcheted down, and a tool would be useless in a bare-chat session anyway,
62
63
  * where the model has no tool call to make.
63
64
  */
64
- 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";
65
66
  import { constants as fsConstants } from "node:fs";
66
67
  import path, { dirname, join } from "node:path";
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";
67
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";
68
73
  import { CHILD_MERGE_STATUS_BATCH_SIZE, buildAlreadyDoneEntries, classifyPlanChildren, selectSkips, } from "./conductor/merged-child-check.js";
69
74
  import { trimDonePlanNodes } from "./conductor/plan-trim.js";
@@ -87,6 +92,8 @@ import { policyDeclaresNotifyWebhook, policyNotifyDestinationsConflict, notifyDe
87
92
  import { getConfigFieldBaseBranch } from "./epic-shared/bridge-client.js";
88
93
  import { createExecFileRunCommand, normalizeCommitSha } from "./epic-shared/cut-protocol.js";
89
94
  import { EPIC_KEY_PATTERN } from "./drive-epic-key.js";
95
+ 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";
96
+ import { hashPlan } from "./conductor/plan.js";
90
97
  import { buildEpicLaunchContext, projectWorkerDatabase, readEpicLaunchContext, writeEpicLaunchContext, writeEpicLaunchOutcome, } from "./epic-launch-context.js";
91
98
  import { flushProcessStdout, writeJsonDocument } from "./conductor/json-output.js";
92
99
  import { BRIDGE_LAUNCHER_ENV } from "./bridge-permissions.js";
@@ -106,12 +113,15 @@ import { resolveMemberInstanceId } from "./plane/supervisor.js";
106
113
  import { validateBranchName } from "./base-ref.js";
107
114
  import { createDefaultRunExecutorLaunchDeps, ensureRunExecutor as ensureRunExecutorDefault, prepareRunExecutor as prepareRunExecutorDefault, } from "./executor-launch.js";
108
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";
109
119
  // BAPI-806: mcp-identity.ts is the SOLE source of the package-name literal, so
110
120
  // the printed invocation interpolates it rather than repeating it.
111
121
  import { MCP_PACKAGE_NAME } from "./mcp-identity.js";
112
122
  import { getDriveEpicAdvancedUsage, getDriveEpicUsage } from "./drive-epic-help.js";
113
123
  export { getDriveEpicUsage };
114
- import { CONSUMER_GUIDE_POINTER, PRINTED_CHECK_NAME_INSTRUCTION, PRINTED_CONDUCTOR_INSTALL_COMMAND, PRINTED_DOCTOR_COMMAND, READINESS_PREREQUISITE_FIXES, resolveReadinessRemedy, } from "./printed-remedy-commands.js";
124
+ import { CONSUMER_GUIDE_POINTER, PRINTED_CHECK_NAME_INSTRUCTION, PRINTED_CONDUCTOR_INSTALL_COMMAND, PRINTED_DOCTOR_COMMAND, READINESS_PREREQUISITE_FIXES, classifyReadinessFix, indexedWorkflowsDisplayRemedy, resolveReadinessRemedy, } from "./printed-remedy-commands.js";
115
125
  /** The conductor paths. Derived types below come from this constant. */
116
126
  export const DRIVE_EPIC_CONDUCTORS = ["v2"];
117
127
  /**
@@ -216,10 +226,18 @@ launchEvidence) {
216
226
  // which reads the policy and refuses if it declares none. Nothing is weakened:
217
227
  // `setup-epic` gates before the create, and the server re-checks the predicate
218
228
  // at approval and probes the URL there.
219
- const deferred = options.approvedStoredPolicy ||
229
+ const notifyDeferred = options.approvedStoredPolicy ||
220
230
  options.effectivePolicy?.escalationChannel === "configured webhook" ||
221
- (options.effectivePolicy === undefined && options.hasPolicyFile)
222
- ? 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"))
223
241
  : V2_READINESS_REQUIREMENTS;
224
242
  // `--into-base` is the second opt-out, and it is structural rather than
225
243
  // declared: it selects the branch-silent composition, whose policy carries no
@@ -319,16 +337,44 @@ function indexedWorkflowsRemedy(readiness) {
319
337
  const fix = row.fix.length > 0
320
338
  ? row.fix
321
339
  : resolveReadinessRemedy({ id: INDEXED_WORKFLOWS_ROW_ID, state: row.check_status === "unknown" ? "unknown" : "not_met" });
322
- if (fix === READINESS_PREREQUISITE_FIXES.no_index || fix === READINESS_PREREQUISITE_FIXES.reindex_manual) {
323
- return READINESS_PREREQUISITE_FIXES.reindex_manual;
340
+ // BAPI-1700 — the exact missing-workflow wire fix gets the display wording that
341
+ // names both ways forward. This must run before the passthrough below, which would
342
+ // otherwise print the managed-workflow instruction as is. Presentation only: the
343
+ // validated row keeps the server's fix.
344
+ const display = indexedWorkflowsDisplayRemedy({ id: row.id, fix }, readiness);
345
+ if (display !== fix)
346
+ return display;
347
+ // Exact known strings first; every other exact key and unknown text falls through
348
+ // to the substring predicates below, unchanged.
349
+ switch (classifyReadinessFix(fix)) {
350
+ case "no_index":
351
+ case "reindex_manual":
352
+ return READINESS_PREREQUISITE_FIXES.reindex_manual;
353
+ case "pending_index":
354
+ return "Wait for indexing to finish, then run drive-epic again.";
355
+ case "setup":
356
+ case "missing_workflow":
357
+ case "missing_review_and_managed_workflows":
358
+ return fix;
359
+ default:
360
+ break;
324
361
  }
325
- if (fix === READINESS_PREREQUISITE_FIXES.pending_index)
326
- return "Wait for indexing to finish, then run drive-epic again.";
327
362
  if (fix.includes("Merge the setup pull request") || fix === READINESS_PREREQUISITE_FIXES.setup || fix.includes("merge the workflow changes"))
328
363
  return fix;
329
364
  return INDEXED_WORKFLOWS_UNCLASSIFIED;
330
365
  }
331
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
+ }
332
378
  /**
333
379
  * Parse argv. Rejects malformed input BEFORE any side effect — no readiness
334
380
  * read, no credential resolution, no delegation.
@@ -1187,6 +1233,9 @@ export async function readLiveEpicRunByKey(access, epicKey, fetchImpl = globalTh
1187
1233
  }
1188
1234
  }
1189
1235
  export function createDefaultDriveEpicDeps() {
1236
+ // BAPI-1706 — the environment before any launch-target adoption (see the
1237
+ // authored-plan seams below). A copy, so later adoption cannot change it.
1238
+ const normalServerEnv = { ...process.env };
1190
1239
  return {
1191
1240
  inspectRepositoryIdentity: async () => {
1192
1241
  const top = await createPlaneExecFile()("git", ["rev-parse", "--show-toplevel"], {
@@ -1256,12 +1305,16 @@ export function createDefaultDriveEpicDeps() {
1256
1305
  fs: createPlaneFsDeps(),
1257
1306
  ...(applicability?.isBridge === false ? { isBridge: false } : {}),
1258
1307
  }),
1259
- collectPlaneFreshness: ({ repoRoot, ownsManifest, expectedPlaneId }) => checkPlaneFreshness(repoRoot, {
1308
+ collectPlaneFreshness: ({ repoRoot, ownsManifest, expectedPlaneId, snapshotFromCheckoutHead }) => checkPlaneFreshness(repoRoot, {
1260
1309
  execFile: createPlaneExecFile(),
1261
1310
  fileExists: (filePath) => fsStat(filePath).then((entry) => entry.isFile(), () => false),
1262
1311
  platform: process.platform,
1263
1312
  readPlaneManifest: (root) => readPlaneManifest(root, createPlaneFsDeps()),
1264
- }, repoRoot, { ownsManifest, ...(expectedPlaneId !== undefined ? { expectedPlaneId } : {}) }),
1313
+ }, repoRoot, {
1314
+ ownsManifest,
1315
+ ...(expectedPlaneId !== undefined ? { expectedPlaneId } : {}),
1316
+ ...(snapshotFromCheckoutHead === true ? { snapshotFromCheckoutHead: true } : {}),
1317
+ }),
1265
1318
  inspectHostSleep: (repoRoot) => inspectHostSleep(repoRoot, { execFile: createPlaneExecFile(), platform: process.platform }),
1266
1319
  inspectRequiredRunners: ({ repoRoot, providerRepository, gateProfile }) => inspectRequiredSelfHostedRunners({
1267
1320
  repoRoot,
@@ -1291,6 +1344,12 @@ export function createDefaultDriveEpicDeps() {
1291
1344
  clearTimeout(timer);
1292
1345
  }
1293
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) }),
1294
1353
  execEngineStatus: createPlaneExecFile(),
1295
1354
  cleanupTerminalRunPlane: (input) => cleanupTerminalRunPlane(input, createTerminalRunCleanupDeps(process.env)),
1296
1355
  listLiveRunIds: (access) => createTerminalRunCleanupDeps(process.env).listLiveRunIds(access),
@@ -1344,6 +1403,22 @@ export function createDefaultDriveEpicDeps() {
1344
1403
  validate: () => validateGeneratedPlan(access, epicKey, dag, (a, request) => validateEpicPlan(a, request)),
1345
1404
  rediscover: () => discoverEpicPlan(epicKey, docsDir, createDefaultPlanDiscoveryFs()),
1346
1405
  }),
1406
+ // BAPI-1706 — authored plans live on the normal Bridge server. The launch
1407
+ // adopts its target into `process.env.BAPI_BASE_URL` (adoptLaunchTarget) before
1408
+ // these run, so both resolve against the environment captured HERE, before any
1409
+ // adoption: a local-plane or --base-url launch still reads the normal server.
1410
+ lookupAuthoredPlan: (epicKey, repo) => lookupAuthoredPlanForLaunch(epicKey, repo, normalServerEnv),
1411
+ uploadAuthoredPlan: ({ epicKey, planDir, repo }) => saveLocalAuthoredPlan({
1412
+ ...createDefaultAuthoredPlanSaveDeps(),
1413
+ env: normalServerEnv,
1414
+ resolveAccess: (r) => resolveAuthoredPlanAccess(r, normalServerEnv),
1415
+ }, {
1416
+ epicKey,
1417
+ planDir,
1418
+ ...(repo !== undefined ? { repo } : {}),
1419
+ ifAbsent: true,
1420
+ }),
1421
+ materializeAuthoredPlan: (snapshot) => materializeAuthoredPlanSnapshot(snapshot),
1347
1422
  readPolicyFile: (filePath) => readFile(filePath, "utf8"),
1348
1423
  readLiveEpicRun: (access, epicKey) => readLiveEpicRunByKey(access, epicKey),
1349
1424
  previewSetupEpic: async ({ argv, baseUrl, handoff, observations, planContents }) => {
@@ -1439,6 +1514,8 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1439
1514
  if (parsed.options.dryRun === true) {
1440
1515
  return await runDriveEpicPreview(deps, parsed.options);
1441
1516
  }
1517
+ // BAPI-1706 — private server-plan hand-off folders, removed however the launch ends.
1518
+ const authoredPlanCleanups = [];
1442
1519
  try {
1443
1520
  // Every async branch below is `return await`ed. A bare `return promise`
1444
1521
  // inside this `try` would let a rejection skip the sanitizing `catch` at the
@@ -1493,9 +1570,34 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1493
1570
  let planWasDiscovered = false;
1494
1571
  // BAPI-1621 — why automatic generation stopped, for the no-plan stop text.
1495
1572
  let generationReason;
1573
+ // BAPI-1706 — with no `--plan-file`, the normal Bridge server is asked FIRST, ONCE.
1574
+ // A found snapshot is the plan for this whole invocation; local files are only
1575
+ // compared with it. An unknown answer never falls back to a local or generated
1576
+ // plan: it stops when (and only when) the launch would create a run.
1577
+ let serverPlan = null;
1578
+ let authoredLookup = null;
1579
+ if (planFile === undefined && deps.lookupAuthoredPlan !== undefined) {
1580
+ authoredLookup = await deps
1581
+ .lookupAuthoredPlan(epicKey, repo)
1582
+ .catch(() => ({ lookup: { kind: "unknown", reason: "network" }, endpoint: null }));
1583
+ if (authoredLookup.lookup.kind === "found") {
1584
+ serverPlan = authoredLookup.lookup.snapshot;
1585
+ planWasDiscovered = true;
1586
+ ctx = { ...ctx, planProvenance: serverPlanProvenance(serverPlan, authoredLookup.endpoint), planHashEvidence: {} };
1587
+ }
1588
+ else if (authoredLookup.lookup.kind === "server_too_old") {
1589
+ deps.errorLog(`${epicKey}: ${AUTHORED_PLAN_SERVER_TOO_OLD_NOTICE}`);
1590
+ }
1591
+ }
1592
+ const authoredPlanUnknown = authoredLookup?.lookup.kind === "unknown";
1496
1593
  if (planFile === undefined) {
1497
1594
  const docs = await deps.resolveDocsDir();
1498
- if (docs.ok) {
1595
+ if (serverPlan !== null || authoredPlanUnknown) {
1596
+ // The local copy is observational only: it never displaces a verified server plan.
1597
+ if (serverPlan !== null && docs.ok)
1598
+ await observeIgnoredLocalPlan(ctx, docs.docsDir, serverPlan);
1599
+ }
1600
+ else if (docs.ok) {
1499
1601
  discovered = await discoverEpicPlan(epicKey, docs.docsDir, deps.discoveryFs);
1500
1602
  if (discovered.status === "plan_not_found") {
1501
1603
  const generated = await generateMissingPlanForLaunch(ctx, docs.docsDir, discovered);
@@ -1511,12 +1613,84 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1511
1613
  docsRootUnresolved = true;
1512
1614
  }
1513
1615
  }
1616
+ if (ctx.planProvenance === undefined) {
1617
+ const source = planFile !== undefined
1618
+ ? "explicit"
1619
+ : discovered?.status === "found"
1620
+ ? discovered.generated !== undefined
1621
+ ? "generated"
1622
+ : "local"
1623
+ : null;
1624
+ if (source !== null)
1625
+ ctx = { ...ctx, planProvenance: nonServerPlanProvenance(source), planHashEvidence: {} };
1626
+ }
1627
+ /**
1628
+ * BAPI-1706 — a local-only authored plan is uploaded (with `if_absent`) the first
1629
+ * time a REAL launch would create a run from it, and only after a definite "no
1630
+ * plan stored". The launch then uses exactly the snapshot the server returned —
1631
+ * its own, or a concurrent writer's. A generated plan is never uploaded.
1632
+ */
1633
+ const uploadLocalPlanIfNeeded = async () => {
1634
+ if (serverPlan !== null ||
1635
+ authoredLookup?.lookup.kind !== "not_stored" ||
1636
+ discovered?.status !== "found" ||
1637
+ discovered.generated !== undefined ||
1638
+ deps.uploadAuthoredPlan === undefined) {
1639
+ return { ok: true };
1640
+ }
1641
+ const uploaded = await deps
1642
+ .uploadAuthoredPlan({ epicKey, planDir: dirname(discovered.path), repo })
1643
+ .catch(() => null);
1644
+ if (uploaded === null || !uploaded.ok) {
1645
+ const retry = uploaded !== null && !uploaded.ok
1646
+ ? uploaded.retryCommand
1647
+ : `npx -y ${MCP_PACKAGE_NAME} epic-plan save --epic-key ${epicKey}`;
1648
+ return {
1649
+ ok: false,
1650
+ code: refuse(deps, [
1651
+ `${epicKey}: REFUSED (${AUTHORED_PLAN_UPLOAD_FAILED_REASON_ID}) — ${authoredPlanUploadFailedRemedy(retry)}`,
1652
+ ]),
1653
+ };
1654
+ }
1655
+ serverPlan = uploaded.result.snapshot;
1656
+ deps.log(`${epicKey}: saved the local plan to the Bridge server as authored version ` +
1657
+ `${serverPlan.authored_version}${uploaded.created ? "" : " (another save got there first; using it)"}.`);
1658
+ const provenance = serverPlanProvenance(serverPlan, uploaded.endpoint);
1659
+ if (ctx.planProvenance !== undefined)
1660
+ Object.assign(ctx.planProvenance, provenance);
1661
+ else
1662
+ ctx = { ...ctx, planProvenance: provenance, planHashEvidence: {} };
1663
+ return { ok: true };
1664
+ };
1665
+ /** Write the selected server snapshot to a private folder and select it for setup. */
1666
+ const selectServerPlanFile = async () => {
1667
+ if (serverPlan === null)
1668
+ return;
1669
+ const materialize = deps.materializeAuthoredPlan ?? materializeAuthoredPlanSnapshot;
1670
+ const written = await materialize(serverPlan);
1671
+ authoredPlanCleanups.push(() => written.cleanup());
1672
+ ctx = { ...ctx, options: { ...ctx.options, planFile: written.planPath } };
1673
+ };
1514
1674
  let foundPlanAnnounced = false;
1515
1675
  /** Names the found plan once, BEFORE anything is created, and surfaces its advisory. */
1516
1676
  const announceFoundPlan = async () => {
1517
- if (foundPlanAnnounced || discovered?.status !== "found")
1677
+ if (foundPlanAnnounced)
1678
+ return;
1679
+ if (serverPlan !== null && ctx.planProvenance !== undefined) {
1680
+ foundPlanAnnounced = true;
1681
+ deps.log(renderPlanProvenanceLine(epicKey, ctx.planProvenance));
1682
+ // BAPI-1706 — the stored eligibility advisory, the one the author saw.
1683
+ const advisory = serverPlan.eligibility_advisory !== null ? parseContainmentEligibilityArtifact(serverPlan.eligibility_advisory) : null;
1684
+ const advisoryText = advisory !== null ? renderContainmentEligibilityAdvisory(advisory) : null;
1685
+ if (advisoryText !== null)
1686
+ deps.log(advisoryText);
1687
+ return;
1688
+ }
1689
+ if (discovered?.status !== "found")
1518
1690
  return;
1519
1691
  foundPlanAnnounced = true;
1692
+ if (ctx.planProvenance !== undefined)
1693
+ deps.log(renderPlanProvenanceLine(epicKey, ctx.planProvenance));
1520
1694
  deps.log(`${epicKey}: using the plan found by epic key: ${discovered.path}`);
1521
1695
  };
1522
1696
  // --- No readiness read at launch (BAPI-1595). -----------------------------
@@ -1534,10 +1708,11 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1534
1708
  (discovered.status === "plan_not_found" || discovered.status === "plan_ambiguous")
1535
1709
  ? discovered
1536
1710
  : null;
1537
- if (planeEndpoint !== null && (ctx.options.planFile !== undefined || noPlanDiscovery !== null)) {
1711
+ if (planeEndpoint !== null &&
1712
+ (ctx.options.planFile !== undefined || noPlanDiscovery !== null || serverPlan !== null)) {
1538
1713
  const probe = await deps.probePlanePort(planeEndpoint.host, planeEndpoint.port).catch(() => ({ kind: "error" }));
1539
1714
  if (probe.kind === "refused") {
1540
- if (ctx.options.planFile !== undefined) {
1715
+ if (ctx.options.planFile !== undefined || serverPlan !== null) {
1541
1716
  // BAPI-1260 — only a SELECTED LOCAL plane is ever started here. A
1542
1717
  // profile approved for durable execution names an authority this
1543
1718
  // machine does not own, so a refused port is that authority being
@@ -1546,6 +1721,12 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1546
1721
  return escalate(deps, epicKey, `launch profile '${launchProfile.name}' selects durable execution, and its control plane is ` +
1547
1722
  "not answering; no local replacement was started");
1548
1723
  }
1724
+ // BAPI-1706 — a cold start creates a run, so a local-only plan is uploaded
1725
+ // first and the server snapshot is what the new plane receives.
1726
+ const upload = await uploadLocalPlanIfNeeded();
1727
+ if (!upload.ok)
1728
+ return upload.code;
1729
+ await selectServerPlanFile();
1549
1730
  // `coldStartPlane` surfaces the containment advisory itself.
1550
1731
  await announceFoundPlan();
1551
1732
  return await coldStartPlane(ctx);
@@ -1601,7 +1782,40 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1601
1782
  // A supplied plan always wins and skips ALL of this, including the extra
1602
1783
  // live-run read: setup-epic does its own Step 0 read and owns reuse.
1603
1784
  let discoveryStop;
1604
- if (planFile === undefined) {
1785
+ if (planFile === undefined && (serverPlan !== null || authoredPlanUnknown)) {
1786
+ // BAPI-1706 — the server answered "found", or could not answer. The live-run
1787
+ // decision still comes first: a live run is attached to with the plan it was
1788
+ // created with, and nothing is uploaded or written.
1789
+ const live = await acquireObservedLive(ctx);
1790
+ if (live.kind === "conflict")
1791
+ return refuse(deps, liveRunAmbiguousRefusal(epicKey).lines);
1792
+ // BAPI-1714 — a `planning` run with a stored server plan is an INCOMPLETE
1793
+ // setup, not a live run to attach to: it has not been approved yet. It
1794
+ // falls through to the setup path below, which reuses the planning run.
1795
+ // Every other live status keeps attaching.
1796
+ if (live.kind === "live" && !isPlanningSetupToFinish(live, serverPlan)) {
1797
+ if (serverPlan !== null) {
1798
+ deps.log(`${epicKey}: a run is already live; it keeps the plan it was created with.`);
1799
+ }
1800
+ return await attachToLiveRun(ctx, readiness, live);
1801
+ }
1802
+ if (serverPlan === null) {
1803
+ return refuse(deps, [
1804
+ `${epicKey}: REFUSED (${AUTHORED_PLAN_UNKNOWN_REASON_ID}) — ${authoredPlanUnknownRemedy(epicKey, repo)}`,
1805
+ ]);
1806
+ }
1807
+ await selectServerPlanFile();
1808
+ const prepared = await prepareSetupSelection(ctx);
1809
+ if (!prepared.ok) {
1810
+ return refuse(deps, [
1811
+ `${epicKey}: REFUSED (${prepared.reasonId}) — the selected run or policy could not be verified.`,
1812
+ "Nothing was created or started.",
1813
+ ]);
1814
+ }
1815
+ ctx = { ...ctx, handoff: prepared.handoff };
1816
+ await announceFoundPlan();
1817
+ }
1818
+ else if (planFile === undefined) {
1605
1819
  if (docsRootUnresolved || discovered === null) {
1606
1820
  return refuse(deps, docsRootRefusal(epicKey).lines);
1607
1821
  }
@@ -1622,6 +1836,12 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1622
1836
  const { planFile: _unusedDiscoveredPlan, ...attachOptions } = ctx.options;
1623
1837
  return await attachToLiveRun({ ...ctx, options: attachOptions }, readiness, live, discovered.path);
1624
1838
  }
1839
+ // BAPI-1706 — the first real create from a local-only authored plan uploads
1840
+ // it, then runs the server-confirmed snapshot.
1841
+ const upload = await uploadLocalPlanIfNeeded();
1842
+ if (!upload.ok)
1843
+ return upload.code;
1844
+ await selectServerPlanFile();
1625
1845
  // The create path: setup selection runs now. The plan was folded into
1626
1846
  // `ctx.options` before readiness; from here it is indistinguishable from
1627
1847
  // a supplied `--plan-file`.
@@ -1864,6 +2084,10 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1864
2084
  deps.errorLog(`drive-epic failed: ${safeDiagnosticMessage(err, "unexpected error")}`);
1865
2085
  return 1;
1866
2086
  }
2087
+ finally {
2088
+ for (const cleanup of authoredPlanCleanups)
2089
+ await cleanup();
2090
+ }
1867
2091
  }
1868
2092
  /**
1869
2093
  * BAPI-1285 — the one remedy sentence an unknown-readiness escalation ends with.
@@ -1899,8 +2123,17 @@ function escalate(deps, epicKey, reason) {
1899
2123
  deps.errorLog(text);
1900
2124
  return 1;
1901
2125
  }
1902
- /** BAPI-1686 — said on every healthy-launch success output. */
2126
+ /**
2127
+ * BAPI-1686 — said on the healthy plane-launch and plane-attach success paths,
2128
+ * where the plane's processes belong to this terminal. A run-scoped executor
2129
+ * prints {@link RUN_EXECUTOR_DETACHED_LINE} instead.
2130
+ */
1903
2131
  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.";
2132
+ /**
2133
+ * BAPI-1725 — said once after a run-scoped executor outcome. That executor is
2134
+ * started detached, so closing the terminal or session does not stop it.
2135
+ */
2136
+ 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.";
1904
2137
  /** The prefix of the default launch-report line. */
1905
2138
  export const LAUNCH_REPORT_PREFIX = "Launch report: ";
1906
2139
  /** How long drive-epic watches a planning run for activation after an uncertain approve. */
@@ -1995,6 +2228,61 @@ async function planGenerationAllowed(fs, epicKey, discovery, attempt) {
1995
2228
  function observeLaunch(ctx, code, message) {
1996
2229
  ctx.launchObservations?.push({ code, message, at: launchNowIso(ctx) });
1997
2230
  }
2231
+ /** BAPI-1706 — the observation code for a local plan that differs from the server plan. */
2232
+ export const LOCAL_PLAN_IGNORED_CODE = "local_plan_ignored";
2233
+ /**
2234
+ * BAPI-1706 — compare the local authored plan (if any) with the selected server
2235
+ * snapshot. A differing readable local DAG is named, never used. A failed read or
2236
+ * an ambiguous folder never displaces or blocks the verified server plan.
2237
+ * Returns the ignored path, or null.
2238
+ */
2239
+ async function localPlanIgnoredPath(deps, epicKey, docsDir, serverPlan) {
2240
+ try {
2241
+ const local = await discoverEpicPlan(epicKey, docsDir, deps.discoveryFs);
2242
+ if (local.status !== "found" || local.generated !== undefined)
2243
+ return null;
2244
+ const parsed = JSON.parse(await deps.readPlanDag(local.path));
2245
+ const localHash = hashPlan(parsed);
2246
+ return localHash === serverPlan.plan_hash ? null : local.path;
2247
+ }
2248
+ catch {
2249
+ return null;
2250
+ }
2251
+ }
2252
+ async function observeIgnoredLocalPlan(ctx, docsDir, serverPlan) {
2253
+ const ignored = await localPlanIgnoredPath(ctx.deps, ctx.epicKey, docsDir, serverPlan);
2254
+ if (ignored === null)
2255
+ return;
2256
+ const message = `local plan ignored: ${ignored} differs from the stored plan (authored version ` +
2257
+ `${serverPlan.authored_version}). Pass it with --plan-file to use it, or save it with epic-plan save.`;
2258
+ observeLaunch(ctx, LOCAL_PLAN_IGNORED_CODE, message);
2259
+ ctx.deps.errorLog(`${ctx.epicKey}: ${message}`);
2260
+ }
2261
+ /**
2262
+ * BAPI-1706 — fill the run-hash fields of the provenance from what setup-epic
2263
+ * stored. Only a store made in this invocation reports a run hash.
2264
+ */
2265
+ function recordRunPlanHash(ctx, result) {
2266
+ const provenance = ctx.planProvenance;
2267
+ if (provenance === undefined || result.storedPlanHash === undefined)
2268
+ return;
2269
+ provenance.run_plan_hash = result.storedPlanHash;
2270
+ if (provenance.plan_hash === null)
2271
+ return;
2272
+ const reasons = explainRunPlanHash({
2273
+ authoredHash: provenance.plan_hash,
2274
+ runHash: result.storedPlanHash,
2275
+ ...(ctx.planHashEvidence?.trimmedHash !== undefined ? { trimmedHash: ctx.planHashEvidence.trimmedHash } : {}),
2276
+ ...(result.orderingEdgesAdded !== undefined ? { orderingEdgesAdded: result.orderingEdgesAdded } : {}),
2277
+ });
2278
+ if (reasons.length === 0) {
2279
+ delete provenance.hash_difference;
2280
+ return;
2281
+ }
2282
+ provenance.hash_difference = reasons;
2283
+ ctx.deps.log(`${ctx.epicKey}: the run's plan hash ${result.storedPlanHash.slice(0, 12)} differs from the authored hash ` +
2284
+ `${provenance.plan_hash.slice(0, 12)} (${reasons.join(", ")}).`);
2285
+ }
1998
2286
  // ---------------------------------------------------------------------------
1999
2287
  // BAPI-1595 — fixed tally lines and stable reason codes
2000
2288
  // ---------------------------------------------------------------------------
@@ -2014,6 +2302,14 @@ export const LIVE_RUN_UNKNOWN_REASON_CODE = "live_run_unknown_continued";
2014
2302
  /** A mandatory diagnostic whose verdict or classification was not established. */
2015
2303
  export const MANDATORY_DIAGNOSTIC_UNKNOWN_WARNING = "mandatory diagnostic: unknown, continuing; server create and approve decide";
2016
2304
  export const MANDATORY_DIAGNOSTIC_UNKNOWN_REASON_CODE = "mandatory_diagnostic_unknown_continued";
2305
+ /**
2306
+ * BAPI-1714 — the repository's review and CI workflows could not be verified.
2307
+ * Preview continues (an unverifiable read is not a proven deficiency), but first
2308
+ * approval re-checks them and may still refuse, so the preview does not promise
2309
+ * approval.
2310
+ */
2311
+ export const REPOSITORY_WORKFLOWS_UNVERIFIABLE_WARNING = "Repository workflows could not be verified. Preview continues; first approval " +
2312
+ "will re-check them and may refuse if they remain unverifiable.";
2017
2313
  /** The escalation channel evidence was not established, so no "no channel" claim is made. */
2018
2314
  export const ESCALATION_CHANNEL_UNCERTAIN_WARNING = "escalation channel: unconfirmed, continuing; server create and approve decide";
2019
2315
  export const ESCALATION_CHANNEL_UNCERTAIN_REASON_CODE = "escalation_channel_unconfirmed_continued";
@@ -2203,6 +2499,7 @@ async function reportLaunchOutcome(ctx, outcome, facts) {
2203
2499
  invoked_at: ctx.invokedAt ?? at,
2204
2500
  first_claimed_job_at: "pending",
2205
2501
  observations,
2502
+ ...(ctx.planProvenance !== undefined ? { plan: { ...ctx.planProvenance } } : {}),
2206
2503
  };
2207
2504
  ctx.deps.reportLaunch?.(report);
2208
2505
  // The durable record: best-effort, so a write failure never changes the exit code.
@@ -2617,7 +2914,9 @@ function reportPlaneCapacity(ctx, lanes, storedLimit, posture) {
2617
2914
  * its caller returns its exit code without requesting lanes or an executor.
2618
2915
  */
2619
2916
  async function runSelectedSetupEpic(ctx) {
2620
- return settleSetupLaunch(ctx, await runSelectedSetupEpicWorkflow(ctx));
2917
+ const result = await runSelectedSetupEpicWorkflow(ctx);
2918
+ recordRunPlanHash(ctx, result);
2919
+ return settleSetupLaunch(ctx, result);
2621
2920
  }
2622
2921
  async function runSelectedSetupEpicWorkflow(ctx) {
2623
2922
  const selected = ctx.handoff
@@ -2688,6 +2987,15 @@ async function runSelectedSetupEpicWorkflow(ctx) {
2688
2987
  }
2689
2988
  }
2690
2989
  const trimmed = trimDonePlanNodes(evaluation.plan, evaluation.skipKeys);
2990
+ // BAPI-1706 — the post-trim hash, so a run hash that differs only by the trim is explained.
2991
+ if (ctx.planHashEvidence !== undefined) {
2992
+ try {
2993
+ ctx.planHashEvidence.trimmedHash = hashPlan(trimmed);
2994
+ }
2995
+ catch {
2996
+ // No evidence recorded: a differing run hash is then reported as unknown.
2997
+ }
2998
+ }
2691
2999
  const withPath = deps.withPlanPath ?? withPlanPath;
2692
3000
  const result = await withPath({
2693
3001
  originalPath: planPath,
@@ -3091,6 +3399,42 @@ async function collectFreshnessObservations(ctx, own) {
3091
3399
  }
3092
3400
  return pending;
3093
3401
  }
3402
+ /**
3403
+ * BAPI-1725 — the cold-start observation: the CURRENT checkout's `HEAD` against
3404
+ * `origin/main`, before any plane exists. Snapshot only: it reads no manifest and
3405
+ * no database, so a stale or absent manifest can never redirect or hide it, and
3406
+ * no database row is ever fabricated. `null` when nothing applies (a non-plane
3407
+ * target, a missing collector, or a collector that fails): unproven evidence is
3408
+ * never a refusal.
3409
+ *
3410
+ * The preview shares one read per invocation (`cached`); a launch reads fresh, so
3411
+ * it never reuses an earlier preview's result.
3412
+ */
3413
+ async function collectCheckoutHeadFreshness(ctx, repoRoot, cached) {
3414
+ const { deps } = ctx;
3415
+ if (planeEndpointForBaseUrl(deps, ctx.access.baseUrl) === null)
3416
+ return null;
3417
+ const collect = deps.collectPlaneFreshness;
3418
+ if (collect === undefined)
3419
+ return null;
3420
+ const read = () => collect({ repoRoot, ownsManifest: false, snapshotFromCheckoutHead: true }).catch(() => null);
3421
+ let observed;
3422
+ if (cached) {
3423
+ const cache = ctx.freshness ?? createPlaneFreshnessCache();
3424
+ const key = `${repoRoot}\u0000checkout-head`;
3425
+ let pending = cache.observations.get(key);
3426
+ if (pending === undefined) {
3427
+ pending = read();
3428
+ cache.observations.set(key, pending);
3429
+ }
3430
+ observed = await pending;
3431
+ }
3432
+ else {
3433
+ observed = await read();
3434
+ }
3435
+ // Only the snapshot report is used, whatever else a collector returned.
3436
+ return observed === null ? null : { snapshot: observed.snapshot };
3437
+ }
3094
3438
  async function collectHostSleep(ctx, repoRoot) {
3095
3439
  const { deps } = ctx;
3096
3440
  if (planeEndpointForBaseUrl(deps, ctx.access.baseUrl) === null)
@@ -3233,10 +3577,13 @@ cleanupPreview = null) {
3233
3577
  ? formatSharedPlaneStaleRemedy(boundRun, cleanupPreview.kind === "live" ? cleanupPreview.epicRunId : null)
3234
3578
  : formatBoundPlaneStaleRemedy(boundRun),
3235
3579
  });
3236
- project(PLANE_DATABASE_HEAD_ID, "Plane database head", reports.database, {
3237
- reasonId: "plane-database-head-mismatch",
3238
- remedy: PLANE_DATABASE_HEAD_REMEDY,
3239
- });
3580
+ // A snapshot-only observation (BAPI-1725) carries no database report; none is invented.
3581
+ if ("database" in reports) {
3582
+ project(PLANE_DATABASE_HEAD_ID, "Plane database head", reports.database, {
3583
+ reasonId: "plane-database-head-mismatch",
3584
+ remedy: PLANE_DATABASE_HEAD_REMEDY,
3585
+ });
3586
+ }
3240
3587
  }
3241
3588
  if (sleep !== null) {
3242
3589
  const duration_ms = sleep.duration_ms ?? elapsedMs(monotonicNow());
@@ -3351,6 +3698,52 @@ async function planeFreshnessCreateGuard(ctx, own, trailer = []) {
3351
3698
  return null;
3352
3699
  }
3353
3700
  }
3701
+ /**
3702
+ * BAPI-1725 — the pre-launch freshness guard for a cold start. It reads the
3703
+ * current checkout's `HEAD` against `origin/main` (a fresh read, never the
3704
+ * preview's), runs the observation through {@link assessPlaneFreshness}
3705
+ * unchanged, and refuses only a confirmed, non-overridden stale result.
3706
+ *
3707
+ * Nothing has started when this refuses, so the output ends with `Nothing was
3708
+ * started.` and carries no running-plane trailer. Unverified evidence logs the
3709
+ * existing warning and the launch continues; an unexpected failure of this
3710
+ * advisory read never stops a launch. A confirmed non-Bridge checkout skips it.
3711
+ */
3712
+ async function coldStartCheckoutHeadGuard(ctx, repoRoot) {
3713
+ if (isConfirmedNonBridge(ctx))
3714
+ return null;
3715
+ try {
3716
+ const reports = await collectCheckoutHeadFreshness(ctx, repoRoot, false);
3717
+ if (reports === null)
3718
+ return null;
3719
+ const assessment = assessPlaneFreshness(reports, null, "create", ctx.options.allowStalePlane === true);
3720
+ const refusal = freshnessRefusalOf(assessment.blockers);
3721
+ const adverse = adverseFreshnessRows(assessment.rows);
3722
+ if (refusal !== null) {
3723
+ return refuse(ctx.deps, [
3724
+ `${ctx.epicKey}: REFUSED (${refusal.reasonId}) — the local plane is not current enough to ` +
3725
+ "create a run against.",
3726
+ ...renderFreshnessRows(adverse),
3727
+ "",
3728
+ "Nothing was started.",
3729
+ ]);
3730
+ }
3731
+ if (adverse.length > 0) {
3732
+ const log = ctx.deps.launchReadinessLog ?? ctx.deps.errorLog;
3733
+ log([
3734
+ assessment.overridden
3735
+ ? `${ctx.epicKey}: plane freshness — proceeding; a confirmed refusal was overridden for this invocation.`
3736
+ : `${ctx.epicKey}: plane freshness — proceeding; some evidence could not be verified.`,
3737
+ ...renderFreshnessRows(adverse),
3738
+ ].join("\n"));
3739
+ }
3740
+ return null;
3741
+ }
3742
+ catch {
3743
+ // An unexpected failure of an advisory read never stops a launch.
3744
+ return null;
3745
+ }
3746
+ }
3354
3747
  /** The warning-only counterpart for an existing run. Never refuses, never throws. */
3355
3748
  async function surfacePlaneFreshnessForExistingRun(ctx, own) {
3356
3749
  if (isConfirmedNonBridge(ctx)) {
@@ -3618,6 +4011,11 @@ async function coldStartPlane(ctx) {
3618
4011
  deps.errorLog(`${epicKey}: ${parallelColdRefusal}\nNothing was started.`);
3619
4012
  return 1;
3620
4013
  }
4014
+ // BAPI-1725: refuse a proven-stale checkout BEFORE anything is launched. The
4015
+ // post-launch guard below stays as the backstop.
4016
+ const staleHead = await coldStartCheckoutHeadGuard(ctx, repoRoot);
4017
+ if (staleHead !== null)
4018
+ return staleHead;
3621
4019
  const coldLanes = parallelLimitToExecutorLanes(ctx.options.parallel ?? DEFAULT_RUN_PARALLEL_LIMIT);
3622
4020
  const controlPlane = await deps.launchControlPlane({ preflight, executors: coldLanes });
3623
4021
  if (!controlPlane.ok) {
@@ -4283,7 +4681,7 @@ function reportExecutorOutcome(ctx, ensured, epicRunId, framing) {
4283
4681
  "It runs on THIS machine: sleep is held off while it runs, but a closed lid, a logout, or a",
4284
4682
  "shutdown stops it. The run stays server-side either way; restart the executor, or use a",
4285
4683
  "durable launch profile for long runs.",
4286
- KEEP_TERMINAL_OPEN_LINE,
4684
+ RUN_EXECUTOR_DETACHED_LINE,
4287
4685
  ].join("\n"));
4288
4686
  return 0;
4289
4687
  }
@@ -4312,6 +4710,10 @@ async function planeServesLiveRun(ctx, live) {
4312
4710
  /**
4313
4711
  * BAPI-1285 — a live run and no usable plan: make sure the run has an executor.
4314
4712
  *
4713
+ * BAPI-1714 — this ATTACHES; it does not finish setup. A `planning` run whose
4714
+ * authored plan the server holds is routed to the setup path instead (see
4715
+ * {@link isPlanningSetupToFinish}), so only an approved or later run reaches here.
4716
+ *
4315
4717
  * It creates nothing and never calls `setup-epic`, which hard-requires a plan
4316
4718
  * file. Readiness gates it exactly as it gates a create (only green proceeds),
4317
4719
  * because starting an executor for a run nothing can drive is not attaching to it.
@@ -4917,6 +5319,7 @@ async function runDriveEpicPreview(deps, options) {
4917
5319
  reason_id: named.reasonId,
4918
5320
  remedy: named.remedy,
4919
5321
  ...(named.authoritative === true ? { authoritative: true } : {}),
5322
+ ...(named.reasonCode !== undefined ? { reason_code: named.reasonCode } : {}),
4920
5323
  };
4921
5324
  preview.decision = "refuse";
4922
5325
  };
@@ -4968,7 +5371,7 @@ async function runDriveEpicPreview(deps, options) {
4968
5371
  needsTask,
4969
5372
  timed("health_status_ms", () => appendHealthCheckFact(deps, preview, observed.repository)),
4970
5373
  timed("escalation_ms", async () => { appendEscalationReachabilityRow(escalation, observed.readiness); }),
4971
- timed("executor_build_ms", () => appendExecutorBuildFreshnessWarning(deps, executor, observed.repository)),
5374
+ timed("executor_build_ms", () => appendExecutorBuildFreshnessWarning(deps, executor)),
4972
5375
  ]);
4973
5376
  const workerIds = new Set(worker.launch_checks?.map((row) => row.id));
4974
5377
  const needRows = needs.launch_checks ?? [];
@@ -4986,6 +5389,8 @@ async function runDriveEpicPreview(deps, options) {
4986
5389
  const collected = await collectLaunchPlanFacts(deps, options, preview, observed);
4987
5390
  // The tally lines do not depend on the builder succeeding.
4988
5391
  recordLaunchPlanObservations(preview, collected.tally);
5392
+ if (collected.uiReadiness !== undefined)
5393
+ preview.ui_readiness = collected.uiReadiness;
4989
5394
  const result = (deps.buildLaunchPlan ?? buildLaunchPlan)(preview, collected.facts);
4990
5395
  if (result)
4991
5396
  preview.launch_plan = result.launch_plan;
@@ -5007,6 +5412,130 @@ const previewPlanChildKeys = new WeakMap();
5007
5412
  /** The most time a launch preview spends reading the prerequisite cache before it carries on without it. */
5008
5413
  const PREREQUISITE_CACHE_READ_TIMEOUT_MS = 10_000;
5009
5414
  const PREREQUISITE_ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
5415
+ /** BAPI-1718 — the most time a create preview spends on ALL its advisory UI reads, shared. */
5416
+ const UI_READINESS_READ_TIMEOUT_MS = 10_000;
5417
+ /**
5418
+ * BAPI-1718 — start independent advisory reads together and finish under ONE
5419
+ * shared deadline. A `null` read was never available (a missing seam or access) and
5420
+ * stays failed. A read that throws, rejects, or has not finished when the deadline
5421
+ * passes is failed too; every read that completed keeps its value. The timer is
5422
+ * always cleared, a late completion is ignored, and nothing is retried.
5423
+ */
5424
+ async function collectAdvisoryReads(reads, timeoutMs) {
5425
+ const results = reads.map(() => ({ state: "failed" }));
5426
+ let closed = false;
5427
+ const settled = reads.map((run, index) => {
5428
+ if (run === null)
5429
+ return Promise.resolve();
5430
+ let pending;
5431
+ try {
5432
+ pending = Promise.resolve(run());
5433
+ }
5434
+ catch {
5435
+ return Promise.resolve();
5436
+ }
5437
+ return pending.then((value) => {
5438
+ if (!closed)
5439
+ results[index] = { state: "ok", value };
5440
+ }, () => undefined);
5441
+ });
5442
+ let timer;
5443
+ const deadline = new Promise((resolve) => {
5444
+ timer = setTimeout(resolve, timeoutMs);
5445
+ });
5446
+ try {
5447
+ await Promise.race([Promise.all(settled), deadline]);
5448
+ }
5449
+ finally {
5450
+ closed = true;
5451
+ if (timer !== undefined)
5452
+ clearTimeout(timer);
5453
+ }
5454
+ return [...results];
5455
+ }
5456
+ const UI_EPIC_SERVER_MODES = ["none", "local", "sfcc_shared_active"];
5457
+ /**
5458
+ * BAPI-1718 — the advisory UI readiness for a `create` preview. It reuses the plan
5459
+ * nodes and child set the preview already holds and reads only what is missing:
5460
+ * the epic and running-child descriptions, the tracked-file list, the worker grant,
5461
+ * and the epic-server record. It never throws and never changes anything the
5462
+ * preview decided; an unexpected failure simply yields no readiness.
5463
+ */
5464
+ async function collectUiReadiness(deps, options, preview, observed, handoff) {
5465
+ try {
5466
+ const access = observed.contextAccess;
5467
+ const repoName = observed.repoName ?? observed.access?.repoName ?? access?.repoName;
5468
+ // The children this launch will run: the plan's keys minus the already-done skips.
5469
+ const skipped = new Set();
5470
+ const merged = preview.already_done_children;
5471
+ if (merged !== undefined && merged.status === "checked") {
5472
+ for (const child of merged.children)
5473
+ if (child.will_skip === true)
5474
+ skipped.add(child.ticket_key);
5475
+ }
5476
+ const running = [...new Set((previewPlanChildKeys.get(preview) ?? []).filter((key) => !skipped.has(key)))];
5477
+ const readDescription = deps.readUiTicketDescription;
5478
+ const describe = (key) => readDescription === undefined || access === undefined ? null : () => readDescription(access, key);
5479
+ const readTracked = deps.listUiTrackedFiles;
5480
+ const readGrant = deps.readUiMcpGrant;
5481
+ const readRecord = deps.readUiEpicServerRecord;
5482
+ const results = await collectAdvisoryReads([
5483
+ describe(options.epicKey),
5484
+ ...running.map(describe),
5485
+ readTracked === undefined ? null : () => readTracked(),
5486
+ readGrant === undefined || repoName === undefined ? null : () => readGrant(repoName),
5487
+ readRecord === undefined || repoName === undefined ? null : () => readRecord(repoName),
5488
+ ], UI_READINESS_READ_TIMEOUT_MS);
5489
+ const asDescription = (read) => read.state === "ok" && typeof read.value === "string" ? { state: "ok", value: read.value } : { state: "failed" };
5490
+ const [epicRead, ...rest] = results;
5491
+ const childReads = rest.slice(0, running.length);
5492
+ const [trackedRead, grantRead, recordRead] = rest.slice(running.length);
5493
+ const tracked = trackedRead.state === "ok" && Array.isArray(trackedRead.value) &&
5494
+ trackedRead.value.every((entry) => typeof entry === "string")
5495
+ ? { state: "ok", value: trackedRead.value }
5496
+ : { state: "failed" };
5497
+ let grant = { state: "failed" };
5498
+ if (grantRead.state === "ok" && grantRead.value !== null && typeof grantRead.value === "object") {
5499
+ const value = grantRead.value;
5500
+ if (value.state === "absent")
5501
+ grant = { state: "absent" };
5502
+ else if (value.state === "unusable")
5503
+ grant = { state: "unusable", reason: "" };
5504
+ else if (value.state === "ok" && Array.isArray(value.grant?.servers))
5505
+ grant = value;
5506
+ }
5507
+ let mode = "unknown";
5508
+ if (recordRead.state === "ok" && recordRead.value !== null && typeof recordRead.value === "object") {
5509
+ const value = recordRead.value;
5510
+ if (value.state === "absent")
5511
+ mode = "none";
5512
+ else if (value.state === "ok" && typeof value.record?.mode === "string" && UI_EPIC_SERVER_MODES.includes(value.record.mode)) {
5513
+ mode = value.record.mode;
5514
+ }
5515
+ }
5516
+ const work = classifyUiWork({
5517
+ epicKey: options.epicKey,
5518
+ epicDescription: asDescription(epicRead),
5519
+ runningChildren: running.map((key, index) => ({ key, description: asDescription(childReads[index]) })),
5520
+ nodes: (preview.plan.generation?.nodes ?? preview.plan.inline?.nodes ?? []).map((node) => ({
5521
+ ticket_key: node.ticket_key,
5522
+ ...(node.touched_files !== undefined ? { touched_files: node.touched_files } : {}),
5523
+ })),
5524
+ trackedFiles: tracked,
5525
+ });
5526
+ return buildUiReadiness({
5527
+ work,
5528
+ verification: classifyUiVerification(grant, mode),
5529
+ mode,
5530
+ playwrightGrant: classifyPlaywrightGrant(grant),
5531
+ handoff,
5532
+ });
5533
+ }
5534
+ catch {
5535
+ // Advisory only: nothing from the failure is shown, and the preview is unchanged.
5536
+ return undefined;
5537
+ }
5538
+ }
5010
5539
  function handoffValueText(value) {
5011
5540
  return value === "unknown" ? "unknown (today's default: proceed)" : value;
5012
5541
  }
@@ -5062,13 +5591,25 @@ async function collectLaunchPlanFacts(deps, options, preview, observed) {
5062
5591
  const presence = new Map();
5063
5592
  const missing = new Map();
5064
5593
  const runtimeChildren = new Set();
5594
+ // BAPI-1704: open decisions are advisory facts, kept apart from every prerequisite
5595
+ // path (no runtime classification, presence check, or kept-off-screen count).
5596
+ const openDecisions = [];
5597
+ const openDecisionSeen = new Set();
5065
5598
  const kept = { minor: 0, "observed present": 0, "worker runtime": 0, "not measurable": 0, skipped: 0 };
5066
5599
  for (const entry of read.entries) {
5067
5600
  if (!members.has(entry.child)) {
5068
- kept.skipped += entry.items.length;
5601
+ kept.skipped += entry.items.filter((item) => !("category" in item && item.category === "open-decision")).length;
5069
5602
  continue;
5070
5603
  }
5071
5604
  for (const item of entry.items) {
5605
+ if ("category" in item && item.category === "open-decision") {
5606
+ const dedupeKey = `${entry.child}\u0000${item.evidence.replace(/\s+/g, " ").trim()}`;
5607
+ if (!openDecisionSeen.has(dedupeKey)) {
5608
+ openDecisionSeen.add(dedupeKey);
5609
+ openDecisions.push({ child: entry.child, summary: item.requirement, clause: item.evidence });
5610
+ }
5611
+ continue;
5612
+ }
5072
5613
  if ("category" in item) {
5073
5614
  kept["worker runtime"] += 1;
5074
5615
  runtimeChildren.add(entry.child);
@@ -5099,6 +5640,13 @@ async function collectLaunchPlanFacts(deps, options, preview, observed) {
5099
5640
  : { ...prior, dependents: prior.dependents.split(", ").includes(item.dependents) ? prior.dependents : `${prior.dependents}, ${item.dependents}` });
5100
5641
  }
5101
5642
  }
5643
+ for (const decision of openDecisions) {
5644
+ // Redacted at the display boundary; the evidence clause is never recorded.
5645
+ tally.push({
5646
+ code: "prerequisite_open_decision",
5647
+ line: `prerequisite scan child ${decision.child}: open decision: ${redactSecrets(decision.summary)}`,
5648
+ });
5649
+ }
5102
5650
  for (const [category, count] of Object.entries(kept)) {
5103
5651
  if (count > 0)
5104
5652
  tally.push({ code: "prerequisite_kept_off_screen", line: `prerequisite scan: kept off the screen: ${category} ${count}` });
@@ -5107,6 +5655,7 @@ async function collectLaunchPlanFacts(deps, options, preview, observed) {
5107
5655
  status: "collected",
5108
5656
  missingCore: [...missing.values()],
5109
5657
  workerRuntimeChildren: [...runtimeChildren],
5658
+ openDecisions,
5110
5659
  };
5111
5660
  }
5112
5661
  }
@@ -5131,7 +5680,15 @@ async function collectLaunchPlanFacts(deps, options, preview, observed) {
5131
5680
  if (suppressed.length > 0) {
5132
5681
  tally.push({ code: "launch_rows_kept_off_screen", line: `launch rows kept off the screen: ${[...new Set(suppressed)].join(", ")}` });
5133
5682
  }
5134
- return { facts: { prerequisites, handoff }, tally };
5683
+ // BAPI-1718 — the UI advisory is computed for a `create` decision only. It adds no
5684
+ // read for attach or any other decision, and never feeds the launch plan or a check.
5685
+ let uiReadiness;
5686
+ if (preview.decision === "create") {
5687
+ uiReadiness = await collectUiReadiness(deps, options, preview, observed, effective);
5688
+ if (uiReadiness !== undefined)
5689
+ tally.push({ code: "ui_readiness", line: uiReadiness.line });
5690
+ }
5691
+ return { facts: { prerequisites, handoff }, tally, ...(uiReadiness !== undefined ? { uiReadiness } : {}) };
5135
5692
  }
5136
5693
  /** Append the collected fixed lines to the preview's tally lines, once each. */
5137
5694
  function recordLaunchPlanObservations(preview, lines) {
@@ -5205,23 +5762,55 @@ function appendEscalationReachabilityRow(preview, readiness) {
5205
5762
  { ...row, duration_ms: elapsedMs(started) },
5206
5763
  ];
5207
5764
  }
5765
+ /**
5766
+ * The Bridge checkout root a launcher override names (BAPI-1725), or `null`.
5767
+ *
5768
+ * A plain whitespace split of the launcher value; the first absolute-path token
5769
+ * with an exact `mcp_server` path component selects the directory holding that
5770
+ * component. This matches the launcher format `resolvePermissionLauncher`
5771
+ * supports, which refuses quoted values, so there is deliberately no quote-aware
5772
+ * tokenization and no reconstruction of space-bearing paths. `mcp_server_extra`
5773
+ * and other lookalike components never qualify.
5774
+ */
5775
+ function bridgeRootFromLauncher(launcher) {
5776
+ for (const token of launcher.trim().split(/\s+/)) {
5777
+ if (token === "" || !path.isAbsolute(token))
5778
+ continue;
5779
+ let current = token;
5780
+ for (;;) {
5781
+ const parent = dirname(current);
5782
+ if (parent === current)
5783
+ break;
5784
+ if (path.basename(current) === "mcp_server")
5785
+ return parent;
5786
+ current = parent;
5787
+ }
5788
+ }
5789
+ return null;
5790
+ }
5208
5791
  /**
5209
5792
  * Append a non-blocking `executor-build-freshness` warning to the preview when a
5210
- * local CLI override (`BAPI_MCP_CLI`) is set and the executor build is stale or
5211
- * unreadable. Fail-open and read-only: it never changes the decision, a refusal,
5793
+ * local CLI override (`BAPI_MCP_CLI`) is set and the Bridge build it names is
5794
+ * stale or unreadable. Fail-open and read-only: it never changes the decision, a refusal,
5212
5795
  * readiness, or the exit code. A passing check, an unset or blank override, or a
5213
5796
  * missing dependency leaves `launch_checks` untouched. A thrown check prints one
5214
5797
  * fixed line and nothing from the exception.
5215
5798
  */
5216
- async function appendExecutorBuildFreshnessWarning(deps, preview, repository) {
5799
+ async function appendExecutorBuildFreshnessWarning(deps, preview) {
5217
5800
  const started = monotonicNow();
5218
5801
  const override = process.env[BRIDGE_LAUNCHER_ENV];
5219
5802
  if (override === undefined || override.trim() === "")
5220
5803
  return;
5221
5804
  if (deps.checkExecutorBuildFreshness === undefined)
5222
5805
  return;
5806
+ // BAPI-1725: the executor runs the Bridge build the launcher names, not the
5807
+ // consumer checkout. No qualifying launcher path means nothing to check; it
5808
+ // never falls back to the consumer's cwd.
5809
+ const bridgeRoot = bridgeRootFromLauncher(override);
5810
+ if (bridgeRoot === null)
5811
+ return;
5223
5812
  try {
5224
- const report = await deps.checkExecutorBuildFreshness(deps.cwd(), repository?.isBridge === false ? { isBridge: false } : undefined);
5813
+ const report = await deps.checkExecutorBuildFreshness(bridgeRoot);
5225
5814
  if (report.diagnostic === null)
5226
5815
  return;
5227
5816
  const outcome = report.outcomes.find((entry) => entry.status === "warn" || entry.status === "fail") ?? report.outcomes[0];
@@ -5258,7 +5847,24 @@ function autoMergeLine(preview) {
5258
5847
  : " Auto-merge: unavailable (older setup-epic output)";
5259
5848
  }
5260
5849
  const intent = merge.state === "on" ? { state: "on" } : { state: "off", reason: merge.reason ?? "" };
5261
- return ` ${formatSetupEpicAutoMergeIntent(intent, preview.summary.branch ?? undefined)}`;
5850
+ return ` ${formatSetupEpicAutoMergeIntent(intent, preview.summary.branch ?? undefined)}${autoMergeForecastSuffix(merge)}`;
5851
+ }
5852
+ /**
5853
+ * BAPI-1526 — the advisory suffix for the one "Auto-merge:" line. Empty for an
5854
+ * `off` intent, `unknown`, `not_requested`, or an absent forecast, so those lines
5855
+ * stay byte-identical. Reason ids are closed tokens, already validated by the parser.
5856
+ */
5857
+ function autoMergeForecastSuffix(merge) {
5858
+ const forecast = merge.forecast;
5859
+ if (merge.state !== "on" || forecast === undefined)
5860
+ return "";
5861
+ const ids = forecast.reason_ids.join(", ");
5862
+ if (forecast.outcome === "merge_approval_required") {
5863
+ return `; first approval will require merge approval${ids === "" ? "" : ` (${ids})`}`;
5864
+ }
5865
+ if (forecast.outcome === "auto_merge_kept" && ids !== "")
5866
+ return `; kept at first approval (${ids})`;
5867
+ return "";
5262
5868
  }
5263
5869
  /** BAPI-1593 — the plan digest setup-epic's dry run says the SERVER validated, per preview. */
5264
5870
  const previewServerPlanDigest = new WeakMap();
@@ -5493,8 +6099,55 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5493
6099
  let generationReason;
5494
6100
  let generatedLiveRunChecked = false;
5495
6101
  let docsRootUnresolved = false;
6102
+ // BAPI-1706 — the same server-first precedence the launch uses, read once and
6103
+ // written nowhere: no upload, no temporary folder, no local file.
6104
+ let previewProvenance = null;
6105
+ let authoredLookupKind = "skipped";
6106
+ let previewServerPlan = null;
6107
+ if (planPath === undefined && deps.lookupAuthoredPlan !== undefined) {
6108
+ const authored = await deps
6109
+ .lookupAuthoredPlan(epicKey, options.repo)
6110
+ .catch(() => ({ lookup: { kind: "unknown", reason: "network" }, endpoint: null }));
6111
+ authoredLookupKind = authored.lookup.kind;
6112
+ if (authored.lookup.kind === "found") {
6113
+ previewServerPlan = authored.lookup.snapshot;
6114
+ previewProvenance = serverPlanProvenance(previewServerPlan, authored.endpoint);
6115
+ }
6116
+ else if (authored.lookup.kind === "server_too_old") {
6117
+ (preview.warnings ??= []).push(AUTHORED_PLAN_SERVER_TOO_OLD_NOTICE);
6118
+ }
6119
+ }
5496
6120
  if (planPath !== undefined) {
5497
6121
  plan = { status: "supplied", path: planPath };
6122
+ previewProvenance = nonServerPlanProvenance("explicit");
6123
+ }
6124
+ else if (previewServerPlan !== null) {
6125
+ // A logical path for the in-memory adapter only; nothing is written there.
6126
+ planPath = path.join(tmpdir(), "bapi-authored-plan-preview", epicKey, "epic-plan.dag.json");
6127
+ plan = {
6128
+ status: "found",
6129
+ inline: { nodes: previewServerPlan.plan_blob.nodes },
6130
+ };
6131
+ ctx = {
6132
+ ...ctx,
6133
+ deps: withInlinePlan(ctx.deps, planPath, JSON.stringify(previewServerPlan.plan_blob, null, 2) + "\n"),
6134
+ };
6135
+ const advisory = previewServerPlan.eligibility_advisory !== null
6136
+ ? parseContainmentEligibilityArtifact(previewServerPlan.eligibility_advisory)
6137
+ : null;
6138
+ const advisoryText = advisory !== null ? renderContainmentEligibilityAdvisory(advisory) : null;
6139
+ if (advisoryText !== null)
6140
+ plan.containment_advisory = advisoryText;
6141
+ const docs = await deps.resolveDocsDir();
6142
+ if (docs.ok) {
6143
+ const ignored = await localPlanIgnoredPath(deps, epicKey, docs.docsDir, previewServerPlan);
6144
+ if (ignored !== null)
6145
+ plan.local_plan_ignored = ignored;
6146
+ }
6147
+ }
6148
+ else if (authoredLookupKind === "unknown") {
6149
+ // No local or generated fallback: an unknown answer is never evidence of absence.
6150
+ plan = { status: "not_found" };
5498
6151
  }
5499
6152
  else {
5500
6153
  const docs = await deps.resolveDocsDir();
@@ -5559,6 +6212,22 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5559
6212
  }
5560
6213
  }
5561
6214
  }
6215
+ // BAPI-1706 — provenance is always present, with predictable nulls.
6216
+ if (previewProvenance === null) {
6217
+ if (plan.status === "found" || plan.status === "generated") {
6218
+ previewProvenance = nonServerPlanProvenance(plan.generated === true ? "generated" : "local");
6219
+ }
6220
+ }
6221
+ Object.assign(plan, {
6222
+ source: previewProvenance?.source ?? null,
6223
+ plan_version: previewProvenance?.plan_version ?? null,
6224
+ plan_hash: previewProvenance?.plan_hash ?? null,
6225
+ saved_by: previewProvenance?.saved_by ?? null,
6226
+ saved_at: previewProvenance?.saved_at ?? null,
6227
+ endpoint: previewProvenance?.endpoint ?? null,
6228
+ authored_lookup: authoredLookupKind,
6229
+ });
6230
+ const authoredPlanUnknown = authoredLookupKind === "unknown";
5562
6231
  // Every later exit, refusal or not, reports the plan state as discovered.
5563
6232
  preview.plan = plan;
5564
6233
  // --- Readiness. -----------------------------------------------------------
@@ -5620,8 +6289,9 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5620
6289
  live_run_checked: generatedLiveRunChecked,
5621
6290
  };
5622
6291
  }
5623
- // No plane exists yet, so there is no snapshot or database to compare;
5624
- // the host-sleep advisory still applies to the plane about to start.
6292
+ // No plane exists yet, so there is no plane snapshot or database to compare.
6293
+ // The checkout's HEAD is compared with origin/main instead (BAPI-1725); the
6294
+ // host-sleep advisory still applies to the plane about to start.
5625
6295
  observed.access = access;
5626
6296
  observed.launchTopology = { kind: "local", repoRoot: null };
5627
6297
  await applyPreviewFreshness(ctx, preview, {}, true);
@@ -5675,12 +6345,15 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5675
6345
  (preview.warnings ??= []).push(LIVE_RUN_UNKNOWN_WARNING);
5676
6346
  if (unknownLive.kind === "live") {
5677
6347
  preview.live_run = { epic_run_id: unknownLive.epicRunId, status: unknownLive.status };
5678
- if (options.planFile === undefined) {
6348
+ if (options.planFile === undefined && !isPlanningSetupToFinish(unknownLive, previewServerPlan)) {
5679
6349
  preview.decision = "attach";
5680
6350
  return;
5681
6351
  }
5682
6352
  }
5683
6353
  if (planPath === undefined) {
6354
+ if (authoredPlanUnknown) {
6355
+ return refuseTopLevel({ reasonId: AUTHORED_PLAN_UNKNOWN_REASON_ID, remedy: authoredPlanUnknownRemedy(epicKey, options.repo) });
6356
+ }
5684
6357
  preview.decision = "stop";
5685
6358
  return;
5686
6359
  }
@@ -5698,7 +6371,11 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5698
6371
  // BAPI-1532 — a DISCOVERED plan beside a live run is unused: the launch attaches,
5699
6372
  // so the effective plan path is cleared while the preview still reports the plan
5700
6373
  // as found. An explicit --plan-file keeps its create-path behavior unchanged.
5701
- const attachingDiscoveredPlan = options.planFile === undefined && (plan.status === "found" || plan.status === "generated") && live.kind === "live";
6374
+ const attachingDiscoveredPlan = options.planFile === undefined &&
6375
+ (plan.status === "found" || plan.status === "generated") &&
6376
+ live.kind === "live" &&
6377
+ // BAPI-1714 — finishing setup for a planning run keeps the stored server plan.
6378
+ !isPlanningSetupToFinish(live, previewServerPlan);
5702
6379
  const effectivePlanPath = attachingDiscoveredPlan ? undefined : planPath;
5703
6380
  const previewCtx = { ...ctx, options: { ...options, ...(effectivePlanPath ? { planFile: effectivePlanPath } : {}) } };
5704
6381
  const observations = {
@@ -5724,6 +6401,18 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5724
6401
  if (mandatoryDiagnosticsUncertain(readiness.diagnostics)) {
5725
6402
  (preview.warnings ??= []).push(MANDATORY_DIAGNOSTIC_UNKNOWN_WARNING);
5726
6403
  }
6404
+ // BAPI-1714 — an unverifiable workflow read warns once, on an applicable
6405
+ // unattended create or setup path. A genuine live-run attach (a live run with no
6406
+ // plan to set up) is excluded: first approval already decided it.
6407
+ const genuineAttach = live.kind === "live" && effectivePlanPath === undefined;
6408
+ if (options.attended !== true &&
6409
+ options.intoBase !== true &&
6410
+ !genuineAttach &&
6411
+ readiness.unattended?.repository_readiness_confirmed === false &&
6412
+ repositoryReadinessVerdict(readiness) === "unknown" &&
6413
+ !(preview.warnings ?? []).includes(REPOSITORY_WORKFLOWS_UNVERIFIABLE_WARNING)) {
6414
+ (preview.warnings ??= []).push(REPOSITORY_WORKFLOWS_UNVERIFIABLE_WARNING);
6415
+ }
5727
6416
  if (classification.kind === 'operator_blocked') {
5728
6417
  const requirement = V2_READINESS_REQUIREMENTS.find(req => req.id === classification.id);
5729
6418
  if (requirement)
@@ -5751,6 +6440,11 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5751
6440
  // --- No plan: attach to a live run, or stop. --------------------------------
5752
6441
  if (effectivePlanPath === undefined) {
5753
6442
  if (live.kind !== "live") {
6443
+ // BAPI-1706 — the server could not say whether a plan is stored, and this
6444
+ // launch would create a run: a named stop, never a local or generated plan.
6445
+ if (authoredPlanUnknown) {
6446
+ return refuseTopLevel({ reasonId: AUTHORED_PLAN_UNKNOWN_REASON_ID, remedy: authoredPlanUnknownRemedy(epicKey, options.repo) });
6447
+ }
5754
6448
  if (selection.kind === "not_ready") {
5755
6449
  return refuseWithReadiness(classification.kind, {
5756
6450
  reasonId: ENGINE_NOT_READY_REASON_ID,
@@ -6013,6 +6707,20 @@ async function finalizeCreatePreview(ctx, preview, planPath, coldStart, refuseTo
6013
6707
  const launch = classifyV2Readiness(payload.launchReadiness, { attended: options.attended, intoBase: options.intoBase });
6014
6708
  if (launch.kind === 'operator_blocked')
6015
6709
  return refuseTopLevel({ reasonId: launch.id, remedy: launch.remedy ?? 'Retry readiness.', authoritative: true });
6710
+ // BAPI-1526 — first approval would refuse this create's required checks. Read
6711
+ // ONLY on this policy-aware launch report (the actual create policy), and only
6712
+ // before a run exists: re-attaching to a live run is the recovery path, and an
6713
+ // approved run carries its own bound evidence. Anything but a proven denial
6714
+ // continues; approval stays the authority.
6715
+ if (payload.existingRunId === null && requiredChecksAdmissionVerdict(payload.launchReadiness) === "denied") {
6716
+ const denied = requiredChecksDeniedRecord(payload.launchReadiness);
6717
+ return refuseTopLevel({
6718
+ reasonId: REQUIRED_CHECKS_ADMISSION_REASON_ID,
6719
+ remedy: `${requiredChecksAdmissionRemedy(payload.launchReadiness)} Nothing was created.`,
6720
+ authoritative: true,
6721
+ ...(denied?.reason ? { reasonCode: denied.reason } : {}),
6722
+ });
6723
+ }
6016
6724
  }
6017
6725
  if (payload.effectivePolicy) {
6018
6726
  const facts = payload.effectivePolicy;
@@ -6048,6 +6756,11 @@ async function finalizeCreatePreview(ctx, preview, planPath, coldStart, refuseTo
6048
6756
  }
6049
6757
  preview.summary.auto_merge =
6050
6758
  intent.state === "off" ? { state: "off", reason: intent.reason } : { state: intent.state };
6759
+ // BAPI-1526 — the server's advisory forecast for THIS create policy (the
6760
+ // launch report). Absent on an older server; never changes the decision.
6761
+ const forecast = payload.launchReadiness?.merge_forecast;
6762
+ if (forecast !== undefined)
6763
+ preview.summary.auto_merge.forecast = forecast;
6051
6764
  preview.summary.auto_merge_scope = intent.state === "on" ? payload.featureBranch : null;
6052
6765
  // The bootstrap reusing a run IS an attach: it reports the run's id.
6053
6766
  if (payload.existingRunId !== null) {
@@ -6101,7 +6814,7 @@ async function applyPreviewFreshness(ctx, preview, topology, coldStart) {
6101
6814
  if (planeEndpointForBaseUrl(deps, ctx.access.baseUrl) === null)
6102
6815
  return;
6103
6816
  try {
6104
- const manifest = topology.manifest ?? null;
6817
+ const manifest = coldStart ? null : topology.manifest ?? null;
6105
6818
  const own = manifest !== null
6106
6819
  ? {
6107
6820
  repoRoot: manifest.repoRoot,
@@ -6110,7 +6823,12 @@ async function applyPreviewFreshness(ctx, preview, topology, coldStart) {
6110
6823
  ...(manifest.epicRunId ? { epicRunId: manifest.epicRunId } : {}),
6111
6824
  }
6112
6825
  : { repoRoot: deps.cwd(), ownsManifest: false };
6113
- const reports = coldStart ? null : await collectFreshnessObservations(ctx, own);
6826
+ // BAPI-1725: a cold start has no plane, so compare the CURRENT checkout's HEAD
6827
+ // (never a manifest's snapshot path) with origin/main; this feeds the same
6828
+ // assessor, override, and refusal as every other freshness observation.
6829
+ const reports = coldStart
6830
+ ? await collectCheckoutHeadFreshness(ctx, deps.cwd(), true)
6831
+ : await collectFreshnessObservations(ctx, own);
6114
6832
  // BAPI-1506: a `create` preview reports host sleep as a launch need on every
6115
6833
  // target (see appendLaunchNeedRows); only `attach` keeps it here.
6116
6834
  const sleep = preview.decision === "attach" ? await collectHostSleep(ctx, own.repoRoot) : null;
@@ -6353,6 +7071,37 @@ function launchPlanLines(plan) {
6353
7071
  lines.push(` ${plan.local_handoff}`);
6354
7072
  return lines;
6355
7073
  }
7074
+ /**
7075
+ * BAPI-1706 — the Plan summary that leads the readable preview: where the plan
7076
+ * comes from, before anything else. Plain text labels, no color.
7077
+ */
7078
+ function planSourceLines(preview) {
7079
+ const plan = preview.plan;
7080
+ const lines = [];
7081
+ if (plan.authored_lookup === "unknown") {
7082
+ lines.push(" Plan source: UNKNOWN — the Bridge server could not say whether a plan is stored. " +
7083
+ "No run will be created until it can.");
7084
+ }
7085
+ else if (plan.source === "server") {
7086
+ lines.push(` Plan source: server — authored version ${plan.plan_version ?? "unknown"}, hash ` +
7087
+ `${plan.plan_hash ? plan.plan_hash.slice(0, 12) : "unknown"}, saved by ${plan.saved_by ?? "unknown"} ` +
7088
+ `at ${plan.saved_at ?? "unknown"}, from ${plan.endpoint ?? "unknown"}`);
7089
+ }
7090
+ else {
7091
+ lines.push(` Plan source: ${plan.source ?? "none"}${plan.authored_lookup === "not_stored" ? " (no plan stored on the Bridge server)" : ""}`);
7092
+ }
7093
+ if (plan.authored_lookup === "server_too_old") {
7094
+ lines.push(" warning: this Bridge server does not store epic plans yet; local plan files are used as before.");
7095
+ }
7096
+ if (plan.local_plan_ignored !== undefined) {
7097
+ lines.push(` local plan ignored: ${plan.local_plan_ignored} (differs from the stored plan)`);
7098
+ }
7099
+ if (plan.containment_advisory !== undefined) {
7100
+ for (const line of plan.containment_advisory.split("\n"))
7101
+ lines.push(` ${line}`);
7102
+ }
7103
+ return lines;
7104
+ }
6356
7105
  /**
6357
7106
  * Print the preview: one JSON line with `--json`, short readable lines otherwise.
6358
7107
  *
@@ -6369,6 +7118,7 @@ async function emitPreview(deps, options, preview) {
6369
7118
  }
6370
7119
  const lines = [
6371
7120
  `${preview.epic_key}: launch preview (read-only; nothing was created or started)`,
7121
+ ...planSourceLines(preview),
6372
7122
  ...(preview.cold_start ? [" Decision: conditional create — drive-epic will attempt guarded startup, recheck the live run, and create only if still appropriate."] : []),
6373
7123
  ` Target: ${preview.target.base_url ?? "unresolved"}${preview.target.kind ? ` (${preview.target.kind})` : ""}`,
6374
7124
  ` Readiness: ${preview.readiness.kind}${preview.readiness.reason_id ? ` (${preview.readiness.reason_id})` : ""}`,