@bridge_gpt/mcp-server 0.2.75 → 0.2.77

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 (94) hide show
  1. package/README.md +8 -6
  2. package/build/agents.generated.js +5 -5
  3. package/build/cli-dispatch.js +333 -0
  4. package/build/codex-auto-recovery.js +25 -7
  5. package/build/commands.generated.js +8 -8
  6. package/build/conductor/bridge-api-client.js +193 -13
  7. package/build/conductor/declare-blocked.js +146 -7
  8. package/build/conductor/driver-pass.js +8 -0
  9. package/build/conductor/driver-register.js +8 -2
  10. package/build/conductor/epic-implementer-cli.js +15 -10
  11. package/build/conductor/epic-server-journal.js +52 -22
  12. package/build/conductor/epic-server-recipe.js +15 -5
  13. package/build/conductor/epic-server-runtime.js +163 -45
  14. package/build/conductor/epic-server.js +13 -6
  15. package/build/conductor/install-doctor.js +30 -2
  16. package/build/conductor/launch-plan.js +28 -7
  17. package/build/conductor/local-merge.js +55 -13
  18. package/build/conductor/pr-ci-producer.js +12 -3
  19. package/build/conductor/readiness-prerequisites.js +89 -2
  20. package/build/conductor/readiness-sections.js +46 -13
  21. package/build/conductor/readiness.js +3 -40
  22. package/build/conductor/recovery-cli.js +14 -12
  23. package/build/conductor/repository-workflow-remedy.js +147 -7
  24. package/build/conductor/ui-readiness.js +224 -0
  25. package/build/conductor/wait-run-attention.js +9 -4
  26. package/build/conductor/wait-run-cli.js +9 -2
  27. package/build/docs.generated.js +67 -4
  28. package/build/doctor.js +97 -1
  29. package/build/drive-epic.js +625 -33
  30. package/build/engine-paths.js +10 -0
  31. package/build/epic-coherence-input-cli.js +105 -10
  32. package/build/epic-coherence-input.js +877 -4
  33. package/build/epic-coherence-input.test-fixtures.js +117 -0
  34. package/build/epic-implementer-bin.js +947 -120
  35. package/build/epic-implementer-env.js +2 -2
  36. package/build/epic-launch-context.js +8 -1
  37. package/build/epic-shared/cut-protocol.js +55 -3
  38. package/build/executor/completion-contract.js +14 -1
  39. package/build/executor/failure-reason-codes.js +2 -0
  40. package/build/executor/guarded-fast-forward-push.js +25 -2
  41. package/build/executor/integration-job.js +56 -2
  42. package/build/executor/job-runner.js +87 -28
  43. package/build/executor/likely-tests.js +78 -6
  44. package/build/executor/merge-job.js +45 -1
  45. package/build/executor/permissions.js +187 -2
  46. package/build/executor/provider-checks.js +101 -5
  47. package/build/executor/rebase-finalization.js +29 -27
  48. package/build/executor/reconcile-overlap-job.js +70 -17
  49. package/build/executor/rename-aside.js +265 -0
  50. package/build/executor/required-work-ledger.js +89 -6
  51. package/build/executor/resume-pre-spawn.js +32 -8
  52. package/build/executor/runner.js +26 -4
  53. package/build/executor/types.js +121 -0
  54. package/build/executor/worktree.js +39 -2
  55. package/build/index.js +2500 -495
  56. package/build/init.js +16 -0
  57. package/build/install-bridge-conductor-answers.js +4 -0
  58. package/build/install-bridge-conductor-apply.js +10 -0
  59. package/build/install-bridge-conductor-assessment.js +84 -0
  60. package/build/install-bridge-conductor-contracts.js +9 -1
  61. package/build/install-bridge-conductor-setup.js +103 -3
  62. package/build/install-bridge-conductor.js +440 -812
  63. package/build/install-bridge.js +4 -11
  64. package/build/language-catalog.generated.js +2649 -0
  65. package/build/mcp-host-config.js +54 -37
  66. package/build/phase-context-git-probe.js +16 -0
  67. package/build/pipelines.generated.js +47 -19
  68. package/build/plan-execution-ledger.js +35 -0
  69. package/build/plan-generation.js +34 -0
  70. package/build/plane/build-freshness.js +6 -0
  71. package/build/plane/cli.js +12 -5
  72. package/build/plane/plane-freshness.js +43 -26
  73. package/build/printed-remedy-commands.js +17 -0
  74. package/build/readiness-prerequisites.generated.js +28 -0
  75. package/build/readme.generated.js +1 -1
  76. package/build/run-unit-tests-launcher.js +3 -1
  77. package/build/secret-redaction.js +3 -0
  78. package/build/server.js +7946 -0
  79. package/build/setup-epic.js +41 -8
  80. package/build/start-tickets-prereqs.js +3 -6
  81. package/build/test-support/console-guard.js +30 -0
  82. package/build/test-support/create-preview-world.js +232 -0
  83. package/build/test-support/module-imports.js +155 -0
  84. package/build/test-support/server-client.js +96 -0
  85. package/build/test-support/stdio-server.js +146 -0
  86. package/build/ticket-delivery.js +65 -0
  87. package/build/v2-readiness-requirements.js +39 -5
  88. package/build/version.generated.js +3 -3
  89. package/build/worktree-core.js +51 -7
  90. package/docs/EPIC-IMPLEMENTER.md +150 -2
  91. package/docs/epic-implementer/getting-started.md +5 -1
  92. package/package.json +3 -3
  93. package/pipelines/implement-ticket.json +2 -2
  94. package/pipelines/learn-repository.json +19 -1
@@ -59,6 +59,9 @@ export const EPIC_SERVER_REASONS = [
59
59
  "ready_timeout",
60
60
  "ready_redirect_refused",
61
61
  "credential_unavailable",
62
+ // BAPI-1733: the app exited before it became ready (a serving failure). Distinct
63
+ // from the post-ready "app_failed" reason, which the "app_exited" EVENT carries.
64
+ "app_exited",
62
65
  "expired",
63
66
  "fenced",
64
67
  "app_failed",
@@ -74,6 +77,7 @@ export const EPIC_SERVER_JOURNAL_MAX_EVENTS = 500;
74
77
  export const EPIC_SERVER_JOURNAL_MAX_READ = 100;
75
78
  const TICKET_RE = /^[A-Z][A-Z0-9_]{0,19}-\d{1,9}$/;
76
79
  const SHA_RE = /^[0-9a-f]{40}$/;
80
+ const EXIT_SIGNAL_RE = /^SIG[A-Z0-9]{1,10}$/;
77
81
  const RUN_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{7,63}$/;
78
82
  /** Build one sanitized entry. Fields outside the closed shapes are dropped. */
79
83
  export function buildJournalEntry(runId, seq, at, event, fields = {}) {
@@ -98,6 +102,13 @@ export function buildJournalEntry(runId, seq, at, event, fields = {}) {
98
102
  entry.reason = fields.reason;
99
103
  if (typeof fields.count === "number" && Number.isSafeInteger(fields.count) && fields.count >= 0)
100
104
  entry.count = fields.count;
105
+ // Exit facts are kept only in their closed shapes; anything else is dropped,
106
+ // never coerced, and a raw process error is never accepted here at all.
107
+ if (typeof fields.exit_code === "number" && Number.isSafeInteger(fields.exit_code) && fields.exit_code >= 0 && fields.exit_code <= 255) {
108
+ entry.exit_code = fields.exit_code;
109
+ }
110
+ if (typeof fields.exit_signal === "string" && EXIT_SIGNAL_RE.test(fields.exit_signal))
111
+ entry.exit_signal = fields.exit_signal;
101
112
  return entry;
102
113
  }
103
114
  /** Validate one parsed entry; anything outside the closed shape is null. */
@@ -123,6 +134,8 @@ export function validateJournalEntry(raw) {
123
134
  outcome: doc.outcome,
124
135
  reason: doc.reason,
125
136
  count: doc.count,
137
+ exit_code: doc.exit_code,
138
+ exit_signal: doc.exit_signal,
126
139
  });
127
140
  if (typeof doc.sha12 === "string" && /^[0-9a-f]{12}$/.test(doc.sha12))
128
141
  rebuilt.sha12 = doc.sha12;
@@ -158,6 +171,13 @@ export class EpicServerJournal {
158
171
  now;
159
172
  maxEvents;
160
173
  doc = null;
174
+ /**
175
+ * Writes run one at a time. Each write replaces the whole document, so two
176
+ * overlapping writes could finish out of order and the older document would
177
+ * erase the newer event (seen as a lost `app_exited` when the app died while
178
+ * `bootstrap_served` was still being written).
179
+ */
180
+ writes = Promise.resolve();
161
181
  constructor(filePath, runId, fs, now = () => new Date(), maxEvents = EPIC_SERVER_JOURNAL_MAX_EVENTS) {
162
182
  this.filePath = filePath;
163
183
  this.runId = runId;
@@ -175,32 +195,42 @@ export class EpicServerJournal {
175
195
  this.doc = parseDocument(raw) ?? emptyDocument();
176
196
  return this.doc;
177
197
  }
178
- /** Append one background event. Never throws, never blocks serving for long. */
179
- async append(event, fields = {}) {
180
- try {
181
- const doc = await this.load();
182
- doc.events.push(buildJournalEntry(this.runId, doc.next_seq, this.now(), event, fields));
183
- doc.next_seq += 1;
184
- this.compact(doc);
185
- await writePrivateFileAtomic(this.fs, this.filePath, `${JSON.stringify(doc)}\n`);
186
- }
187
- catch {
188
- /* journaling is best-effort; serving continues */
189
- }
198
+ /** Run `write` after every earlier write has settled. */
199
+ serialized(write) {
200
+ const next = this.writes.then(write, write);
201
+ this.writes = next.catch(() => undefined);
202
+ return next;
190
203
  }
191
- /** Record the driver's acknowledgement (a status cursor). */
192
- async acknowledge(cursor) {
193
- try {
194
- const doc = await this.load();
195
- if (Number.isSafeInteger(cursor) && cursor > doc.acked_seq && cursor < doc.next_seq) {
196
- doc.acked_seq = cursor;
204
+ /** Append one background event. Never throws, never blocks serving for long. */
205
+ append(event, fields = {}) {
206
+ return this.serialized(async () => {
207
+ try {
208
+ const doc = await this.load();
209
+ doc.events.push(buildJournalEntry(this.runId, doc.next_seq, this.now(), event, fields));
210
+ doc.next_seq += 1;
197
211
  this.compact(doc);
198
212
  await writePrivateFileAtomic(this.fs, this.filePath, `${JSON.stringify(doc)}\n`);
199
213
  }
200
- }
201
- catch {
202
- /* best-effort */
203
- }
214
+ catch {
215
+ /* journaling is best-effort; serving continues */
216
+ }
217
+ });
218
+ }
219
+ /** Record the driver's acknowledgement (a status cursor). */
220
+ acknowledge(cursor) {
221
+ return this.serialized(async () => {
222
+ try {
223
+ const doc = await this.load();
224
+ if (Number.isSafeInteger(cursor) && cursor > doc.acked_seq && cursor < doc.next_seq) {
225
+ doc.acked_seq = cursor;
226
+ this.compact(doc);
227
+ await writePrivateFileAtomic(this.fs, this.filePath, `${JSON.stringify(doc)}\n`);
228
+ }
229
+ }
230
+ catch {
231
+ /* best-effort */
232
+ }
233
+ });
204
234
  }
205
235
  compact(doc) {
206
236
  if (doc.events.length <= this.maxEvents)
@@ -88,6 +88,16 @@ function hasControlChars(value) {
88
88
  }
89
89
  return false;
90
90
  }
91
+ const SAFE_ENTRY_LABEL_RE = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
92
+ /**
93
+ * BAPI-1733 — a diagnostic label for one `inputs` / `credential_refs` entry. The
94
+ * entry name appears only when it is a plain identifier; anything else (punctuation,
95
+ * newlines, over-long text) is replaced so a name can never carry a value or
96
+ * injected text into an error.
97
+ */
98
+ function entryLabel(section, name) {
99
+ return `${section}.${SAFE_ENTRY_LABEL_RE.test(name) ? name : "an entry"}`;
100
+ }
91
101
  /** True for a name a recipe may set in a command environment. */
92
102
  export function isRecipeEnvName(name) {
93
103
  if (!ENV_NAME_RE.test(name) || RESERVED_ENV_NAMES.has(name))
@@ -292,9 +302,9 @@ export function validateEpicServerRecipe(raw) {
292
302
  }
293
303
  for (const [name, value] of Object.entries(raw.inputs)) {
294
304
  if (!isRecipeEnvName(name))
295
- return { ok: false, error: "inputs: a name is reserved or unusable" };
305
+ return { ok: false, error: `${entryLabel("inputs", name)}: the name is reserved or unusable` };
296
306
  if (typeof value !== "string" || value.length > MAX_ENV_VALUE_CHARS || value.includes("\0") || hasControlChars(value)) {
297
- return { ok: false, error: "inputs: a value is unusable" };
307
+ return { ok: false, error: `${entryLabel("inputs", name)}: the value is unusable` };
298
308
  }
299
309
  inputs[name] = value;
300
310
  }
@@ -306,13 +316,13 @@ export function validateEpicServerRecipe(raw) {
306
316
  }
307
317
  for (const [name, value] of Object.entries(raw.credential_refs)) {
308
318
  if (!isRecipeEnvName(name) || name in inputs)
309
- return { ok: false, error: "credential_refs: a name is reserved or unusable" };
319
+ return { ok: false, error: `${entryLabel("credential_refs", name)}: the name is reserved or unusable` };
310
320
  if (!isPlainObject(value) || !isValidCredentialReference(value.ref) || typeof value.key !== "string" || !/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(value.key)) {
311
- return { ok: false, error: "credential_refs: each entry needs a ref and a key name" };
321
+ return { ok: false, error: `${entryLabel("credential_refs", name)}: each entry needs a ref and a key name` };
312
322
  }
313
323
  if (Object.keys(value).some((k) => k !== "ref" && k !== "key")) {
314
324
  // A raw secret value never belongs here.
315
- return { ok: false, error: "credential_refs: an entry holds more than a reference" };
325
+ return { ok: false, error: `${entryLabel("credential_refs", name)}: an entry holds more than a reference` };
316
326
  }
317
327
  credentialRefs[name] = { ref: value.ref, key: value.key };
318
328
  }
@@ -36,6 +36,56 @@ import { boundedResult, ensurePrivateDirectory, epicServerLoginFilePath, epicSer
36
36
  import { buildEpicServerCommandEnv, formatLoginFile, isOwnershipInspectionSupported, parseSeedOutput, readProcessStartTime, stopOwnedProcessGroup, verifyOwnedProcess, } from "./epic-server-processes.js";
37
37
  import { dropTurnDatabase, isCurrentTurnDatabase, provisionTurnDatabase, sweepOwnLeftoverDatabases, } from "./epic-server-database.js";
38
38
  import { epicServerRecipeDigest, proofCoversStart, substituteRecipeArgv, validateEpicServerProof, validateEpicServerRecipe, EPIC_SERVER_PROOF_VERSION, } from "./epic-server-recipe.js";
39
+ function watchStartupExit(child) {
40
+ let latched = null;
41
+ let resolveExit = () => undefined;
42
+ const exited = new Promise((resolve) => {
43
+ resolveExit = resolve;
44
+ });
45
+ const latch = (exit) => {
46
+ if (latched !== null)
47
+ return;
48
+ latched = exit;
49
+ resolveExit(exit);
50
+ };
51
+ const onExit = (code, signal) => {
52
+ child.off("error", onError);
53
+ latch({ code: typeof code === "number" ? code : null, signal: typeof signal === "string" ? signal : null });
54
+ };
55
+ // A spawn error carries raw text that may hold secrets: it is never retained.
56
+ const onError = () => {
57
+ child.off("exit", onExit);
58
+ latch({ code: null, signal: null });
59
+ };
60
+ child.once("exit", onExit);
61
+ child.once("error", onError);
62
+ // An exit that completed before the listeners attached is seeded from the child.
63
+ if (typeof child.exitCode === "number" || typeof child.signalCode === "string") {
64
+ child.off("exit", onExit);
65
+ child.off("error", onError);
66
+ latch({
67
+ code: typeof child.exitCode === "number" ? child.exitCode : null,
68
+ signal: typeof child.signalCode === "string" ? child.signalCode : null,
69
+ });
70
+ }
71
+ return {
72
+ latched: () => latched,
73
+ exited,
74
+ dispose: () => {
75
+ child.off("exit", onExit);
76
+ child.off("error", onError);
77
+ },
78
+ };
79
+ }
80
+ /** Race a promise against app exit; the loser's eventual rejection is always handled. */
81
+ async function raceStartupExit(work, watcher) {
82
+ work.catch(() => undefined);
83
+ const winner = await Promise.race([
84
+ work.then((value) => ({ exited: false, value })),
85
+ watcher.exited.then(() => ({ exited: true })),
86
+ ]);
87
+ return winner;
88
+ }
39
89
  async function resolveCredentials(recipe, deps) {
40
90
  const out = {};
41
91
  for (const [name, { ref, key }] of Object.entries(recipe.credential_refs)) {
@@ -66,49 +116,80 @@ async function runSteps(steps, cwd, env, port, ctx) {
66
116
  }
67
117
  return "ok";
68
118
  }
69
- async function awaitReady(ctx, env, cwd) {
119
+ async function awaitReady(ctx, env, cwd, watcher) {
70
120
  const ready = ctx.recipe.ready;
71
121
  const deadline = Date.now() + ready.timeout_seconds * 1000;
72
122
  const base = epicServerLoopbackUrl(ctx.port);
123
+ const exitedResult = () => {
124
+ const exit = watcher.latched();
125
+ return exit === null ? null : { outcome: "app_exited", exit };
126
+ };
73
127
  while (Date.now() < deadline) {
74
128
  if (ctx.signal?.aborted)
75
- return "cancelled";
129
+ return { outcome: "cancelled" };
130
+ const early = exitedResult();
131
+ if (early !== null)
132
+ return early;
76
133
  if (ready.kind === "url") {
77
- const res = await ctx.deps.http.get(`${base}${ready.path}`, Math.min(5_000, Math.max(1, deadline - Date.now())));
134
+ const probe = await raceStartupExit(ctx.deps.http.get(`${base}${ready.path}`, Math.min(5_000, Math.max(1, deadline - Date.now()))), watcher);
135
+ if (probe.exited)
136
+ return exitedResult() ?? { outcome: "app_exited" };
137
+ const res = probe.value;
78
138
  if (res !== null) {
79
139
  if (res.status >= 200 && res.status < 300)
80
- return "ok";
140
+ return exitedResult() ?? { outcome: "ok" };
81
141
  if (res.status >= 300 && res.status < 400) {
82
142
  // A redirect is ready only when it stays on the run's own address.
83
143
  if (res.location === null)
84
- return "ready_redirect_refused";
144
+ return { outcome: "ready_redirect_refused" };
85
145
  let target;
86
146
  try {
87
147
  target = new URL(res.location, base);
88
148
  }
89
149
  catch {
90
- return "ready_redirect_refused";
150
+ return { outcome: "ready_redirect_refused" };
91
151
  }
92
- return target.origin === base ? "ok" : "ready_redirect_refused";
152
+ return target.origin === base ? (exitedResult() ?? { outcome: "ok" }) : { outcome: "ready_redirect_refused" };
93
153
  }
94
154
  }
95
155
  }
96
156
  else {
97
- const outcome = await ctx.deps.runCommand(substituteRecipeArgv(ready.argv, ctx.port), {
98
- cwd,
99
- env,
100
- timeoutMs: Math.max(1, Math.min(10_000, deadline - Date.now())),
101
- captureStdout: false,
102
- ...(ctx.signal ? { signal: ctx.signal } : {}),
103
- });
104
- if (outcome.kind === "ok")
105
- return "ok";
106
- if (outcome.kind === "cancelled")
107
- return "cancelled";
157
+ // Each probe gets its own signal, chained to the run's, so app exit can stop
158
+ // a pending command without being mistaken for a cancellation.
159
+ const probeController = new AbortController();
160
+ const onParentAbort = () => probeController.abort();
161
+ if (ctx.signal?.aborted)
162
+ probeController.abort();
163
+ else
164
+ ctx.signal?.addEventListener("abort", onParentAbort, { once: true });
165
+ try {
166
+ const probe = await raceStartupExit(ctx.deps.runCommand(substituteRecipeArgv(ready.argv, ctx.port), {
167
+ cwd,
168
+ env,
169
+ timeoutMs: Math.max(1, Math.min(10_000, deadline - Date.now())),
170
+ captureStdout: false,
171
+ signal: probeController.signal,
172
+ }), watcher);
173
+ if (probe.exited) {
174
+ probeController.abort();
175
+ return exitedResult() ?? { outcome: "app_exited" };
176
+ }
177
+ const outcome = probe.value;
178
+ if (outcome.kind === "ok")
179
+ return exitedResult() ?? { outcome: "ok" };
180
+ if (outcome.kind === "cancelled") {
181
+ return exitedResult() ?? { outcome: "cancelled" };
182
+ }
183
+ }
184
+ finally {
185
+ ctx.signal?.removeEventListener("abort", onParentAbort);
186
+ }
108
187
  }
109
- await ctx.deps.sleep(Math.min(500, Math.max(1, deadline - Date.now())));
188
+ const slept = await raceStartupExit(ctx.deps.sleep(Math.min(500, Math.max(1, deadline - Date.now()))), watcher);
189
+ if (slept.exited)
190
+ return exitedResult() ?? { outcome: "app_exited" };
110
191
  }
111
- return "ready_timeout";
192
+ return exitedResult() ?? { outcome: "ready_timeout" };
112
193
  }
113
194
  /**
114
195
  * Replay the recipe against one exact head: a fresh detached serving checkout,
@@ -119,7 +200,12 @@ async function awaitReady(ctx, env, cwd) {
119
200
  export async function runServingPipeline(ctx, sha, generation) {
120
201
  const { deps, paths, recipe } = ctx;
121
202
  const turn = { generation, sha, app: null, database: null, loginFile: null };
122
- const fail = (reason) => ({ ok: false, reason, partial: turn });
203
+ const fail = (reason, exit) => ({
204
+ ok: false,
205
+ reason,
206
+ partial: turn,
207
+ ...(exit !== undefined ? { exit } : {}),
208
+ });
123
209
  // A fresh checkout for every head: ignored artifacts and generated files from
124
210
  // an earlier turn can never reach another worker's verification.
125
211
  const worktree = paths.servingWorktree;
@@ -190,17 +276,27 @@ export async function runServingPipeline(ctx, sha, generation) {
190
276
  const started = deps.startApp(substituteRecipeArgv(recipe.start.argv, ctx.port), { cwd: worktree, env });
191
277
  if (started === null)
192
278
  return fail("start_failed");
193
- const startedAt = await readProcessStartTime(started.pid, deps.proc);
194
- if (startedAt === null) {
195
- // The app died at once, or its identity cannot be read: never signalled blind.
196
- return fail("start_failed");
279
+ // Latch termination from the moment the child exists, before any await, so no
280
+ // exit shape between here and readiness can be missed.
281
+ const watcher = watchStartupExit(started.child);
282
+ try {
283
+ const startedAt = await readProcessStartTime(started.pid, deps.proc);
284
+ if (startedAt === null) {
285
+ // The app died at once, or its identity cannot be read: never signalled blind.
286
+ return fail("start_failed");
287
+ }
288
+ turn.app = { pid: started.pid, started_at: startedAt, child: started.child };
289
+ await ctx.recordOwnership({ app: { pid: started.pid, started_at: startedAt } });
290
+ const ready = await awaitReady(ctx, env, worktree, watcher);
291
+ if (ready.outcome !== "ok")
292
+ return fail(ready.outcome, ready.exit);
293
+ return { ok: true, turn };
294
+ }
295
+ finally {
296
+ // Success, failure, and cancellation all hand over cleanly: the post-ready
297
+ // `watchApp` listener (or `teardownTurn`) takes it from here.
298
+ watcher.dispose();
197
299
  }
198
- turn.app = { pid: started.pid, started_at: startedAt, child: started.child };
199
- await ctx.recordOwnership({ app: { pid: started.pid, started_at: startedAt } });
200
- const ready = await awaitReady(ctx, env, worktree);
201
- if (ready !== "ok")
202
- return fail(ready);
203
- return { ok: true, turn };
204
300
  }
205
301
  /**
206
302
  * Tear one turn down: stop the app (guarded), drop its database, remove its
@@ -238,15 +334,12 @@ export async function teardownTurn(ctx, turn) {
238
334
  });
239
335
  return clean;
240
336
  }
241
- // ---------------------------------------------------------------------------
242
- // Recipe, proof, and ownership files
243
- // ---------------------------------------------------------------------------
244
337
  export async function readRecipe(paths, fs) {
245
338
  const raw = await readPrivateJson(fs, paths.recipe);
246
339
  if (raw === null)
247
- return null;
340
+ return { ok: false, detail: "recipe file is missing or unreadable" };
248
341
  const validated = validateEpicServerRecipe(raw);
249
- return validated.ok ? validated.recipe : null;
342
+ return validated.ok ? { ok: true, recipe: validated.recipe } : { ok: false, detail: validated.error };
250
343
  }
251
344
  export async function readProof(paths, fs) {
252
345
  return validateEpicServerProof(await readPrivateJson(fs, paths.proof));
@@ -314,6 +407,14 @@ export async function recoverAbandonedResources(paths, deps) {
314
407
  }
315
408
  return "retained";
316
409
  }
410
+ /** Format startup-exit evidence. Explicit null checks keep exit code 0 from being lost. */
411
+ function formatStartupExit(exit) {
412
+ if (exit !== undefined && exit.code !== null)
413
+ return `app exited with code ${exit.code}`;
414
+ if (exit !== undefined && exit.signal !== null)
415
+ return `app exited on signal ${exit.signal}`;
416
+ return "app exited without an exit code or signal";
417
+ }
317
418
  /**
318
419
  * Prove one recipe revision against the exact epic head: an exclusively owned
319
420
  * run of the serving pipeline, fully cleaned up before returning. A matching
@@ -323,9 +424,10 @@ export async function proveRecipe(input, deps) {
323
424
  const { paths } = input;
324
425
  if (!isOwnershipInspectionSupported(deps.proc.platform))
325
426
  return { ok: false, reason: "inspection_unsupported" };
326
- const recipe = await readRecipe(paths, deps.fs);
327
- if (recipe === null)
328
- return { ok: false, reason: "recipe_invalid" };
427
+ const recipeRead = await readRecipe(paths, deps.fs);
428
+ if (!recipeRead.ok)
429
+ return { ok: false, reason: "recipe_invalid", detail: recipeRead.detail };
430
+ const recipe = recipeRead.recipe;
329
431
  const live = await readEpicServerLiveState(paths.state, input.runId, { fs: deps.fs, probe: { identity: async (pid) => {
330
432
  const s = await readProcessStartTime(pid, deps.proc);
331
433
  return s === null ? null : { startedAt: s };
@@ -392,8 +494,11 @@ export async function proveRecipe(input, deps) {
392
494
  if (clean)
393
495
  await removeFileQuietly(deps.fs, paths.ownership);
394
496
  await removeFileQuietly(deps.fs, paths.claim);
395
- if (!served.ok)
396
- return { ok: false, reason: served.reason };
497
+ if (!served.ok) {
498
+ return served.reason === "app_exited"
499
+ ? { ok: false, reason: served.reason, detail: formatStartupExit(served.exit) }
500
+ : { ok: false, reason: served.reason };
501
+ }
397
502
  if (!clean)
398
503
  return { ok: false, reason: "cleanup_incomplete" };
399
504
  const proof = {
@@ -870,7 +975,19 @@ export class EpicServerHelper {
870
975
  this.turn = served.partial;
871
976
  await this.endTurn();
872
977
  await this.writeState();
873
- await this.options.journal.append("serving_failed", { generation, ticket: next.ticket, sha: next.head, reason: served.reason, outcome: "failed" });
978
+ await this.options.journal.append("serving_failed", {
979
+ generation,
980
+ ticket: next.ticket,
981
+ sha: next.head,
982
+ reason: served.reason,
983
+ outcome: "failed",
984
+ ...(served.reason === "app_exited" && served.exit !== undefined
985
+ ? {
986
+ ...(served.exit.code !== null ? { exit_code: served.exit.code } : {}),
987
+ ...(served.exit.signal !== null ? { exit_signal: served.exit.signal } : {}),
988
+ }
989
+ : {}),
990
+ });
874
991
  if (!next.cancelled) {
875
992
  next.cancelled = true;
876
993
  next.respond({ ok: false, outcome: "unavailable", reason: served.reason === "cancelled" ? "build_timeout" : served.reason });
@@ -996,9 +1113,10 @@ export async function startEpicServerHelper(input, deps) {
996
1113
  const { paths } = input;
997
1114
  if (!isOwnershipInspectionSupported(rt.proc.platform))
998
1115
  return { ok: false, reason: "inspection_unsupported" };
999
- const recipe = await readRecipe(paths, rt.fs);
1000
- if (recipe === null)
1001
- return { ok: false, reason: "recipe_invalid" };
1116
+ const recipeRead = await readRecipe(paths, rt.fs);
1117
+ if (!recipeRead.ok)
1118
+ return { ok: false, reason: "recipe_invalid", detail: recipeRead.detail };
1119
+ const recipe = recipeRead.recipe;
1002
1120
  if (!proofCoversStart(await readProof(paths, rt.fs), recipe, input.epicHead))
1003
1121
  return { ok: false, reason: "not_proven" };
1004
1122
  const deadline = Date.now() + recipe.timing.start_seconds * 1000;
@@ -409,8 +409,11 @@ async function runProve(deps, cmd) {
409
409
  }
410
410
  const outcome = await proveRecipe({ paths, repoRoot, epicHead: cmd.head, runId: cmd.epicRunId }, deps.runtime());
411
411
  if (!outcome.ok) {
412
- emit(deps, { outcome: "failed", verb: "prove", reason: outcome.reason });
413
- deps.stderr(`epic-server prove: failed (${outcome.reason}); the run continues with the epic server unavailable`);
412
+ // BAPI-1733: detail is closed-form evidence (a safe recipe field label or a
413
+ // formatted exit), only for these two reasons, and never a raw error or value.
414
+ const detail = (outcome.reason === "recipe_invalid" || outcome.reason === "app_exited") && outcome.detail !== undefined ? outcome.detail : undefined;
415
+ emit(deps, { outcome: "failed", verb: "prove", reason: outcome.reason, ...(detail !== undefined ? { detail } : {}) });
416
+ deps.stderr(`epic-server prove: failed (${outcome.reason}${detail !== undefined ? `: ${detail}` : ""}); the run continues with the epic server unavailable`);
414
417
  return 1;
415
418
  }
416
419
  emit(deps, { outcome: "proven", recipe_revision: outcome.proof.recipe_revision, epic_head: outcome.proof.epic_head });
@@ -428,8 +431,9 @@ async function runStart(deps, cmd) {
428
431
  }
429
432
  const outcome = await startEpicServerHelper({ paths, epicKey: cmd.epicKey, runId: cmd.epicRunId, repoName: mode.repoName, repoRoot, epicHead: cmd.head }, { runtime: deps.runtime(), launchHelper: deps.launchHelper });
430
433
  if (!outcome.ok) {
431
- emit(deps, { outcome: "failed", verb: "start", reason: outcome.reason });
432
- deps.stderr(`epic-server start: failed (${outcome.reason}); the run continues with the epic server unavailable`);
434
+ const detail = outcome.reason === "recipe_invalid" && outcome.detail !== undefined ? outcome.detail : undefined;
435
+ emit(deps, { outcome: "failed", verb: "start", reason: outcome.reason, ...(detail !== undefined ? { detail } : {}) });
436
+ deps.stderr(`epic-server start: failed (${outcome.reason}${detail !== undefined ? `: ${detail}` : ""}); the run continues with the epic server unavailable`);
433
437
  return 1;
434
438
  }
435
439
  emit(deps, {
@@ -584,9 +588,12 @@ async function runHelper(deps, cmd) {
584
588
  const nonce = deps.env.BRIDGE_EPIC_SERVER_INSTANCE_TAG;
585
589
  if (paths === null || typeof nonce !== "string" || !/^[0-9a-f]{64}$/.test(nonce))
586
590
  return 1;
587
- const recipe = await readRecipe(paths, rt.fs);
591
+ const recipeRead = await readRecipe(paths, rt.fs);
592
+ if (!recipeRead.ok)
593
+ return 1;
594
+ const recipe = recipeRead.recipe;
588
595
  const proof = validateEpicServerProof(await import("./epic-server-state.js").then((m) => m.readPrivateJson(rt.fs, paths.proof)));
589
- if (recipe === null || !proofCoversStart(proof, recipe, cmd.head))
596
+ if (!proofCoversStart(proof, recipe, cmd.head))
590
597
  return 1;
591
598
  const journal = new EpicServerJournal(paths.journal, cmd.epicRunId, rt.fs, rt.now);
592
599
  const helper = new EpicServerHelper({
@@ -30,7 +30,8 @@
30
30
  * workflow scaffold, no schema migration, no hook installation. It is invoked
31
31
  * from a write-capable installer, so that boundary is pinned by tests.
32
32
  */
33
- import { readdir as fsReaddir, readFile as fsReadFile, stat as fsStat } from "node:fs/promises";
33
+ import { readdir as fsReaddir, readFile as fsReadFile, stat as fsStat, lstat as fsLstat } from "node:fs/promises";
34
+ import { readEpicServerRecord } from "../epic-server-record.js";
34
35
  import os from "node:os";
35
36
  import { buildConductorDoctorReport, formatConductorDoctorReport, } from "./doctor.js";
36
37
  import { inspectBridgeApiProfileToken, } from "../mcp-host-config.js";
@@ -56,6 +57,25 @@ async function settle(collect) {
56
57
  return { value: null, failed: true };
57
58
  }
58
59
  }
60
+ /** A usable repository-scoped epic-server record, read through the shared validator. Never throws. */
61
+ async function epicServerRecordUsable(deps) {
62
+ const repoName = deps.access?.repoName;
63
+ if (repoName === undefined || repoName === "")
64
+ return false;
65
+ try {
66
+ const read = deps.readEpicServerRecord ??
67
+ ((name) => readEpicServerRecord(name, {
68
+ env: process.env,
69
+ homedir: os.homedir,
70
+ readFile: (filePath) => fsReadFile(filePath, "utf-8"),
71
+ lstat: (filePath) => fsLstat(filePath),
72
+ }));
73
+ return (await read(repoName)).state === "ok";
74
+ }
75
+ catch {
76
+ return false;
77
+ }
78
+ }
59
79
  /**
60
80
  * Build the unified report. Never throws: every probe failure becomes a section.
61
81
  */
@@ -244,7 +264,15 @@ export async function runConductorInstallDoctor(deps) {
244
264
  // collection gap rather than losing the section.
245
265
  }
246
266
  const conductorContext = detectConductorContext(legacyConductor, profileToken);
247
- sections.push(conductorProfileTokenSection(profileToken, conductorContext));
267
+ // BAPI-1719: the profile section also reads RECORDED setup, because a missing group is exactly
268
+ // what keeps the conductor-context detection above from firing. The hook-target section keeps
269
+ // `conductorContext` unchanged. A usable repository-scoped epic-server record is read only when
270
+ // readiness itself is unavailable; any missing, unusable, or throwing read is "not recorded".
271
+ let setupRecorded = readiness?.supervisor?.setup_present === true;
272
+ if (!setupRecorded && readiness === null)
273
+ setupRecorded = await epicServerRecordUsable(deps);
274
+ const profileContext = conductorContext || setupRecorded;
275
+ sections.push(conductorProfileTokenSection(profileToken, profileContext));
248
276
  sections.push(conductorHookTargetsSection(legacyConductor, conductorContext));
249
277
  sections.push(conductorLedgerLoadabilitySection(legacyConductor));
250
278
  // BAPI-1135 — this HOST's ability to observe the merge capability, beside the
@@ -1,4 +1,5 @@
1
1
  import { EPIC_KEY_PATTERN } from "../drive-epic-key.js";
2
+ import { PLAN_ORDER_NEEDED_REASON_ID } from "../plan-generation.js";
2
3
  import { WORKER_DATABASE_DOCTOR_OWNER, WORKER_DATABASE_DOCTOR_RUNBOOK_SECTION } from "./doctor.js";
3
4
  import { redactSecrets } from "../secret-redaction.js";
4
5
  import { LAUNCH_NEED_REMEDIES, LAUNCH_NEED_ROW_IDS, LAUNCH_NEEDS } from "./readiness-sections.js";
@@ -61,6 +62,17 @@ export const LAUNCH_PLAN_COPY = {
61
62
  reason: "The run needs the machine awake to keep working.",
62
63
  },
63
64
  };
65
+ /**
66
+ * BAPI-1782 — the copy for the preview's authoritative `plan_order_needed`
67
+ * refusal. It is a planning block, not proven harm, so it never uses
68
+ * `blockedSummary`.
69
+ */
70
+ export const LAUNCH_PLAN_ORDER_NEEDED_COPY = {
71
+ summary: "This epic has more than one child to run and no ordered child manifest.",
72
+ reason: "Ticket-key order can start a child before the work it needs, and a live run's plan cannot be changed.",
73
+ recommendation: "don't launch yet, and give the epic a dependency order.",
74
+ verdictReason: "The epic needs a dependency order before it can run. Nothing has been created.",
75
+ };
64
76
  function isObject(value) {
65
77
  return value !== null && typeof value === "object" && !Array.isArray(value);
66
78
  }
@@ -219,11 +231,13 @@ export function buildLaunchPlan(preview, facts = NO_LAUNCH_PLAN_FACTS) {
219
231
  if (refusal !== null) {
220
232
  const webhook = prerequisiteRow(SERVER_WEBHOOK_ROW_ID);
221
233
  const branch = prerequisiteRow(SERVER_PROVIDER_BRANCH_ROW_ID);
222
- const copy = webhook?.check_status === "not_met" && webhook.impact === "blocking" && refusal.reason_id === LAUNCH_PRE_CREATE_CODES.ESCALATION_WEBHOOK_UNREACHABLE
223
- ? LAUNCH_PLAN_COPY.blockedWebhook
224
- : branch?.check_status === "not_met" && branch.impact === "blocking" && refusal.reason_id === LAUNCH_PRE_CREATE_CODES.PROVIDER_DEFAULT_BRANCH_UNREADABLE
225
- ? LAUNCH_PLAN_COPY.blockedProviderBranch
226
- : { summary: LAUNCH_PLAN_COPY.blockedSummary, reason: "Bridge stops here so nothing is started that could cause harm." };
234
+ const copy = refusal.reason_id === PLAN_ORDER_NEEDED_REASON_ID
235
+ ? { summary: LAUNCH_PLAN_ORDER_NEEDED_COPY.summary, reason: LAUNCH_PLAN_ORDER_NEEDED_COPY.reason }
236
+ : webhook?.check_status === "not_met" && webhook.impact === "blocking" && refusal.reason_id === LAUNCH_PRE_CREATE_CODES.ESCALATION_WEBHOOK_UNREACHABLE
237
+ ? LAUNCH_PLAN_COPY.blockedWebhook
238
+ : branch?.check_status === "not_met" && branch.impact === "blocking" && refusal.reason_id === LAUNCH_PRE_CREATE_CODES.PROVIDER_DEFAULT_BRANCH_UNREADABLE
239
+ ? LAUNCH_PLAN_COPY.blockedProviderBranch
240
+ : { summary: LAUNCH_PLAN_COPY.blockedSummary, reason: "Bridge stops here so nothing is started that could cause harm." };
227
241
  add("blocks_launch", { summary: copy.summary, reason: copy.reason, remedy: refusal.remedy }, refusal.reason_id);
228
242
  }
229
243
  // --- worth knowing: webhook fell back to email (never a refusal) ------------------
@@ -313,8 +327,15 @@ export function buildLaunchPlan(preview, facts = NO_LAUNCH_PLAN_FACTS) {
313
327
  };
314
328
  if (blocked) {
315
329
  push(nothingOption(1, "Don't launch yet", true), "create_nothing");
316
- recommendation = "don't launch yet, and fix the problem below.";
317
- reason = "Bridge found a proven problem. Nothing has been created.";
330
+ if (refusal.reason_id === PLAN_ORDER_NEEDED_REASON_ID) {
331
+ // BAPI-1782 — a planning block, not a proven problem.
332
+ recommendation = LAUNCH_PLAN_ORDER_NEEDED_COPY.recommendation;
333
+ reason = LAUNCH_PLAN_ORDER_NEEDED_COPY.verdictReason;
334
+ }
335
+ else {
336
+ recommendation = "don't launch yet, and fix the problem below.";
337
+ reason = "Bridge found a proven problem. Nothing has been created.";
338
+ }
318
339
  }
319
340
  else if (boundaryProven) {
320
341
  push(launchOption(1, "Launch anyway", local, false), "launch");