@bridge_gpt/mcp-server 0.2.76 → 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 (58) hide show
  1. package/README.md +8 -6
  2. package/build/agents.generated.js +3 -3
  3. package/build/cli-dispatch.js +333 -0
  4. package/build/commands.generated.js +5 -5
  5. package/build/conductor/bridge-api-client.js +52 -7
  6. package/build/conductor/declare-blocked.js +142 -7
  7. package/build/conductor/driver-register.js +8 -2
  8. package/build/conductor/epic-implementer-cli.js +11 -7
  9. package/build/conductor/epic-server-journal.js +39 -22
  10. package/build/conductor/launch-plan.js +28 -7
  11. package/build/conductor/local-merge.js +1 -1
  12. package/build/conductor/readiness-prerequisites.js +89 -2
  13. package/build/conductor/recovery-cli.js +2 -0
  14. package/build/docs.generated.js +67 -4
  15. package/build/doctor.js +97 -1
  16. package/build/drive-epic.js +223 -6
  17. package/build/engine-paths.js +10 -0
  18. package/build/epic-coherence-input-cli.js +105 -10
  19. package/build/epic-coherence-input.js +877 -4
  20. package/build/epic-coherence-input.test-fixtures.js +117 -0
  21. package/build/epic-implementer-bin.js +901 -94
  22. package/build/epic-implementer-env.js +2 -2
  23. package/build/executor/completion-contract.js +14 -1
  24. package/build/executor/guarded-fast-forward-push.js +25 -2
  25. package/build/executor/job-runner.js +83 -27
  26. package/build/executor/likely-tests.js +78 -6
  27. package/build/executor/provider-checks.js +73 -0
  28. package/build/executor/rebase-finalization.js +29 -27
  29. package/build/executor/rename-aside.js +265 -0
  30. package/build/executor/required-work-ledger.js +82 -4
  31. package/build/executor/types.js +121 -0
  32. package/build/executor/worktree.js +27 -1
  33. package/build/index.js +2449 -386
  34. package/build/install-bridge-conductor-assessment.js +13 -0
  35. package/build/install-bridge-conductor.js +60 -776
  36. package/build/install-bridge.js +4 -11
  37. package/build/language-catalog.generated.js +2649 -0
  38. package/build/pipelines.generated.js +45 -17
  39. package/build/plan-execution-ledger.js +8 -0
  40. package/build/plan-generation.js +34 -0
  41. package/build/plane/build-freshness.js +6 -0
  42. package/build/plane/cli.js +12 -5
  43. package/build/printed-remedy-commands.js +9 -0
  44. package/build/readiness-prerequisites.generated.js +28 -0
  45. package/build/readme.generated.js +1 -1
  46. package/build/run-unit-tests-launcher.js +3 -1
  47. package/build/server.js +7946 -0
  48. package/build/start-tickets-prereqs.js +3 -6
  49. package/build/test-support/console-guard.js +30 -0
  50. package/build/test-support/module-imports.js +155 -0
  51. package/build/test-support/server-client.js +96 -0
  52. package/build/test-support/stdio-server.js +146 -0
  53. package/build/v2-readiness-requirements.js +31 -2
  54. package/build/version.generated.js +3 -3
  55. package/docs/EPIC-IMPLEMENTER.md +71 -2
  56. package/docs/epic-implementer/getting-started.md +4 -0
  57. package/package.json +3 -3
  58. package/pipelines/learn-repository.json +19 -1
@@ -3984,6 +3984,45 @@ const RETIRED_ROW_TEXT_MAX = 400;
3984
3984
  function isBoundedServerText(value) {
3985
3985
  return typeof value === 'string' && value.length <= RETIRED_ROW_TEXT_MAX && !/[\u0000-\u001f\u007f]/.test(value);
3986
3986
  }
3987
+ const FINDING_NAME_MAX = 100;
3988
+ const FINDING_NAMES_MAX = 20;
3989
+ /**
3990
+ * BAPI-1747 — validate optional findings. Unusable findings are dropped on their own;
3991
+ * they never cost the row or the list. Names must be short, printable, and plain.
3992
+ */
3993
+ function parseReadinessFindings(raw) {
3994
+ if (!Array.isArray(raw))
3995
+ return undefined;
3996
+ const out = [];
3997
+ for (const item of raw.slice(0, 50)) {
3998
+ if (typeof item !== 'object' || item === null || Array.isArray(item))
3999
+ continue;
4000
+ const f = item;
4001
+ if (typeof f.reason !== 'string' || !/^[a-z_]{1,40}$/.test(f.reason))
4002
+ continue;
4003
+ if (f.status !== 'not_met' && f.status !== 'unknown')
4004
+ continue;
4005
+ const names = Array.isArray(f.names) ? f.names : [];
4006
+ if (names.length > FINDING_NAMES_MAX || !names.every(n => typeof n === 'string' && n.length > 0 && n.length <= FINDING_NAME_MAX && /^[A-Za-z0-9 _./:()[\]@#+-]+$/.test(n)))
4007
+ continue;
4008
+ const finding = { reason: f.reason, status: f.status, names: names };
4009
+ if (typeof f.count === 'number' && Number.isInteger(f.count) && f.count >= 0)
4010
+ finding.count = f.count;
4011
+ out.push(finding);
4012
+ }
4013
+ return out.length ? out : undefined;
4014
+ }
4015
+ const PREREQUISITE_ROW_KEYS = 'check_status,fix,id,impact,label,scope';
4016
+ /** The six original keys, with an optional `findings` key (BAPI-1747). */
4017
+ function hasPrerequisiteRowKeys(r) {
4018
+ const keys = Object.keys(r).filter(k => k !== 'findings').sort().join(',');
4019
+ return keys === PREREQUISITE_ROW_KEYS;
4020
+ }
4021
+ function withFindings(r) {
4022
+ const { findings, ...row } = r;
4023
+ const parsed = parseReadinessFindings(findings);
4024
+ return (parsed ? { ...row, findings: parsed } : row);
4025
+ }
3987
4026
  export function parseReadinessPrerequisites(raw) {
3988
4027
  if (!Array.isArray(raw))
3989
4028
  return undefined;
@@ -3993,24 +4032,30 @@ export function parseReadinessPrerequisites(raw) {
3993
4032
  if (typeof item !== 'object' || item === null || Array.isArray(item))
3994
4033
  return undefined;
3995
4034
  const r = item;
3996
- if (typeof r.id === 'string' && RETIRED_READINESS_PREREQUISITE_IDS.has(r.id) && !READINESS_PREREQUISITE_BY_ID.has(r.id)) {
3997
- if (seen.has(r.id) || Object.keys(r).sort().join(',') !== 'check_status,fix,id,impact,label,scope' ||
4035
+ // BAPI-1602 retired rows, and BAPI-1747 rows a NEWER server sends that this build
4036
+ // does not know: kept with the server's own bounded text and rendered after the
4037
+ // catalog rows, never dropped, so one new row cannot hide the whole list.
4038
+ if (typeof r.id === 'string' && !READINESS_PREREQUISITE_BY_ID.has(r.id)) {
4039
+ if (seen.has(r.id) || !/^[a-z][a-z0-9_.-]{0,99}$/.test(r.id) || !hasPrerequisiteRowKeys(r) ||
3998
4040
  !isBoundedServerText(r.label) || !isBoundedServerText(r.fix) || !['customer', 'self_host'].includes(String(r.scope)) ||
3999
4041
  !['met', 'not_met', 'unknown', 'not_applicable'].includes(String(r.check_status)) || !['blocking', 'warning', 'info'].includes(String(r.impact)) ||
4000
- (r.check_status === 'unknown' && r.impact === 'blocking'))
4001
- return undefined;
4042
+ (r.check_status === 'unknown' && r.impact === 'blocking')) {
4043
+ if (RETIRED_READINESS_PREREQUISITE_IDS.has(r.id))
4044
+ return undefined;
4045
+ continue;
4046
+ }
4002
4047
  seen.add(r.id);
4003
- result.push(r);
4048
+ result.push(withFindings(r));
4004
4049
  continue;
4005
4050
  }
4006
4051
  const d = typeof r.id === 'string' ? READINESS_PREREQUISITE_BY_ID.get(r.id) : undefined;
4007
- if (!d || seen.has(d.id) || Object.keys(r).sort().join(',') !== 'check_status,fix,id,impact,label,scope' || r.label !== d.label || r.scope !== d.scope ||
4052
+ if (!d || seen.has(d.id) || !hasPrerequisiteRowKeys(r) || r.label !== d.label || r.scope !== d.scope ||
4008
4053
  !['met', 'not_met', 'unknown', 'not_applicable'].includes(String(r.check_status)) || !['blocking', 'warning', 'info'].includes(String(r.impact)) ||
4009
4054
  typeof r.fix !== 'string' || !(Object.values(READINESS_PREREQUISITE_FIXES).includes(r.fix) || PREVIOUS_SERVER_READINESS_FIXES.includes(r.fix)) ||
4010
4055
  (r.check_status === 'unknown' && r.impact === 'blocking'))
4011
4056
  return undefined;
4012
4057
  seen.add(d.id);
4013
- result.push(r);
4058
+ result.push(withFindings(r));
4014
4059
  }
4015
4060
  return result;
4016
4061
  }
@@ -334,6 +334,118 @@ async function waiterFor(roots, env, launcher, epicRunId, epicKey) {
334
334
  }
335
335
  return renderPlainWaiterCommand(launcher, epicRunId);
336
336
  }
337
+ // ---------------------------------------------------------------------------
338
+ // BAPI-1781 — bounded delivery re-read
339
+ // ---------------------------------------------------------------------------
340
+ /** The whole re-read phase's budget, request timeouts and pauses included. */
341
+ export const DELIVERY_REREAD_BUDGET_MS = 5_000;
342
+ /** The short pause between re-read rounds. */
343
+ export const DELIVERY_REREAD_INTERVAL_MS = 500;
344
+ /** Printed when the stored status is still `queued` after the bounded re-read. */
345
+ export const DELIVERY_QUEUED_TEXT = "queued, not yet handed off";
346
+ /** Printed when the escalation was accepted but no re-read succeeded. */
347
+ export const DELIVERY_UNVERIFIED_TEXT = "accepted, but delivery could not be verified";
348
+ /**
349
+ * A stored status that will not change by waiting a few seconds. `queued` is
350
+ * the normal first answer (the sweep runs every 60 seconds) and `unknown...`
351
+ * may still settle, so both keep polling; every other status is conclusive.
352
+ */
353
+ export function isConclusiveDeliveryStatus(status) {
354
+ return status !== "queued" && !status.startsWith("unknown");
355
+ }
356
+ /** A fetch that also aborts when `deadline` aborts (Node 18 has no AbortSignal.any). */
357
+ function deadlineBoundFetch(deadline) {
358
+ const base = globalThis.fetch;
359
+ return (url, init) => {
360
+ const combined = new AbortController();
361
+ const abort = () => combined.abort();
362
+ if (init.signal.aborted || deadline.aborted)
363
+ combined.abort();
364
+ init.signal.addEventListener("abort", abort, { once: true });
365
+ deadline.addEventListener("abort", abort, { once: true });
366
+ return base(url, { ...init, signal: combined.signal }).finally(() => {
367
+ init.signal.removeEventListener("abort", abort);
368
+ deadline.removeEventListener("abort", abort);
369
+ });
370
+ };
371
+ }
372
+ /** Run one call, bounded by `ms`; resolves `null` when the bound runs out or the call fails. */
373
+ async function boundedCall(ms, call) {
374
+ const controller = new AbortController();
375
+ let timer;
376
+ const expired = new Promise((resolve) => {
377
+ timer = setTimeout(() => { controller.abort(); resolve(null); }, Math.max(0, ms));
378
+ });
379
+ try {
380
+ return await Promise.race([call(controller.signal).catch(() => null), expired]);
381
+ }
382
+ finally {
383
+ if (timer !== undefined)
384
+ clearTimeout(timer);
385
+ }
386
+ }
387
+ /**
388
+ * Re-read each accepted escalation's delivery status from storage within ONE
389
+ * bounded budget. The only mechanism is replaying the identical accepted
390
+ * request: the server resolves the same notification identity (`created=False`)
391
+ * and reports `_delivery_status` from the stored row. A response for a different
392
+ * notification is ignored. The last valid stored status is kept; a later
393
+ * timeout never replaces it. Nothing here triggers the notification sweep.
394
+ */
395
+ export async function rereadDeliveryStatuses(access, accepted, deps) {
396
+ const clock = deps.monotonicNow ?? (() => performance.now());
397
+ const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
398
+ const budget = deps.rereadBudgetMs ?? DELIVERY_REREAD_BUDGET_MS;
399
+ const interval = deps.rereadIntervalMs ?? DELIVERY_REREAD_INTERVAL_MS;
400
+ const reread = deps.reread ?? (deps.escalate
401
+ ? (a, r) => deps.escalate(a, r)
402
+ : (a, r, signal) => escalateTicket(a, r, deadlineBoundFetch(signal)));
403
+ const results = accepted.map(({ response }) => isConclusiveDeliveryStatus(response.delivery_status)
404
+ ? { status: response.delivery_status, source: "response" }
405
+ : { status: response.delivery_status, source: "unverified" });
406
+ const pending = () => results
407
+ .map((r, i) => (r.source === "response" || (r.source === "storage" && isConclusiveDeliveryStatus(r.status)) ? -1 : i))
408
+ .filter((i) => i >= 0);
409
+ const deadline = clock() + budget;
410
+ while (pending().length > 0) {
411
+ for (const i of pending()) {
412
+ const remaining = deadline - clock();
413
+ if (remaining <= 0)
414
+ return results;
415
+ const { request, response } = accepted[i];
416
+ const replay = { ...request };
417
+ const answer = await boundedCall(remaining, (signal) => reread(access, replay, signal));
418
+ if (answer && answer.notification_id === response.notification_id &&
419
+ typeof answer.delivery_status === "string" && answer.delivery_status !== "") {
420
+ results[i] = { status: answer.delivery_status, source: "storage" };
421
+ }
422
+ }
423
+ if (pending().length === 0)
424
+ break;
425
+ const remaining = deadline - clock();
426
+ if (remaining <= 0)
427
+ break;
428
+ await sleep(Math.min(interval, remaining));
429
+ }
430
+ return results;
431
+ }
432
+ /** The operator-facing delivery phrase for one accepted escalation. */
433
+ export function renderDeliveryOutcome(delivery, statusCommand) {
434
+ if (delivery.source === "unverified") {
435
+ return `${DELIVERY_UNVERIFIED_TEXT}; check it with ${statusCommand}`;
436
+ }
437
+ if (delivery.status === "queued") {
438
+ return `delivery ${DELIVERY_QUEUED_TEXT}; check later with ${statusCommand} or the explain_run MCP tool`;
439
+ }
440
+ if (!isConclusiveDeliveryStatus(delivery.status)) {
441
+ return `delivery ${delivery.status}; check later with ${statusCommand} or the explain_run MCP tool`;
442
+ }
443
+ return `delivery ${delivery.status}`;
444
+ }
445
+ /** The status-check command named in delivery output. */
446
+ export function deliveryStatusCommand(epicRunId) {
447
+ return `epic-implementer epic-status --epic-run-id ${epicRunId}`;
448
+ }
337
449
  /** Run `declare-blocked`. Never throws; returns the exit code. */
338
450
  export async function runDeclareBlockedCommand(argv, deps = {}) {
339
451
  const env = deps.env ?? process.env;
@@ -449,10 +561,11 @@ export async function runDeclareBlockedCommand(argv, deps = {}) {
449
561
  }
450
562
  guided.set(ticket, classification.guidedCommand);
451
563
  try {
452
- const response = await (deps.escalate ?? escalateTicket)(access, {
564
+ const request = {
453
565
  epicRunId, ticketKey: ticket, cause: DECLARE_BLOCKED_CAUSES[args.entry], actionNeeded: composeActionNeeded(args),
454
- });
455
- outcomes.push({ ticket, class: "accepted", response });
566
+ };
567
+ const response = await (deps.escalate ?? escalateTicket)(access, { ...request });
568
+ outcomes.push({ ticket, class: "accepted", response, request });
456
569
  }
457
570
  catch (error) {
458
571
  if (error instanceof ConductorBridgeApiError && error.status === 422) {
@@ -468,6 +581,23 @@ export async function runDeclareBlockedCommand(argv, deps = {}) {
468
581
  outcomes.push({ ticket, class: "scope_unknown", reason: "processing_failed" });
469
582
  }
470
583
  }
584
+ // BAPI-1781 — the real delivery outcome: one bounded re-read phase for every
585
+ // accepted escalation whose answer was not already conclusive. Advisory: a
586
+ // failure here never changes the class or the exit code.
587
+ const acceptedOutcomes = outcomes.filter((o) => o.class === "accepted");
588
+ try {
589
+ const readbacks = await rereadDeliveryStatuses(access, acceptedOutcomes.map((o) => ({
590
+ request: o.request ?? { epicRunId, ticketKey: o.ticket, cause: DECLARE_BLOCKED_CAUSES[args.entry],
591
+ actionNeeded: composeActionNeeded(args) },
592
+ response: o.response,
593
+ })), deps);
594
+ acceptedOutcomes.forEach((o, i) => { o.delivery = readbacks[i]; });
595
+ }
596
+ catch {
597
+ for (const o of acceptedOutcomes)
598
+ o.delivery ??= { status: o.response.delivery_status, source: "unverified" };
599
+ }
600
+ const deliveryOf = (o) => o.delivery ?? { status: o.response.delivery_status, source: "unverified" };
471
601
  // Records: one receipt and one closed-valued tally line per ticket. A failed
472
602
  // write is reported, never fatal to the advice already computed.
473
603
  let recordsFailed = false;
@@ -480,7 +610,7 @@ export async function runDeclareBlockedCommand(argv, deps = {}) {
480
610
  entry: args.entry,
481
611
  guided_command: guided.get(outcome.ticket) ?? null,
482
612
  notification_id: accepted?.notification_id ?? null,
483
- delivery_status: accepted?.delivery_status ?? null,
613
+ delivery_status: outcome.class === "accepted" ? deliveryOf(outcome).status : null,
484
614
  requirement: args.requirement,
485
615
  evidence: args.evidence,
486
616
  tried: args.triedText,
@@ -489,7 +619,8 @@ export async function runDeclareBlockedCommand(argv, deps = {}) {
489
619
  const fields = { ticket: outcome.ticket, class: outcome.class, entry: args.entry };
490
620
  if (accepted) {
491
621
  fields.notification_id = accepted.notification_id;
492
- fields.delivery_status = deliveryStatusToken(accepted.delivery_status);
622
+ fields.delivery_status = deliveryStatusToken(outcome.class === "accepted" ? deliveryOf(outcome).status
623
+ : accepted.delivery_status);
493
624
  }
494
625
  if (outcome.class === "scope_unknown" || outcome.class === "escalation_failed")
495
626
  fields.reason = outcome.reason;
@@ -512,7 +643,8 @@ export async function runDeclareBlockedCommand(argv, deps = {}) {
512
643
  }
513
644
  else if (o.class === "accepted") {
514
645
  lines.push(`${o.ticket}: accepted, escalated (${DECLARE_BLOCKED_CAUSES[args.entry]}; notification ` +
515
- `${o.response.notification_id}; delivery ${o.response.delivery_status}; ${o.response.blocker_enforcement}).`);
646
+ `${o.response.notification_id}; ${renderDeliveryOutcome(deliveryOf(o), deliveryStatusCommand(epicRunId))}; ` +
647
+ `${o.response.blocker_enforcement}).`);
516
648
  }
517
649
  else if (o.class === "scope_unknown") {
518
650
  lines.push(`${o.ticket}: scope unknown (${o.reason}); supervision continues.`);
@@ -542,7 +674,10 @@ export async function runDeclareBlockedCommand(argv, deps = {}) {
542
674
  epic_key: epicKey,
543
675
  outcomes: outcomes.map((o) => o.class === "accepted"
544
676
  ? { ticket: o.ticket, class: o.class, notification_id: o.response.notification_id,
545
- delivery_status: o.response.delivery_status, blocks: o.response.blocks,
677
+ delivery_status: deliveryOf(o).status, delivery_readback: deliveryOf(o).source,
678
+ ...(deliveryOf(o).source === "unverified" || !isConclusiveDeliveryStatus(deliveryOf(o).status)
679
+ ? { status_command: deliveryStatusCommand(epicRunId) } : {}),
680
+ blocks: o.response.blocks,
546
681
  blocker_enforcement: o.response.blocker_enforcement }
547
682
  : o),
548
683
  summary,
@@ -19,10 +19,11 @@
19
19
  * step (keep monitoring in the foreground) and never stops the run.
20
20
  */
21
21
  import { randomBytes } from "node:crypto";
22
+ import { stat } from "node:fs/promises";
22
23
  import { fetchEpicRunState, resolveConductorBridgeApiAccess, } from "./bridge-api-client.js";
23
24
  import { renderReleaseCommand, renderWaiterCommand, resolveDriverLauncher, } from "./driver-commands.js";
24
25
  import { transcribeLapseResult } from "./driver-lapse.js";
25
- import { DRIVER_KEY_PATTERN, DRIVER_RUN_REF_PATTERN, DRIVER_SESSION_ID_PATTERN, DRIVER_STATE_VERSION, appendDriverTallyLine, createDriverJsonExclusive, currentPointerPath, formatDriverTallyLine, generationFilePath, generationLabel, parseRegistration, readDriverJson, registrationPath, resolveDriverStateRoots, writeDriverJsonAtomic, } from "./driver-session-state.js";
26
+ import { DRIVER_KEY_PATTERN, DRIVER_RUN_REF_PATTERN, DRIVER_SESSION_ID_PATTERN, DRIVER_STATE_VERSION, appendDriverTallyLine, createDriverJsonExclusive, currentPointerPath, formatDriverTallyLine, generationFilePath, generationLabel, parseRegistration, readDriverJson, registrationPath, resolveDriverStateRoots, tallyPath, writeDriverJsonAtomic, } from "./driver-session-state.js";
26
27
  const TERMINAL_RUN_STATUSES = new Set(["done", "abandoned"]);
27
28
  const NOT_ARMED_NEXT_STEP = "Keep monitoring in the foreground; do not end a turn while the run is active.";
28
29
  export function getDriverRegisterUsage() {
@@ -148,7 +149,12 @@ export async function runDriverRegisterCommand(argv, deps = {}) {
148
149
  registered_at: now().toISOString(),
149
150
  };
150
151
  await publishRegistration(roots, registration);
151
- await appendDriverTallyLine(roots, run.epic_key, formatDriverTallyLine("driver-guard", { event: "register", generation: generationLabel(generation) }, now())).catch(() => undefined);
152
+ // BAPI-1782 — never CREATE the tally here: operation 8 writes its header first.
153
+ // Append the register line only to a tally that already exists; skip silently otherwise.
154
+ const tallyExists = await stat(tallyPath(roots, run.epic_key)).then((info) => info.isFile(), () => false);
155
+ if (tallyExists) {
156
+ await appendDriverTallyLine(roots, run.epic_key, formatDriverTallyLine("driver-guard", { event: "register", generation: generationLabel(generation) }, now())).catch(() => undefined);
157
+ }
152
158
  if (parsed.json) {
153
159
  out(JSON.stringify({
154
160
  armed: true,
@@ -91,10 +91,11 @@ export function getConductorUsage() {
91
91
  " likely-tests --base <sha> Local advisory test references for committed changes.",
92
92
  " file-scope-guard Warn-only: compare the branch diff against the declared",
93
93
  " touched-file set (always exits 0; never blocks a PR)",
94
- " stop-run Stop an epic run: block dispatch and cancel queued work",
95
- " (the run record is preserved). Idempotent.",
96
- " abandon-run Abandon an epic run — TERMINAL and IRREVERSIBLE.",
97
- " Idempotent on an already-abandoned run.",
94
+ " stop-run Pause an epic run: block dispatch and cancel queued work",
95
+ " (the run record is preserved; it does NOT end the run).",
96
+ " Idempotent. To end a run, use abandon-run.",
97
+ " abandon-run End an active or stopped epic run in one step — TERMINAL",
98
+ " and IRREVERSIBLE. Idempotent on an already-abandoned run.",
98
99
  " unpark Move a parked (needs_human) ticket back into its gate",
99
100
  " machine. Retries internally on a concurrent change.",
100
101
  " adopt-current-head-and-unpark",
@@ -322,9 +323,12 @@ export function getConductorUsage() {
322
323
  " --epic-run-id <id> Epic run identifier (required)",
323
324
  " --json Print compact JSON result",
324
325
  " --help Print this usage message",
325
- " stop-run BLOCKS new dispatch and CANCELS queued work; the run record is",
326
- " preserved and the run cannot resume on its own — it is an emergency brake,",
327
- " not a pause. abandon-run is the SAME plus a TERMINAL, IRREVERSIBLE close-out:",
326
+ " stop-run PAUSES a run: it BLOCKS new dispatch and CANCELS queued work; the",
327
+ " run record is preserved and the run cannot resume on its own. stop-run does",
328
+ " NOT end the run — a stopped run stays live (blocked) until it is abandoned.",
329
+ " abandon-run --epic-run-id <id> is the one-step way to END an active or",
330
+ " stopped run: the server applies the same stop fence (block dispatch, cancel",
331
+ " queued work) and then commits the TERMINAL, IRREVERSIBLE abandoned status;",
328
332
  " once abandoned, the run can never resume or be reused. Both are idempotent —",
329
333
  " repeating either is a safe no-op once the run is already stopped/abandoned.",
330
334
  "",
@@ -171,6 +171,13 @@ export class EpicServerJournal {
171
171
  now;
172
172
  maxEvents;
173
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();
174
181
  constructor(filePath, runId, fs, now = () => new Date(), maxEvents = EPIC_SERVER_JOURNAL_MAX_EVENTS) {
175
182
  this.filePath = filePath;
176
183
  this.runId = runId;
@@ -188,32 +195,42 @@ export class EpicServerJournal {
188
195
  this.doc = parseDocument(raw) ?? emptyDocument();
189
196
  return this.doc;
190
197
  }
191
- /** Append one background event. Never throws, never blocks serving for long. */
192
- async append(event, fields = {}) {
193
- try {
194
- const doc = await this.load();
195
- doc.events.push(buildJournalEntry(this.runId, doc.next_seq, this.now(), event, fields));
196
- doc.next_seq += 1;
197
- this.compact(doc);
198
- await writePrivateFileAtomic(this.fs, this.filePath, `${JSON.stringify(doc)}\n`);
199
- }
200
- catch {
201
- /* journaling is best-effort; serving continues */
202
- }
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;
203
203
  }
204
- /** Record the driver's acknowledgement (a status cursor). */
205
- async acknowledge(cursor) {
206
- try {
207
- const doc = await this.load();
208
- if (Number.isSafeInteger(cursor) && cursor > doc.acked_seq && cursor < doc.next_seq) {
209
- 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;
210
211
  this.compact(doc);
211
212
  await writePrivateFileAtomic(this.fs, this.filePath, `${JSON.stringify(doc)}\n`);
212
213
  }
213
- }
214
- catch {
215
- /* best-effort */
216
- }
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
+ });
217
234
  }
218
235
  compact(doc) {
219
236
  if (doc.events.length <= this.maxEvents)
@@ -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");
@@ -250,7 +250,7 @@ export function sanitizeLocalMergeOutput(text, credentials = []) {
250
250
  * child when the injected abort signal fires. Never builds a shell string and
251
251
  * never logs raw stdout/stderr.
252
252
  */
253
- async function defaultRunCommand(cmd, args, env, signal) {
253
+ export async function defaultRunCommand(cmd, args, env, signal) {
254
254
  // BAPI-1136: `env` arrives ALREADY built by `buildLocalMergeChildEnv` and is
255
255
  // the complete child environment. The former `{ ...process.env, ...env }`
256
256
  // merge is gone — it re-inherited the ambient identity the caller had just
@@ -2,6 +2,7 @@
2
2
  import { READINESS_PREREQUISITE_BY_ID, READINESS_LEGACY_IDS, READINESS_PREREQUISITE_CATALOG } from '../readiness-prerequisites.generated.js';
3
3
  import { resolveReadinessRemedy } from '../printed-remedy-commands.js';
4
4
  import { createReadinessCheckSafely } from '../readiness-check.js';
5
+ import { profileMergeNeededFrom } from '../mcp-host-config.js';
5
6
  export function mergeReadinessPrerequisites(checks, server = []) {
6
7
  const rows = new Map();
7
8
  for (const check of checks) {
@@ -40,8 +41,85 @@ export function mergeReadinessPrerequisites(checks, server = []) {
40
41
  ...[...rows.values()].filter(row => !known.has(row.id)),
41
42
  ];
42
43
  }
44
+ /** BAPI-1747 — the install.run-tools-visible row: the one row only this host can observe. */
45
+ export const RUN_TOOLS_VISIBLE_ID = 'install.run-tools-visible';
46
+ /**
47
+ * BAPI-1719/1747 — project one read-only profile inspection onto the tool-visibility
48
+ * state. The single owner of that mapping: install's setup item and the readiness
49
+ * overlay both use it, so `local.tool-visibility` and the contract row cannot disagree.
50
+ * A config that registers Bridge twice comes first (the writer refuses it); an
51
+ * unreadable config is never read as satisfied.
52
+ */
53
+ export function toolVisibilityStateFromInspection(inspection) {
54
+ const duplicates = inspection.configs.filter((c) => c.duplicateRegistration === true).map((c) => c.path);
55
+ if (duplicates.length > 0)
56
+ return { state: 'duplicate_registration', configPaths: duplicates };
57
+ if (profileMergeNeededFrom(inspection)) {
58
+ return { state: 'needs_merge', configPaths: inspection.configs.filter((c) => c.state === 'token-absent').map((c) => c.path) };
59
+ }
60
+ if (inspection.configs.some((c) => c.state === 'unreadable'))
61
+ return { state: 'unknown', reason: 'inspection' };
62
+ return inspection.bridgeEntryPresent ? { state: 'met' } : { state: 'no_entry' };
63
+ }
64
+ const SAFE_FINDING_NAME = /^[A-Za-z0-9 _./:()[\]@#+-]{1,100}$/;
65
+ /**
66
+ * The run-tools-visible row for a local observation. Never blocking and never
67
+ * authorization evidence: a confirmed hidden group is a warning, and no observation
68
+ * (a server-only caller, or an unreadable config) is `unknown`.
69
+ */
70
+ export function toolVisibilityPrerequisite(state) {
71
+ const descriptor = READINESS_PREREQUISITE_BY_ID.get(RUN_TOOLS_VISIBLE_ID);
72
+ const base = { id: descriptor.id, label: descriptor.label, scope: descriptor.scope };
73
+ if (state?.state === 'met')
74
+ return { ...base, check_status: 'met', impact: 'info', fix: '' };
75
+ if (state === undefined || state.state === 'unknown') {
76
+ return { ...base, check_status: 'unknown', impact: 'warning',
77
+ fix: resolveReadinessRemedy({ id: descriptor.id, state: 'unknown', scope: descriptor.scope }),
78
+ findings: [{ reason: 'tools_unobserved', status: 'unknown', names: [] }] };
79
+ }
80
+ const paths = state.state === 'no_entry' ? [] : state.configPaths.filter(p => SAFE_FINDING_NAME.test(p)).slice(0, 20);
81
+ return { ...base, check_status: 'not_met', impact: 'warning',
82
+ fix: resolveReadinessRemedy({ id: descriptor.id, state: 'not_met', scope: descriptor.scope, impact: 'warning' }),
83
+ findings: [{ reason: 'tools_hidden', status: 'not_met', names: paths }] };
84
+ }
85
+ const CATALOG_ORDER = new Map(READINESS_PREREQUISITE_CATALOG.map((d, i) => [d.id, i]));
86
+ /**
87
+ * BAPI-1747 — the one client overlay every readiness surface (launch preview, install's
88
+ * final verdict, doctor) composes its rows with. It merges the server rows exactly as
89
+ * {@link mergeReadinessPrerequisites} does, then replaces ONLY the run-tools-visible row
90
+ * with this invocation's local observation. With no server row and no local observation
91
+ * the row is left out, so a caller that knows nothing about tool visibility is unchanged.
92
+ * Inputs are never mutated; catalog rows stay before rows this build does not know.
93
+ */
94
+ export function overlayReadinessPrerequisites(checks, server = [], toolVisibility) {
95
+ const merged = mergeReadinessPrerequisites(checks, server);
96
+ const present = merged.some(p => p.id === RUN_TOOLS_VISIBLE_ID);
97
+ if (!present && toolVisibility === undefined)
98
+ return merged;
99
+ const local = toolVisibilityPrerequisite(toolVisibility);
100
+ const rows = present ? merged.map(p => p.id === RUN_TOOLS_VISIBLE_ID ? local : p) : [...merged, local];
101
+ const rank = (id) => CATALOG_ORDER.get(id) ?? Number.MAX_SAFE_INTEGER;
102
+ // A stable sort keeps unknown server rows in their arrival order after the catalog.
103
+ return rows.map((row, i) => ({ row, i })).sort((a, b) => rank(a.row.id) - rank(b.row.id) || a.i - b.i).map(x => x.row);
104
+ }
105
+ function findingNames(f) {
106
+ const names = f.names.join(', ');
107
+ const extra = typeof f.count === 'number' && f.count > f.names.length ? ` (+${f.count - f.names.length} more)` : '';
108
+ return names ? `${names}${extra}` : extra.trim();
109
+ }
110
+ /** One line per finding, gaps first: the reason token and the names it concerns. */
111
+ export function formatReadinessFindings(findings, indent = ' ') {
112
+ if (!findings?.length)
113
+ return [];
114
+ const ordered = [...findings.filter(f => f.status === 'not_met'), ...findings.filter(f => f.status === 'unknown')];
115
+ return ordered.map(f => {
116
+ const kind = f.status === 'not_met' ? 'Gap' : "Couldn't check";
117
+ const names = findingNames(f);
118
+ return `${indent}${kind} (${f.reason})${names ? `: ${names}` : ''}`;
119
+ });
120
+ }
43
121
  export function prerequisiteChecks(items) {
44
- return items.map(p => createReadinessCheckSafely({ id: p.id, source: 'server', label: p.label,
122
+ return items.map(p => createReadinessCheckSafely({ id: p.id, source: 'server', label: p.label || p.id,
45
123
  status: p.check_status === 'met' ? 'pass' : p.check_status === 'not_applicable' ? 'skip' : p.check_status === 'unknown' || p.impact !== 'blocking' ? 'warn' : 'fail',
46
124
  blocking: p.impact === 'blocking', detail: p.check_status,
47
125
  ...(p.fix ? { remediation: p.fix } : {}) }));
@@ -53,7 +131,16 @@ export function formatReadinessPrerequisites(items, options = {}) {
53
131
  const verdict = blockers.length ? `Not ready: ${blockers.length} blocking` : warnings.length ? `Ready, with ${warnings.length} warnings` : 'Ready to launch';
54
132
  const selected = options.all ? visible : [...blockers, ...warnings];
55
133
  const state = { met: 'Met', not_met: 'Not met', unknown: "Couldn't check", not_applicable: 'Not applicable' };
56
- return [verdict, ...selected.flatMap(p => [` ${p.label}: ${state[p.check_status]}`, ...(p.fix && ['not_met', 'unknown'].includes(p.check_status) ? [` ${p.fix}`] : [])])];
134
+ const severity = (p) => p.check_status === 'not_met' ? (p.impact === 'blocking' ? ' (blocking)' : ' (warning)') : '';
135
+ // A row with named findings, or one this build does not know, prints its ID after
136
+ // the state so every surface names the same row (BAPI-1747); other rows keep their
137
+ // label-only line. Findings follow their row, gaps before unreadable observations.
138
+ const showId = (p) => (p.findings?.length ?? 0) > 0 || !READINESS_PREREQUISITE_BY_ID.has(p.id);
139
+ return [verdict, ...selected.flatMap(p => [
140
+ ` ${p.label || p.id}: ${state[p.check_status]}${severity(p)}${showId(p) ? ` [${p.id}]` : ''}`,
141
+ ...formatReadinessFindings(['not_met', 'unknown'].includes(p.check_status) ? p.findings : undefined),
142
+ ...(p.fix && ['not_met', 'unknown'].includes(p.check_status) ? [` ${p.fix}`] : []),
143
+ ])];
57
144
  }
58
145
  /** The explicit assessment path never derives policy from legacy text. */
59
146
  export { composeReadinessAssessment, deriveAdvisoryVerdict } from './readiness-assessment.js';
@@ -215,6 +215,8 @@ const STOP_RUN_USAGE = [
215
215
  "Stop an epic run: block new dispatch and cancel its queued work. The run",
216
216
  "record is preserved (never deleted) so its history stays inspectable.",
217
217
  "Idempotent — repeating it once stopped is a safe no-op.",
218
+ "A stopped run is paused, not ended. To end an active or stopped run in one",
219
+ "step, use: epic-implementer abandon-run --epic-run-id <id>",
218
220
  ].join("\n");
219
221
  function renderStopRunResult(result, json) {
220
222
  if (json) {