@bridge_gpt/mcp-server 0.2.73 → 0.2.74

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 (90) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +12 -0
  3. package/build/agents.generated.js +3 -3
  4. package/build/bridge-config.js +7 -1
  5. package/build/bridge-permissions.js +3 -0
  6. package/build/command-provisioning.js +4 -3
  7. package/build/commands.generated.js +5 -5
  8. package/build/conductor/bridge-api-client.js +26 -1
  9. package/build/conductor/command-drift.js +1 -1
  10. package/build/conductor/declared-extras.js +335 -0
  11. package/build/conductor/doctor.js +2 -0
  12. package/build/conductor/driver-pass-output.js +104 -0
  13. package/build/conductor/driver-pass.js +571 -0
  14. package/build/conductor/epic-branch-ci-inspection.js +61 -16
  15. package/build/conductor/epic-implementer-cli.js +33 -0
  16. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  17. package/build/conductor/epic-server-sfcc.js +58 -80
  18. package/build/conductor/epic-server.js +57 -4
  19. package/build/conductor/gate-discovery.js +46 -6
  20. package/build/conductor/gate-settings-review.js +51 -14
  21. package/build/credential-delivery.js +280 -0
  22. package/build/credential-launch-safety.js +142 -0
  23. package/build/credential-materialization.js +91 -16
  24. package/build/credential-references-node-deps.js +29 -0
  25. package/build/credential-references.js +1394 -0
  26. package/build/credential-references.test-fixtures.js +211 -0
  27. package/build/credential-scan-conventions.js +145 -0
  28. package/build/credential-scan.js +517 -0
  29. package/build/credential-store.js +50 -0
  30. package/build/credentials-cli.js +252 -3
  31. package/build/dependency-install-declarations.js +47 -1
  32. package/build/docs.generated.js +8 -1
  33. package/build/doctor.js +41 -0
  34. package/build/drive-epic.js +297 -37
  35. package/build/epic-branch-ci-summary.js +18 -1
  36. package/build/epic-capability-statement.js +71 -3
  37. package/build/epic-ci-workflow-drift.js +52 -13
  38. package/build/epic-ci-workflow-install.js +31 -6
  39. package/build/epic-ci-workflow-v3.js +273 -0
  40. package/build/epic-ci-workflow.js +128 -7
  41. package/build/epic-implementer-bin.js +161 -70
  42. package/build/epic-launch-context.js +102 -7
  43. package/build/epic-server-record.js +30 -15
  44. package/build/executor/credential-delivery-step.js +168 -0
  45. package/build/executor/deps.js +3 -1
  46. package/build/executor/env.js +39 -1
  47. package/build/executor/epic-server-context.js +23 -7
  48. package/build/executor/guarded-fast-forward-push.js +13 -8
  49. package/build/executor/job-runner.js +159 -17
  50. package/build/executor/permissions.js +85 -3
  51. package/build/executor/prompt-spec.js +37 -3
  52. package/build/executor-launch.js +4 -2
  53. package/build/git-exclude-lock.js +187 -0
  54. package/build/index.js +398 -269
  55. package/build/install-bridge-conductor-answers.js +84 -21
  56. package/build/install-bridge-conductor-apply.js +30 -1
  57. package/build/install-bridge-conductor-assessment.js +375 -48
  58. package/build/install-bridge-conductor-compact.js +27 -2
  59. package/build/install-bridge-conductor-contracts.js +10 -1
  60. package/build/install-bridge-conductor-gate.js +124 -11
  61. package/build/install-bridge-conductor-setup.js +46 -8
  62. package/build/install-bridge-conductor.js +625 -113
  63. package/build/install-bridge.js +88 -11
  64. package/build/install-doctor.js +38 -8
  65. package/build/install-sfcc-detection.js +120 -0
  66. package/build/install-sfcc-setup.js +185 -0
  67. package/build/mcp-grant-candidates.js +108 -96
  68. package/build/mcp-invoke.js +168 -4
  69. package/build/mcp-provisioning.js +21 -4
  70. package/build/mcp-server-invocation.js +13 -0
  71. package/build/merge-workflow-install.js +9 -1
  72. package/build/pipelines.generated.js +2 -1
  73. package/build/plane/status.js +8 -2
  74. package/build/printed-remedy-commands.js +5 -0
  75. package/build/project-root.js +40 -0
  76. package/build/readme.generated.js +1 -1
  77. package/build/repository-state-paths.js +5 -2
  78. package/build/repository-toolchains.js +6 -3
  79. package/build/setup-epic.js +116 -15
  80. package/build/sfcc/credentials.js +3 -2
  81. package/build/sfcc/hostname.js +98 -2
  82. package/build/sfcc/tool-wrapper.js +6 -95
  83. package/build/start-tickets.js +193 -29
  84. package/build/test-support/executor-source-files.js +200 -0
  85. package/build/testing-config-client.js +25 -2
  86. package/build/third-party-mcp-targets.js +35 -4
  87. package/build/version.generated.js +3 -3
  88. package/build/with-credentials.js +208 -0
  89. package/build/worktree-credential-delivery.js +340 -0
  90. package/package.json +1 -1
package/build/doctor.js CHANGED
@@ -47,6 +47,8 @@ import { CONDUCTOR_DEFAULT_BASE_URL, resolveConductorBridgeApiAccess } from "./c
47
47
  import { validateHttpBaseUrl } from "./base-url.js";
48
48
  import { getLiveRepositoryConductors, getParseDispatcherHealth, } from "./epic-shared/bridge-client.js";
49
49
  import { resolveRequiredStartTicketsRepoName } from "./start-tickets-repo.js";
50
+ import { collectCredentialReferenceDiagnostic, formatCredentialReferenceDiagnosticReport, } from "./credential-references.js";
51
+ import { createNodeCredentialReferenceDeps } from "./credential-references-node-deps.js";
50
52
  import { collectMcpGrantDiagnostic, formatMcpGrantDiagnosticReport, } from "./mcp-grant-doctor.js";
51
53
  import { collectWorkerContainmentDiagnostic, formatWorkerContainmentDiagnosticReport, } from "./worker-containment-diagnostic.js";
52
54
  import { BRIDGE_PACKAGE_NAME, describeLauncherReason, DUPLICATE_REGISTRATION_GUIDANCE, inspectLauncherConfigs, isExactVersion, isPrerequisiteFailure, parseLauncherPin as parseSharedLauncherPin, } from "./launcher-config-inspection.js";
@@ -180,6 +182,14 @@ export function getDoctorUsage() {
180
182
  "never prints a command, argument, or secret, writes nothing, and never",
181
183
  "changes the exit code.",
182
184
  "",
185
+ "It also includes an advisory 'Worker credential references' section: whether",
186
+ "this repository has recorded credential references (present, absent, or",
187
+ "unusable) and, for each, its name, level, source location, consumers, and",
188
+ "whether the source is present, missing, or unreadable, with a closed reason",
189
+ "(source_missing, key_missing, unreadable, parse_error). Production entries are",
190
+ "inspected but marked as excluded from delivery. It never prints a credential",
191
+ "value, writes nothing, and never changes the exit code.",
192
+ "",
183
193
  "It also includes an advisory '/drive-epic-run permission rules' section",
184
194
  "whether the project permissions.allow rules and the optional user",
185
195
  "autoMode entries (the run's sandbox description, added only by you running",
@@ -2283,6 +2293,37 @@ export async function runDoctorCli(argv, overrides = {}) {
2283
2293
  /* the grant section is advisory; never block the doctor report */
2284
2294
  }
2285
2295
  }
2296
+ // BAPI-1646 worker credential references section. Read-only (the record and the
2297
+ // approved source paths), advisory, never the exit code, never a value.
2298
+ if (overrides.credentialReferences !== false) {
2299
+ try {
2300
+ const refOverrides = overrides.credentialReferences ?? {};
2301
+ const injected = deps;
2302
+ const defaults = createNodeCredentialReferenceDeps(refOverrides.env ?? deps.env);
2303
+ const refReadFile = refOverrides.readFile ?? injected.readFile ?? defaults.readFile;
2304
+ let refRepoName = refOverrides.repoName ?? null;
2305
+ if (refOverrides.repoName === undefined) {
2306
+ try {
2307
+ const resolved = await resolveRequiredStartTicketsRepoName({ env: deps.env, cwd: deps.cwd, readFile: refReadFile });
2308
+ refRepoName = resolved.ok ? resolved.repoName : null;
2309
+ }
2310
+ catch {
2311
+ refRepoName = null;
2312
+ }
2313
+ }
2314
+ log(formatCredentialReferenceDiagnosticReport(await collectCredentialReferenceDiagnostic({
2315
+ ...defaults,
2316
+ ...refOverrides,
2317
+ env: refOverrides.env ?? deps.env,
2318
+ homedir: refOverrides.homedir ?? injected.homedir ?? defaults.homedir,
2319
+ readFile: refReadFile,
2320
+ repoName: refRepoName,
2321
+ })));
2322
+ }
2323
+ catch {
2324
+ /* the credential-reference section is advisory; never block the doctor report */
2325
+ }
2326
+ }
2286
2327
  // Worker containment advisory section (BAPI-1019/A.7). Placed beside the other
2287
2328
  // advisory sections and, uniquely, issuing NO probe of any kind — no command,
2288
2329
  // no file read, no network call. That is what keeps doctor's "an unsupported
@@ -74,6 +74,8 @@ import { validateHttpBaseUrl, describeBaseUrlRejection } from "./base-url.js";
74
74
  import { BRING_UP_REFUSAL_MESSAGES, BRING_UP_RUNBOOK, firstBringUpRefusal, firstProvenBringUpRefusal, } from "./conductor/bring-up-facts.js";
75
75
  import { V2_READINESS_REQUIREMENTS, buildLaunchEvidenceChecks, buildLaunchReadinessChecks, firstLaunchEvidenceBlocker, projectReadinessRowBlocking, unattendedPostureCheck, } from "./v2-readiness-requirements.js";
76
76
  import { classifyLocalGhPreflight, probeLocalMergeCapability, } from "./conductor/local-merge.js";
77
+ import { statusOnly } from "./credential-references.js";
78
+ import { createNodeCredentialReferenceDeps } from "./credential-references-node-deps.js";
77
79
  import { nodeGithubMergeCredentialReadDeps, resolveMergeCredentialAtAction, } from "./conductor/stored-merge-credential.js";
78
80
  import { resolveWorktreeSettingsExclude, } from "./executor/permissions.js";
79
81
  import { collectWorkerDatabaseDoctorSection, WORKER_DATABASE_DOCTOR_TIMEOUT_MS, } from "./conductor/doctor.js";
@@ -81,10 +83,11 @@ import { buildHostPowerLaunchRow, buildSelfHostedRunnerLaunchRow, buildWorkerDbR
81
83
  import { createWorkflowSource, inspectRequiredSelfHostedRunners, } from "./conductor/launch-need-probes.js";
82
84
  import { createWorkerDatabaseDoctorInspector } from "./conductor/worker-database-doctor-inspector.js";
83
85
  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";
86
+ 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
87
  import { getConfigFieldBaseBranch } from "./epic-shared/bridge-client.js";
88
+ import { createExecFileRunCommand, normalizeCommitSha } from "./epic-shared/cut-protocol.js";
86
89
  import { EPIC_KEY_PATTERN } from "./drive-epic-key.js";
87
- import { buildEpicLaunchContext, projectWorkerDatabase, readEpicLaunchContext, writeEpicLaunchContext, } from "./epic-launch-context.js";
90
+ import { buildEpicLaunchContext, projectWorkerDatabase, readEpicLaunchContext, writeEpicLaunchContext, writeEpicLaunchOutcome, } from "./epic-launch-context.js";
88
91
  import { flushProcessStdout, writeJsonDocument } from "./conductor/json-output.js";
89
92
  import { BRIDGE_LAUNCHER_ENV } from "./bridge-permissions.js";
90
93
  import { checkPlaneBuildFreshness, PLANE_BUILD_FIX_REMEDIATION } from "./plane/build-freshness.js";
@@ -1200,6 +1203,7 @@ export function createDefaultDriveEpicDeps() {
1200
1203
  throw new Error("repository_identity_unverifiable");
1201
1204
  return { repoRoot, isBridge: applicability === "bridge" };
1202
1205
  },
1206
+ readCredentialReferenceStatus: (repoName) => statusOnly(repoName, createNodeCredentialReferenceDeps(process.env)),
1203
1207
  readScopeBaseBranch: async (access) => {
1204
1208
  const configured = await getConfigFieldBaseBranch(access, globalThis.fetch);
1205
1209
  if (!configured.ok)
@@ -1226,6 +1230,7 @@ export function createDefaultDriveEpicDeps() {
1226
1230
  },
1227
1231
  readReadiness: (access) => fetchConductorReadiness(access, globalThis.fetch),
1228
1232
  writeLaunchContext: (context) => writeEpicLaunchContext(context),
1233
+ writeLaunchOutcome: (input) => writeEpicLaunchOutcome(input),
1229
1234
  reportLaunch: (report) => console.error(`${LAUNCH_REPORT_PREFIX}${JSON.stringify(report)}`),
1230
1235
  runSetupEpic: (argv, handoff) => runSetupEpicWorkflow(argv, {}, handoff),
1231
1236
  readEligibilityArtifact: (path) => readFile(path, "utf8"),
@@ -1471,6 +1476,7 @@ export async function runDriveEpicCli(argv, overrides = {}) {
1471
1476
  liveObservation: {},
1472
1477
  invokedAt: new Date((deps.now ?? Date.now)()).toISOString(),
1473
1478
  launchReportState: { reported: false },
1479
+ launchOutcomeState: { warned: false },
1474
1480
  };
1475
1481
  // BAPI-1285 — with no `--plan-file`, look for the plan BEFORE readiness. A
1476
1482
  // discovered plan must count as a supplied one for the BAPI-1153 cold-start
@@ -1893,6 +1899,8 @@ function escalate(deps, epicKey, reason) {
1893
1899
  deps.errorLog(text);
1894
1900
  return 1;
1895
1901
  }
1902
+ /** BAPI-1686 — said on every healthy-launch success output. */
1903
+ 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
1904
  /** The prefix of the default launch-report line. */
1897
1905
  export const LAUNCH_REPORT_PREFIX = "Launch report: ";
1898
1906
  /** How long drive-epic watches a planning run for activation after an uncertain approve. */
@@ -2172,7 +2180,7 @@ async function acquireObservedLive(ctx) {
2172
2180
  * Print the launch report once per invocation. Setup's observations follow
2173
2181
  * drive's own, in order, with exact duplicates dropped.
2174
2182
  */
2175
- function reportLaunchOutcome(ctx, outcome, facts) {
2183
+ async function reportLaunchOutcome(ctx, outcome, facts) {
2176
2184
  const state = ctx.launchReportState;
2177
2185
  if (state === undefined || state.reported)
2178
2186
  return;
@@ -2197,10 +2205,56 @@ function reportLaunchOutcome(ctx, outcome, facts) {
2197
2205
  observations,
2198
2206
  };
2199
2207
  ctx.deps.reportLaunch?.(report);
2208
+ // The durable record: best-effort, so a write failure never changes the exit code.
2209
+ const record = {
2210
+ outcome,
2211
+ ...(facts.epicRunId !== undefined ? { epicRunId: facts.epicRunId } : {}),
2212
+ ...(facts.runStatus !== undefined ? { runStatus: facts.runStatus } : {}),
2213
+ ...(facts.refusedBeforeCreate === true ? { refusedBeforeCreate: true } : {}),
2214
+ ...(facts.branchMove !== undefined ? { branchMove: facts.branchMove } : {}),
2215
+ observations: observations.map((o) => ({ code: o.code })),
2216
+ };
2217
+ if (ctx.launchOutcomeState !== undefined)
2218
+ ctx.launchOutcomeState.last = record;
2219
+ await writeLaunchOutcomeRecord(ctx, record, "not_applicable");
2220
+ }
2221
+ /**
2222
+ * Write `launch-outcome.json` for this invocation. Awaited, never throws, and
2223
+ * never a stop: a failed or refused write prints one fixed warning per invocation
2224
+ * and the caller carries on with its primary exit code.
2225
+ */
2226
+ async function writeLaunchOutcomeRecord(ctx, record, windDown) {
2227
+ const write = ctx.deps.writeLaunchOutcome;
2228
+ if (write === undefined)
2229
+ return true;
2230
+ let ok = false;
2231
+ try {
2232
+ const written = await write({
2233
+ epicKey: ctx.epicKey,
2234
+ invokedAt: ctx.invokedAt ?? launchNowIso(ctx),
2235
+ writtenAt: launchNowIso(ctx),
2236
+ launchOutcome: record.outcome,
2237
+ epicRunId: record.epicRunId ?? null,
2238
+ runStatus: record.runStatus ?? null,
2239
+ refusedBeforeCreate: record.refusedBeforeCreate === true,
2240
+ branchMove: record.branchMove ?? null,
2241
+ windDown,
2242
+ observations: record.observations,
2243
+ });
2244
+ ok = written.ok;
2245
+ }
2246
+ catch {
2247
+ ok = false;
2248
+ }
2249
+ if (!ok && ctx.launchOutcomeState !== undefined && !ctx.launchOutcomeState.warned) {
2250
+ ctx.launchOutcomeState.warned = true;
2251
+ ctx.deps.errorLog(`${ctx.epicKey}: [warn] The launch outcome record could not be written; the exit code is unchanged.`);
2252
+ }
2253
+ return ok;
2200
2254
  }
2201
2255
  /** A refusal that also settles the launch outcome. */
2202
- function refuseLaunch(ctx, lines) {
2203
- reportLaunchOutcome(ctx, "refused", {});
2256
+ async function refuseLaunch(ctx, lines) {
2257
+ await reportLaunchOutcome(ctx, "refused", {});
2204
2258
  return refuse(ctx.deps, lines);
2205
2259
  }
2206
2260
  /**
@@ -2242,19 +2296,21 @@ async function settleSetupLaunch(ctx, setup) {
2242
2296
  ...(setup.epicRunId !== undefined ? { epicRunId: setup.epicRunId } : {}),
2243
2297
  ...(setup.runStatus !== undefined ? { runStatus: setup.runStatus } : {}),
2244
2298
  ...(setup.observations !== undefined ? { observations: setup.observations } : {}),
2299
+ ...(setup.refusedBeforeCreate === true ? { refusedBeforeCreate: true } : {}),
2300
+ ...(setup.branchMove !== undefined ? { branchMove: setup.branchMove } : {}),
2245
2301
  };
2246
2302
  if (setup.exitCode !== 0) {
2247
- reportLaunchOutcome(ctx, setup.launchOutcome === "terminal" ? "terminal" : "refused", facts);
2303
+ await reportLaunchOutcome(ctx, setup.launchOutcome === "terminal" ? "terminal" : "refused", facts);
2248
2304
  return setup;
2249
2305
  }
2250
2306
  if (setup.launchOutcome === "not_confirmed") {
2251
- reportLaunchOutcome(ctx, "not_confirmed", facts);
2307
+ await reportLaunchOutcome(ctx, "not_confirmed", facts);
2252
2308
  return { ...setup, launchHandled: true };
2253
2309
  }
2254
2310
  if (setup.launchOutcome === "pending_activation" && setup.epicRunId !== undefined) {
2255
2311
  if (setup.runStatus !== "planning") {
2256
2312
  deps.log(`${epicKey}: run ${setup.epicRunId} is ${setup.runStatus ?? "not active"}; attached without changing it.`);
2257
- reportLaunchOutcome(ctx, "pending_activation", facts);
2313
+ await reportLaunchOutcome(ctx, "pending_activation", facts);
2258
2314
  return { ...setup, launchHandled: true };
2259
2315
  }
2260
2316
  deps.errorLog(`${epicKey}: run ${setup.epicRunId}: ${RUN_WAITING_FOR_APPROVAL_PHRASE}. Watching for activation ` +
@@ -2262,22 +2318,22 @@ async function settleSetupLaunch(ctx, setup) {
2262
2318
  const activation = await awaitRunActivation(ctx, setup.epicRunId);
2263
2319
  if (activation.kind === "active") {
2264
2320
  observeLaunch(ctx, "launch_outcome_reread", "approve re-read: run activated while attached");
2265
- reportLaunchOutcome(ctx, "active", { ...facts, runStatus: "active" });
2321
+ await reportLaunchOutcome(ctx, "active", { ...facts, runStatus: "active" });
2266
2322
  return { ...setup, launchOutcome: "active", runStatus: "active" };
2267
2323
  }
2268
2324
  if (activation.kind === "changed") {
2269
2325
  const terminal = isTerminalEpicRunStatus(activation.status);
2270
2326
  deps.log(`${epicKey}: run ${setup.epicRunId} is ${activation.status}; attached without changing it.`);
2271
- reportLaunchOutcome(ctx, terminal ? "terminal" : "pending_activation", { ...facts, runStatus: activation.status });
2327
+ await reportLaunchOutcome(ctx, terminal ? "terminal" : "pending_activation", { ...facts, runStatus: activation.status });
2272
2328
  return { ...setup, exitCode: terminal ? 1 : 0, launchHandled: true };
2273
2329
  }
2274
2330
  deps.errorLog(`${epicKey}: [warn] ${APPROVAL_NOT_CONFIRMED_WARNING}. Re-run setup with: ` +
2275
2331
  launchReconnectCommand(epicKey, ctx.access));
2276
- reportLaunchOutcome(ctx, "pending_activation", facts);
2332
+ await reportLaunchOutcome(ctx, "pending_activation", facts);
2277
2333
  return { ...setup, launchHandled: true };
2278
2334
  }
2279
2335
  // Never inferred from exit 0: only a reported `active` status counts.
2280
- reportLaunchOutcome(ctx, setup.launchOutcome === "active" || setup.runStatus === "active" ? "active" : "pending_activation", facts);
2336
+ await reportLaunchOutcome(ctx, setup.launchOutcome === "active" || setup.runStatus === "active" ? "active" : "pending_activation", facts);
2281
2337
  return setup;
2282
2338
  }
2283
2339
  /** Resolve policy intent once for the setup delegation, after a fresh run read. */
@@ -2569,7 +2625,7 @@ async function runSelectedSetupEpicWorkflow(ctx) {
2569
2625
  : await prepareSetupSelection(ctx);
2570
2626
  if (!selected.ok) {
2571
2627
  ctx.deps.errorLog(`${ctx.epicKey}: REFUSED (${selected.reasonId}) — the selected run or policy could not be verified.`);
2572
- return { exitCode: 1 };
2628
+ return { exitCode: 1, refusedBeforeCreate: true };
2573
2629
  }
2574
2630
  // BAPI-1595 — readiness is acquired by the PREVIEW and never by a launch. The
2575
2631
  // hand-off says so explicitly (an in-process contract, not an argv flag), and
@@ -2598,7 +2654,7 @@ async function runSelectedSetupEpicWorkflow(ctx) {
2598
2654
  if (evaluation.refusals.length > 0) {
2599
2655
  deps.errorLog(`${epicKey}: REFUSED (skip-child-refused) — ${skipRefusalRemedy(evaluation.refusals)}`);
2600
2656
  deps.errorLog("No run was created.");
2601
- return { exitCode: 1 };
2657
+ return { exitCode: 1, refusedBeforeCreate: true };
2602
2658
  }
2603
2659
  if (evaluation.state.status === "not_checked") {
2604
2660
  if (evaluation.state.reason === "cut_commit_unavailable" || evaluation.state.reason === "check_failed") {
@@ -2612,7 +2668,7 @@ async function runSelectedSetupEpicWorkflow(ctx) {
2612
2668
  if (evaluation.skipKeys.size >= evaluation.childKeys.length) {
2613
2669
  deps.errorLog(`${epicKey}: REFUSED (${EPIC_ALREADY_COMPLETE_REASON_ID}) — ${EPIC_ALREADY_COMPLETE_REMEDY}`);
2614
2670
  deps.errorLog("No run was created.");
2615
- return { exitCode: 1 };
2671
+ return { exitCode: 1, refusedBeforeCreate: true };
2616
2672
  }
2617
2673
  const skipped = evaluation.childKeys
2618
2674
  .filter((key) => evaluation.skipKeys.has(key))
@@ -3704,6 +3760,63 @@ async function attachToPlane(ctx, manifest, readiness) {
3704
3760
  laneCount: attachedPlaneLaneCount(manifest),
3705
3761
  }, readiness);
3706
3762
  }
3763
+ /**
3764
+ * The first lines of a setup refusal's follow-up text: the outcome first. A proven
3765
+ * pre-create refusal leads with "No run was created."; a confirmed branch move is
3766
+ * always named, so nothing ever claims "no branch changed" after one. Anything not
3767
+ * proven keeps today's text (no lead at all).
3768
+ */
3769
+ function refusalLeadLines(setup) {
3770
+ const lines = [];
3771
+ if (setup.refusedBeforeCreate === true)
3772
+ lines.push("", "No run was created.");
3773
+ if (setup.branchMove !== undefined) {
3774
+ const { branch, from, to } = setup.branchMove;
3775
+ lines.push(`Branch origin/${branch} was moved from ${from} to ${to} before this refusal.`);
3776
+ }
3777
+ return lines;
3778
+ }
3779
+ /**
3780
+ * Wind down the plane THIS invocation launched, but only when a leftover plane is
3781
+ * proven to hold no run: setup refused before any create request, no run id was
3782
+ * resolved, the plane was launched here (not attached), and a fresh manifest read
3783
+ * names the same plane with no bound run. Everything else returns
3784
+ * `not_applicable` and starts no shutdown.
3785
+ *
3786
+ * The outcome record is written (and awaited) as `pending` BEFORE `plane down`, and
3787
+ * rewritten as `completed` or `failed` after. A failed record write never blocks the
3788
+ * shutdown (the record is best-effort), and a failed shutdown never changes the
3789
+ * setup failure's exit code. `plane down` keeps enforcing its own ownership checks;
3790
+ * no retry, lifecycle state, or supervisor change is added here.
3791
+ */
3792
+ async function windDownProvenUnboundPlane(ctx, plane, setup) {
3793
+ if (setup.refusedBeforeCreate !== true || plane.origin !== "launched" || setup.epicRunId !== undefined) {
3794
+ return "not_applicable";
3795
+ }
3796
+ let unbound = false;
3797
+ try {
3798
+ const read = await ctx.deps.readPlaneManifest(plane.repoRoot);
3799
+ unbound = read.kind === "valid" && read.manifest.planeId === plane.planeId && read.manifest.epicRunId === undefined;
3800
+ }
3801
+ catch {
3802
+ unbound = false;
3803
+ }
3804
+ if (!unbound)
3805
+ return "not_applicable";
3806
+ const last = ctx.launchOutcomeState?.last ?? { outcome: "refused", observations: [] };
3807
+ const record = { ...last, refusedBeforeCreate: true };
3808
+ await writeLaunchOutcomeRecord(ctx, record, "pending");
3809
+ let confirmed = false;
3810
+ try {
3811
+ confirmed = (await ctx.deps.runPlane(["down"], { cwd: plane.repoRoot })) === 0;
3812
+ }
3813
+ catch {
3814
+ confirmed = false;
3815
+ }
3816
+ const finalState = confirmed ? "completed" : "failed";
3817
+ await writeLaunchOutcomeRecord(ctx, record, finalState);
3818
+ return finalState;
3819
+ }
3707
3820
  /**
3708
3821
  * The shared tail: create/approve/cut through `setup-epic`, then request lanes
3709
3822
  * scoped to exactly that run.
@@ -3728,25 +3841,43 @@ async function createRunAndRequestLanes(ctx, plane, readiness) {
3728
3841
  if (setup.launchHandled === true)
3729
3842
  return setup.exitCode;
3730
3843
  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"));
3844
+ // The control plane is LEFT RUNNING unless a narrow case is PROVEN safe, and NO
3845
+ // EXECUTOR LANE was spawned — there is nothing to claim a job that may not exist.
3846
+ // Winding down in general would stop the very run `setup-epic` may have just
3847
+ // created, because `plane down` stops the manifest-bound run before terminating
3848
+ // processes. The one exception is below: setup proved (by control flow, never by
3849
+ // text or exit code) that it refused BEFORE any create request, this invocation
3850
+ // started the plane, no run id was resolved, and the plane's manifest still names
3851
+ // this plane with no bound run. Then no run exists for `plane down` to stop.
3852
+ const windDown = await windDownProvenUnboundPlane(ctx, plane, setup);
3853
+ const lead = refusalLeadLines(setup);
3854
+ if (windDown === "completed") {
3855
+ deps.errorLog([...lead, `${epicKey}: the control plane this invocation started was shut down automatically.`].join("\n"));
3856
+ return setup.exitCode;
3857
+ }
3858
+ deps.errorLog([
3859
+ ...lead,
3860
+ ...(windDown === "failed"
3861
+ ? [
3862
+ "",
3863
+ `${epicKey}: Automatic shutdown could not be confirmed. Check the plane with \`plane status\`,`,
3864
+ "and wind it down with `plane down` if it is still running.",
3865
+ ]
3866
+ : launched
3867
+ ? [
3868
+ "",
3869
+ `${epicKey}: the Epic Implementer CONTROL PLANE was started by this invocation and is STILL RUNNING.`,
3870
+ "No executor lane was spawned, so nothing is claiming jobs.",
3871
+ "It was not wound down automatically, because doing so would stop a run that may",
3872
+ "already have been created and approved. Inspect it with `plane status`, and wind it",
3873
+ "down with `plane down` once you have decided what to do with the run.",
3874
+ ]
3875
+ : [
3876
+ "",
3877
+ `${epicKey}: the plane this invocation attached to was left running exactly as it was.`,
3878
+ "No executor lane was requested. Inspect it with `plane status`.",
3879
+ ]),
3880
+ ].join("\n"));
3750
3881
  return setup.exitCode;
3751
3882
  }
3752
3883
  if (setup.epicRunId === undefined) {
@@ -3805,6 +3936,7 @@ async function createRunAndRequestLanes(ctx, plane, readiness) {
3805
3936
  `${epicKey}: attached — executor lane(s) scoped to run ${setup.epicRunId} were requested`,
3806
3937
  "from the running plane, whose runtime starts them and then the dead-man observer.",
3807
3938
  "`plane status` reports their progress; the run's own status reports dispatch.",
3939
+ KEEP_TERMINAL_OPEN_LINE,
3808
3940
  ].join("\n"));
3809
3941
  return 0;
3810
3942
  }
@@ -3840,6 +3972,7 @@ async function createRunAndRequestLanes(ctx, plane, readiness) {
3840
3972
  "That reports PROCESSES. If this run cuts an epic branch, the reconciler holds ticket",
3841
3973
  "dispatch until its index scope finishes preparing; `plane status` and the run's own",
3842
3974
  "status report that separately.",
3975
+ KEEP_TERMINAL_OPEN_LINE,
3843
3976
  ].join("\n"));
3844
3977
  return 0;
3845
3978
  }
@@ -4065,7 +4198,7 @@ async function createRunWithRunExecutor(ctx, readiness) {
4065
4198
  return setup.exitCode;
4066
4199
  if (setup.exitCode !== 0) {
4067
4200
  // setup-epic already said why. Nothing was started for a run that may not exist.
4068
- deps.errorLog(`\n${epicKey}: no executor was started.`);
4201
+ deps.errorLog([...refusalLeadLines(setup), `\n${epicKey}: no executor was started.`].join("\n"));
4069
4202
  return setup.exitCode;
4070
4203
  }
4071
4204
  if (setup.epicRunId === undefined) {
@@ -4150,6 +4283,7 @@ function reportExecutorOutcome(ctx, ensured, epicRunId, framing) {
4150
4283
  "It runs on THIS machine: sleep is held off while it runs, but a closed lid, a logout, or a",
4151
4284
  "shutdown stops it. The run stays server-side either way; restart the executor, or use a",
4152
4285
  "durable launch profile for long runs.",
4286
+ KEEP_TERMINAL_OPEN_LINE,
4153
4287
  ].join("\n"));
4154
4288
  return 0;
4155
4289
  }
@@ -4210,7 +4344,7 @@ async function attachToLiveRun(ctx, readiness, live, unusedDiscoveredPlan) {
4210
4344
  return refuseRemoteRuntime(ctx, readiness);
4211
4345
  return refuse(deps, localReconcilerRefusal(epicKey, readiness).lines);
4212
4346
  }
4213
- reportLaunchOutcome(ctx, live.status === "active" ? "active" : "pending_activation", {
4347
+ await reportLaunchOutcome(ctx, live.status === "active" ? "active" : "pending_activation", {
4214
4348
  epicRunId: live.epicRunId,
4215
4349
  runStatus: live.status,
4216
4350
  });
@@ -4694,6 +4828,32 @@ async function readGeneratedPlanNodes(deps, planPath) {
4694
4828
  return null;
4695
4829
  }
4696
4830
  }
4831
+ /**
4832
+ * BAPI-1648 — the names of approved credential references whose source is
4833
+ * missing or unreadable. The repository name is the verified Bridge name the
4834
+ * preview already resolved, never a folder or remote name. Every failure, and an
4835
+ * absent or unusable record, yields an empty list: this is a display aid and
4836
+ * must not reach launch control flow.
4837
+ */
4838
+ async function collectMissingCredentialNames(deps, observed) {
4839
+ const repoName = observed.repoName ?? observed.access?.repoName ?? observed.contextAccess?.repoName;
4840
+ if (repoName === undefined || deps.readCredentialReferenceStatus === undefined)
4841
+ return [];
4842
+ try {
4843
+ const result = await deps.readCredentialReferenceStatus(repoName);
4844
+ if (result.state !== "ok")
4845
+ return [];
4846
+ const names = new Set();
4847
+ for (const status of result.statuses) {
4848
+ if (status.state === "missing" || status.state === "unreadable")
4849
+ names.add(status.name);
4850
+ }
4851
+ return [...names].sort();
4852
+ }
4853
+ catch {
4854
+ return [];
4855
+ }
4856
+ }
4697
4857
  /**
4698
4858
  * Run the read-only preview. Returns `0` for a `create` or `attach` decision and
4699
4859
  * `1` for `refuse` or `stop`. Never throws: an unexpected failure becomes one
@@ -4776,6 +4936,7 @@ async function runDriveEpicPreview(deps, options) {
4776
4936
  });
4777
4937
  }
4778
4938
  ensureRefusalExplained(preview);
4939
+ preview.credentials_missing = await collectMissingCredentialNames(deps, observed);
4779
4940
  await writePreviewLaunchContext(deps, options, preview, observed);
4780
4941
  if (observed.repository?.isBridge === false && !preview.launch_checks?.some((row) => row.id === "plane-snapshot-freshness")) {
4781
4942
  preview.launch_checks = [...(preview.launch_checks ?? []), ...nonBridgeRows(["plane-snapshot-freshness", "plane-database-head"])];
@@ -5646,6 +5807,91 @@ async function previewDecision(deps, options, preview, refuseWithReadiness, refu
5646
5807
  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
5808
  await applyPreviewFreshness(ctx, preview, topology, false);
5648
5809
  }
5810
+ /** The `git ls-remote --symref origin HEAD` answer: the default branch and its commit. */
5811
+ function parseRemoteDefaultHead(stdout) {
5812
+ let branch = null;
5813
+ let sha = null;
5814
+ for (const line of stdout.split("\n")) {
5815
+ const symref = /^ref:\s+refs\/heads\/(\S+)\s+HEAD\s*$/.exec(line.trim());
5816
+ if (symref)
5817
+ branch = symref[1];
5818
+ const direct = /^([0-9a-fA-F]{40})\s+HEAD\s*$/.exec(line.trim());
5819
+ if (direct)
5820
+ sha = normalizeCommitSha(direct[1]);
5821
+ }
5822
+ return branch !== null && sha !== null ? { branch, sha } : null;
5823
+ }
5824
+ /**
5825
+ * Preview-time check of the epic branch a new run would cut.
5826
+ *
5827
+ * Returns a refusal ONLY for a proven conflict (`has_own_commits`). Anything it
5828
+ * cannot establish (no target, an unreadable remote, an exception) emits one fixed
5829
+ * warning and returns null: the real launch decides. Read-only: the shared
5830
+ * classifier never updates a branch, and nothing here trusts a local tracking ref.
5831
+ */
5832
+ async function previewEpicBranchConflict(ctx, input) {
5833
+ const { deps } = ctx;
5834
+ const skipped = () => {
5835
+ deps.errorLog("[warn] The epic branch could not be checked during preview; the launch will check it.");
5836
+ return null;
5837
+ };
5838
+ try {
5839
+ const gitDeps = {
5840
+ runCommand: deps.runCommand ?? createExecFileRunCommand(),
5841
+ cwd: deps.cwd(),
5842
+ fetchImpl: globalThis.fetch,
5843
+ errorLog: () => undefined,
5844
+ };
5845
+ const readRemote = async (args) => Promise.resolve(gitDeps.runCommand("git", args, { cwd: gitDeps.cwd }));
5846
+ // No remote branch means nothing can conflict: no target is needed.
5847
+ const branchHead = await readRemote(["ls-remote", "--heads", "origin", `refs/heads/${input.branch}`]);
5848
+ if (branchHead.exitCode === 0 && branchHead.stdout.trim() === "")
5849
+ return null;
5850
+ let target = input.cutCommitSha === null ? null : normalizeCommitSha(input.cutCommitSha);
5851
+ let base = input.configuredBase;
5852
+ let defaultAssumed = null;
5853
+ if (target === null && base !== null) {
5854
+ const head = await readRemote(["ls-remote", "--heads", "origin", `refs/heads/${base}`]);
5855
+ const sha = head.exitCode === 0 ? normalizeCommitSha(head.stdout.trim().split(/\s+/)[0]) : null;
5856
+ target = sha;
5857
+ }
5858
+ if (target === null || base === null) {
5859
+ if (base === null) {
5860
+ // Cold preview with no configured-base evidence: the remote's default branch.
5861
+ const symref = await readRemote(["ls-remote", "--symref", "origin", "HEAD"]);
5862
+ const parsed = symref.exitCode === 0 ? parseRemoteDefaultHead(symref.stdout) : null;
5863
+ if (parsed === null)
5864
+ return skipped();
5865
+ base = parsed.branch;
5866
+ defaultAssumed = parsed.branch;
5867
+ if (target === null)
5868
+ target = parsed.sha;
5869
+ }
5870
+ }
5871
+ if (target === null || base === null)
5872
+ return skipped();
5873
+ const classified = await classifyRemoteEpicBranch(gitDeps, input.branch, target);
5874
+ if (classified.status === "unknown")
5875
+ return skipped();
5876
+ if (classified.status !== "has_own_commits")
5877
+ return null;
5878
+ const lines = [
5879
+ `origin/${input.branch} already holds commits that are not on the commit this run would start from.`,
5880
+ "Inspect them:",
5881
+ `git log origin/${base}..origin/${input.branch}`,
5882
+ "Then finish that work, or delete the branch:",
5883
+ `git push origin --delete ${input.branch}`,
5884
+ "Then preview again. Nothing was created.",
5885
+ ];
5886
+ if (defaultAssumed !== null) {
5887
+ lines.push(`If this repository's base is not ${defaultAssumed}, bring its plane up and preview again.`);
5888
+ }
5889
+ return { reasonId: "epic-branch-has-own-commits", remedy: lines.join("\n") };
5890
+ }
5891
+ catch {
5892
+ return skipped();
5893
+ }
5894
+ }
5649
5895
  async function finalizeCreatePreview(ctx, preview, planPath, coldStart, refuseTopLevel, liveRunKnown = false) {
5650
5896
  const { deps, options, access } = ctx;
5651
5897
  const prepared = ctx.handoff
@@ -5746,6 +5992,18 @@ async function finalizeCreatePreview(ctx, preview, planPath, coldStart, refuseTo
5746
5992
  preview.summary.branch = payload.featureBranch;
5747
5993
  if (payload.scopeBaseBranch !== null)
5748
5994
  previewScopeBaseBranch.set(preview, payload.scopeBaseBranch);
5995
+ // A leftover epic branch with its own commits would refuse the real launch after a
5996
+ // plane had started. Say so now. Outside the setup dry run on purpose, so the
5997
+ // generic `setup-preview-failed` remedy cannot replace these exact instructions.
5998
+ if (!liveRunKnown && payload.featureBranch !== null && payload.existingRunId === null) {
5999
+ const conflict = await previewEpicBranchConflict(ctx, {
6000
+ branch: payload.featureBranch,
6001
+ configuredBase: payload.scopeBaseBranch,
6002
+ cutCommitSha: evaluation?.cutCommitSha ?? null,
6003
+ });
6004
+ if (conflict !== null)
6005
+ return refuseTopLevel(conflict);
6006
+ }
5749
6007
  if (payload.serverPlanHash !== null)
5750
6008
  previewServerPlanDigest.set(preview, payload.serverPlanHash);
5751
6009
  preview.summary.ticket_review = payload.ticketReview;
@@ -6139,7 +6397,9 @@ async function emitPreview(deps, options, preview) {
6139
6397
  lines.push(` skipped: ${skipped.path} (${skipped.reason})`);
6140
6398
  }
6141
6399
  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}`);
6400
+ 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
6401
+ ? [` Credentials: advisory — not available on this machine: ${preview.credentials_missing.join(", ")}`]
6402
+ : []), ...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
6403
  if (isPlaneDownStop(preview)) {
6144
6404
  // The shared stop text, verbatim and unindented, so it reads exactly as the
6145
6405
  // real launch prints it. It is a stop, not a refusal.
@@ -74,7 +74,7 @@ export function describeEpicBranchCi(input) {
74
74
  const parts = [];
75
75
  const unsupported = unsupportedSystemsSentence(input.ciSystems);
76
76
  if (input.coverage === "covers") {
77
- parts.push("A workflow already runs on pull requests into epic branches, so each child can wait for its checks before it merges.");
77
+ parts.push("A workflow is configured to start on pull requests into epic branches, so each child can wait for its checks to run before it merges.");
78
78
  if (unsupported)
79
79
  parts.push(unsupported);
80
80
  return parts.join(" ");
@@ -129,6 +129,23 @@ export function describeDeclinedCiChange(input) {
129
129
  finalIntegrationSentence(input.integrationTarget),
130
130
  ].join(" ");
131
131
  }
132
+ /**
133
+ * BAPI-1679 — the text for a recommended `include` that lost its only support: the setup pull
134
+ * request did not open on this apply, or setup could not confirm that it did.
135
+ */
136
+ export function describeUnopenedSetupCredit(input) {
137
+ return [
138
+ input.confirmed
139
+ ? "The setup pull request did not open, so it adds no checks."
140
+ : "Setup could not confirm that the setup pull request opened, so it does not count on its checks.",
141
+ "Setup recorded decline for epic-branch CI instead of the recommended include.",
142
+ input.coverage === "does_not_cover"
143
+ ? "Child pull requests merge into the epic branch without checks."
144
+ : "Child pull requests may merge into the epic branch without checks.",
145
+ finalIntegrationSentence(input.integrationTarget),
146
+ "Once a workflow runs on pull requests into epic branches, run setup again and it records include.",
147
+ ].join(" ");
148
+ }
132
149
  /** The text for an opened or reused CI pull request: proposed, not coverage. */
133
150
  export function describeProposedCiChange(actionClass, path, url) {
134
151
  const where = url !== null ? ` in ${url}` : "";