@bridge_gpt/mcp-server 0.2.75 → 0.2.76

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +5 -5
  2. package/build/agents.generated.js +4 -4
  3. package/build/codex-auto-recovery.js +25 -7
  4. package/build/commands.generated.js +6 -6
  5. package/build/conductor/bridge-api-client.js +141 -6
  6. package/build/conductor/declare-blocked.js +4 -0
  7. package/build/conductor/driver-pass.js +8 -0
  8. package/build/conductor/epic-implementer-cli.js +4 -3
  9. package/build/conductor/epic-server-journal.js +13 -0
  10. package/build/conductor/epic-server-recipe.js +15 -5
  11. package/build/conductor/epic-server-runtime.js +163 -45
  12. package/build/conductor/epic-server.js +13 -6
  13. package/build/conductor/install-doctor.js +30 -2
  14. package/build/conductor/local-merge.js +54 -12
  15. package/build/conductor/pr-ci-producer.js +12 -3
  16. package/build/conductor/readiness-sections.js +46 -13
  17. package/build/conductor/readiness.js +3 -40
  18. package/build/conductor/recovery-cli.js +12 -12
  19. package/build/conductor/repository-workflow-remedy.js +147 -7
  20. package/build/conductor/ui-readiness.js +224 -0
  21. package/build/conductor/wait-run-attention.js +9 -4
  22. package/build/conductor/wait-run-cli.js +9 -2
  23. package/build/docs.generated.js +2 -2
  24. package/build/drive-epic.js +402 -27
  25. package/build/epic-implementer-bin.js +62 -42
  26. package/build/epic-launch-context.js +8 -1
  27. package/build/epic-shared/cut-protocol.js +55 -3
  28. package/build/executor/failure-reason-codes.js +2 -0
  29. package/build/executor/integration-job.js +56 -2
  30. package/build/executor/job-runner.js +4 -1
  31. package/build/executor/merge-job.js +45 -1
  32. package/build/executor/permissions.js +187 -2
  33. package/build/executor/provider-checks.js +28 -5
  34. package/build/executor/reconcile-overlap-job.js +70 -17
  35. package/build/executor/required-work-ledger.js +7 -2
  36. package/build/executor/resume-pre-spawn.js +32 -8
  37. package/build/executor/runner.js +26 -4
  38. package/build/executor/worktree.js +12 -1
  39. package/build/index.js +376 -434
  40. package/build/init.js +16 -0
  41. package/build/install-bridge-conductor-answers.js +4 -0
  42. package/build/install-bridge-conductor-apply.js +10 -0
  43. package/build/install-bridge-conductor-assessment.js +71 -0
  44. package/build/install-bridge-conductor-contracts.js +9 -1
  45. package/build/install-bridge-conductor-setup.js +103 -3
  46. package/build/install-bridge-conductor.js +437 -93
  47. package/build/mcp-host-config.js +54 -37
  48. package/build/phase-context-git-probe.js +16 -0
  49. package/build/pipelines.generated.js +9 -9
  50. package/build/plan-execution-ledger.js +27 -0
  51. package/build/plane/plane-freshness.js +43 -26
  52. package/build/printed-remedy-commands.js +8 -0
  53. package/build/readme.generated.js +1 -1
  54. package/build/secret-redaction.js +3 -0
  55. package/build/setup-epic.js +41 -8
  56. package/build/test-support/create-preview-world.js +232 -0
  57. package/build/ticket-delivery.js +65 -0
  58. package/build/v2-readiness-requirements.js +8 -3
  59. package/build/version.generated.js +3 -3
  60. package/build/worktree-core.js +51 -7
  61. package/docs/EPIC-IMPLEMENTER.md +79 -0
  62. package/docs/epic-implementer/getting-started.md +1 -1
  63. package/package.json +1 -1
  64. package/pipelines/implement-ticket.json +2 -2
@@ -62,10 +62,13 @@ import { READINESS_PRE_CREATE_CODES, READINESS_PREREQUISITE_BY_ID, READINESS_LEG
62
62
  * ratcheted down, and a tool would be useless in a bare-chat session anyway,
63
63
  * where the model has no tool call to make.
64
64
  */
65
- import { access as fsAccess, readdir, readFile, realpath, stat as fsStat } from "node:fs/promises";
65
+ import { access as fsAccess, lstat as fsLstat, readdir, readFile, realpath, stat as fsStat } from "node:fs/promises";
66
66
  import { constants as fsConstants } from "node:fs";
67
67
  import path, { dirname, join } from "node:path";
68
- import { tmpdir } from "node:os";
68
+ import { homedir, tmpdir } from "node:os";
69
+ import { readMcpGrant } from "./mcp-grant.js";
70
+ import { readEpicServerRecord } from "./epic-server-record.js";
71
+ import { buildUiReadiness, classifyPlaywrightGrant, classifyUiVerification, classifyUiWork, } from "./conductor/ui-readiness.js";
69
72
  import { ConductorBridgeApiError, createReadinessAcquisition, resolveEpicLaunchBridgeApiAccess, fetchConductorReadiness, isSchemaIncompatibleError, SCHEMA_INCOMPATIBLE_REPAIR_ROUTE, fetchEpicRunState, isProviderRepositoryIdentity, safeDiagnosticMessage, classifyChildMergeStatus as classifyChildMergeStatusClient, recordSkippedChildren as recordSkippedChildrenClient, fetchEpicChildren, fetchStoredTicketDescription, resolveConductorBridgeApiAccess, validateEpicPlan, } from "./conductor/bridge-api-client.js";
70
73
  import { CHILD_MERGE_STATUS_BATCH_SIZE, buildAlreadyDoneEntries, classifyPlanChildren, selectSkips, } from "./conductor/merged-child-check.js";
71
74
  import { trimDonePlanNodes } from "./conductor/plan-trim.js";
@@ -110,6 +113,9 @@ import { resolveMemberInstanceId } from "./plane/supervisor.js";
110
113
  import { validateBranchName } from "./base-ref.js";
111
114
  import { createDefaultRunExecutorLaunchDeps, ensureRunExecutor as ensureRunExecutorDefault, prepareRunExecutor as prepareRunExecutorDefault, } from "./executor-launch.js";
112
115
  import { isTerminalEpicRunStatus } from "./epic-run-status.js";
116
+ import { repositoryReadinessVerdict, requiredChecksAdmissionRemedy, requiredChecksAdmissionVerdict, requiredChecksDeniedRecord, } from "./conductor/repository-workflow-remedy.js";
117
+ /** BAPI-1526 — the existing catalog row id for a denied required-checks admission. */
118
+ const REQUIRED_CHECKS_ADMISSION_REASON_ID = "server.admission-required-checks";
113
119
  // BAPI-806: mcp-identity.ts is the SOLE source of the package-name literal, so
114
120
  // the printed invocation interpolates it rather than repeating it.
115
121
  import { MCP_PACKAGE_NAME } from "./mcp-identity.js";
@@ -220,10 +226,18 @@ launchEvidence) {
220
226
  // which reads the policy and refuses if it declares none. Nothing is weakened:
221
227
  // `setup-epic` gates before the create, and the server re-checks the predicate
222
228
  // at approval and probes the URL there.
223
- const deferred = options.approvedStoredPolicy ||
229
+ const notifyDeferred = options.approvedStoredPolicy ||
224
230
  options.effectivePolicy?.escalationChannel === "configured webhook" ||
225
- (options.effectivePolicy === undefined && options.hasPolicyFile)
226
- ? V2_READINESS_REQUIREMENTS.filter((req) => req.id !== "server.unattended-notify-default")
231
+ (options.effectivePolicy === undefined && options.hasPolicyFile);
232
+ // BAPI-1714 — a genuine attach to a live run has already been through first
233
+ // approval, which owns the repository-workflow decision for that run, so it is
234
+ // not re-judged from the repository report. Notify-only deferral (a configured
235
+ // webhook or `--policy-file`) deliberately does NOT exempt it: neither option
236
+ // says anything about the repository's workflows.
237
+ const workflowExempt = options.approvedStoredPolicy === true;
238
+ const deferred = notifyDeferred || workflowExempt
239
+ ? V2_READINESS_REQUIREMENTS.filter((req) => !(notifyDeferred && req.id === "server.unattended-notify-default") &&
240
+ !(workflowExempt && req.id === "server.repository-workflow-readiness"))
227
241
  : V2_READINESS_REQUIREMENTS;
228
242
  // `--into-base` is the second opt-out, and it is structural rather than
229
243
  // declared: it selects the branch-silent composition, whose policy carries no
@@ -350,6 +364,17 @@ function indexedWorkflowsRemedy(readiness) {
350
364
  return INDEXED_WORKFLOWS_UNCLASSIFIED;
351
365
  }
352
366
  const INDEXED_WORKFLOWS_UNCLASSIFIED = "The state blocking the indexed workflows could not be established; run readiness again to read it.";
367
+ /**
368
+ * BAPI-1714 — a live run that is still `planning` while the server holds its
369
+ * authored plan is an UNFINISHED SETUP, not a run to attach to: approval has not
370
+ * happened, so there is nothing to attach an executor to. It routes through the
371
+ * setup path, which reuses the planning run. Every other live status, a planning
372
+ * run with no stored server plan, and the separate discovered-local-plan path all
373
+ * keep attaching. Pure: it reads only the two values it is given.
374
+ */
375
+ function isPlanningSetupToFinish(live, serverPlan) {
376
+ return live.kind === "live" && live.status === "planning" && serverPlan !== null;
377
+ }
353
378
  /**
354
379
  * Parse argv. Rejects malformed input BEFORE any side effect — no readiness
355
380
  * read, no credential resolution, no delegation.
@@ -1280,12 +1305,16 @@ export function createDefaultDriveEpicDeps() {
1280
1305
  fs: createPlaneFsDeps(),
1281
1306
  ...(applicability?.isBridge === false ? { isBridge: false } : {}),
1282
1307
  }),
1283
- collectPlaneFreshness: ({ repoRoot, ownsManifest, expectedPlaneId }) => checkPlaneFreshness(repoRoot, {
1308
+ collectPlaneFreshness: ({ repoRoot, ownsManifest, expectedPlaneId, snapshotFromCheckoutHead }) => checkPlaneFreshness(repoRoot, {
1284
1309
  execFile: createPlaneExecFile(),
1285
1310
  fileExists: (filePath) => fsStat(filePath).then((entry) => entry.isFile(), () => false),
1286
1311
  platform: process.platform,
1287
1312
  readPlaneManifest: (root) => readPlaneManifest(root, createPlaneFsDeps()),
1288
- }, repoRoot, { ownsManifest, ...(expectedPlaneId !== undefined ? { expectedPlaneId } : {}) }),
1313
+ }, repoRoot, {
1314
+ ownsManifest,
1315
+ ...(expectedPlaneId !== undefined ? { expectedPlaneId } : {}),
1316
+ ...(snapshotFromCheckoutHead === true ? { snapshotFromCheckoutHead: true } : {}),
1317
+ }),
1289
1318
  inspectHostSleep: (repoRoot) => inspectHostSleep(repoRoot, { execFile: createPlaneExecFile(), platform: process.platform }),
1290
1319
  inspectRequiredRunners: ({ repoRoot, providerRepository, gateProfile }) => inspectRequiredSelfHostedRunners({
1291
1320
  repoRoot,
@@ -1315,6 +1344,12 @@ export function createDefaultDriveEpicDeps() {
1315
1344
  clearTimeout(timer);
1316
1345
  }
1317
1346
  },
1347
+ // BAPI-1718 — the advisory UI-readiness reads delegate to the existing readers.
1348
+ // The captured environment keeps them off any later launch-target adoption.
1349
+ readUiTicketDescription: (access, ticketKey) => fetchStoredTicketDescription(access, ticketKey),
1350
+ listUiTrackedFiles: () => listTrackedFilesWithGit(process.cwd()),
1351
+ readUiMcpGrant: (repoName) => readMcpGrant(repoName, { env: normalServerEnv, homedir, readFile: (p) => readFile(p, "utf8") }),
1352
+ readUiEpicServerRecord: (repoName) => readEpicServerRecord(repoName, { env: normalServerEnv, homedir, readFile: (p) => readFile(p, "utf8"), lstat: (p) => fsLstat(p) }),
1318
1353
  execEngineStatus: createPlaneExecFile(),
1319
1354
  cleanupTerminalRunPlane: (input) => cleanupTerminalRunPlane(input, createTerminalRunCleanupDeps(process.env)),
1320
1355
  listLiveRunIds: (access) => createTerminalRunCleanupDeps(process.env).listLiveRunIds(access),
@@ -1754,7 +1789,11 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1754
1789
  const live = await acquireObservedLive(ctx);
1755
1790
  if (live.kind === "conflict")
1756
1791
  return refuse(deps, liveRunAmbiguousRefusal(epicKey).lines);
1757
- if (live.kind === "live") {
1792
+ // BAPI-1714 — a `planning` run with a stored server plan is an INCOMPLETE
1793
+ // setup, not a live run to attach to: it has not been approved yet. It
1794
+ // falls through to the setup path below, which reuses the planning run.
1795
+ // Every other live status keeps attaching.
1796
+ if (live.kind === "live" && !isPlanningSetupToFinish(live, serverPlan)) {
1758
1797
  if (serverPlan !== null) {
1759
1798
  deps.log(`${epicKey}: a run is already live; it keeps the plan it was created with.`);
1760
1799
  }
@@ -2084,8 +2123,17 @@ function escalate(deps, epicKey, reason) {
2084
2123
  deps.errorLog(text);
2085
2124
  return 1;
2086
2125
  }
2087
- /** BAPI-1686 — said on every healthy-launch success output. */
2126
+ /**
2127
+ * BAPI-1686 — said on the healthy plane-launch and plane-attach success paths,
2128
+ * where the plane's processes belong to this terminal. A run-scoped executor
2129
+ * prints {@link RUN_EXECUTOR_DETACHED_LINE} instead.
2130
+ */
2088
2131
  export const KEEP_TERMINAL_OPEN_LINE = "Keep this terminal open and this machine awake. If the run stops moving, re-run this command: it attaches to the live run.";
2132
+ /**
2133
+ * BAPI-1725 — said once after a run-scoped executor outcome. That executor is
2134
+ * started detached, so closing the terminal or session does not stop it.
2135
+ */
2136
+ export const RUN_EXECUTOR_DETACHED_LINE = "Closing this terminal or session does not stop it. If the run stops moving, re-run this command: it attaches to the live run.";
2089
2137
  /** The prefix of the default launch-report line. */
2090
2138
  export const LAUNCH_REPORT_PREFIX = "Launch report: ";
2091
2139
  /** How long drive-epic watches a planning run for activation after an uncertain approve. */
@@ -2254,6 +2302,14 @@ export const LIVE_RUN_UNKNOWN_REASON_CODE = "live_run_unknown_continued";
2254
2302
  /** A mandatory diagnostic whose verdict or classification was not established. */
2255
2303
  export const MANDATORY_DIAGNOSTIC_UNKNOWN_WARNING = "mandatory diagnostic: unknown, continuing; server create and approve decide";
2256
2304
  export const MANDATORY_DIAGNOSTIC_UNKNOWN_REASON_CODE = "mandatory_diagnostic_unknown_continued";
2305
+ /**
2306
+ * BAPI-1714 — the repository's review and CI workflows could not be verified.
2307
+ * Preview continues (an unverifiable read is not a proven deficiency), but first
2308
+ * approval re-checks them and may still refuse, so the preview does not promise
2309
+ * approval.
2310
+ */
2311
+ export const REPOSITORY_WORKFLOWS_UNVERIFIABLE_WARNING = "Repository workflows could not be verified. Preview continues; first approval " +
2312
+ "will re-check them and may refuse if they remain unverifiable.";
2257
2313
  /** The escalation channel evidence was not established, so no "no channel" claim is made. */
2258
2314
  export const ESCALATION_CHANNEL_UNCERTAIN_WARNING = "escalation channel: unconfirmed, continuing; server create and approve decide";
2259
2315
  export const ESCALATION_CHANNEL_UNCERTAIN_REASON_CODE = "escalation_channel_unconfirmed_continued";
@@ -3343,6 +3399,42 @@ async function collectFreshnessObservations(ctx, own) {
3343
3399
  }
3344
3400
  return pending;
3345
3401
  }
3402
+ /**
3403
+ * BAPI-1725 — the cold-start observation: the CURRENT checkout's `HEAD` against
3404
+ * `origin/main`, before any plane exists. Snapshot only: it reads no manifest and
3405
+ * no database, so a stale or absent manifest can never redirect or hide it, and
3406
+ * no database row is ever fabricated. `null` when nothing applies (a non-plane
3407
+ * target, a missing collector, or a collector that fails): unproven evidence is
3408
+ * never a refusal.
3409
+ *
3410
+ * The preview shares one read per invocation (`cached`); a launch reads fresh, so
3411
+ * it never reuses an earlier preview's result.
3412
+ */
3413
+ async function collectCheckoutHeadFreshness(ctx, repoRoot, cached) {
3414
+ const { deps } = ctx;
3415
+ if (planeEndpointForBaseUrl(deps, ctx.access.baseUrl) === null)
3416
+ return null;
3417
+ const collect = deps.collectPlaneFreshness;
3418
+ if (collect === undefined)
3419
+ return null;
3420
+ const read = () => collect({ repoRoot, ownsManifest: false, snapshotFromCheckoutHead: true }).catch(() => null);
3421
+ let observed;
3422
+ if (cached) {
3423
+ const cache = ctx.freshness ?? createPlaneFreshnessCache();
3424
+ const key = `${repoRoot}\u0000checkout-head`;
3425
+ let pending = cache.observations.get(key);
3426
+ if (pending === undefined) {
3427
+ pending = read();
3428
+ cache.observations.set(key, pending);
3429
+ }
3430
+ observed = await pending;
3431
+ }
3432
+ else {
3433
+ observed = await read();
3434
+ }
3435
+ // Only the snapshot report is used, whatever else a collector returned.
3436
+ return observed === null ? null : { snapshot: observed.snapshot };
3437
+ }
3346
3438
  async function collectHostSleep(ctx, repoRoot) {
3347
3439
  const { deps } = ctx;
3348
3440
  if (planeEndpointForBaseUrl(deps, ctx.access.baseUrl) === null)
@@ -3485,10 +3577,13 @@ cleanupPreview = null) {
3485
3577
  ? formatSharedPlaneStaleRemedy(boundRun, cleanupPreview.kind === "live" ? cleanupPreview.epicRunId : null)
3486
3578
  : formatBoundPlaneStaleRemedy(boundRun),
3487
3579
  });
3488
- project(PLANE_DATABASE_HEAD_ID, "Plane database head", reports.database, {
3489
- reasonId: "plane-database-head-mismatch",
3490
- remedy: PLANE_DATABASE_HEAD_REMEDY,
3491
- });
3580
+ // A snapshot-only observation (BAPI-1725) carries no database report; none is invented.
3581
+ if ("database" in reports) {
3582
+ project(PLANE_DATABASE_HEAD_ID, "Plane database head", reports.database, {
3583
+ reasonId: "plane-database-head-mismatch",
3584
+ remedy: PLANE_DATABASE_HEAD_REMEDY,
3585
+ });
3586
+ }
3492
3587
  }
3493
3588
  if (sleep !== null) {
3494
3589
  const duration_ms = sleep.duration_ms ?? elapsedMs(monotonicNow());
@@ -3603,6 +3698,52 @@ async function planeFreshnessCreateGuard(ctx, own, trailer = []) {
3603
3698
  return null;
3604
3699
  }
3605
3700
  }
3701
+ /**
3702
+ * BAPI-1725 — the pre-launch freshness guard for a cold start. It reads the
3703
+ * current checkout's `HEAD` against `origin/main` (a fresh read, never the
3704
+ * preview's), runs the observation through {@link assessPlaneFreshness}
3705
+ * unchanged, and refuses only a confirmed, non-overridden stale result.
3706
+ *
3707
+ * Nothing has started when this refuses, so the output ends with `Nothing was
3708
+ * started.` and carries no running-plane trailer. Unverified evidence logs the
3709
+ * existing warning and the launch continues; an unexpected failure of this
3710
+ * advisory read never stops a launch. A confirmed non-Bridge checkout skips it.
3711
+ */
3712
+ async function coldStartCheckoutHeadGuard(ctx, repoRoot) {
3713
+ if (isConfirmedNonBridge(ctx))
3714
+ return null;
3715
+ try {
3716
+ const reports = await collectCheckoutHeadFreshness(ctx, repoRoot, false);
3717
+ if (reports === null)
3718
+ return null;
3719
+ const assessment = assessPlaneFreshness(reports, null, "create", ctx.options.allowStalePlane === true);
3720
+ const refusal = freshnessRefusalOf(assessment.blockers);
3721
+ const adverse = adverseFreshnessRows(assessment.rows);
3722
+ if (refusal !== null) {
3723
+ return refuse(ctx.deps, [
3724
+ `${ctx.epicKey}: REFUSED (${refusal.reasonId}) — the local plane is not current enough to ` +
3725
+ "create a run against.",
3726
+ ...renderFreshnessRows(adverse),
3727
+ "",
3728
+ "Nothing was started.",
3729
+ ]);
3730
+ }
3731
+ if (adverse.length > 0) {
3732
+ const log = ctx.deps.launchReadinessLog ?? ctx.deps.errorLog;
3733
+ log([
3734
+ assessment.overridden
3735
+ ? `${ctx.epicKey}: plane freshness — proceeding; a confirmed refusal was overridden for this invocation.`
3736
+ : `${ctx.epicKey}: plane freshness — proceeding; some evidence could not be verified.`,
3737
+ ...renderFreshnessRows(adverse),
3738
+ ].join("\n"));
3739
+ }
3740
+ return null;
3741
+ }
3742
+ catch {
3743
+ // An unexpected failure of an advisory read never stops a launch.
3744
+ return null;
3745
+ }
3746
+ }
3606
3747
  /** The warning-only counterpart for an existing run. Never refuses, never throws. */
3607
3748
  async function surfacePlaneFreshnessForExistingRun(ctx, own) {
3608
3749
  if (isConfirmedNonBridge(ctx)) {
@@ -3870,6 +4011,11 @@ async function coldStartPlane(ctx) {
3870
4011
  deps.errorLog(`${epicKey}: ${parallelColdRefusal}\nNothing was started.`);
3871
4012
  return 1;
3872
4013
  }
4014
+ // BAPI-1725: refuse a proven-stale checkout BEFORE anything is launched. The
4015
+ // post-launch guard below stays as the backstop.
4016
+ const staleHead = await coldStartCheckoutHeadGuard(ctx, repoRoot);
4017
+ if (staleHead !== null)
4018
+ return staleHead;
3873
4019
  const coldLanes = parallelLimitToExecutorLanes(ctx.options.parallel ?? DEFAULT_RUN_PARALLEL_LIMIT);
3874
4020
  const controlPlane = await deps.launchControlPlane({ preflight, executors: coldLanes });
3875
4021
  if (!controlPlane.ok) {
@@ -4535,7 +4681,7 @@ function reportExecutorOutcome(ctx, ensured, epicRunId, framing) {
4535
4681
  "It runs on THIS machine: sleep is held off while it runs, but a closed lid, a logout, or a",
4536
4682
  "shutdown stops it. The run stays server-side either way; restart the executor, or use a",
4537
4683
  "durable launch profile for long runs.",
4538
- KEEP_TERMINAL_OPEN_LINE,
4684
+ RUN_EXECUTOR_DETACHED_LINE,
4539
4685
  ].join("\n"));
4540
4686
  return 0;
4541
4687
  }
@@ -4564,6 +4710,10 @@ async function planeServesLiveRun(ctx, live) {
4564
4710
  /**
4565
4711
  * BAPI-1285 — a live run and no usable plan: make sure the run has an executor.
4566
4712
  *
4713
+ * BAPI-1714 — this ATTACHES; it does not finish setup. A `planning` run whose
4714
+ * authored plan the server holds is routed to the setup path instead (see
4715
+ * {@link isPlanningSetupToFinish}), so only an approved or later run reaches here.
4716
+ *
4567
4717
  * It creates nothing and never calls `setup-epic`, which hard-requires a plan
4568
4718
  * file. Readiness gates it exactly as it gates a create (only green proceeds),
4569
4719
  * because starting an executor for a run nothing can drive is not attaching to it.
@@ -5169,6 +5319,7 @@ async function runDriveEpicPreview(deps, options) {
5169
5319
  reason_id: named.reasonId,
5170
5320
  remedy: named.remedy,
5171
5321
  ...(named.authoritative === true ? { authoritative: true } : {}),
5322
+ ...(named.reasonCode !== undefined ? { reason_code: named.reasonCode } : {}),
5172
5323
  };
5173
5324
  preview.decision = "refuse";
5174
5325
  };
@@ -5220,7 +5371,7 @@ async function runDriveEpicPreview(deps, options) {
5220
5371
  needsTask,
5221
5372
  timed("health_status_ms", () => appendHealthCheckFact(deps, preview, observed.repository)),
5222
5373
  timed("escalation_ms", async () => { appendEscalationReachabilityRow(escalation, observed.readiness); }),
5223
- timed("executor_build_ms", () => appendExecutorBuildFreshnessWarning(deps, executor, observed.repository)),
5374
+ timed("executor_build_ms", () => appendExecutorBuildFreshnessWarning(deps, executor)),
5224
5375
  ]);
5225
5376
  const workerIds = new Set(worker.launch_checks?.map((row) => row.id));
5226
5377
  const needRows = needs.launch_checks ?? [];
@@ -5238,6 +5389,8 @@ async function runDriveEpicPreview(deps, options) {
5238
5389
  const collected = await collectLaunchPlanFacts(deps, options, preview, observed);
5239
5390
  // The tally lines do not depend on the builder succeeding.
5240
5391
  recordLaunchPlanObservations(preview, collected.tally);
5392
+ if (collected.uiReadiness !== undefined)
5393
+ preview.ui_readiness = collected.uiReadiness;
5241
5394
  const result = (deps.buildLaunchPlan ?? buildLaunchPlan)(preview, collected.facts);
5242
5395
  if (result)
5243
5396
  preview.launch_plan = result.launch_plan;
@@ -5259,6 +5412,130 @@ const previewPlanChildKeys = new WeakMap();
5259
5412
  /** The most time a launch preview spends reading the prerequisite cache before it carries on without it. */
5260
5413
  const PREREQUISITE_CACHE_READ_TIMEOUT_MS = 10_000;
5261
5414
  const PREREQUISITE_ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
5415
+ /** BAPI-1718 — the most time a create preview spends on ALL its advisory UI reads, shared. */
5416
+ const UI_READINESS_READ_TIMEOUT_MS = 10_000;
5417
+ /**
5418
+ * BAPI-1718 — start independent advisory reads together and finish under ONE
5419
+ * shared deadline. A `null` read was never available (a missing seam or access) and
5420
+ * stays failed. A read that throws, rejects, or has not finished when the deadline
5421
+ * passes is failed too; every read that completed keeps its value. The timer is
5422
+ * always cleared, a late completion is ignored, and nothing is retried.
5423
+ */
5424
+ async function collectAdvisoryReads(reads, timeoutMs) {
5425
+ const results = reads.map(() => ({ state: "failed" }));
5426
+ let closed = false;
5427
+ const settled = reads.map((run, index) => {
5428
+ if (run === null)
5429
+ return Promise.resolve();
5430
+ let pending;
5431
+ try {
5432
+ pending = Promise.resolve(run());
5433
+ }
5434
+ catch {
5435
+ return Promise.resolve();
5436
+ }
5437
+ return pending.then((value) => {
5438
+ if (!closed)
5439
+ results[index] = { state: "ok", value };
5440
+ }, () => undefined);
5441
+ });
5442
+ let timer;
5443
+ const deadline = new Promise((resolve) => {
5444
+ timer = setTimeout(resolve, timeoutMs);
5445
+ });
5446
+ try {
5447
+ await Promise.race([Promise.all(settled), deadline]);
5448
+ }
5449
+ finally {
5450
+ closed = true;
5451
+ if (timer !== undefined)
5452
+ clearTimeout(timer);
5453
+ }
5454
+ return [...results];
5455
+ }
5456
+ const UI_EPIC_SERVER_MODES = ["none", "local", "sfcc_shared_active"];
5457
+ /**
5458
+ * BAPI-1718 — the advisory UI readiness for a `create` preview. It reuses the plan
5459
+ * nodes and child set the preview already holds and reads only what is missing:
5460
+ * the epic and running-child descriptions, the tracked-file list, the worker grant,
5461
+ * and the epic-server record. It never throws and never changes anything the
5462
+ * preview decided; an unexpected failure simply yields no readiness.
5463
+ */
5464
+ async function collectUiReadiness(deps, options, preview, observed, handoff) {
5465
+ try {
5466
+ const access = observed.contextAccess;
5467
+ const repoName = observed.repoName ?? observed.access?.repoName ?? access?.repoName;
5468
+ // The children this launch will run: the plan's keys minus the already-done skips.
5469
+ const skipped = new Set();
5470
+ const merged = preview.already_done_children;
5471
+ if (merged !== undefined && merged.status === "checked") {
5472
+ for (const child of merged.children)
5473
+ if (child.will_skip === true)
5474
+ skipped.add(child.ticket_key);
5475
+ }
5476
+ const running = [...new Set((previewPlanChildKeys.get(preview) ?? []).filter((key) => !skipped.has(key)))];
5477
+ const readDescription = deps.readUiTicketDescription;
5478
+ const describe = (key) => readDescription === undefined || access === undefined ? null : () => readDescription(access, key);
5479
+ const readTracked = deps.listUiTrackedFiles;
5480
+ const readGrant = deps.readUiMcpGrant;
5481
+ const readRecord = deps.readUiEpicServerRecord;
5482
+ const results = await collectAdvisoryReads([
5483
+ describe(options.epicKey),
5484
+ ...running.map(describe),
5485
+ readTracked === undefined ? null : () => readTracked(),
5486
+ readGrant === undefined || repoName === undefined ? null : () => readGrant(repoName),
5487
+ readRecord === undefined || repoName === undefined ? null : () => readRecord(repoName),
5488
+ ], UI_READINESS_READ_TIMEOUT_MS);
5489
+ const asDescription = (read) => read.state === "ok" && typeof read.value === "string" ? { state: "ok", value: read.value } : { state: "failed" };
5490
+ const [epicRead, ...rest] = results;
5491
+ const childReads = rest.slice(0, running.length);
5492
+ const [trackedRead, grantRead, recordRead] = rest.slice(running.length);
5493
+ const tracked = trackedRead.state === "ok" && Array.isArray(trackedRead.value) &&
5494
+ trackedRead.value.every((entry) => typeof entry === "string")
5495
+ ? { state: "ok", value: trackedRead.value }
5496
+ : { state: "failed" };
5497
+ let grant = { state: "failed" };
5498
+ if (grantRead.state === "ok" && grantRead.value !== null && typeof grantRead.value === "object") {
5499
+ const value = grantRead.value;
5500
+ if (value.state === "absent")
5501
+ grant = { state: "absent" };
5502
+ else if (value.state === "unusable")
5503
+ grant = { state: "unusable", reason: "" };
5504
+ else if (value.state === "ok" && Array.isArray(value.grant?.servers))
5505
+ grant = value;
5506
+ }
5507
+ let mode = "unknown";
5508
+ if (recordRead.state === "ok" && recordRead.value !== null && typeof recordRead.value === "object") {
5509
+ const value = recordRead.value;
5510
+ if (value.state === "absent")
5511
+ mode = "none";
5512
+ else if (value.state === "ok" && typeof value.record?.mode === "string" && UI_EPIC_SERVER_MODES.includes(value.record.mode)) {
5513
+ mode = value.record.mode;
5514
+ }
5515
+ }
5516
+ const work = classifyUiWork({
5517
+ epicKey: options.epicKey,
5518
+ epicDescription: asDescription(epicRead),
5519
+ runningChildren: running.map((key, index) => ({ key, description: asDescription(childReads[index]) })),
5520
+ nodes: (preview.plan.generation?.nodes ?? preview.plan.inline?.nodes ?? []).map((node) => ({
5521
+ ticket_key: node.ticket_key,
5522
+ ...(node.touched_files !== undefined ? { touched_files: node.touched_files } : {}),
5523
+ })),
5524
+ trackedFiles: tracked,
5525
+ });
5526
+ return buildUiReadiness({
5527
+ work,
5528
+ verification: classifyUiVerification(grant, mode),
5529
+ mode,
5530
+ playwrightGrant: classifyPlaywrightGrant(grant),
5531
+ handoff,
5532
+ });
5533
+ }
5534
+ catch {
5535
+ // Advisory only: nothing from the failure is shown, and the preview is unchanged.
5536
+ return undefined;
5537
+ }
5538
+ }
5262
5539
  function handoffValueText(value) {
5263
5540
  return value === "unknown" ? "unknown (today's default: proceed)" : value;
5264
5541
  }
@@ -5403,7 +5680,15 @@ async function collectLaunchPlanFacts(deps, options, preview, observed) {
5403
5680
  if (suppressed.length > 0) {
5404
5681
  tally.push({ code: "launch_rows_kept_off_screen", line: `launch rows kept off the screen: ${[...new Set(suppressed)].join(", ")}` });
5405
5682
  }
5406
- return { facts: { prerequisites, handoff }, tally };
5683
+ // BAPI-1718 — the UI advisory is computed for a `create` decision only. It adds no
5684
+ // read for attach or any other decision, and never feeds the launch plan or a check.
5685
+ let uiReadiness;
5686
+ if (preview.decision === "create") {
5687
+ uiReadiness = await collectUiReadiness(deps, options, preview, observed, effective);
5688
+ if (uiReadiness !== undefined)
5689
+ tally.push({ code: "ui_readiness", line: uiReadiness.line });
5690
+ }
5691
+ return { facts: { prerequisites, handoff }, tally, ...(uiReadiness !== undefined ? { uiReadiness } : {}) };
5407
5692
  }
5408
5693
  /** Append the collected fixed lines to the preview's tally lines, once each. */
5409
5694
  function recordLaunchPlanObservations(preview, lines) {
@@ -5477,23 +5762,55 @@ function appendEscalationReachabilityRow(preview, readiness) {
5477
5762
  { ...row, duration_ms: elapsedMs(started) },
5478
5763
  ];
5479
5764
  }
5765
+ /**
5766
+ * The Bridge checkout root a launcher override names (BAPI-1725), or `null`.
5767
+ *
5768
+ * A plain whitespace split of the launcher value; the first absolute-path token
5769
+ * with an exact `mcp_server` path component selects the directory holding that
5770
+ * component. This matches the launcher format `resolvePermissionLauncher`
5771
+ * supports, which refuses quoted values, so there is deliberately no quote-aware
5772
+ * tokenization and no reconstruction of space-bearing paths. `mcp_server_extra`
5773
+ * and other lookalike components never qualify.
5774
+ */
5775
+ function bridgeRootFromLauncher(launcher) {
5776
+ for (const token of launcher.trim().split(/\s+/)) {
5777
+ if (token === "" || !path.isAbsolute(token))
5778
+ continue;
5779
+ let current = token;
5780
+ for (;;) {
5781
+ const parent = dirname(current);
5782
+ if (parent === current)
5783
+ break;
5784
+ if (path.basename(current) === "mcp_server")
5785
+ return parent;
5786
+ current = parent;
5787
+ }
5788
+ }
5789
+ return null;
5790
+ }
5480
5791
  /**
5481
5792
  * Append a non-blocking `executor-build-freshness` warning to the preview when a
5482
- * local CLI override (`BAPI_MCP_CLI`) is set and the executor build is stale or
5483
- * unreadable. Fail-open and read-only: it never changes the decision, a refusal,
5793
+ * local CLI override (`BAPI_MCP_CLI`) is set and the Bridge build it names is
5794
+ * stale or unreadable. Fail-open and read-only: it never changes the decision, a refusal,
5484
5795
  * readiness, or the exit code. A passing check, an unset or blank override, or a
5485
5796
  * missing dependency leaves `launch_checks` untouched. A thrown check prints one
5486
5797
  * fixed line and nothing from the exception.
5487
5798
  */
5488
- async function appendExecutorBuildFreshnessWarning(deps, preview, repository) {
5799
+ async function appendExecutorBuildFreshnessWarning(deps, preview) {
5489
5800
  const started = monotonicNow();
5490
5801
  const override = process.env[BRIDGE_LAUNCHER_ENV];
5491
5802
  if (override === undefined || override.trim() === "")
5492
5803
  return;
5493
5804
  if (deps.checkExecutorBuildFreshness === undefined)
5494
5805
  return;
5806
+ // BAPI-1725: the executor runs the Bridge build the launcher names, not the
5807
+ // consumer checkout. No qualifying launcher path means nothing to check; it
5808
+ // never falls back to the consumer's cwd.
5809
+ const bridgeRoot = bridgeRootFromLauncher(override);
5810
+ if (bridgeRoot === null)
5811
+ return;
5495
5812
  try {
5496
- const report = await deps.checkExecutorBuildFreshness(deps.cwd(), repository?.isBridge === false ? { isBridge: false } : undefined);
5813
+ const report = await deps.checkExecutorBuildFreshness(bridgeRoot);
5497
5814
  if (report.diagnostic === null)
5498
5815
  return;
5499
5816
  const outcome = report.outcomes.find((entry) => entry.status === "warn" || entry.status === "fail") ?? report.outcomes[0];
@@ -5530,7 +5847,24 @@ function autoMergeLine(preview) {
5530
5847
  : " Auto-merge: unavailable (older setup-epic output)";
5531
5848
  }
5532
5849
  const intent = merge.state === "on" ? { state: "on" } : { state: "off", reason: merge.reason ?? "" };
5533
- return ` ${formatSetupEpicAutoMergeIntent(intent, preview.summary.branch ?? undefined)}`;
5850
+ return ` ${formatSetupEpicAutoMergeIntent(intent, preview.summary.branch ?? undefined)}${autoMergeForecastSuffix(merge)}`;
5851
+ }
5852
+ /**
5853
+ * BAPI-1526 — the advisory suffix for the one "Auto-merge:" line. Empty for an
5854
+ * `off` intent, `unknown`, `not_requested`, or an absent forecast, so those lines
5855
+ * stay byte-identical. Reason ids are closed tokens, already validated by the parser.
5856
+ */
5857
+ function autoMergeForecastSuffix(merge) {
5858
+ const forecast = merge.forecast;
5859
+ if (merge.state !== "on" || forecast === undefined)
5860
+ return "";
5861
+ const ids = forecast.reason_ids.join(", ");
5862
+ if (forecast.outcome === "merge_approval_required") {
5863
+ return `; first approval will require merge approval${ids === "" ? "" : ` (${ids})`}`;
5864
+ }
5865
+ if (forecast.outcome === "auto_merge_kept" && ids !== "")
5866
+ return `; kept at first approval (${ids})`;
5867
+ return "";
5534
5868
  }
5535
5869
  /** BAPI-1593 — the plan digest setup-epic's dry run says the SERVER validated, per preview. */
5536
5870
  const previewServerPlanDigest = new WeakMap();
@@ -5955,8 +6289,9 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5955
6289
  live_run_checked: generatedLiveRunChecked,
5956
6290
  };
5957
6291
  }
5958
- // No plane exists yet, so there is no snapshot or database to compare;
5959
- // the host-sleep advisory still applies to the plane about to start.
6292
+ // No plane exists yet, so there is no plane snapshot or database to compare.
6293
+ // The checkout's HEAD is compared with origin/main instead (BAPI-1725); the
6294
+ // host-sleep advisory still applies to the plane about to start.
5960
6295
  observed.access = access;
5961
6296
  observed.launchTopology = { kind: "local", repoRoot: null };
5962
6297
  await applyPreviewFreshness(ctx, preview, {}, true);
@@ -6010,7 +6345,7 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
6010
6345
  (preview.warnings ??= []).push(LIVE_RUN_UNKNOWN_WARNING);
6011
6346
  if (unknownLive.kind === "live") {
6012
6347
  preview.live_run = { epic_run_id: unknownLive.epicRunId, status: unknownLive.status };
6013
- if (options.planFile === undefined) {
6348
+ if (options.planFile === undefined && !isPlanningSetupToFinish(unknownLive, previewServerPlan)) {
6014
6349
  preview.decision = "attach";
6015
6350
  return;
6016
6351
  }
@@ -6036,7 +6371,11 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
6036
6371
  // BAPI-1532 — a DISCOVERED plan beside a live run is unused: the launch attaches,
6037
6372
  // so the effective plan path is cleared while the preview still reports the plan
6038
6373
  // as found. An explicit --plan-file keeps its create-path behavior unchanged.
6039
- const attachingDiscoveredPlan = options.planFile === undefined && (plan.status === "found" || plan.status === "generated") && live.kind === "live";
6374
+ const attachingDiscoveredPlan = options.planFile === undefined &&
6375
+ (plan.status === "found" || plan.status === "generated") &&
6376
+ live.kind === "live" &&
6377
+ // BAPI-1714 — finishing setup for a planning run keeps the stored server plan.
6378
+ !isPlanningSetupToFinish(live, previewServerPlan);
6040
6379
  const effectivePlanPath = attachingDiscoveredPlan ? undefined : planPath;
6041
6380
  const previewCtx = { ...ctx, options: { ...options, ...(effectivePlanPath ? { planFile: effectivePlanPath } : {}) } };
6042
6381
  const observations = {
@@ -6062,6 +6401,18 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
6062
6401
  if (mandatoryDiagnosticsUncertain(readiness.diagnostics)) {
6063
6402
  (preview.warnings ??= []).push(MANDATORY_DIAGNOSTIC_UNKNOWN_WARNING);
6064
6403
  }
6404
+ // BAPI-1714 — an unverifiable workflow read warns once, on an applicable
6405
+ // unattended create or setup path. A genuine live-run attach (a live run with no
6406
+ // plan to set up) is excluded: first approval already decided it.
6407
+ const genuineAttach = live.kind === "live" && effectivePlanPath === undefined;
6408
+ if (options.attended !== true &&
6409
+ options.intoBase !== true &&
6410
+ !genuineAttach &&
6411
+ readiness.unattended?.repository_readiness_confirmed === false &&
6412
+ repositoryReadinessVerdict(readiness) === "unknown" &&
6413
+ !(preview.warnings ?? []).includes(REPOSITORY_WORKFLOWS_UNVERIFIABLE_WARNING)) {
6414
+ (preview.warnings ??= []).push(REPOSITORY_WORKFLOWS_UNVERIFIABLE_WARNING);
6415
+ }
6065
6416
  if (classification.kind === 'operator_blocked') {
6066
6417
  const requirement = V2_READINESS_REQUIREMENTS.find(req => req.id === classification.id);
6067
6418
  if (requirement)
@@ -6356,6 +6707,20 @@ async function finalizeCreatePreview(ctx, preview, planPath, coldStart, refuseTo
6356
6707
  const launch = classifyV2Readiness(payload.launchReadiness, { attended: options.attended, intoBase: options.intoBase });
6357
6708
  if (launch.kind === 'operator_blocked')
6358
6709
  return refuseTopLevel({ reasonId: launch.id, remedy: launch.remedy ?? 'Retry readiness.', authoritative: true });
6710
+ // BAPI-1526 — first approval would refuse this create's required checks. Read
6711
+ // ONLY on this policy-aware launch report (the actual create policy), and only
6712
+ // before a run exists: re-attaching to a live run is the recovery path, and an
6713
+ // approved run carries its own bound evidence. Anything but a proven denial
6714
+ // continues; approval stays the authority.
6715
+ if (payload.existingRunId === null && requiredChecksAdmissionVerdict(payload.launchReadiness) === "denied") {
6716
+ const denied = requiredChecksDeniedRecord(payload.launchReadiness);
6717
+ return refuseTopLevel({
6718
+ reasonId: REQUIRED_CHECKS_ADMISSION_REASON_ID,
6719
+ remedy: `${requiredChecksAdmissionRemedy(payload.launchReadiness)} Nothing was created.`,
6720
+ authoritative: true,
6721
+ ...(denied?.reason ? { reasonCode: denied.reason } : {}),
6722
+ });
6723
+ }
6359
6724
  }
6360
6725
  if (payload.effectivePolicy) {
6361
6726
  const facts = payload.effectivePolicy;
@@ -6391,6 +6756,11 @@ async function finalizeCreatePreview(ctx, preview, planPath, coldStart, refuseTo
6391
6756
  }
6392
6757
  preview.summary.auto_merge =
6393
6758
  intent.state === "off" ? { state: "off", reason: intent.reason } : { state: intent.state };
6759
+ // BAPI-1526 — the server's advisory forecast for THIS create policy (the
6760
+ // launch report). Absent on an older server; never changes the decision.
6761
+ const forecast = payload.launchReadiness?.merge_forecast;
6762
+ if (forecast !== undefined)
6763
+ preview.summary.auto_merge.forecast = forecast;
6394
6764
  preview.summary.auto_merge_scope = intent.state === "on" ? payload.featureBranch : null;
6395
6765
  // The bootstrap reusing a run IS an attach: it reports the run's id.
6396
6766
  if (payload.existingRunId !== null) {
@@ -6444,7 +6814,7 @@ async function applyPreviewFreshness(ctx, preview, topology, coldStart) {
6444
6814
  if (planeEndpointForBaseUrl(deps, ctx.access.baseUrl) === null)
6445
6815
  return;
6446
6816
  try {
6447
- const manifest = topology.manifest ?? null;
6817
+ const manifest = coldStart ? null : topology.manifest ?? null;
6448
6818
  const own = manifest !== null
6449
6819
  ? {
6450
6820
  repoRoot: manifest.repoRoot,
@@ -6453,7 +6823,12 @@ async function applyPreviewFreshness(ctx, preview, topology, coldStart) {
6453
6823
  ...(manifest.epicRunId ? { epicRunId: manifest.epicRunId } : {}),
6454
6824
  }
6455
6825
  : { repoRoot: deps.cwd(), ownsManifest: false };
6456
- const reports = coldStart ? null : await collectFreshnessObservations(ctx, own);
6826
+ // BAPI-1725: a cold start has no plane, so compare the CURRENT checkout's HEAD
6827
+ // (never a manifest's snapshot path) with origin/main; this feeds the same
6828
+ // assessor, override, and refusal as every other freshness observation.
6829
+ const reports = coldStart
6830
+ ? await collectCheckoutHeadFreshness(ctx, deps.cwd(), true)
6831
+ : await collectFreshnessObservations(ctx, own);
6457
6832
  // BAPI-1506: a `create` preview reports host sleep as a launch need on every
6458
6833
  // target (see appendLaunchNeedRows); only `attach` keeps it here.
6459
6834
  const sleep = preview.decision === "attach" ? await collectHostSleep(ctx, own.repoRoot) : null;