@bridge_gpt/mcp-server 0.2.73 → 0.2.75

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 (123) hide show
  1. package/README.md +14 -7
  2. package/build/agent-launchers/claude-executor-adapter.js +12 -0
  3. package/build/agent-launchers/prompt.js +9 -21
  4. package/build/agents.generated.js +4 -4
  5. package/build/authored-plan.js +542 -0
  6. package/build/bridge-config.js +7 -1
  7. package/build/bridge-permissions.js +11 -0
  8. package/build/command-provisioning.js +4 -3
  9. package/build/commands.generated.js +6 -6
  10. package/build/conductor/bridge-api-client.js +692 -47
  11. package/build/conductor/command-drift.js +1 -1
  12. package/build/conductor/declared-extras.js +335 -0
  13. package/build/conductor/doctor.js +2 -0
  14. package/build/conductor/driver-pass-output.js +104 -0
  15. package/build/conductor/driver-pass.js +571 -0
  16. package/build/conductor/epic-branch-ci-inspection.js +61 -16
  17. package/build/conductor/epic-implementer-cli.js +370 -93
  18. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  19. package/build/conductor/epic-server-sfcc.js +58 -80
  20. package/build/conductor/epic-server.js +57 -4
  21. package/build/conductor/gate-discovery.js +253 -13
  22. package/build/conductor/gate-settings-review.js +58 -25
  23. package/build/conductor/launch-plan.js +58 -12
  24. package/build/conductor/open-decision-phrases.js +50 -0
  25. package/build/conductor/prerequisite-inputs.js +181 -14
  26. package/build/connect-github-api.js +18 -0
  27. package/build/connect-github.js +35 -18
  28. package/build/credential-delivery.js +280 -0
  29. package/build/credential-launch-safety.js +142 -0
  30. package/build/credential-materialization.js +91 -16
  31. package/build/credential-references-node-deps.js +29 -0
  32. package/build/credential-references.js +1394 -0
  33. package/build/credential-references.test-fixtures.js +211 -0
  34. package/build/credential-scan-conventions.js +145 -0
  35. package/build/credential-scan.js +517 -0
  36. package/build/credential-store.js +50 -0
  37. package/build/credentials-cli.js +252 -3
  38. package/build/dependency-install-declarations.js +47 -1
  39. package/build/docs.generated.js +8 -1
  40. package/build/doctor.js +41 -0
  41. package/build/drive-epic.js +684 -49
  42. package/build/epic-branch-ci-summary.js +18 -1
  43. package/build/epic-capability-statement.js +71 -3
  44. package/build/epic-ci-workflow-drift.js +52 -13
  45. package/build/epic-ci-workflow-install.js +31 -6
  46. package/build/epic-ci-workflow-v3.js +273 -0
  47. package/build/epic-ci-workflow.js +129 -7
  48. package/build/epic-implementer-bin.js +288 -83
  49. package/build/epic-implementer-bundle-cli.js +61 -0
  50. package/build/epic-implementer-claude-hook-bin.js +1 -1
  51. package/build/epic-implementer-env.js +3 -4
  52. package/build/epic-integration-pr.js +5 -2
  53. package/build/epic-launch-context.js +102 -7
  54. package/build/epic-server-record.js +30 -15
  55. package/build/executor/completion-contract.js +24 -1
  56. package/build/executor/credential-delivery-step.js +168 -0
  57. package/build/executor/deps.js +3 -1
  58. package/build/executor/env.js +39 -1
  59. package/build/executor/epic-server-context.js +23 -7
  60. package/build/executor/gate-qualification-job.js +193 -23
  61. package/build/executor/gate-qualification-tests-ran.js +232 -0
  62. package/build/executor/guarded-fast-forward-push.js +13 -8
  63. package/build/executor/job-runner.js +167 -738
  64. package/build/executor/job-type-wrappers.js +734 -0
  65. package/build/executor/permissions.js +85 -3
  66. package/build/executor/preflight.js +6 -2
  67. package/build/executor/process-containment.js +8 -1
  68. package/build/executor/prompt-spec.js +37 -3
  69. package/build/executor/required-verification.js +28 -2
  70. package/build/executor/runner.js +4 -1
  71. package/build/executor/types.js +9 -0
  72. package/build/executor/worker-database.js +6 -1
  73. package/build/executor/worker-guard-hook.js +24 -2
  74. package/build/executor-launch.js +4 -2
  75. package/build/generated/ticket-status.js +20 -0
  76. package/build/git-exclude-lock.js +187 -0
  77. package/build/index.js +589 -326
  78. package/build/install-bridge-conductor-answers.js +112 -22
  79. package/build/install-bridge-conductor-apply.js +38 -1
  80. package/build/install-bridge-conductor-assessment.js +482 -53
  81. package/build/install-bridge-conductor-compact.js +29 -2
  82. package/build/install-bridge-conductor-contracts.js +10 -1
  83. package/build/install-bridge-conductor-gate.js +379 -89
  84. package/build/install-bridge-conductor-setup.js +46 -8
  85. package/build/install-bridge-conductor-trial-report.js +170 -0
  86. package/build/install-bridge-conductor.js +925 -141
  87. package/build/install-bridge.js +88 -11
  88. package/build/install-doctor.js +38 -8
  89. package/build/install-sfcc-detection.js +120 -0
  90. package/build/install-sfcc-setup.js +185 -0
  91. package/build/mcp-grant-candidates.js +108 -96
  92. package/build/mcp-invoke.js +168 -4
  93. package/build/mcp-provisioning.js +21 -4
  94. package/build/mcp-server-invocation.js +13 -0
  95. package/build/merge-workflow-install.js +9 -1
  96. package/build/pipelines.generated.js +8 -7
  97. package/build/plan-generation.js +17 -0
  98. package/build/plane/status.js +8 -2
  99. package/build/printed-remedy-commands.js +59 -0
  100. package/build/project-root.js +40 -0
  101. package/build/readme.generated.js +1 -1
  102. package/build/repository-state-paths.js +5 -2
  103. package/build/repository-toolchains.js +16 -7
  104. package/build/scripts/saved-commands-config-field-driver.js +65 -0
  105. package/build/setup-epic.js +126 -16
  106. package/build/sfcc/credentials.js +3 -2
  107. package/build/sfcc/hostname.js +98 -2
  108. package/build/sfcc/tool-wrapper.js +6 -95
  109. package/build/start-tickets.js +193 -29
  110. package/build/test-support/executor-source-files.js +200 -0
  111. package/build/testing-config-client.js +25 -2
  112. package/build/third-party-mcp-targets.js +35 -4
  113. package/build/v2-readiness-requirements.js +5 -1
  114. package/build/version.generated.js +3 -3
  115. package/build/with-credentials.js +208 -0
  116. package/build/worker-guard-hook-bin.js +2 -2
  117. package/build/worktree-credential-delivery.js +340 -0
  118. package/docs/EPIC-IMPLEMENTER.md +4 -4
  119. package/docs/install/github-app.md +79 -92
  120. package/package.json +1 -1
  121. package/build/conductor/epic-reconcile.js +0 -603
  122. package/build/conductor/epic-runtime.js +0 -2020
  123. 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";
@@ -64,6 +65,7 @@ import { READINESS_PRE_CREATE_CODES, READINESS_PREREQUISITE_BY_ID, READINESS_LEG
64
65
  import { access as fsAccess, 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 { tmpdir } from "node:os";
67
69
  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
70
  import { CHILD_MERGE_STATUS_BATCH_SIZE, buildAlreadyDoneEntries, classifyPlanChildren, selectSkips, } from "./conductor/merged-child-check.js";
69
71
  import { trimDonePlanNodes } from "./conductor/plan-trim.js";
@@ -74,6 +76,8 @@ import { validateHttpBaseUrl, describeBaseUrlRejection } from "./base-url.js";
74
76
  import { BRING_UP_REFUSAL_MESSAGES, BRING_UP_RUNBOOK, firstBringUpRefusal, firstProvenBringUpRefusal, } from "./conductor/bring-up-facts.js";
75
77
  import { V2_READINESS_REQUIREMENTS, buildLaunchEvidenceChecks, buildLaunchReadinessChecks, firstLaunchEvidenceBlocker, projectReadinessRowBlocking, unattendedPostureCheck, } from "./v2-readiness-requirements.js";
76
78
  import { classifyLocalGhPreflight, probeLocalMergeCapability, } from "./conductor/local-merge.js";
79
+ import { statusOnly } from "./credential-references.js";
80
+ import { createNodeCredentialReferenceDeps } from "./credential-references-node-deps.js";
77
81
  import { nodeGithubMergeCredentialReadDeps, resolveMergeCredentialAtAction, } from "./conductor/stored-merge-credential.js";
78
82
  import { resolveWorktreeSettingsExclude, } from "./executor/permissions.js";
79
83
  import { collectWorkerDatabaseDoctorSection, WORKER_DATABASE_DOCTOR_TIMEOUT_MS, } from "./conductor/doctor.js";
@@ -81,10 +85,13 @@ import { buildHostPowerLaunchRow, buildSelfHostedRunnerLaunchRow, buildWorkerDbR
81
85
  import { createWorkflowSource, inspectRequiredSelfHostedRunners, } from "./conductor/launch-need-probes.js";
82
86
  import { createWorkerDatabaseDoctorInspector } from "./conductor/worker-database-doctor-inspector.js";
83
87
  import { ENGINE_PATHS } from "./engine-paths.js";
84
- import { policyDeclaresNotifyWebhook, policyNotifyDestinationsConflict, notifyDestinationsConflictMessage, effectivePolicyFacts, evaluateParallelPolicyPreflight, parseParallelLimit, readSetupEpicPolicyFile, retainedParallelLimitNotice, resolveFeatureBranchSelection, readCanonicalParseTruth as readSetupCanonicalParseTruth, runSetupEpicWorkflow, launchReconnectCommand, READINESS_UNKNOWN_CONTINUING_WARNING, RUN_WAITING_FOR_APPROVAL_PHRASE, formatSetupEpicAutoMergeIntent, resolveSetupEpicAutoMergeIntent, readinessSnapshotFromLaunchContext, } from "./setup-epic.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";
85
89
  import { getConfigFieldBaseBranch } from "./epic-shared/bridge-client.js";
90
+ import { createExecFileRunCommand, normalizeCommitSha } from "./epic-shared/cut-protocol.js";
86
91
  import { EPIC_KEY_PATTERN } from "./drive-epic-key.js";
87
- import { buildEpicLaunchContext, projectWorkerDatabase, readEpicLaunchContext, writeEpicLaunchContext, } from "./epic-launch-context.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";
93
+ import { hashPlan } from "./conductor/plan.js";
94
+ import { buildEpicLaunchContext, projectWorkerDatabase, readEpicLaunchContext, writeEpicLaunchContext, writeEpicLaunchOutcome, } from "./epic-launch-context.js";
88
95
  import { flushProcessStdout, writeJsonDocument } from "./conductor/json-output.js";
89
96
  import { BRIDGE_LAUNCHER_ENV } from "./bridge-permissions.js";
90
97
  import { checkPlaneBuildFreshness, PLANE_BUILD_FIX_REMEDIATION } from "./plane/build-freshness.js";
@@ -108,7 +115,7 @@ import { isTerminalEpicRunStatus } from "./epic-run-status.js";
108
115
  import { MCP_PACKAGE_NAME } from "./mcp-identity.js";
109
116
  import { getDriveEpicAdvancedUsage, getDriveEpicUsage } from "./drive-epic-help.js";
110
117
  export { getDriveEpicUsage };
111
- import { CONSUMER_GUIDE_POINTER, PRINTED_CHECK_NAME_INSTRUCTION, PRINTED_CONDUCTOR_INSTALL_COMMAND, PRINTED_DOCTOR_COMMAND, READINESS_PREREQUISITE_FIXES, resolveReadinessRemedy, } from "./printed-remedy-commands.js";
118
+ 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";
112
119
  /** The conductor paths. Derived types below come from this constant. */
113
120
  export const DRIVE_EPIC_CONDUCTORS = ["v2"];
114
121
  /**
@@ -316,11 +323,28 @@ function indexedWorkflowsRemedy(readiness) {
316
323
  const fix = row.fix.length > 0
317
324
  ? row.fix
318
325
  : resolveReadinessRemedy({ id: INDEXED_WORKFLOWS_ROW_ID, state: row.check_status === "unknown" ? "unknown" : "not_met" });
319
- if (fix === READINESS_PREREQUISITE_FIXES.no_index || fix === READINESS_PREREQUISITE_FIXES.reindex_manual) {
320
- return READINESS_PREREQUISITE_FIXES.reindex_manual;
326
+ // BAPI-1700 — the exact missing-workflow wire fix gets the display wording that
327
+ // names both ways forward. This must run before the passthrough below, which would
328
+ // otherwise print the managed-workflow instruction as is. Presentation only: the
329
+ // validated row keeps the server's fix.
330
+ const display = indexedWorkflowsDisplayRemedy({ id: row.id, fix }, readiness);
331
+ if (display !== fix)
332
+ return display;
333
+ // Exact known strings first; every other exact key and unknown text falls through
334
+ // to the substring predicates below, unchanged.
335
+ switch (classifyReadinessFix(fix)) {
336
+ case "no_index":
337
+ case "reindex_manual":
338
+ return READINESS_PREREQUISITE_FIXES.reindex_manual;
339
+ case "pending_index":
340
+ return "Wait for indexing to finish, then run drive-epic again.";
341
+ case "setup":
342
+ case "missing_workflow":
343
+ case "missing_review_and_managed_workflows":
344
+ return fix;
345
+ default:
346
+ break;
321
347
  }
322
- if (fix === READINESS_PREREQUISITE_FIXES.pending_index)
323
- return "Wait for indexing to finish, then run drive-epic again.";
324
348
  if (fix.includes("Merge the setup pull request") || fix === READINESS_PREREQUISITE_FIXES.setup || fix.includes("merge the workflow changes"))
325
349
  return fix;
326
350
  return INDEXED_WORKFLOWS_UNCLASSIFIED;
@@ -1184,6 +1208,9 @@ export async function readLiveEpicRunByKey(access, epicKey, fetchImpl = globalTh
1184
1208
  }
1185
1209
  }
1186
1210
  export function createDefaultDriveEpicDeps() {
1211
+ // BAPI-1706 — the environment before any launch-target adoption (see the
1212
+ // authored-plan seams below). A copy, so later adoption cannot change it.
1213
+ const normalServerEnv = { ...process.env };
1187
1214
  return {
1188
1215
  inspectRepositoryIdentity: async () => {
1189
1216
  const top = await createPlaneExecFile()("git", ["rev-parse", "--show-toplevel"], {
@@ -1200,6 +1227,7 @@ export function createDefaultDriveEpicDeps() {
1200
1227
  throw new Error("repository_identity_unverifiable");
1201
1228
  return { repoRoot, isBridge: applicability === "bridge" };
1202
1229
  },
1230
+ readCredentialReferenceStatus: (repoName) => statusOnly(repoName, createNodeCredentialReferenceDeps(process.env)),
1203
1231
  readScopeBaseBranch: async (access) => {
1204
1232
  const configured = await getConfigFieldBaseBranch(access, globalThis.fetch);
1205
1233
  if (!configured.ok)
@@ -1226,6 +1254,7 @@ export function createDefaultDriveEpicDeps() {
1226
1254
  },
1227
1255
  readReadiness: (access) => fetchConductorReadiness(access, globalThis.fetch),
1228
1256
  writeLaunchContext: (context) => writeEpicLaunchContext(context),
1257
+ writeLaunchOutcome: (input) => writeEpicLaunchOutcome(input),
1229
1258
  reportLaunch: (report) => console.error(`${LAUNCH_REPORT_PREFIX}${JSON.stringify(report)}`),
1230
1259
  runSetupEpic: (argv, handoff) => runSetupEpicWorkflow(argv, {}, handoff),
1231
1260
  readEligibilityArtifact: (path) => readFile(path, "utf8"),
@@ -1339,6 +1368,22 @@ export function createDefaultDriveEpicDeps() {
1339
1368
  validate: () => validateGeneratedPlan(access, epicKey, dag, (a, request) => validateEpicPlan(a, request)),
1340
1369
  rediscover: () => discoverEpicPlan(epicKey, docsDir, createDefaultPlanDiscoveryFs()),
1341
1370
  }),
1371
+ // BAPI-1706 — authored plans live on the normal Bridge server. The launch
1372
+ // adopts its target into `process.env.BAPI_BASE_URL` (adoptLaunchTarget) before
1373
+ // these run, so both resolve against the environment captured HERE, before any
1374
+ // adoption: a local-plane or --base-url launch still reads the normal server.
1375
+ lookupAuthoredPlan: (epicKey, repo) => lookupAuthoredPlanForLaunch(epicKey, repo, normalServerEnv),
1376
+ uploadAuthoredPlan: ({ epicKey, planDir, repo }) => saveLocalAuthoredPlan({
1377
+ ...createDefaultAuthoredPlanSaveDeps(),
1378
+ env: normalServerEnv,
1379
+ resolveAccess: (r) => resolveAuthoredPlanAccess(r, normalServerEnv),
1380
+ }, {
1381
+ epicKey,
1382
+ planDir,
1383
+ ...(repo !== undefined ? { repo } : {}),
1384
+ ifAbsent: true,
1385
+ }),
1386
+ materializeAuthoredPlan: (snapshot) => materializeAuthoredPlanSnapshot(snapshot),
1342
1387
  readPolicyFile: (filePath) => readFile(filePath, "utf8"),
1343
1388
  readLiveEpicRun: (access, epicKey) => readLiveEpicRunByKey(access, epicKey),
1344
1389
  previewSetupEpic: async ({ argv, baseUrl, handoff, observations, planContents }) => {
@@ -1434,6 +1479,8 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1434
1479
  if (parsed.options.dryRun === true) {
1435
1480
  return await runDriveEpicPreview(deps, parsed.options);
1436
1481
  }
1482
+ // BAPI-1706 — private server-plan hand-off folders, removed however the launch ends.
1483
+ const authoredPlanCleanups = [];
1437
1484
  try {
1438
1485
  // Every async branch below is `return await`ed. A bare `return promise`
1439
1486
  // inside this `try` would let a rejection skip the sanitizing `catch` at the
@@ -1471,6 +1518,7 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1471
1518
  liveObservation: {},
1472
1519
  invokedAt: new Date((deps.now ?? Date.now)()).toISOString(),
1473
1520
  launchReportState: { reported: false },
1521
+ launchOutcomeState: { warned: false },
1474
1522
  };
1475
1523
  // BAPI-1285 — with no `--plan-file`, look for the plan BEFORE readiness. A
1476
1524
  // discovered plan must count as a supplied one for the BAPI-1153 cold-start
@@ -1487,9 +1535,34 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1487
1535
  let planWasDiscovered = false;
1488
1536
  // BAPI-1621 — why automatic generation stopped, for the no-plan stop text.
1489
1537
  let generationReason;
1538
+ // BAPI-1706 — with no `--plan-file`, the normal Bridge server is asked FIRST, ONCE.
1539
+ // A found snapshot is the plan for this whole invocation; local files are only
1540
+ // compared with it. An unknown answer never falls back to a local or generated
1541
+ // plan: it stops when (and only when) the launch would create a run.
1542
+ let serverPlan = null;
1543
+ let authoredLookup = null;
1544
+ if (planFile === undefined && deps.lookupAuthoredPlan !== undefined) {
1545
+ authoredLookup = await deps
1546
+ .lookupAuthoredPlan(epicKey, repo)
1547
+ .catch(() => ({ lookup: { kind: "unknown", reason: "network" }, endpoint: null }));
1548
+ if (authoredLookup.lookup.kind === "found") {
1549
+ serverPlan = authoredLookup.lookup.snapshot;
1550
+ planWasDiscovered = true;
1551
+ ctx = { ...ctx, planProvenance: serverPlanProvenance(serverPlan, authoredLookup.endpoint), planHashEvidence: {} };
1552
+ }
1553
+ else if (authoredLookup.lookup.kind === "server_too_old") {
1554
+ deps.errorLog(`${epicKey}: ${AUTHORED_PLAN_SERVER_TOO_OLD_NOTICE}`);
1555
+ }
1556
+ }
1557
+ const authoredPlanUnknown = authoredLookup?.lookup.kind === "unknown";
1490
1558
  if (planFile === undefined) {
1491
1559
  const docs = await deps.resolveDocsDir();
1492
- if (docs.ok) {
1560
+ if (serverPlan !== null || authoredPlanUnknown) {
1561
+ // The local copy is observational only: it never displaces a verified server plan.
1562
+ if (serverPlan !== null && docs.ok)
1563
+ await observeIgnoredLocalPlan(ctx, docs.docsDir, serverPlan);
1564
+ }
1565
+ else if (docs.ok) {
1493
1566
  discovered = await discoverEpicPlan(epicKey, docs.docsDir, deps.discoveryFs);
1494
1567
  if (discovered.status === "plan_not_found") {
1495
1568
  const generated = await generateMissingPlanForLaunch(ctx, docs.docsDir, discovered);
@@ -1505,12 +1578,84 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1505
1578
  docsRootUnresolved = true;
1506
1579
  }
1507
1580
  }
1581
+ if (ctx.planProvenance === undefined) {
1582
+ const source = planFile !== undefined
1583
+ ? "explicit"
1584
+ : discovered?.status === "found"
1585
+ ? discovered.generated !== undefined
1586
+ ? "generated"
1587
+ : "local"
1588
+ : null;
1589
+ if (source !== null)
1590
+ ctx = { ...ctx, planProvenance: nonServerPlanProvenance(source), planHashEvidence: {} };
1591
+ }
1592
+ /**
1593
+ * BAPI-1706 — a local-only authored plan is uploaded (with `if_absent`) the first
1594
+ * time a REAL launch would create a run from it, and only after a definite "no
1595
+ * plan stored". The launch then uses exactly the snapshot the server returned —
1596
+ * its own, or a concurrent writer's. A generated plan is never uploaded.
1597
+ */
1598
+ const uploadLocalPlanIfNeeded = async () => {
1599
+ if (serverPlan !== null ||
1600
+ authoredLookup?.lookup.kind !== "not_stored" ||
1601
+ discovered?.status !== "found" ||
1602
+ discovered.generated !== undefined ||
1603
+ deps.uploadAuthoredPlan === undefined) {
1604
+ return { ok: true };
1605
+ }
1606
+ const uploaded = await deps
1607
+ .uploadAuthoredPlan({ epicKey, planDir: dirname(discovered.path), repo })
1608
+ .catch(() => null);
1609
+ if (uploaded === null || !uploaded.ok) {
1610
+ const retry = uploaded !== null && !uploaded.ok
1611
+ ? uploaded.retryCommand
1612
+ : `npx -y ${MCP_PACKAGE_NAME} epic-plan save --epic-key ${epicKey}`;
1613
+ return {
1614
+ ok: false,
1615
+ code: refuse(deps, [
1616
+ `${epicKey}: REFUSED (${AUTHORED_PLAN_UPLOAD_FAILED_REASON_ID}) — ${authoredPlanUploadFailedRemedy(retry)}`,
1617
+ ]),
1618
+ };
1619
+ }
1620
+ serverPlan = uploaded.result.snapshot;
1621
+ deps.log(`${epicKey}: saved the local plan to the Bridge server as authored version ` +
1622
+ `${serverPlan.authored_version}${uploaded.created ? "" : " (another save got there first; using it)"}.`);
1623
+ const provenance = serverPlanProvenance(serverPlan, uploaded.endpoint);
1624
+ if (ctx.planProvenance !== undefined)
1625
+ Object.assign(ctx.planProvenance, provenance);
1626
+ else
1627
+ ctx = { ...ctx, planProvenance: provenance, planHashEvidence: {} };
1628
+ return { ok: true };
1629
+ };
1630
+ /** Write the selected server snapshot to a private folder and select it for setup. */
1631
+ const selectServerPlanFile = async () => {
1632
+ if (serverPlan === null)
1633
+ return;
1634
+ const materialize = deps.materializeAuthoredPlan ?? materializeAuthoredPlanSnapshot;
1635
+ const written = await materialize(serverPlan);
1636
+ authoredPlanCleanups.push(() => written.cleanup());
1637
+ ctx = { ...ctx, options: { ...ctx.options, planFile: written.planPath } };
1638
+ };
1508
1639
  let foundPlanAnnounced = false;
1509
1640
  /** Names the found plan once, BEFORE anything is created, and surfaces its advisory. */
1510
1641
  const announceFoundPlan = async () => {
1511
- if (foundPlanAnnounced || discovered?.status !== "found")
1642
+ if (foundPlanAnnounced)
1643
+ return;
1644
+ if (serverPlan !== null && ctx.planProvenance !== undefined) {
1645
+ foundPlanAnnounced = true;
1646
+ deps.log(renderPlanProvenanceLine(epicKey, ctx.planProvenance));
1647
+ // BAPI-1706 — the stored eligibility advisory, the one the author saw.
1648
+ const advisory = serverPlan.eligibility_advisory !== null ? parseContainmentEligibilityArtifact(serverPlan.eligibility_advisory) : null;
1649
+ const advisoryText = advisory !== null ? renderContainmentEligibilityAdvisory(advisory) : null;
1650
+ if (advisoryText !== null)
1651
+ deps.log(advisoryText);
1652
+ return;
1653
+ }
1654
+ if (discovered?.status !== "found")
1512
1655
  return;
1513
1656
  foundPlanAnnounced = true;
1657
+ if (ctx.planProvenance !== undefined)
1658
+ deps.log(renderPlanProvenanceLine(epicKey, ctx.planProvenance));
1514
1659
  deps.log(`${epicKey}: using the plan found by epic key: ${discovered.path}`);
1515
1660
  };
1516
1661
  // --- No readiness read at launch (BAPI-1595). -----------------------------
@@ -1528,10 +1673,11 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1528
1673
  (discovered.status === "plan_not_found" || discovered.status === "plan_ambiguous")
1529
1674
  ? discovered
1530
1675
  : null;
1531
- if (planeEndpoint !== null && (ctx.options.planFile !== undefined || noPlanDiscovery !== null)) {
1676
+ if (planeEndpoint !== null &&
1677
+ (ctx.options.planFile !== undefined || noPlanDiscovery !== null || serverPlan !== null)) {
1532
1678
  const probe = await deps.probePlanePort(planeEndpoint.host, planeEndpoint.port).catch(() => ({ kind: "error" }));
1533
1679
  if (probe.kind === "refused") {
1534
- if (ctx.options.planFile !== undefined) {
1680
+ if (ctx.options.planFile !== undefined || serverPlan !== null) {
1535
1681
  // BAPI-1260 — only a SELECTED LOCAL plane is ever started here. A
1536
1682
  // profile approved for durable execution names an authority this
1537
1683
  // machine does not own, so a refused port is that authority being
@@ -1540,6 +1686,12 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1540
1686
  return escalate(deps, epicKey, `launch profile '${launchProfile.name}' selects durable execution, and its control plane is ` +
1541
1687
  "not answering; no local replacement was started");
1542
1688
  }
1689
+ // BAPI-1706 — a cold start creates a run, so a local-only plan is uploaded
1690
+ // first and the server snapshot is what the new plane receives.
1691
+ const upload = await uploadLocalPlanIfNeeded();
1692
+ if (!upload.ok)
1693
+ return upload.code;
1694
+ await selectServerPlanFile();
1543
1695
  // `coldStartPlane` surfaces the containment advisory itself.
1544
1696
  await announceFoundPlan();
1545
1697
  return await coldStartPlane(ctx);
@@ -1595,7 +1747,36 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1595
1747
  // A supplied plan always wins and skips ALL of this, including the extra
1596
1748
  // live-run read: setup-epic does its own Step 0 read and owns reuse.
1597
1749
  let discoveryStop;
1598
- if (planFile === undefined) {
1750
+ if (planFile === undefined && (serverPlan !== null || authoredPlanUnknown)) {
1751
+ // BAPI-1706 — the server answered "found", or could not answer. The live-run
1752
+ // decision still comes first: a live run is attached to with the plan it was
1753
+ // created with, and nothing is uploaded or written.
1754
+ const live = await acquireObservedLive(ctx);
1755
+ if (live.kind === "conflict")
1756
+ return refuse(deps, liveRunAmbiguousRefusal(epicKey).lines);
1757
+ if (live.kind === "live") {
1758
+ if (serverPlan !== null) {
1759
+ deps.log(`${epicKey}: a run is already live; it keeps the plan it was created with.`);
1760
+ }
1761
+ return await attachToLiveRun(ctx, readiness, live);
1762
+ }
1763
+ if (serverPlan === null) {
1764
+ return refuse(deps, [
1765
+ `${epicKey}: REFUSED (${AUTHORED_PLAN_UNKNOWN_REASON_ID}) — ${authoredPlanUnknownRemedy(epicKey, repo)}`,
1766
+ ]);
1767
+ }
1768
+ await selectServerPlanFile();
1769
+ const prepared = await prepareSetupSelection(ctx);
1770
+ if (!prepared.ok) {
1771
+ return refuse(deps, [
1772
+ `${epicKey}: REFUSED (${prepared.reasonId}) — the selected run or policy could not be verified.`,
1773
+ "Nothing was created or started.",
1774
+ ]);
1775
+ }
1776
+ ctx = { ...ctx, handoff: prepared.handoff };
1777
+ await announceFoundPlan();
1778
+ }
1779
+ else if (planFile === undefined) {
1599
1780
  if (docsRootUnresolved || discovered === null) {
1600
1781
  return refuse(deps, docsRootRefusal(epicKey).lines);
1601
1782
  }
@@ -1616,6 +1797,12 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1616
1797
  const { planFile: _unusedDiscoveredPlan, ...attachOptions } = ctx.options;
1617
1798
  return await attachToLiveRun({ ...ctx, options: attachOptions }, readiness, live, discovered.path);
1618
1799
  }
1800
+ // BAPI-1706 — the first real create from a local-only authored plan uploads
1801
+ // it, then runs the server-confirmed snapshot.
1802
+ const upload = await uploadLocalPlanIfNeeded();
1803
+ if (!upload.ok)
1804
+ return upload.code;
1805
+ await selectServerPlanFile();
1619
1806
  // The create path: setup selection runs now. The plan was folded into
1620
1807
  // `ctx.options` before readiness; from here it is indistinguishable from
1621
1808
  // a supplied `--plan-file`.
@@ -1858,6 +2045,10 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1858
2045
  deps.errorLog(`drive-epic failed: ${safeDiagnosticMessage(err, "unexpected error")}`);
1859
2046
  return 1;
1860
2047
  }
2048
+ finally {
2049
+ for (const cleanup of authoredPlanCleanups)
2050
+ await cleanup();
2051
+ }
1861
2052
  }
1862
2053
  /**
1863
2054
  * BAPI-1285 — the one remedy sentence an unknown-readiness escalation ends with.
@@ -1893,6 +2084,8 @@ function escalate(deps, epicKey, reason) {
1893
2084
  deps.errorLog(text);
1894
2085
  return 1;
1895
2086
  }
2087
+ /** BAPI-1686 — said on every healthy-launch success output. */
2088
+ 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.";
1896
2089
  /** The prefix of the default launch-report line. */
1897
2090
  export const LAUNCH_REPORT_PREFIX = "Launch report: ";
1898
2091
  /** How long drive-epic watches a planning run for activation after an uncertain approve. */
@@ -1987,6 +2180,61 @@ async function planGenerationAllowed(fs, epicKey, discovery, attempt) {
1987
2180
  function observeLaunch(ctx, code, message) {
1988
2181
  ctx.launchObservations?.push({ code, message, at: launchNowIso(ctx) });
1989
2182
  }
2183
+ /** BAPI-1706 — the observation code for a local plan that differs from the server plan. */
2184
+ export const LOCAL_PLAN_IGNORED_CODE = "local_plan_ignored";
2185
+ /**
2186
+ * BAPI-1706 — compare the local authored plan (if any) with the selected server
2187
+ * snapshot. A differing readable local DAG is named, never used. A failed read or
2188
+ * an ambiguous folder never displaces or blocks the verified server plan.
2189
+ * Returns the ignored path, or null.
2190
+ */
2191
+ async function localPlanIgnoredPath(deps, epicKey, docsDir, serverPlan) {
2192
+ try {
2193
+ const local = await discoverEpicPlan(epicKey, docsDir, deps.discoveryFs);
2194
+ if (local.status !== "found" || local.generated !== undefined)
2195
+ return null;
2196
+ const parsed = JSON.parse(await deps.readPlanDag(local.path));
2197
+ const localHash = hashPlan(parsed);
2198
+ return localHash === serverPlan.plan_hash ? null : local.path;
2199
+ }
2200
+ catch {
2201
+ return null;
2202
+ }
2203
+ }
2204
+ async function observeIgnoredLocalPlan(ctx, docsDir, serverPlan) {
2205
+ const ignored = await localPlanIgnoredPath(ctx.deps, ctx.epicKey, docsDir, serverPlan);
2206
+ if (ignored === null)
2207
+ return;
2208
+ const message = `local plan ignored: ${ignored} differs from the stored plan (authored version ` +
2209
+ `${serverPlan.authored_version}). Pass it with --plan-file to use it, or save it with epic-plan save.`;
2210
+ observeLaunch(ctx, LOCAL_PLAN_IGNORED_CODE, message);
2211
+ ctx.deps.errorLog(`${ctx.epicKey}: ${message}`);
2212
+ }
2213
+ /**
2214
+ * BAPI-1706 — fill the run-hash fields of the provenance from what setup-epic
2215
+ * stored. Only a store made in this invocation reports a run hash.
2216
+ */
2217
+ function recordRunPlanHash(ctx, result) {
2218
+ const provenance = ctx.planProvenance;
2219
+ if (provenance === undefined || result.storedPlanHash === undefined)
2220
+ return;
2221
+ provenance.run_plan_hash = result.storedPlanHash;
2222
+ if (provenance.plan_hash === null)
2223
+ return;
2224
+ const reasons = explainRunPlanHash({
2225
+ authoredHash: provenance.plan_hash,
2226
+ runHash: result.storedPlanHash,
2227
+ ...(ctx.planHashEvidence?.trimmedHash !== undefined ? { trimmedHash: ctx.planHashEvidence.trimmedHash } : {}),
2228
+ ...(result.orderingEdgesAdded !== undefined ? { orderingEdgesAdded: result.orderingEdgesAdded } : {}),
2229
+ });
2230
+ if (reasons.length === 0) {
2231
+ delete provenance.hash_difference;
2232
+ return;
2233
+ }
2234
+ provenance.hash_difference = reasons;
2235
+ ctx.deps.log(`${ctx.epicKey}: the run's plan hash ${result.storedPlanHash.slice(0, 12)} differs from the authored hash ` +
2236
+ `${provenance.plan_hash.slice(0, 12)} (${reasons.join(", ")}).`);
2237
+ }
1990
2238
  // ---------------------------------------------------------------------------
1991
2239
  // BAPI-1595 — fixed tally lines and stable reason codes
1992
2240
  // ---------------------------------------------------------------------------
@@ -2172,7 +2420,7 @@ async function acquireObservedLive(ctx) {
2172
2420
  * Print the launch report once per invocation. Setup's observations follow
2173
2421
  * drive's own, in order, with exact duplicates dropped.
2174
2422
  */
2175
- function reportLaunchOutcome(ctx, outcome, facts) {
2423
+ async function reportLaunchOutcome(ctx, outcome, facts) {
2176
2424
  const state = ctx.launchReportState;
2177
2425
  if (state === undefined || state.reported)
2178
2426
  return;
@@ -2195,12 +2443,59 @@ function reportLaunchOutcome(ctx, outcome, facts) {
2195
2443
  invoked_at: ctx.invokedAt ?? at,
2196
2444
  first_claimed_job_at: "pending",
2197
2445
  observations,
2446
+ ...(ctx.planProvenance !== undefined ? { plan: { ...ctx.planProvenance } } : {}),
2198
2447
  };
2199
2448
  ctx.deps.reportLaunch?.(report);
2449
+ // The durable record: best-effort, so a write failure never changes the exit code.
2450
+ const record = {
2451
+ outcome,
2452
+ ...(facts.epicRunId !== undefined ? { epicRunId: facts.epicRunId } : {}),
2453
+ ...(facts.runStatus !== undefined ? { runStatus: facts.runStatus } : {}),
2454
+ ...(facts.refusedBeforeCreate === true ? { refusedBeforeCreate: true } : {}),
2455
+ ...(facts.branchMove !== undefined ? { branchMove: facts.branchMove } : {}),
2456
+ observations: observations.map((o) => ({ code: o.code })),
2457
+ };
2458
+ if (ctx.launchOutcomeState !== undefined)
2459
+ ctx.launchOutcomeState.last = record;
2460
+ await writeLaunchOutcomeRecord(ctx, record, "not_applicable");
2461
+ }
2462
+ /**
2463
+ * Write `launch-outcome.json` for this invocation. Awaited, never throws, and
2464
+ * never a stop: a failed or refused write prints one fixed warning per invocation
2465
+ * and the caller carries on with its primary exit code.
2466
+ */
2467
+ async function writeLaunchOutcomeRecord(ctx, record, windDown) {
2468
+ const write = ctx.deps.writeLaunchOutcome;
2469
+ if (write === undefined)
2470
+ return true;
2471
+ let ok = false;
2472
+ try {
2473
+ const written = await write({
2474
+ epicKey: ctx.epicKey,
2475
+ invokedAt: ctx.invokedAt ?? launchNowIso(ctx),
2476
+ writtenAt: launchNowIso(ctx),
2477
+ launchOutcome: record.outcome,
2478
+ epicRunId: record.epicRunId ?? null,
2479
+ runStatus: record.runStatus ?? null,
2480
+ refusedBeforeCreate: record.refusedBeforeCreate === true,
2481
+ branchMove: record.branchMove ?? null,
2482
+ windDown,
2483
+ observations: record.observations,
2484
+ });
2485
+ ok = written.ok;
2486
+ }
2487
+ catch {
2488
+ ok = false;
2489
+ }
2490
+ if (!ok && ctx.launchOutcomeState !== undefined && !ctx.launchOutcomeState.warned) {
2491
+ ctx.launchOutcomeState.warned = true;
2492
+ ctx.deps.errorLog(`${ctx.epicKey}: [warn] The launch outcome record could not be written; the exit code is unchanged.`);
2493
+ }
2494
+ return ok;
2200
2495
  }
2201
2496
  /** A refusal that also settles the launch outcome. */
2202
- function refuseLaunch(ctx, lines) {
2203
- reportLaunchOutcome(ctx, "refused", {});
2497
+ async function refuseLaunch(ctx, lines) {
2498
+ await reportLaunchOutcome(ctx, "refused", {});
2204
2499
  return refuse(ctx.deps, lines);
2205
2500
  }
2206
2501
  /**
@@ -2242,19 +2537,21 @@ async function settleSetupLaunch(ctx, setup) {
2242
2537
  ...(setup.epicRunId !== undefined ? { epicRunId: setup.epicRunId } : {}),
2243
2538
  ...(setup.runStatus !== undefined ? { runStatus: setup.runStatus } : {}),
2244
2539
  ...(setup.observations !== undefined ? { observations: setup.observations } : {}),
2540
+ ...(setup.refusedBeforeCreate === true ? { refusedBeforeCreate: true } : {}),
2541
+ ...(setup.branchMove !== undefined ? { branchMove: setup.branchMove } : {}),
2245
2542
  };
2246
2543
  if (setup.exitCode !== 0) {
2247
- reportLaunchOutcome(ctx, setup.launchOutcome === "terminal" ? "terminal" : "refused", facts);
2544
+ await reportLaunchOutcome(ctx, setup.launchOutcome === "terminal" ? "terminal" : "refused", facts);
2248
2545
  return setup;
2249
2546
  }
2250
2547
  if (setup.launchOutcome === "not_confirmed") {
2251
- reportLaunchOutcome(ctx, "not_confirmed", facts);
2548
+ await reportLaunchOutcome(ctx, "not_confirmed", facts);
2252
2549
  return { ...setup, launchHandled: true };
2253
2550
  }
2254
2551
  if (setup.launchOutcome === "pending_activation" && setup.epicRunId !== undefined) {
2255
2552
  if (setup.runStatus !== "planning") {
2256
2553
  deps.log(`${epicKey}: run ${setup.epicRunId} is ${setup.runStatus ?? "not active"}; attached without changing it.`);
2257
- reportLaunchOutcome(ctx, "pending_activation", facts);
2554
+ await reportLaunchOutcome(ctx, "pending_activation", facts);
2258
2555
  return { ...setup, launchHandled: true };
2259
2556
  }
2260
2557
  deps.errorLog(`${epicKey}: run ${setup.epicRunId}: ${RUN_WAITING_FOR_APPROVAL_PHRASE}. Watching for activation ` +
@@ -2262,22 +2559,22 @@ async function settleSetupLaunch(ctx, setup) {
2262
2559
  const activation = await awaitRunActivation(ctx, setup.epicRunId);
2263
2560
  if (activation.kind === "active") {
2264
2561
  observeLaunch(ctx, "launch_outcome_reread", "approve re-read: run activated while attached");
2265
- reportLaunchOutcome(ctx, "active", { ...facts, runStatus: "active" });
2562
+ await reportLaunchOutcome(ctx, "active", { ...facts, runStatus: "active" });
2266
2563
  return { ...setup, launchOutcome: "active", runStatus: "active" };
2267
2564
  }
2268
2565
  if (activation.kind === "changed") {
2269
2566
  const terminal = isTerminalEpicRunStatus(activation.status);
2270
2567
  deps.log(`${epicKey}: run ${setup.epicRunId} is ${activation.status}; attached without changing it.`);
2271
- reportLaunchOutcome(ctx, terminal ? "terminal" : "pending_activation", { ...facts, runStatus: activation.status });
2568
+ await reportLaunchOutcome(ctx, terminal ? "terminal" : "pending_activation", { ...facts, runStatus: activation.status });
2272
2569
  return { ...setup, exitCode: terminal ? 1 : 0, launchHandled: true };
2273
2570
  }
2274
2571
  deps.errorLog(`${epicKey}: [warn] ${APPROVAL_NOT_CONFIRMED_WARNING}. Re-run setup with: ` +
2275
2572
  launchReconnectCommand(epicKey, ctx.access));
2276
- reportLaunchOutcome(ctx, "pending_activation", facts);
2573
+ await reportLaunchOutcome(ctx, "pending_activation", facts);
2277
2574
  return { ...setup, launchHandled: true };
2278
2575
  }
2279
2576
  // Never inferred from exit 0: only a reported `active` status counts.
2280
- reportLaunchOutcome(ctx, setup.launchOutcome === "active" || setup.runStatus === "active" ? "active" : "pending_activation", facts);
2577
+ await reportLaunchOutcome(ctx, setup.launchOutcome === "active" || setup.runStatus === "active" ? "active" : "pending_activation", facts);
2281
2578
  return setup;
2282
2579
  }
2283
2580
  /** Resolve policy intent once for the setup delegation, after a fresh run read. */
@@ -2561,7 +2858,9 @@ function reportPlaneCapacity(ctx, lanes, storedLimit, posture) {
2561
2858
  * its caller returns its exit code without requesting lanes or an executor.
2562
2859
  */
2563
2860
  async function runSelectedSetupEpic(ctx) {
2564
- return settleSetupLaunch(ctx, await runSelectedSetupEpicWorkflow(ctx));
2861
+ const result = await runSelectedSetupEpicWorkflow(ctx);
2862
+ recordRunPlanHash(ctx, result);
2863
+ return settleSetupLaunch(ctx, result);
2565
2864
  }
2566
2865
  async function runSelectedSetupEpicWorkflow(ctx) {
2567
2866
  const selected = ctx.handoff
@@ -2569,7 +2868,7 @@ async function runSelectedSetupEpicWorkflow(ctx) {
2569
2868
  : await prepareSetupSelection(ctx);
2570
2869
  if (!selected.ok) {
2571
2870
  ctx.deps.errorLog(`${ctx.epicKey}: REFUSED (${selected.reasonId}) — the selected run or policy could not be verified.`);
2572
- return { exitCode: 1 };
2871
+ return { exitCode: 1, refusedBeforeCreate: true };
2573
2872
  }
2574
2873
  // BAPI-1595 — readiness is acquired by the PREVIEW and never by a launch. The
2575
2874
  // hand-off says so explicitly (an in-process contract, not an argv flag), and
@@ -2598,7 +2897,7 @@ async function runSelectedSetupEpicWorkflow(ctx) {
2598
2897
  if (evaluation.refusals.length > 0) {
2599
2898
  deps.errorLog(`${epicKey}: REFUSED (skip-child-refused) — ${skipRefusalRemedy(evaluation.refusals)}`);
2600
2899
  deps.errorLog("No run was created.");
2601
- return { exitCode: 1 };
2900
+ return { exitCode: 1, refusedBeforeCreate: true };
2602
2901
  }
2603
2902
  if (evaluation.state.status === "not_checked") {
2604
2903
  if (evaluation.state.reason === "cut_commit_unavailable" || evaluation.state.reason === "check_failed") {
@@ -2612,7 +2911,7 @@ async function runSelectedSetupEpicWorkflow(ctx) {
2612
2911
  if (evaluation.skipKeys.size >= evaluation.childKeys.length) {
2613
2912
  deps.errorLog(`${epicKey}: REFUSED (${EPIC_ALREADY_COMPLETE_REASON_ID}) — ${EPIC_ALREADY_COMPLETE_REMEDY}`);
2614
2913
  deps.errorLog("No run was created.");
2615
- return { exitCode: 1 };
2914
+ return { exitCode: 1, refusedBeforeCreate: true };
2616
2915
  }
2617
2916
  const skipped = evaluation.childKeys
2618
2917
  .filter((key) => evaluation.skipKeys.has(key))
@@ -2632,6 +2931,15 @@ async function runSelectedSetupEpicWorkflow(ctx) {
2632
2931
  }
2633
2932
  }
2634
2933
  const trimmed = trimDonePlanNodes(evaluation.plan, evaluation.skipKeys);
2934
+ // BAPI-1706 — the post-trim hash, so a run hash that differs only by the trim is explained.
2935
+ if (ctx.planHashEvidence !== undefined) {
2936
+ try {
2937
+ ctx.planHashEvidence.trimmedHash = hashPlan(trimmed);
2938
+ }
2939
+ catch {
2940
+ // No evidence recorded: a differing run hash is then reported as unknown.
2941
+ }
2942
+ }
2635
2943
  const withPath = deps.withPlanPath ?? withPlanPath;
2636
2944
  const result = await withPath({
2637
2945
  originalPath: planPath,
@@ -3704,6 +4012,63 @@ async function attachToPlane(ctx, manifest, readiness) {
3704
4012
  laneCount: attachedPlaneLaneCount(manifest),
3705
4013
  }, readiness);
3706
4014
  }
4015
+ /**
4016
+ * The first lines of a setup refusal's follow-up text: the outcome first. A proven
4017
+ * pre-create refusal leads with "No run was created."; a confirmed branch move is
4018
+ * always named, so nothing ever claims "no branch changed" after one. Anything not
4019
+ * proven keeps today's text (no lead at all).
4020
+ */
4021
+ function refusalLeadLines(setup) {
4022
+ const lines = [];
4023
+ if (setup.refusedBeforeCreate === true)
4024
+ lines.push("", "No run was created.");
4025
+ if (setup.branchMove !== undefined) {
4026
+ const { branch, from, to } = setup.branchMove;
4027
+ lines.push(`Branch origin/${branch} was moved from ${from} to ${to} before this refusal.`);
4028
+ }
4029
+ return lines;
4030
+ }
4031
+ /**
4032
+ * Wind down the plane THIS invocation launched, but only when a leftover plane is
4033
+ * proven to hold no run: setup refused before any create request, no run id was
4034
+ * resolved, the plane was launched here (not attached), and a fresh manifest read
4035
+ * names the same plane with no bound run. Everything else returns
4036
+ * `not_applicable` and starts no shutdown.
4037
+ *
4038
+ * The outcome record is written (and awaited) as `pending` BEFORE `plane down`, and
4039
+ * rewritten as `completed` or `failed` after. A failed record write never blocks the
4040
+ * shutdown (the record is best-effort), and a failed shutdown never changes the
4041
+ * setup failure's exit code. `plane down` keeps enforcing its own ownership checks;
4042
+ * no retry, lifecycle state, or supervisor change is added here.
4043
+ */
4044
+ async function windDownProvenUnboundPlane(ctx, plane, setup) {
4045
+ if (setup.refusedBeforeCreate !== true || plane.origin !== "launched" || setup.epicRunId !== undefined) {
4046
+ return "not_applicable";
4047
+ }
4048
+ let unbound = false;
4049
+ try {
4050
+ const read = await ctx.deps.readPlaneManifest(plane.repoRoot);
4051
+ unbound = read.kind === "valid" && read.manifest.planeId === plane.planeId && read.manifest.epicRunId === undefined;
4052
+ }
4053
+ catch {
4054
+ unbound = false;
4055
+ }
4056
+ if (!unbound)
4057
+ return "not_applicable";
4058
+ const last = ctx.launchOutcomeState?.last ?? { outcome: "refused", observations: [] };
4059
+ const record = { ...last, refusedBeforeCreate: true };
4060
+ await writeLaunchOutcomeRecord(ctx, record, "pending");
4061
+ let confirmed = false;
4062
+ try {
4063
+ confirmed = (await ctx.deps.runPlane(["down"], { cwd: plane.repoRoot })) === 0;
4064
+ }
4065
+ catch {
4066
+ confirmed = false;
4067
+ }
4068
+ const finalState = confirmed ? "completed" : "failed";
4069
+ await writeLaunchOutcomeRecord(ctx, record, finalState);
4070
+ return finalState;
4071
+ }
3707
4072
  /**
3708
4073
  * The shared tail: create/approve/cut through `setup-epic`, then request lanes
3709
4074
  * scoped to exactly that run.
@@ -3728,25 +4093,43 @@ async function createRunAndRequestLanes(ctx, plane, readiness) {
3728
4093
  if (setup.launchHandled === true)
3729
4094
  return setup.exitCode;
3730
4095
  if (setup.exitCode !== 0) {
3731
- // The control plane is deliberately LEFT RUNNING, and NO EXECUTOR LANE
3732
- // was spawned — there is nothing to claim a job that may not exist.
3733
- // Winding down automatically would stop the very run `setup-epic` may
3734
- // have just created, because `plane down` stops the manifest-bound run
3735
- // before terminating processes.
3736
- deps.errorLog((launched
3737
- ? [
3738
- "",
3739
- `${epicKey}: the Epic Implementer CONTROL PLANE was started by this invocation and is STILL RUNNING.`,
3740
- "No executor lane was spawned, so nothing is claiming jobs.",
3741
- "It was not wound down automatically, because doing so would stop a run that may",
3742
- "already have been created and approved. Inspect it with `plane status`, and wind it",
3743
- "down with `plane down` once you have decided what to do with the run.",
3744
- ]
3745
- : [
3746
- "",
3747
- `${epicKey}: the plane this invocation attached to was left running exactly as it was.`,
3748
- "No executor lane was requested. Inspect it with `plane status`.",
3749
- ]).join("\n"));
4096
+ // The control plane is LEFT RUNNING unless a narrow case is PROVEN safe, and NO
4097
+ // EXECUTOR LANE was spawned — there is nothing to claim a job that may not exist.
4098
+ // Winding down in general would stop the very run `setup-epic` may have just
4099
+ // created, because `plane down` stops the manifest-bound run before terminating
4100
+ // processes. The one exception is below: setup proved (by control flow, never by
4101
+ // text or exit code) that it refused BEFORE any create request, this invocation
4102
+ // started the plane, no run id was resolved, and the plane's manifest still names
4103
+ // this plane with no bound run. Then no run exists for `plane down` to stop.
4104
+ const windDown = await windDownProvenUnboundPlane(ctx, plane, setup);
4105
+ const lead = refusalLeadLines(setup);
4106
+ if (windDown === "completed") {
4107
+ deps.errorLog([...lead, `${epicKey}: the control plane this invocation started was shut down automatically.`].join("\n"));
4108
+ return setup.exitCode;
4109
+ }
4110
+ deps.errorLog([
4111
+ ...lead,
4112
+ ...(windDown === "failed"
4113
+ ? [
4114
+ "",
4115
+ `${epicKey}: Automatic shutdown could not be confirmed. Check the plane with \`plane status\`,`,
4116
+ "and wind it down with `plane down` if it is still running.",
4117
+ ]
4118
+ : launched
4119
+ ? [
4120
+ "",
4121
+ `${epicKey}: the Epic Implementer CONTROL PLANE was started by this invocation and is STILL RUNNING.`,
4122
+ "No executor lane was spawned, so nothing is claiming jobs.",
4123
+ "It was not wound down automatically, because doing so would stop a run that may",
4124
+ "already have been created and approved. Inspect it with `plane status`, and wind it",
4125
+ "down with `plane down` once you have decided what to do with the run.",
4126
+ ]
4127
+ : [
4128
+ "",
4129
+ `${epicKey}: the plane this invocation attached to was left running exactly as it was.`,
4130
+ "No executor lane was requested. Inspect it with `plane status`.",
4131
+ ]),
4132
+ ].join("\n"));
3750
4133
  return setup.exitCode;
3751
4134
  }
3752
4135
  if (setup.epicRunId === undefined) {
@@ -3805,6 +4188,7 @@ async function createRunAndRequestLanes(ctx, plane, readiness) {
3805
4188
  `${epicKey}: attached — executor lane(s) scoped to run ${setup.epicRunId} were requested`,
3806
4189
  "from the running plane, whose runtime starts them and then the dead-man observer.",
3807
4190
  "`plane status` reports their progress; the run's own status reports dispatch.",
4191
+ KEEP_TERMINAL_OPEN_LINE,
3808
4192
  ].join("\n"));
3809
4193
  return 0;
3810
4194
  }
@@ -3840,6 +4224,7 @@ async function createRunAndRequestLanes(ctx, plane, readiness) {
3840
4224
  "That reports PROCESSES. If this run cuts an epic branch, the reconciler holds ticket",
3841
4225
  "dispatch until its index scope finishes preparing; `plane status` and the run's own",
3842
4226
  "status report that separately.",
4227
+ KEEP_TERMINAL_OPEN_LINE,
3843
4228
  ].join("\n"));
3844
4229
  return 0;
3845
4230
  }
@@ -4065,7 +4450,7 @@ async function createRunWithRunExecutor(ctx, readiness) {
4065
4450
  return setup.exitCode;
4066
4451
  if (setup.exitCode !== 0) {
4067
4452
  // setup-epic already said why. Nothing was started for a run that may not exist.
4068
- deps.errorLog(`\n${epicKey}: no executor was started.`);
4453
+ deps.errorLog([...refusalLeadLines(setup), `\n${epicKey}: no executor was started.`].join("\n"));
4069
4454
  return setup.exitCode;
4070
4455
  }
4071
4456
  if (setup.epicRunId === undefined) {
@@ -4150,6 +4535,7 @@ function reportExecutorOutcome(ctx, ensured, epicRunId, framing) {
4150
4535
  "It runs on THIS machine: sleep is held off while it runs, but a closed lid, a logout, or a",
4151
4536
  "shutdown stops it. The run stays server-side either way; restart the executor, or use a",
4152
4537
  "durable launch profile for long runs.",
4538
+ KEEP_TERMINAL_OPEN_LINE,
4153
4539
  ].join("\n"));
4154
4540
  return 0;
4155
4541
  }
@@ -4210,7 +4596,7 @@ async function attachToLiveRun(ctx, readiness, live, unusedDiscoveredPlan) {
4210
4596
  return refuseRemoteRuntime(ctx, readiness);
4211
4597
  return refuse(deps, localReconcilerRefusal(epicKey, readiness).lines);
4212
4598
  }
4213
- reportLaunchOutcome(ctx, live.status === "active" ? "active" : "pending_activation", {
4599
+ await reportLaunchOutcome(ctx, live.status === "active" ? "active" : "pending_activation", {
4214
4600
  epicRunId: live.epicRunId,
4215
4601
  runStatus: live.status,
4216
4602
  });
@@ -4694,6 +5080,32 @@ async function readGeneratedPlanNodes(deps, planPath) {
4694
5080
  return null;
4695
5081
  }
4696
5082
  }
5083
+ /**
5084
+ * BAPI-1648 — the names of approved credential references whose source is
5085
+ * missing or unreadable. The repository name is the verified Bridge name the
5086
+ * preview already resolved, never a folder or remote name. Every failure, and an
5087
+ * absent or unusable record, yields an empty list: this is a display aid and
5088
+ * must not reach launch control flow.
5089
+ */
5090
+ async function collectMissingCredentialNames(deps, observed) {
5091
+ const repoName = observed.repoName ?? observed.access?.repoName ?? observed.contextAccess?.repoName;
5092
+ if (repoName === undefined || deps.readCredentialReferenceStatus === undefined)
5093
+ return [];
5094
+ try {
5095
+ const result = await deps.readCredentialReferenceStatus(repoName);
5096
+ if (result.state !== "ok")
5097
+ return [];
5098
+ const names = new Set();
5099
+ for (const status of result.statuses) {
5100
+ if (status.state === "missing" || status.state === "unreadable")
5101
+ names.add(status.name);
5102
+ }
5103
+ return [...names].sort();
5104
+ }
5105
+ catch {
5106
+ return [];
5107
+ }
5108
+ }
4697
5109
  /**
4698
5110
  * Run the read-only preview. Returns `0` for a `create` or `attach` decision and
4699
5111
  * `1` for `refuse` or `stop`. Never throws: an unexpected failure becomes one
@@ -4776,6 +5188,7 @@ async function runDriveEpicPreview(deps, options) {
4776
5188
  });
4777
5189
  }
4778
5190
  ensureRefusalExplained(preview);
5191
+ preview.credentials_missing = await collectMissingCredentialNames(deps, observed);
4779
5192
  await writePreviewLaunchContext(deps, options, preview, observed);
4780
5193
  if (observed.repository?.isBridge === false && !preview.launch_checks?.some((row) => row.id === "plane-snapshot-freshness")) {
4781
5194
  preview.launch_checks = [...(preview.launch_checks ?? []), ...nonBridgeRows(["plane-snapshot-freshness", "plane-database-head"])];
@@ -4901,13 +5314,25 @@ async function collectLaunchPlanFacts(deps, options, preview, observed) {
4901
5314
  const presence = new Map();
4902
5315
  const missing = new Map();
4903
5316
  const runtimeChildren = new Set();
5317
+ // BAPI-1704: open decisions are advisory facts, kept apart from every prerequisite
5318
+ // path (no runtime classification, presence check, or kept-off-screen count).
5319
+ const openDecisions = [];
5320
+ const openDecisionSeen = new Set();
4904
5321
  const kept = { minor: 0, "observed present": 0, "worker runtime": 0, "not measurable": 0, skipped: 0 };
4905
5322
  for (const entry of read.entries) {
4906
5323
  if (!members.has(entry.child)) {
4907
- kept.skipped += entry.items.length;
5324
+ kept.skipped += entry.items.filter((item) => !("category" in item && item.category === "open-decision")).length;
4908
5325
  continue;
4909
5326
  }
4910
5327
  for (const item of entry.items) {
5328
+ if ("category" in item && item.category === "open-decision") {
5329
+ const dedupeKey = `${entry.child}\u0000${item.evidence.replace(/\s+/g, " ").trim()}`;
5330
+ if (!openDecisionSeen.has(dedupeKey)) {
5331
+ openDecisionSeen.add(dedupeKey);
5332
+ openDecisions.push({ child: entry.child, summary: item.requirement, clause: item.evidence });
5333
+ }
5334
+ continue;
5335
+ }
4911
5336
  if ("category" in item) {
4912
5337
  kept["worker runtime"] += 1;
4913
5338
  runtimeChildren.add(entry.child);
@@ -4938,6 +5363,13 @@ async function collectLaunchPlanFacts(deps, options, preview, observed) {
4938
5363
  : { ...prior, dependents: prior.dependents.split(", ").includes(item.dependents) ? prior.dependents : `${prior.dependents}, ${item.dependents}` });
4939
5364
  }
4940
5365
  }
5366
+ for (const decision of openDecisions) {
5367
+ // Redacted at the display boundary; the evidence clause is never recorded.
5368
+ tally.push({
5369
+ code: "prerequisite_open_decision",
5370
+ line: `prerequisite scan child ${decision.child}: open decision: ${redactSecrets(decision.summary)}`,
5371
+ });
5372
+ }
4941
5373
  for (const [category, count] of Object.entries(kept)) {
4942
5374
  if (count > 0)
4943
5375
  tally.push({ code: "prerequisite_kept_off_screen", line: `prerequisite scan: kept off the screen: ${category} ${count}` });
@@ -4946,6 +5378,7 @@ async function collectLaunchPlanFacts(deps, options, preview, observed) {
4946
5378
  status: "collected",
4947
5379
  missingCore: [...missing.values()],
4948
5380
  workerRuntimeChildren: [...runtimeChildren],
5381
+ openDecisions,
4949
5382
  };
4950
5383
  }
4951
5384
  }
@@ -5332,8 +5765,55 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5332
5765
  let generationReason;
5333
5766
  let generatedLiveRunChecked = false;
5334
5767
  let docsRootUnresolved = false;
5768
+ // BAPI-1706 — the same server-first precedence the launch uses, read once and
5769
+ // written nowhere: no upload, no temporary folder, no local file.
5770
+ let previewProvenance = null;
5771
+ let authoredLookupKind = "skipped";
5772
+ let previewServerPlan = null;
5773
+ if (planPath === undefined && deps.lookupAuthoredPlan !== undefined) {
5774
+ const authored = await deps
5775
+ .lookupAuthoredPlan(epicKey, options.repo)
5776
+ .catch(() => ({ lookup: { kind: "unknown", reason: "network" }, endpoint: null }));
5777
+ authoredLookupKind = authored.lookup.kind;
5778
+ if (authored.lookup.kind === "found") {
5779
+ previewServerPlan = authored.lookup.snapshot;
5780
+ previewProvenance = serverPlanProvenance(previewServerPlan, authored.endpoint);
5781
+ }
5782
+ else if (authored.lookup.kind === "server_too_old") {
5783
+ (preview.warnings ??= []).push(AUTHORED_PLAN_SERVER_TOO_OLD_NOTICE);
5784
+ }
5785
+ }
5335
5786
  if (planPath !== undefined) {
5336
5787
  plan = { status: "supplied", path: planPath };
5788
+ previewProvenance = nonServerPlanProvenance("explicit");
5789
+ }
5790
+ else if (previewServerPlan !== null) {
5791
+ // A logical path for the in-memory adapter only; nothing is written there.
5792
+ planPath = path.join(tmpdir(), "bapi-authored-plan-preview", epicKey, "epic-plan.dag.json");
5793
+ plan = {
5794
+ status: "found",
5795
+ inline: { nodes: previewServerPlan.plan_blob.nodes },
5796
+ };
5797
+ ctx = {
5798
+ ...ctx,
5799
+ deps: withInlinePlan(ctx.deps, planPath, JSON.stringify(previewServerPlan.plan_blob, null, 2) + "\n"),
5800
+ };
5801
+ const advisory = previewServerPlan.eligibility_advisory !== null
5802
+ ? parseContainmentEligibilityArtifact(previewServerPlan.eligibility_advisory)
5803
+ : null;
5804
+ const advisoryText = advisory !== null ? renderContainmentEligibilityAdvisory(advisory) : null;
5805
+ if (advisoryText !== null)
5806
+ plan.containment_advisory = advisoryText;
5807
+ const docs = await deps.resolveDocsDir();
5808
+ if (docs.ok) {
5809
+ const ignored = await localPlanIgnoredPath(deps, epicKey, docs.docsDir, previewServerPlan);
5810
+ if (ignored !== null)
5811
+ plan.local_plan_ignored = ignored;
5812
+ }
5813
+ }
5814
+ else if (authoredLookupKind === "unknown") {
5815
+ // No local or generated fallback: an unknown answer is never evidence of absence.
5816
+ plan = { status: "not_found" };
5337
5817
  }
5338
5818
  else {
5339
5819
  const docs = await deps.resolveDocsDir();
@@ -5398,6 +5878,22 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5398
5878
  }
5399
5879
  }
5400
5880
  }
5881
+ // BAPI-1706 — provenance is always present, with predictable nulls.
5882
+ if (previewProvenance === null) {
5883
+ if (plan.status === "found" || plan.status === "generated") {
5884
+ previewProvenance = nonServerPlanProvenance(plan.generated === true ? "generated" : "local");
5885
+ }
5886
+ }
5887
+ Object.assign(plan, {
5888
+ source: previewProvenance?.source ?? null,
5889
+ plan_version: previewProvenance?.plan_version ?? null,
5890
+ plan_hash: previewProvenance?.plan_hash ?? null,
5891
+ saved_by: previewProvenance?.saved_by ?? null,
5892
+ saved_at: previewProvenance?.saved_at ?? null,
5893
+ endpoint: previewProvenance?.endpoint ?? null,
5894
+ authored_lookup: authoredLookupKind,
5895
+ });
5896
+ const authoredPlanUnknown = authoredLookupKind === "unknown";
5401
5897
  // Every later exit, refusal or not, reports the plan state as discovered.
5402
5898
  preview.plan = plan;
5403
5899
  // --- Readiness. -----------------------------------------------------------
@@ -5520,6 +6016,9 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5520
6016
  }
5521
6017
  }
5522
6018
  if (planPath === undefined) {
6019
+ if (authoredPlanUnknown) {
6020
+ return refuseTopLevel({ reasonId: AUTHORED_PLAN_UNKNOWN_REASON_ID, remedy: authoredPlanUnknownRemedy(epicKey, options.repo) });
6021
+ }
5523
6022
  preview.decision = "stop";
5524
6023
  return;
5525
6024
  }
@@ -5590,6 +6089,11 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5590
6089
  // --- No plan: attach to a live run, or stop. --------------------------------
5591
6090
  if (effectivePlanPath === undefined) {
5592
6091
  if (live.kind !== "live") {
6092
+ // BAPI-1706 — the server could not say whether a plan is stored, and this
6093
+ // launch would create a run: a named stop, never a local or generated plan.
6094
+ if (authoredPlanUnknown) {
6095
+ return refuseTopLevel({ reasonId: AUTHORED_PLAN_UNKNOWN_REASON_ID, remedy: authoredPlanUnknownRemedy(epicKey, options.repo) });
6096
+ }
5593
6097
  if (selection.kind === "not_ready") {
5594
6098
  return refuseWithReadiness(classification.kind, {
5595
6099
  reasonId: ENGINE_NOT_READY_REASON_ID,
@@ -5646,6 +6150,91 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5646
6150
  await finalizeCreatePreview(prepared?.ok ? { ...previewCtx, handoff: prepared.handoff, previewObservations: observations, previewMergedEvaluation: mergedEvaluation } : { ...previewCtx, previewObservations: observations, previewMergedEvaluation: mergedEvaluation }, preview, planPathForCreate, false, refuseTopLevel, live.kind === "live");
5647
6151
  await applyPreviewFreshness(ctx, preview, topology, false);
5648
6152
  }
6153
+ /** The `git ls-remote --symref origin HEAD` answer: the default branch and its commit. */
6154
+ function parseRemoteDefaultHead(stdout) {
6155
+ let branch = null;
6156
+ let sha = null;
6157
+ for (const line of stdout.split("\n")) {
6158
+ const symref = /^ref:\s+refs\/heads\/(\S+)\s+HEAD\s*$/.exec(line.trim());
6159
+ if (symref)
6160
+ branch = symref[1];
6161
+ const direct = /^([0-9a-fA-F]{40})\s+HEAD\s*$/.exec(line.trim());
6162
+ if (direct)
6163
+ sha = normalizeCommitSha(direct[1]);
6164
+ }
6165
+ return branch !== null && sha !== null ? { branch, sha } : null;
6166
+ }
6167
+ /**
6168
+ * Preview-time check of the epic branch a new run would cut.
6169
+ *
6170
+ * Returns a refusal ONLY for a proven conflict (`has_own_commits`). Anything it
6171
+ * cannot establish (no target, an unreadable remote, an exception) emits one fixed
6172
+ * warning and returns null: the real launch decides. Read-only: the shared
6173
+ * classifier never updates a branch, and nothing here trusts a local tracking ref.
6174
+ */
6175
+ async function previewEpicBranchConflict(ctx, input) {
6176
+ const { deps } = ctx;
6177
+ const skipped = () => {
6178
+ deps.errorLog("[warn] The epic branch could not be checked during preview; the launch will check it.");
6179
+ return null;
6180
+ };
6181
+ try {
6182
+ const gitDeps = {
6183
+ runCommand: deps.runCommand ?? createExecFileRunCommand(),
6184
+ cwd: deps.cwd(),
6185
+ fetchImpl: globalThis.fetch,
6186
+ errorLog: () => undefined,
6187
+ };
6188
+ const readRemote = async (args) => Promise.resolve(gitDeps.runCommand("git", args, { cwd: gitDeps.cwd }));
6189
+ // No remote branch means nothing can conflict: no target is needed.
6190
+ const branchHead = await readRemote(["ls-remote", "--heads", "origin", `refs/heads/${input.branch}`]);
6191
+ if (branchHead.exitCode === 0 && branchHead.stdout.trim() === "")
6192
+ return null;
6193
+ let target = input.cutCommitSha === null ? null : normalizeCommitSha(input.cutCommitSha);
6194
+ let base = input.configuredBase;
6195
+ let defaultAssumed = null;
6196
+ if (target === null && base !== null) {
6197
+ const head = await readRemote(["ls-remote", "--heads", "origin", `refs/heads/${base}`]);
6198
+ const sha = head.exitCode === 0 ? normalizeCommitSha(head.stdout.trim().split(/\s+/)[0]) : null;
6199
+ target = sha;
6200
+ }
6201
+ if (target === null || base === null) {
6202
+ if (base === null) {
6203
+ // Cold preview with no configured-base evidence: the remote's default branch.
6204
+ const symref = await readRemote(["ls-remote", "--symref", "origin", "HEAD"]);
6205
+ const parsed = symref.exitCode === 0 ? parseRemoteDefaultHead(symref.stdout) : null;
6206
+ if (parsed === null)
6207
+ return skipped();
6208
+ base = parsed.branch;
6209
+ defaultAssumed = parsed.branch;
6210
+ if (target === null)
6211
+ target = parsed.sha;
6212
+ }
6213
+ }
6214
+ if (target === null || base === null)
6215
+ return skipped();
6216
+ const classified = await classifyRemoteEpicBranch(gitDeps, input.branch, target);
6217
+ if (classified.status === "unknown")
6218
+ return skipped();
6219
+ if (classified.status !== "has_own_commits")
6220
+ return null;
6221
+ const lines = [
6222
+ `origin/${input.branch} already holds commits that are not on the commit this run would start from.`,
6223
+ "Inspect them:",
6224
+ `git log origin/${base}..origin/${input.branch}`,
6225
+ "Then finish that work, or delete the branch:",
6226
+ `git push origin --delete ${input.branch}`,
6227
+ "Then preview again. Nothing was created.",
6228
+ ];
6229
+ if (defaultAssumed !== null) {
6230
+ lines.push(`If this repository's base is not ${defaultAssumed}, bring its plane up and preview again.`);
6231
+ }
6232
+ return { reasonId: "epic-branch-has-own-commits", remedy: lines.join("\n") };
6233
+ }
6234
+ catch {
6235
+ return skipped();
6236
+ }
6237
+ }
5649
6238
  async function finalizeCreatePreview(ctx, preview, planPath, coldStart, refuseTopLevel, liveRunKnown = false) {
5650
6239
  const { deps, options, access } = ctx;
5651
6240
  const prepared = ctx.handoff
@@ -5746,6 +6335,18 @@ async function finalizeCreatePreview(ctx, preview, planPath, coldStart, refuseTo
5746
6335
  preview.summary.branch = payload.featureBranch;
5747
6336
  if (payload.scopeBaseBranch !== null)
5748
6337
  previewScopeBaseBranch.set(preview, payload.scopeBaseBranch);
6338
+ // A leftover epic branch with its own commits would refuse the real launch after a
6339
+ // plane had started. Say so now. Outside the setup dry run on purpose, so the
6340
+ // generic `setup-preview-failed` remedy cannot replace these exact instructions.
6341
+ if (!liveRunKnown && payload.featureBranch !== null && payload.existingRunId === null) {
6342
+ const conflict = await previewEpicBranchConflict(ctx, {
6343
+ branch: payload.featureBranch,
6344
+ configuredBase: payload.scopeBaseBranch,
6345
+ cutCommitSha: evaluation?.cutCommitSha ?? null,
6346
+ });
6347
+ if (conflict !== null)
6348
+ return refuseTopLevel(conflict);
6349
+ }
5749
6350
  if (payload.serverPlanHash !== null)
5750
6351
  previewServerPlanDigest.set(preview, payload.serverPlanHash);
5751
6352
  preview.summary.ticket_review = payload.ticketReview;
@@ -6095,6 +6696,37 @@ function launchPlanLines(plan) {
6095
6696
  lines.push(` ${plan.local_handoff}`);
6096
6697
  return lines;
6097
6698
  }
6699
+ /**
6700
+ * BAPI-1706 — the Plan summary that leads the readable preview: where the plan
6701
+ * comes from, before anything else. Plain text labels, no color.
6702
+ */
6703
+ function planSourceLines(preview) {
6704
+ const plan = preview.plan;
6705
+ const lines = [];
6706
+ if (plan.authored_lookup === "unknown") {
6707
+ lines.push(" Plan source: UNKNOWN — the Bridge server could not say whether a plan is stored. " +
6708
+ "No run will be created until it can.");
6709
+ }
6710
+ else if (plan.source === "server") {
6711
+ lines.push(` Plan source: server — authored version ${plan.plan_version ?? "unknown"}, hash ` +
6712
+ `${plan.plan_hash ? plan.plan_hash.slice(0, 12) : "unknown"}, saved by ${plan.saved_by ?? "unknown"} ` +
6713
+ `at ${plan.saved_at ?? "unknown"}, from ${plan.endpoint ?? "unknown"}`);
6714
+ }
6715
+ else {
6716
+ lines.push(` Plan source: ${plan.source ?? "none"}${plan.authored_lookup === "not_stored" ? " (no plan stored on the Bridge server)" : ""}`);
6717
+ }
6718
+ if (plan.authored_lookup === "server_too_old") {
6719
+ lines.push(" warning: this Bridge server does not store epic plans yet; local plan files are used as before.");
6720
+ }
6721
+ if (plan.local_plan_ignored !== undefined) {
6722
+ lines.push(` local plan ignored: ${plan.local_plan_ignored} (differs from the stored plan)`);
6723
+ }
6724
+ if (plan.containment_advisory !== undefined) {
6725
+ for (const line of plan.containment_advisory.split("\n"))
6726
+ lines.push(` ${line}`);
6727
+ }
6728
+ return lines;
6729
+ }
6098
6730
  /**
6099
6731
  * Print the preview: one JSON line with `--json`, short readable lines otherwise.
6100
6732
  *
@@ -6111,6 +6743,7 @@ async function emitPreview(deps, options, preview) {
6111
6743
  }
6112
6744
  const lines = [
6113
6745
  `${preview.epic_key}: launch preview (read-only; nothing was created or started)`,
6746
+ ...planSourceLines(preview),
6114
6747
  ...(preview.cold_start ? [" Decision: conditional create — drive-epic will attempt guarded startup, recheck the live run, and create only if still appropriate."] : []),
6115
6748
  ` Target: ${preview.target.base_url ?? "unresolved"}${preview.target.kind ? ` (${preview.target.kind})` : ""}`,
6116
6749
  ` Readiness: ${preview.readiness.kind}${preview.readiness.reason_id ? ` (${preview.readiness.reason_id})` : ""}`,
@@ -6139,7 +6772,9 @@ async function emitPreview(deps, options, preview) {
6139
6772
  lines.push(` skipped: ${skipped.path} (${skipped.reason})`);
6140
6773
  }
6141
6774
  const s = preview.summary;
6142
- lines.push(` Ticket review: ${s.ticket_review ?? "on"}`, ` Posture: ${s.posture ?? "n/a"}`, ` Parallel limit: ${s.parallel_limit === undefined ? "unavailable" : s.parallel_limit === "server_default" ? "server default" : s.parallel_limit}`, ` ${PARALLEL_LIMIT_MEANING_COPY}`, ` ${PARALLEL_LIMIT_CHANGE_ADVISORY}`, ` Children: ${s.child_count ?? "n/a"}`, ...alreadyDoneLines(preview), ` Branch: ${s.branch ?? "n/a"}`, autoMergeLine(preview), ` Escalation: ${s.escalation_channel ?? "n/a"}`, ...reachabilityLines(preview), ...(preview.launch_plan ? launchPlanLines(preview.launch_plan) : []), ` Validation: ${preview.cold_start ? "Partial — plane is not yet running" : s.server_validation ?? "n/a"}`, ` Decision: ${preview.decision}`);
6775
+ lines.push(` Ticket review: ${s.ticket_review ?? "on"}`, ` Posture: ${s.posture ?? "n/a"}`, ` Parallel limit: ${s.parallel_limit === undefined ? "unavailable" : s.parallel_limit === "server_default" ? "server default" : s.parallel_limit}`, ` ${PARALLEL_LIMIT_MEANING_COPY}`, ` ${PARALLEL_LIMIT_CHANGE_ADVISORY}`, ` Children: ${s.child_count ?? "n/a"}`, ...alreadyDoneLines(preview), ` Branch: ${s.branch ?? "n/a"}`, autoMergeLine(preview), ` Escalation: ${s.escalation_channel ?? "n/a"}`, ...(preview.credentials_missing && preview.credentials_missing.length > 0
6776
+ ? [` Credentials: advisory — not available on this machine: ${preview.credentials_missing.join(", ")}`]
6777
+ : []), ...reachabilityLines(preview), ...(preview.launch_plan ? launchPlanLines(preview.launch_plan) : []), ` Validation: ${preview.cold_start ? "Partial — plane is not yet running" : s.server_validation ?? "n/a"}`, ` Decision: ${preview.decision}`);
6143
6778
  if (isPlaneDownStop(preview)) {
6144
6779
  // The shared stop text, verbatim and unindented, so it reads exactly as the
6145
6780
  // real launch prints it. It is a stop, not a refusal.