@bridge_gpt/mcp-server 0.2.74 → 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 (62) hide show
  1. package/README.md +14 -7
  2. package/build/agent-launchers/prompt.js +9 -21
  3. package/build/agents.generated.js +2 -2
  4. package/build/authored-plan.js +542 -0
  5. package/build/bridge-permissions.js +8 -0
  6. package/build/commands.generated.js +5 -5
  7. package/build/conductor/bridge-api-client.js +666 -46
  8. package/build/conductor/epic-implementer-cli.js +337 -93
  9. package/build/conductor/gate-discovery.js +209 -9
  10. package/build/conductor/gate-settings-review.js +7 -11
  11. package/build/conductor/launch-plan.js +58 -12
  12. package/build/conductor/open-decision-phrases.js +50 -0
  13. package/build/conductor/prerequisite-inputs.js +181 -14
  14. package/build/connect-github-api.js +18 -0
  15. package/build/connect-github.js +35 -18
  16. package/build/docs.generated.js +2 -2
  17. package/build/drive-epic.js +387 -12
  18. package/build/epic-ci-workflow.js +3 -2
  19. package/build/epic-implementer-bin.js +152 -38
  20. package/build/epic-implementer-bundle-cli.js +61 -0
  21. package/build/epic-implementer-claude-hook-bin.js +1 -1
  22. package/build/epic-implementer-env.js +3 -4
  23. package/build/epic-integration-pr.js +5 -2
  24. package/build/executor/completion-contract.js +24 -1
  25. package/build/executor/gate-qualification-job.js +193 -23
  26. package/build/executor/gate-qualification-tests-ran.js +232 -0
  27. package/build/executor/job-runner.js +9 -722
  28. package/build/executor/job-type-wrappers.js +734 -0
  29. package/build/executor/preflight.js +6 -2
  30. package/build/executor/process-containment.js +8 -1
  31. package/build/executor/required-verification.js +28 -2
  32. package/build/executor/runner.js +4 -1
  33. package/build/executor/types.js +9 -0
  34. package/build/executor/worker-database.js +6 -1
  35. package/build/executor/worker-guard-hook.js +24 -2
  36. package/build/generated/ticket-status.js +20 -0
  37. package/build/index.js +391 -257
  38. package/build/install-bridge-conductor-answers.js +28 -1
  39. package/build/install-bridge-conductor-apply.js +11 -3
  40. package/build/install-bridge-conductor-assessment.js +114 -12
  41. package/build/install-bridge-conductor-compact.js +2 -0
  42. package/build/install-bridge-conductor-gate.js +257 -80
  43. package/build/install-bridge-conductor-setup.js +4 -4
  44. package/build/install-bridge-conductor-trial-report.js +170 -0
  45. package/build/install-bridge-conductor.js +303 -31
  46. package/build/pipelines.generated.js +7 -7
  47. package/build/plan-generation.js +17 -0
  48. package/build/printed-remedy-commands.js +54 -0
  49. package/build/readme.generated.js +1 -1
  50. package/build/repository-toolchains.js +11 -5
  51. package/build/scripts/saved-commands-config-field-driver.js +65 -0
  52. package/build/setup-epic.js +10 -1
  53. package/build/test-support/executor-source-files.js +1 -1
  54. package/build/v2-readiness-requirements.js +5 -1
  55. package/build/version.generated.js +3 -3
  56. package/build/worker-guard-hook-bin.js +2 -2
  57. package/docs/EPIC-IMPLEMENTER.md +4 -4
  58. package/docs/install/github-app.md +79 -92
  59. package/package.json +1 -1
  60. package/build/conductor/epic-reconcile.js +0 -603
  61. package/build/conductor/epic-runtime.js +0 -2020
  62. 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";
@@ -87,6 +89,8 @@ import { policyDeclaresNotifyWebhook, policyNotifyDestinationsConflict, notifyDe
87
89
  import { getConfigFieldBaseBranch } from "./epic-shared/bridge-client.js";
88
90
  import { createExecFileRunCommand, normalizeCommitSha } from "./epic-shared/cut-protocol.js";
89
91
  import { EPIC_KEY_PATTERN } from "./drive-epic-key.js";
92
+ import { AUTHORED_PLAN_SERVER_TOO_OLD_NOTICE, AUTHORED_PLAN_UNKNOWN_REASON_ID, AUTHORED_PLAN_UPLOAD_FAILED_REASON_ID, authoredPlanUnknownRemedy, authoredPlanUploadFailedRemedy, createDefaultAuthoredPlanSaveDeps, explainRunPlanHash, lookupAuthoredPlanForLaunch, materializeAuthoredPlanSnapshot, resolveAuthoredPlanAccess, nonServerPlanProvenance, renderPlanProvenanceLine, saveLocalAuthoredPlan, serverPlanProvenance, } from "./authored-plan.js";
93
+ import { hashPlan } from "./conductor/plan.js";
90
94
  import { buildEpicLaunchContext, projectWorkerDatabase, readEpicLaunchContext, writeEpicLaunchContext, writeEpicLaunchOutcome, } from "./epic-launch-context.js";
91
95
  import { flushProcessStdout, writeJsonDocument } from "./conductor/json-output.js";
92
96
  import { BRIDGE_LAUNCHER_ENV } from "./bridge-permissions.js";
@@ -111,7 +115,7 @@ import { isTerminalEpicRunStatus } from "./epic-run-status.js";
111
115
  import { MCP_PACKAGE_NAME } from "./mcp-identity.js";
112
116
  import { getDriveEpicAdvancedUsage, getDriveEpicUsage } from "./drive-epic-help.js";
113
117
  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";
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";
115
119
  /** The conductor paths. Derived types below come from this constant. */
116
120
  export const DRIVE_EPIC_CONDUCTORS = ["v2"];
117
121
  /**
@@ -319,11 +323,28 @@ function indexedWorkflowsRemedy(readiness) {
319
323
  const fix = row.fix.length > 0
320
324
  ? row.fix
321
325
  : 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;
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;
324
347
  }
325
- if (fix === READINESS_PREREQUISITE_FIXES.pending_index)
326
- return "Wait for indexing to finish, then run drive-epic again.";
327
348
  if (fix.includes("Merge the setup pull request") || fix === READINESS_PREREQUISITE_FIXES.setup || fix.includes("merge the workflow changes"))
328
349
  return fix;
329
350
  return INDEXED_WORKFLOWS_UNCLASSIFIED;
@@ -1187,6 +1208,9 @@ export async function readLiveEpicRunByKey(access, epicKey, fetchImpl = globalTh
1187
1208
  }
1188
1209
  }
1189
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 };
1190
1214
  return {
1191
1215
  inspectRepositoryIdentity: async () => {
1192
1216
  const top = await createPlaneExecFile()("git", ["rev-parse", "--show-toplevel"], {
@@ -1344,6 +1368,22 @@ export function createDefaultDriveEpicDeps() {
1344
1368
  validate: () => validateGeneratedPlan(access, epicKey, dag, (a, request) => validateEpicPlan(a, request)),
1345
1369
  rediscover: () => discoverEpicPlan(epicKey, docsDir, createDefaultPlanDiscoveryFs()),
1346
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),
1347
1387
  readPolicyFile: (filePath) => readFile(filePath, "utf8"),
1348
1388
  readLiveEpicRun: (access, epicKey) => readLiveEpicRunByKey(access, epicKey),
1349
1389
  previewSetupEpic: async ({ argv, baseUrl, handoff, observations, planContents }) => {
@@ -1439,6 +1479,8 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1439
1479
  if (parsed.options.dryRun === true) {
1440
1480
  return await runDriveEpicPreview(deps, parsed.options);
1441
1481
  }
1482
+ // BAPI-1706 — private server-plan hand-off folders, removed however the launch ends.
1483
+ const authoredPlanCleanups = [];
1442
1484
  try {
1443
1485
  // Every async branch below is `return await`ed. A bare `return promise`
1444
1486
  // inside this `try` would let a rejection skip the sanitizing `catch` at the
@@ -1493,9 +1535,34 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1493
1535
  let planWasDiscovered = false;
1494
1536
  // BAPI-1621 — why automatic generation stopped, for the no-plan stop text.
1495
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";
1496
1558
  if (planFile === undefined) {
1497
1559
  const docs = await deps.resolveDocsDir();
1498
- 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) {
1499
1566
  discovered = await discoverEpicPlan(epicKey, docs.docsDir, deps.discoveryFs);
1500
1567
  if (discovered.status === "plan_not_found") {
1501
1568
  const generated = await generateMissingPlanForLaunch(ctx, docs.docsDir, discovered);
@@ -1511,12 +1578,84 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1511
1578
  docsRootUnresolved = true;
1512
1579
  }
1513
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
+ };
1514
1639
  let foundPlanAnnounced = false;
1515
1640
  /** Names the found plan once, BEFORE anything is created, and surfaces its advisory. */
1516
1641
  const announceFoundPlan = async () => {
1517
- 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")
1518
1655
  return;
1519
1656
  foundPlanAnnounced = true;
1657
+ if (ctx.planProvenance !== undefined)
1658
+ deps.log(renderPlanProvenanceLine(epicKey, ctx.planProvenance));
1520
1659
  deps.log(`${epicKey}: using the plan found by epic key: ${discovered.path}`);
1521
1660
  };
1522
1661
  // --- No readiness read at launch (BAPI-1595). -----------------------------
@@ -1534,10 +1673,11 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1534
1673
  (discovered.status === "plan_not_found" || discovered.status === "plan_ambiguous")
1535
1674
  ? discovered
1536
1675
  : null;
1537
- if (planeEndpoint !== null && (ctx.options.planFile !== undefined || noPlanDiscovery !== null)) {
1676
+ if (planeEndpoint !== null &&
1677
+ (ctx.options.planFile !== undefined || noPlanDiscovery !== null || serverPlan !== null)) {
1538
1678
  const probe = await deps.probePlanePort(planeEndpoint.host, planeEndpoint.port).catch(() => ({ kind: "error" }));
1539
1679
  if (probe.kind === "refused") {
1540
- if (ctx.options.planFile !== undefined) {
1680
+ if (ctx.options.planFile !== undefined || serverPlan !== null) {
1541
1681
  // BAPI-1260 — only a SELECTED LOCAL plane is ever started here. A
1542
1682
  // profile approved for durable execution names an authority this
1543
1683
  // machine does not own, so a refused port is that authority being
@@ -1546,6 +1686,12 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1546
1686
  return escalate(deps, epicKey, `launch profile '${launchProfile.name}' selects durable execution, and its control plane is ` +
1547
1687
  "not answering; no local replacement was started");
1548
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();
1549
1695
  // `coldStartPlane` surfaces the containment advisory itself.
1550
1696
  await announceFoundPlan();
1551
1697
  return await coldStartPlane(ctx);
@@ -1601,7 +1747,36 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1601
1747
  // A supplied plan always wins and skips ALL of this, including the extra
1602
1748
  // live-run read: setup-epic does its own Step 0 read and owns reuse.
1603
1749
  let discoveryStop;
1604
- 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) {
1605
1780
  if (docsRootUnresolved || discovered === null) {
1606
1781
  return refuse(deps, docsRootRefusal(epicKey).lines);
1607
1782
  }
@@ -1622,6 +1797,12 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1622
1797
  const { planFile: _unusedDiscoveredPlan, ...attachOptions } = ctx.options;
1623
1798
  return await attachToLiveRun({ ...ctx, options: attachOptions }, readiness, live, discovered.path);
1624
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();
1625
1806
  // The create path: setup selection runs now. The plan was folded into
1626
1807
  // `ctx.options` before readiness; from here it is indistinguishable from
1627
1808
  // a supplied `--plan-file`.
@@ -1864,6 +2045,10 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1864
2045
  deps.errorLog(`drive-epic failed: ${safeDiagnosticMessage(err, "unexpected error")}`);
1865
2046
  return 1;
1866
2047
  }
2048
+ finally {
2049
+ for (const cleanup of authoredPlanCleanups)
2050
+ await cleanup();
2051
+ }
1867
2052
  }
1868
2053
  /**
1869
2054
  * BAPI-1285 — the one remedy sentence an unknown-readiness escalation ends with.
@@ -1995,6 +2180,61 @@ async function planGenerationAllowed(fs, epicKey, discovery, attempt) {
1995
2180
  function observeLaunch(ctx, code, message) {
1996
2181
  ctx.launchObservations?.push({ code, message, at: launchNowIso(ctx) });
1997
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
+ }
1998
2238
  // ---------------------------------------------------------------------------
1999
2239
  // BAPI-1595 — fixed tally lines and stable reason codes
2000
2240
  // ---------------------------------------------------------------------------
@@ -2203,6 +2443,7 @@ async function reportLaunchOutcome(ctx, outcome, facts) {
2203
2443
  invoked_at: ctx.invokedAt ?? at,
2204
2444
  first_claimed_job_at: "pending",
2205
2445
  observations,
2446
+ ...(ctx.planProvenance !== undefined ? { plan: { ...ctx.planProvenance } } : {}),
2206
2447
  };
2207
2448
  ctx.deps.reportLaunch?.(report);
2208
2449
  // The durable record: best-effort, so a write failure never changes the exit code.
@@ -2617,7 +2858,9 @@ function reportPlaneCapacity(ctx, lanes, storedLimit, posture) {
2617
2858
  * its caller returns its exit code without requesting lanes or an executor.
2618
2859
  */
2619
2860
  async function runSelectedSetupEpic(ctx) {
2620
- return settleSetupLaunch(ctx, await runSelectedSetupEpicWorkflow(ctx));
2861
+ const result = await runSelectedSetupEpicWorkflow(ctx);
2862
+ recordRunPlanHash(ctx, result);
2863
+ return settleSetupLaunch(ctx, result);
2621
2864
  }
2622
2865
  async function runSelectedSetupEpicWorkflow(ctx) {
2623
2866
  const selected = ctx.handoff
@@ -2688,6 +2931,15 @@ async function runSelectedSetupEpicWorkflow(ctx) {
2688
2931
  }
2689
2932
  }
2690
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
+ }
2691
2943
  const withPath = deps.withPlanPath ?? withPlanPath;
2692
2944
  const result = await withPath({
2693
2945
  originalPath: planPath,
@@ -5062,13 +5314,25 @@ async function collectLaunchPlanFacts(deps, options, preview, observed) {
5062
5314
  const presence = new Map();
5063
5315
  const missing = new Map();
5064
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();
5065
5321
  const kept = { minor: 0, "observed present": 0, "worker runtime": 0, "not measurable": 0, skipped: 0 };
5066
5322
  for (const entry of read.entries) {
5067
5323
  if (!members.has(entry.child)) {
5068
- kept.skipped += entry.items.length;
5324
+ kept.skipped += entry.items.filter((item) => !("category" in item && item.category === "open-decision")).length;
5069
5325
  continue;
5070
5326
  }
5071
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
+ }
5072
5336
  if ("category" in item) {
5073
5337
  kept["worker runtime"] += 1;
5074
5338
  runtimeChildren.add(entry.child);
@@ -5099,6 +5363,13 @@ async function collectLaunchPlanFacts(deps, options, preview, observed) {
5099
5363
  : { ...prior, dependents: prior.dependents.split(", ").includes(item.dependents) ? prior.dependents : `${prior.dependents}, ${item.dependents}` });
5100
5364
  }
5101
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
+ }
5102
5373
  for (const [category, count] of Object.entries(kept)) {
5103
5374
  if (count > 0)
5104
5375
  tally.push({ code: "prerequisite_kept_off_screen", line: `prerequisite scan: kept off the screen: ${category} ${count}` });
@@ -5107,6 +5378,7 @@ async function collectLaunchPlanFacts(deps, options, preview, observed) {
5107
5378
  status: "collected",
5108
5379
  missingCore: [...missing.values()],
5109
5380
  workerRuntimeChildren: [...runtimeChildren],
5381
+ openDecisions,
5110
5382
  };
5111
5383
  }
5112
5384
  }
@@ -5493,8 +5765,55 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5493
5765
  let generationReason;
5494
5766
  let generatedLiveRunChecked = false;
5495
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
+ }
5496
5786
  if (planPath !== undefined) {
5497
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" };
5498
5817
  }
5499
5818
  else {
5500
5819
  const docs = await deps.resolveDocsDir();
@@ -5559,6 +5878,22 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5559
5878
  }
5560
5879
  }
5561
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";
5562
5897
  // Every later exit, refusal or not, reports the plan state as discovered.
5563
5898
  preview.plan = plan;
5564
5899
  // --- Readiness. -----------------------------------------------------------
@@ -5681,6 +6016,9 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5681
6016
  }
5682
6017
  }
5683
6018
  if (planPath === undefined) {
6019
+ if (authoredPlanUnknown) {
6020
+ return refuseTopLevel({ reasonId: AUTHORED_PLAN_UNKNOWN_REASON_ID, remedy: authoredPlanUnknownRemedy(epicKey, options.repo) });
6021
+ }
5684
6022
  preview.decision = "stop";
5685
6023
  return;
5686
6024
  }
@@ -5751,6 +6089,11 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5751
6089
  // --- No plan: attach to a live run, or stop. --------------------------------
5752
6090
  if (effectivePlanPath === undefined) {
5753
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
+ }
5754
6097
  if (selection.kind === "not_ready") {
5755
6098
  return refuseWithReadiness(classification.kind, {
5756
6099
  reasonId: ENGINE_NOT_READY_REASON_ID,
@@ -6353,6 +6696,37 @@ function launchPlanLines(plan) {
6353
6696
  lines.push(` ${plan.local_handoff}`);
6354
6697
  return lines;
6355
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
+ }
6356
6730
  /**
6357
6731
  * Print the preview: one JSON line with `--json`, short readable lines otherwise.
6358
6732
  *
@@ -6369,6 +6743,7 @@ async function emitPreview(deps, options, preview) {
6369
6743
  }
6370
6744
  const lines = [
6371
6745
  `${preview.epic_key}: launch preview (read-only; nothing was created or started)`,
6746
+ ...planSourceLines(preview),
6372
6747
  ...(preview.cold_start ? [" Decision: conditional create — drive-epic will attempt guarded startup, recheck the live run, and create only if still appropriate."] : []),
6373
6748
  ` Target: ${preview.target.base_url ?? "unresolved"}${preview.target.kind ? ` (${preview.target.kind})` : ""}`,
6374
6749
  ` Readiness: ${preview.readiness.kind}${preview.readiness.reason_id ? ` (${preview.readiness.reason_id})` : ""}`,
@@ -178,8 +178,9 @@ function fixedInstallCommands(lines) {
178
178
  /**
179
179
  * True when an approved entry replaces this fixed install command: it runs the same manager at the
180
180
  * repository root, where the fixed step runs. An entry elsewhere does not install the root's
181
- * dependencies. pip is never replaced, because setup never proposes it, so an approved list that
182
- * leaves pip out has not decided anything about it.
181
+ * dependencies. pip's fixed CI install is never replaced: setup's only pip proposal (BAPI-1698) is a
182
+ * checkout-local `.venv` bootstrap run through `sh`, which does not install into CI's interpreter.
183
+ * An approved pip entry therefore ADDS an install step and the fixed one stays.
183
184
  */
184
185
  function entriesReplaceFixedInstall(command, entries) {
185
186
  const manager = command.split(" ")[0];