@bridge_gpt/mcp-server 0.2.71 → 0.2.72

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 (116) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +19 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +4 -4
  5. package/build/bridge-permissions.js +4 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/claude-review-workflow.js +1 -1
  9. package/build/cli-help.js +6 -0
  10. package/build/codex-auto-recovery.js +126 -0
  11. package/build/codex-skill-adapter.js +2 -0
  12. package/build/commands.generated.js +5 -5
  13. package/build/conductor/bridge-api-client.js +518 -23
  14. package/build/conductor/doctor.js +84 -10
  15. package/build/conductor/epic-implementer-cli.js +51 -2
  16. package/build/conductor/gate-discovery.js +136 -10
  17. package/build/conductor/gate-settings-review.js +305 -5
  18. package/build/conductor/git-hooks-uninstall.js +112 -0
  19. package/build/conductor/git-hooks.js +81 -15
  20. package/build/conductor/guided-repair.js +10 -1
  21. package/build/conductor/install-doctor.js +2 -4
  22. package/build/conductor/launch-plan.js +42 -2
  23. package/build/conductor/local-merge.js +12 -1
  24. package/build/conductor/merge-execution-contract.js +1 -1
  25. package/build/conductor/merged-child-check.js +2 -1
  26. package/build/conductor/prerequisite-inputs.js +379 -0
  27. package/build/conductor/readiness-assessment.js +78 -0
  28. package/build/conductor/readiness-cli.js +10 -0
  29. package/build/conductor/readiness-prerequisites.js +53 -0
  30. package/build/conductor/readiness-sections.js +21 -8
  31. package/build/conductor/readiness.js +20 -2
  32. package/build/conductor/recovery-cli.js +223 -13
  33. package/build/conductor/recovery-operations.js +34 -4
  34. package/build/conductor/repair-contract.js +33 -0
  35. package/build/conductor/tools.js +34 -3
  36. package/build/conductor/wait-run-attention.js +115 -0
  37. package/build/conductor/wait-run-cli.js +96 -3
  38. package/build/conductor/worker-database-doctor-inspector.js +1 -0
  39. package/build/credential-store.js +25 -20
  40. package/build/dependency-install-declarations.js +157 -0
  41. package/build/docs.generated.js +4 -4
  42. package/build/doctor.js +37 -5
  43. package/build/drive-epic-help.js +2 -2
  44. package/build/drive-epic.js +52 -11
  45. package/build/epic-implementer-bin.js +118 -43
  46. package/build/epic-launch-profile.js +1 -1
  47. package/build/executor/cli.js +2 -0
  48. package/build/executor/completion-contract.js +16 -0
  49. package/build/executor/credentials.js +1 -1
  50. package/build/executor/delivery-observations.js +113 -0
  51. package/build/executor/delivery-outcome.js +30 -0
  52. package/build/executor/dependency-refresh-runner.js +132 -0
  53. package/build/executor/dependency-refresh.js +530 -0
  54. package/build/executor/deps.js +4 -0
  55. package/build/executor/env.js +67 -2
  56. package/build/executor/harness-coverage.js +19 -0
  57. package/build/executor/http-client.js +35 -1
  58. package/build/executor/index.js +2 -1
  59. package/build/executor/install-preflight.js +1 -1
  60. package/build/executor/job-runner.js +246 -28
  61. package/build/executor/likely-tests.js +94 -97
  62. package/build/executor/prompt-spec.js +13 -3
  63. package/build/executor/required-verification.js +28 -0
  64. package/build/executor/required-work-diagnostics.js +30 -0
  65. package/build/executor/required-work-ledger.js +19 -1
  66. package/build/executor/results.js +42 -0
  67. package/build/executor/service-discovery.js +42 -0
  68. package/build/executor/service-lifecycle.js +109 -2
  69. package/build/executor/service-uninstall.js +205 -0
  70. package/build/executor/service-unit.js +5 -3
  71. package/build/executor/test-clock.js +3 -0
  72. package/build/executor/verification-hints.js +179 -0
  73. package/build/executor/worker-command.js +54 -2
  74. package/build/executor/worker-database.js +271 -31
  75. package/build/executor/worker-finalization.js +65 -10
  76. package/build/executor/worker-guard-hook.js +10 -2
  77. package/build/executor/worker-verification-guidance.js +37 -2
  78. package/build/executor/worktree-inspection.js +42 -0
  79. package/build/github-sign-in.js +1 -1
  80. package/build/index.js +679 -278
  81. package/build/init.js +3 -3
  82. package/build/install-bridge-conductor-gate.js +236 -42
  83. package/build/install-bridge-conductor-setup.js +115 -26
  84. package/build/install-bridge-conductor.js +448 -350
  85. package/build/install-bridge.js +418 -123
  86. package/build/install-maintenance.js +104 -0
  87. package/build/install-reexec.js +1 -1
  88. package/build/local-cleanup.js +59 -0
  89. package/build/mcp-install-state.js +68 -2
  90. package/build/merge-workflow-install.js +2 -2
  91. package/build/package-script-semantics.js +10 -0
  92. package/build/pipeline-utils.js +1 -1
  93. package/build/pipelines.generated.js +5 -5
  94. package/build/plan-execution-ledger.js +148 -2
  95. package/build/plane/plane-freshness.js +6 -7
  96. package/build/plane/terminal-run-cleanup.js +5 -1
  97. package/build/plane/terminal-run-status.js +4 -0
  98. package/build/printed-remedy-commands.js +24 -4
  99. package/build/readiness-check.js +1 -78
  100. package/build/readiness-prerequisites.generated.js +199 -0
  101. package/build/readme.generated.js +1 -1
  102. package/build/repository-toolchains.js +50 -8
  103. package/build/setup-change-policy.js +32 -0
  104. package/build/setup-epic.js +2 -2
  105. package/build/setup-question.js +62 -0
  106. package/build/start-tickets.js +4 -0
  107. package/build/test-command-detection.js +32 -88
  108. package/build/test-support/notes-fs.js +40 -0
  109. package/build/ticket-delivery-enrollment.js +21 -8
  110. package/build/ticket-delivery-run-scope.js +128 -0
  111. package/build/version.generated.js +3 -3
  112. package/build/worker-guard-hook-bin.js +2 -2
  113. package/build/worktrees.js +105 -0
  114. package/docs/EPIC-IMPLEMENTER.md +5 -0
  115. package/docs/epic-implementer/getting-started.md +40 -15
  116. package/package.json +1 -1
@@ -23,6 +23,7 @@ import { isRemainingWork, validateCorrectionIntent } from "./correction-dispatch
23
23
  import { readRequiredVerification } from "./completion-supervision.js";
24
24
  import { isValidExecutorEpicRunId } from "./claim-scope.js";
25
25
  import path from "node:path";
26
+ import { isSafeRepoRelativePath } from "../dependency-install-declarations.js";
26
27
  /**
27
28
  * BAPI-1296: `ci_fix` is the one recovery job with a FOCUSED prompt route. It
28
29
  * renders its server-authored `payload.prompt_spec` (the dispatched failing and
@@ -118,7 +119,7 @@ function resolveExecutorPromptLegacy(job, trusted) {
118
119
  : "";
119
120
  const pushing = job.job_type !== "reconcile_overlap" && kind !== "overlap_reconciliation";
120
121
  const guidance = pushing ? renderWorkerPushAndCommitGuidance(job.job_type === "rebase") +
121
- "\n\n" + renderWorkerTestInvocationGuidance() +
122
+ "\n\n" + renderWorkerTestInvocationGuidance(payload.verification_handoff_enabled === true) +
122
123
  (trusted ? "\n\n" + renderWorkerVerificationGuidance(trusted.comparisonSha) : "") : "";
123
124
  const focusedHeader = `${header}${operatorContext}${prGuidance}${guidance}`;
124
125
  if (kind === "approved_spec_delta") {
@@ -251,6 +252,14 @@ const RECOGNIZED_DATABASE_CATEGORIES = new Set([
251
252
  "bridgeapi_reachable", "boundary_unknown", "alembic_missing", "create_failed",
252
253
  "migration_failed", "timeout", "cancelled",
253
254
  ]);
255
+ /**
256
+ * The closed migration causes the section may name. Mirrors
257
+ * `WorkerDatabaseMigrationCause`; the annotation makes the compiler reject a
258
+ * member the type does not have. Anything else is omitted from the line.
259
+ */
260
+ const RECOGNIZED_DATABASE_CAUSES = new Set([
261
+ "multiple_heads", "revision_missing", "ssl_refused", "connection_refused", "permission_denied", "timeout", "other",
262
+ ]);
254
263
  /**
255
264
  * Mirrors the server renderer's admission rules
256
265
  * (`render_reproduction_section` in `prompt_specs.py`): the first 64 entries,
@@ -264,6 +273,17 @@ const REPRODUCE_SOURCES = new Set(["check_hint", "test_command", "none"]);
264
273
  const REPRODUCE_SOURCE_NONE = "none";
265
274
  /** Python `str.strip()` whitespace, which differs from JavaScript's `trim()`. */
266
275
  const PYTHON_BLANK = /^[\t\n\v\f\r\x1c-\x1f \x85\xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]*$/;
276
+ /** BAPI-1551: the fixed stale-dependency wording, keyed by closed reason. */
277
+ const STALE_DEPENDENCY_TEXT = {
278
+ install_failed: "install failed",
279
+ lockfile_unreadable: "lockfile could not be read",
280
+ no_budget: "not enough job time to refresh",
281
+ copy_uncertain: "background copy still running or completion unknown",
282
+ shared_inode: "dependency files have shared inodes",
283
+ marker_uncleared: "refresh marker could not be cleared",
284
+ };
285
+ /** BAPI-1551: the line added when CI has no database and this worker has one. */
286
+ export const CI_DATABASE_NONE_LINE = "- CI runs without a database. Reproduce database-touching failures with the database variables unset.";
267
287
  /** Same text transforms as the server's `_reproduction_text`, for the first argv item. */
268
288
  function reproductionText(value, maxChars) {
269
289
  if (typeof value !== "string")
@@ -350,8 +370,11 @@ export function renderLocalEnvironmentLimits(options) {
350
370
  const lines = [];
351
371
  if (!options.databaseAvailable) {
352
372
  const category = options.databaseUnavailableCategory;
373
+ const cause = options.databaseUnavailableCause;
374
+ const causeText = category === "migration_failed" && typeof cause === "string" &&
375
+ RECOGNIZED_DATABASE_CAUSES.has(cause) ? `, cause: ${cause}` : "";
353
376
  const reason = category !== undefined && RECOGNIZED_DATABASE_CATEGORIES.has(category)
354
- ? ` (reason: ${category})` : "";
377
+ ? ` (reason: ${category}${causeText})` : "";
355
378
  lines.push(`- No disposable database was provisioned for this worker${reason}, so database-backed ` +
356
379
  "verification cannot run locally. CI at the pushed head is the verifier.");
357
380
  }
@@ -360,6 +383,14 @@ export function renderLocalEnvironmentLimits(options) {
360
383
  "the program its command starts with is not runnable on this machine. Do not attempt that " +
361
384
  "command. CI at the pushed head is the verifier.");
362
385
  }
386
+ if (options.ciDatabase === "none" && options.databaseAvailable)
387
+ lines.push(CI_DATABASE_NONE_LINE);
388
+ for (const stale of options.staleDependencyCwds ?? []) {
389
+ const text = STALE_DEPENDENCY_TEXT[stale.reason];
390
+ if (text === undefined || !isSafeRepoRelativePath(stale.cwd, { allowRoot: true }))
391
+ continue;
392
+ lines.push(`- dependencies for ${stale.cwd} may be stale: ${text}`);
393
+ }
363
394
  if (lines.length === 0)
364
395
  return "";
365
396
  return [
@@ -369,3 +400,24 @@ export function renderLocalEnvironmentLimits(options) {
369
400
  "This section is informational. It adds no completion obligation, evidence rule, or exit.",
370
401
  ].join("\n");
371
402
  }
403
+ // ---------------------------------------------------------------------------
404
+ // REQUIRED BEFORE PUSH (BAPI-1551)
405
+ // ---------------------------------------------------------------------------
406
+ /** The heading of the section naming the repository's always-run guard tests. */
407
+ export const REQUIRED_BEFORE_PUSH_HEADING = "## REQUIRED BEFORE PUSH ##";
408
+ /**
409
+ * Render the `REQUIRED BEFORE PUSH` section from the ADMITTED `always` entries of
410
+ * `.bridge/verification-hints.json`, or `""` when there are none. The entries are
411
+ * test references, never shell text; the worker maps them through the
412
+ * repository's declared runner.
413
+ */
414
+ export function renderRequiredBeforePush(references) {
415
+ if (references.length === 0)
416
+ return "";
417
+ return [
418
+ REQUIRED_BEFORE_PUSH_HEADING,
419
+ "This repository declares always-run guard tests: run these before you push, whatever you changed, " +
420
+ "through the repository's declared test runner. They are test references, not shell commands.",
421
+ ...references.map((reference) => `- ${reference}`),
422
+ ].join("\n");
423
+ }
@@ -1,3 +1,4 @@
1
+ import { sanitizeHarnessCoverage } from "./harness-coverage.js";
1
2
  import { monotonicNow, elapsedMs } from "../conductor/precheck-timings.js";
2
3
  /**
3
4
  * Disposable worker database lifecycle (BAPI-1479).
@@ -64,6 +65,23 @@ const RANDOM_SUFFIX_PATTERN = /^[0-9a-f]{4,16}$/;
64
65
  const ISO_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
65
66
  const SAFE_JOB_ID_FOR_LOG = /^[A-Za-z0-9_-]{1,64}$/;
66
67
  const HEX_PATTERN = /^(?:[0-9a-f]{2})*$/;
68
+ const MIGRATION_CAUSES = new Set([
69
+ "multiple_heads",
70
+ "revision_missing",
71
+ "ssl_refused",
72
+ "connection_refused",
73
+ "permission_denied",
74
+ "timeout",
75
+ "other",
76
+ ]);
77
+ /** True only for a member of the closed {@link WorkerDatabaseMigrationCause} vocabulary. */
78
+ export function isWorkerDatabaseMigrationCause(value) {
79
+ return typeof value === "string" && MIGRATION_CAUSES.has(value);
80
+ }
81
+ /** Only this many leading bytes of stderr are ever inspected for a cause. */
82
+ const MIGRATION_CAUSE_STDERR_BYTES = 4_096;
83
+ /** Per-step cap for one offline Alembic inspection command (inside the stage budget). */
84
+ export const WORKER_DATABASE_ALEMBIC_INSPECTION_STEP_TIMEOUT_MS = 5_000;
67
85
  const UNAVAILABLE_CATEGORIES = new Set([
68
86
  "client_missing",
69
87
  "postgres_unavailable",
@@ -493,7 +511,106 @@ const LISTING_COLUMNS = "encode(convert_to(datname::text, 'UTF8'), 'hex'), " +
493
511
  "encode(convert_to(coalesce(shobj_description(oid, 'pg_database'), ''), 'UTF8'), 'hex')";
494
512
  const WORKER_LISTING_SQL = `SELECT ${LISTING_COLUMNS} FROM pg_database WHERE ${exactPrefixPredicate(WORKER_DATABASE_PREFIX)} ` +
495
513
  `ORDER BY datname LIMIT ${MAX_LISTED_DATABASES}`;
496
- const HARNESS_COUNT_SQL = `SELECT count(*) FROM pg_database WHERE ${exactPrefixPredicate(HARNESS_DATABASE_PREFIX)}`;
514
+ /** Most owners one harness listing returns (one representative database each). */
515
+ const MAX_HARNESS_OWNERS = 5;
516
+ /** A PostgreSQL role name the doctor and launch plan may display: ASCII, no whitespace or control characters. */
517
+ const HARNESS_OWNER_ROLE_PATTERN = /^[A-Za-z_][A-Za-z0-9_$-]{0,62}$/;
518
+ /** True only for a whole-string valid owner role name; nothing is trimmed into validity. */
519
+ export function isValidHarnessOwnerRole(value) {
520
+ return typeof value === "string" && HARNESS_OWNER_ROLE_PATTERN.test(value);
521
+ }
522
+ /**
523
+ * Harness databases with their owners. Totals are computed over the full set
524
+ * BEFORE the row limit: the exact database count, and the exact count of distinct
525
+ * VALID owners. The listing then ranks owners in byte order and returns one
526
+ * representative database per owner for the first five, so many databases owned
527
+ * by one role cannot hide another owner. Invalid owners are counted in the total
528
+ * only. Names and owners are hex-encoded so no separator or newline can split a
529
+ * row. At most five rows, far below the runner's capture limit.
530
+ */
531
+ /** Explicit CI-owner declaration is the authority; syntax validation alone grants nothing. */
532
+ export const HARNESS_CI_OWNER_ENV = "BAPI_HARNESS_CI_OWNER_ROLE";
533
+ function harnessListingSql(ciOwner, activity = true) {
534
+ const ci = isValidHarnessOwnerRole(ciOwner)
535
+ ? `pg_get_userbyid(datdba)::text = ${sqlLiteral(ciOwner)}` : "false";
536
+ const used = activity
537
+ ? "EXISTS (SELECT 1 FROM pg_stat_activity a WHERE a.datid = pg_database.oid AND a.backend_type = 'client backend')"
538
+ : "false";
539
+ return `WITH h AS (SELECT datname::text AS n, pg_get_userbyid(datdba)::text AS o, ${used} AS in_use, ${ci} AS ci_owned FROM pg_database ` +
540
+ `WHERE ${exactPrefixPredicate(HARNESS_DATABASE_PREFIX)}), ` +
541
+ `v AS (SELECT n, o FROM h WHERE o ~ ${sqlLiteral(HARNESS_OWNER_ROLE_PATTERN.source)}), ` +
542
+ `t AS (SELECT (SELECT count(*) FROM h) AS total, (SELECT count(DISTINCT o) FROM v) AS owners, ` +
543
+ `(SELECT count(*) FROM h WHERE in_use) AS used, (SELECT count(*) FROM h WHERE ci_owned) AS ci, ` +
544
+ `(SELECT count(*) FROM h WHERE in_use OR ci_owned) AS covered), ` +
545
+ `r AS (SELECT n, o, row_number() OVER (PARTITION BY o ORDER BY n COLLATE "C") AS rn, ` +
546
+ `dense_rank() OVER (ORDER BY o COLLATE "C") AS orank FROM v), ` +
547
+ `x AS (SELECT n, o, orank FROM r WHERE rn = 1 AND orank <= ${MAX_HARNESS_OWNERS}) ` +
548
+ `SELECT t.total, t.owners, coalesce(encode(convert_to(x.n, 'UTF8'), 'hex'), ''), ` +
549
+ `coalesce(encode(convert_to(x.o, 'UTF8'), 'hex'), ''), t.used, t.ci, t.covered, t.total - t.covered FROM t LEFT JOIN x ON true ` +
550
+ `ORDER BY x.orank LIMIT ${MAX_HARNESS_OWNERS}`;
551
+ }
552
+ /**
553
+ * Parse the harness listing. Null on any malformed output: wrong field count, bad
554
+ * hex, a name outside the exact harness prefix, inconsistent totals, or an unsafe
555
+ * integer. Empty output is a successful count of zero. An owner that fails the role
556
+ * rule is dropped here too (defense in depth) and never returned.
557
+ */
558
+ export function parseHarnessListing(stdout) {
559
+ const lines = stdout.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
560
+ if (lines.length === 0)
561
+ return { count: 0, owners: [], ownerCount: 0 };
562
+ if (lines.length > MAX_HARNESS_OWNERS)
563
+ return null;
564
+ let total;
565
+ let ownerTotal;
566
+ const owners = new Set();
567
+ let coverage;
568
+ for (const line of lines) {
569
+ const fields = line.split("|");
570
+ if (fields.length !== 8)
571
+ return null;
572
+ const [totalText, ownersText, nameHex, ownerHex] = fields;
573
+ if (!/^\d{1,15}$/.test(totalText) || !/^\d{1,15}$/.test(ownersText))
574
+ return null;
575
+ const lineTotal = Number(totalText);
576
+ const lineOwners = Number(ownersText);
577
+ if (!Number.isSafeInteger(lineTotal) || !Number.isSafeInteger(lineOwners))
578
+ return null;
579
+ if (total !== undefined && (total !== lineTotal || ownerTotal !== lineOwners))
580
+ return null;
581
+ const counts = fields.slice(4);
582
+ if (counts.some((n) => !/^\d{1,15}$/.test(n)))
583
+ return null;
584
+ const [inUse, ciOwned, covered, uncovered] = counts.map(Number);
585
+ const parsed = sanitizeHarnessCoverage({ total: lineTotal, activity: "known", inUse, ciOwned, covered, uncovered });
586
+ if (!parsed || (coverage && JSON.stringify(coverage) !== JSON.stringify(parsed)))
587
+ return null;
588
+ coverage = parsed;
589
+ total = lineTotal;
590
+ ownerTotal = lineOwners;
591
+ if (!HEX_PATTERN.test(nameHex) || !HEX_PATTERN.test(ownerHex))
592
+ return null;
593
+ if (nameHex.length === 0 && ownerHex.length === 0)
594
+ continue;
595
+ if (nameHex.length === 0 || ownerHex.length === 0)
596
+ return null;
597
+ const name = Buffer.from(nameHex, "hex").toString("utf8");
598
+ if (!name.startsWith(HARNESS_DATABASE_PREFIX))
599
+ return null;
600
+ const owner = Buffer.from(ownerHex, "hex").toString("utf8");
601
+ if (Buffer.from(name, "utf8").toString("hex") !== nameHex ||
602
+ Buffer.from(owner, "utf8").toString("hex") !== ownerHex)
603
+ return null;
604
+ if (isValidHarnessOwnerRole(owner))
605
+ owners.add(owner);
606
+ }
607
+ if (total === undefined || ownerTotal === undefined)
608
+ return null;
609
+ if (ownerTotal > total || owners.size > ownerTotal)
610
+ return null;
611
+ const sorted = [...owners].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)).slice(0, MAX_HARNESS_OWNERS);
612
+ return { count: total, owners: sorted, ownerCount: ownerTotal, coverage };
613
+ }
497
614
  function singleDatabaseListingSql(name) {
498
615
  return `SELECT ${LISTING_COLUMNS} FROM pg_database WHERE datname = ${sqlLiteral(validateWorkerDatabaseName(name))}`;
499
616
  }
@@ -588,6 +705,28 @@ async function guardedDropWorkerDatabase(name, deps, budgetMs, signal) {
588
705
  function alembicFailureCategory(ctx, r) {
589
706
  return interruption(ctx, r) ?? (r.timedOut ? "timeout" : "migration_failed");
590
707
  }
708
+ /**
709
+ * Classify a failed Alembic subprocess into the closed cause vocabulary. Pure.
710
+ * Inspects only the first {@link MIGRATION_CAUSE_STDERR_BYTES} bytes of stderr for
711
+ * fixed phrases and returns a token — never any part of the input.
712
+ */
713
+ export function classifyWorkerDatabaseMigrationFailure(result) {
714
+ if (result.timedOut)
715
+ return "timeout";
716
+ const raw = typeof result.stderr === "string" ? result.stderr : "";
717
+ const text = Buffer.from(raw, "utf8").subarray(0, MIGRATION_CAUSE_STDERR_BYTES).toString("utf8").toLowerCase();
718
+ if (text.includes("multiple head revisions"))
719
+ return "multiple_heads";
720
+ if (text.includes("can't locate revision"))
721
+ return "revision_missing";
722
+ if (text.includes("server does not support ssl, but ssl was required"))
723
+ return "ssl_refused";
724
+ if (text.includes("connection refused") || text.includes("could not connect"))
725
+ return "connection_refused";
726
+ if (text.includes("permission denied") || text.includes("must be owner"))
727
+ return "permission_denied";
728
+ return "other";
729
+ }
591
730
  /**
592
731
  * The migration subprocess environment. BAPI-1521: delegated to the shared
593
732
  * builder so the compatibility-versus-declaration choice, and the declaration
@@ -622,19 +761,24 @@ export async function provisionWorkerDatabase(options, deps) {
622
761
  const reserve = Math.min(WORKER_DATABASE_DROP_BUDGET_MS, Math.floor(budgetMs / 4));
623
762
  const finalDeadline = start + budgetMs;
624
763
  const ctx = { deps, signal: options.signal, deadline: finalDeadline - reserve };
625
- const unavailable = (category, retainedName) => {
626
- deps.diagnostic?.(formatWorkerDatabaseUnavailableLine(options.jobId, category));
764
+ const unavailable = (category, retainedName, cause) => {
765
+ deps.diagnostic?.(formatWorkerDatabaseUnavailableLine(options.jobId, category, cause));
766
+ const result = { kind: "unavailable", category };
767
+ if (cause)
768
+ result.cause = cause;
627
769
  if (retainedName) {
628
770
  deps.diagnostic?.(formatWorkerDatabaseDropFailedLine(options.jobId, retainedName));
629
- return { kind: "unavailable", category, retainedName };
771
+ result.retainedName = retainedName;
630
772
  }
631
- return { kind: "unavailable", category };
773
+ return result;
632
774
  };
633
- const rollback = async (name, category) => {
775
+ const rollback = async (name, category, cause) => {
634
776
  // A small floor keeps a rollback possible even when a runner overshot its timeout.
635
777
  const rollbackBudget = Math.max(Math.min(reserve, 5_000), finalDeadline - deps.now(), 1);
636
778
  const outcome = await guardedDropWorkerDatabase(name, deps, rollbackBudget);
637
- return outcome.kind === "dropped" ? unavailable(category) : unavailable(category, name);
779
+ // A cancelled job was not a migration failure, so it carries no cause.
780
+ const kept = category === "cancelled" ? undefined : cause;
781
+ return outcome.kind === "dropped" ? unavailable(category, undefined, kept) : unavailable(category, name, kept);
638
782
  };
639
783
  if (options.signal?.aborted)
640
784
  return unavailable("cancelled");
@@ -699,21 +843,23 @@ export async function provisionWorkerDatabase(options, deps) {
699
843
  if (remaining(ctx) <= 0)
700
844
  return rollback(name, "timeout");
701
845
  const upgraded = await runAlembic(["-c", "alembic.ini", "upgrade", "head"]);
702
- if (!succeeded(upgraded))
703
- return rollback(name, alembicFailureCategory(ctx, upgraded));
846
+ if (!succeeded(upgraded)) {
847
+ return rollback(name, alembicFailureCategory(ctx, upgraded), classifyWorkerDatabaseMigrationFailure(upgraded));
848
+ }
704
849
  const outputs = [];
705
850
  for (const args of [["-c", "alembic.ini", "heads"], ["-c", "alembic.ini", "current"]]) {
706
851
  if (remaining(ctx) <= 0)
707
852
  return rollback(name, "timeout");
708
853
  const r = await runAlembic(args);
709
- if (!succeeded(r))
710
- return rollback(name, alembicFailureCategory(ctx, r));
854
+ if (!succeeded(r)) {
855
+ return rollback(name, alembicFailureCategory(ctx, r), classifyWorkerDatabaseMigrationFailure(r));
856
+ }
711
857
  outputs.push(r.stdout);
712
858
  }
713
859
  const heads = parseAlembicRevisions(outputs[0]);
714
860
  const current = parseAlembicRevisions(outputs[1]);
715
861
  if (!heads || heads.length !== 1 || !current || current.length !== 1 || heads[0] !== current[0]) {
716
- return rollback(name, "migration_failed");
862
+ return rollback(name, "migration_failed", heads && heads.length >= 2 ? "multiple_heads" : "other");
717
863
  }
718
864
  if (options.signal?.aborted)
719
865
  return rollback(name, "cancelled");
@@ -818,9 +964,94 @@ export async function sweepOrphanedWorkerDatabases(options, deps) {
818
964
  // Read-only inspection for doctor
819
965
  // ---------------------------------------------------------------------------
820
966
  /**
821
- * Doctor's worker-database rows. STRICTLY read-only: only SELECT statements and a
822
- * `bridgeapi` connection attempt — no CREATE, DROP, COMMENT, or session
823
- * termination, and no directory creation.
967
+ * The offline Alembic environment: the SAME shared construction as
968
+ * {@link buildAlembicEnv} but with the executor's sentinel database target and no
969
+ * ambient environment — no operator `DATABASE_URL`, `PG*`/`POSTGRES_*`
970
+ * credential, or unrelated secret. Only client-owned `PATH`/`HOME` are carried.
971
+ */
972
+ function buildOfflineAlembicEnv(deps) {
973
+ const env = buildExecutorBaseWorkerEnv({ PATH: deps.clientPath, HOME: deps.clientHome }, { legacyNotice: false });
974
+ delete env.BRIDGE_SKIP_PREPUSH;
975
+ delete env.MAX_MCP_OUTPUT_TOKENS;
976
+ return env;
977
+ }
978
+ /** Run one offline Alembic command and map interruption and failure to a row result. */
979
+ async function runOfflineAlembicStep(ctx, file, cwd, env, args) {
980
+ if (remaining(ctx) <= 0)
981
+ return { kind: "row", row: { state: "unsafe", cause: "timeout" } };
982
+ if (ctx.signal?.aborted)
983
+ return { kind: "row", row: { state: "unknown" } };
984
+ const r = await ctx.deps.runProcess({
985
+ file,
986
+ args,
987
+ cwd,
988
+ env,
989
+ timeoutMs: stepTimeout(ctx, WORKER_DATABASE_ALEMBIC_INSPECTION_STEP_TIMEOUT_MS),
990
+ signal: ctx.signal,
991
+ });
992
+ if (r.aborted || ctx.signal?.aborted || r.spawnFailed)
993
+ return { kind: "row", row: { state: "unknown" } };
994
+ if (r.timedOut)
995
+ return { kind: "row", row: { state: "unsafe", cause: "timeout" } };
996
+ if (r.exitCode === null)
997
+ return { kind: "row", row: { state: "unknown" } };
998
+ if (r.exitCode !== 0) {
999
+ return { kind: "row", row: { state: "unsafe", cause: classifyWorkerDatabaseMigrationFailure(r) } };
1000
+ }
1001
+ return { kind: "ok", stdout: r.stdout };
1002
+ }
1003
+ /**
1004
+ * The two offline Alembic checks: `heads` (one head?) and, only after that,
1005
+ * `upgrade base:head --sql` (does the whole chain render?). Argument arrays, `--sql`
1006
+ * (offline mode), and the controlled environment keep this read-only; the
1007
+ * guarantee rests on the repository's offline `env.py`, not on process-level
1008
+ * network isolation. Rendered SQL is discarded at once and never stored.
1009
+ */
1010
+ async function inspectOfflineAlembic(options, ctx) {
1011
+ const { deps } = ctx;
1012
+ let alembic;
1013
+ try {
1014
+ alembic = resolveRepositoryAlembicCommand(options.operatorRepositoryRoot, deps.platform);
1015
+ if (!(await deps.isExecutable(alembic)))
1016
+ return { state: "unsafe" };
1017
+ }
1018
+ catch {
1019
+ return { state: "unknown" };
1020
+ }
1021
+ try {
1022
+ const env = buildOfflineAlembicEnv(deps);
1023
+ const cwd = options.operatorRepositoryRoot;
1024
+ const heads = await runOfflineAlembicStep(ctx, alembic, cwd, env, ["-c", "alembic.ini", "heads"]);
1025
+ if (heads.kind === "row")
1026
+ return heads.row;
1027
+ const revisions = parseAlembicRevisions(heads.stdout);
1028
+ if (!revisions)
1029
+ return { state: "unsafe", cause: "other" };
1030
+ if (revisions.length >= 2)
1031
+ return { state: "unsafe", cause: "multiple_heads" };
1032
+ const rendered = await runOfflineAlembicStep(ctx, alembic, cwd, env, [
1033
+ "-c",
1034
+ "alembic.ini",
1035
+ "upgrade",
1036
+ "base:head",
1037
+ "--sql",
1038
+ ]);
1039
+ if (rendered.kind === "row")
1040
+ return rendered.row;
1041
+ return { state: "healthy" };
1042
+ }
1043
+ catch {
1044
+ return { state: "unknown" };
1045
+ }
1046
+ }
1047
+ /**
1048
+ * Doctor's worker-database rows. STRICTLY read-only: only SELECT statements, a
1049
+ * `bridgeapi` connection attempt, and exactly two offline Alembic commands —
1050
+ * `alembic -c alembic.ini heads` and `alembic -c alembic.ini upgrade base:head --sql`
1051
+ * (argument arrays, `--sql` offline render, controlled non-ambient environment,
1052
+ * run last) — no CREATE, DROP, COMMENT, or session termination, and no directory
1053
+ * creation. Alembic's read-only behavior relies on the repository's offline
1054
+ * `env.py`, not on process-level network isolation.
824
1055
  */
825
1056
  export async function inspectWorkerDatabaseReadiness(options, deps) {
826
1057
  const ctx = {
@@ -852,27 +1083,30 @@ export async function inspectWorkerDatabaseReadiness(options, deps) {
852
1083
  }
853
1084
  timings["worker-db-boundary"] = elapsedMs(started);
854
1085
  started = monotonicNow();
855
- let alembic;
856
- try {
857
- const exists = await deps.isExecutable(resolveRepositoryAlembicCommand(options.operatorRepositoryRoot, deps.platform));
858
- alembic = { state: exists ? "healthy" : "unsafe" };
859
- }
860
- catch {
861
- alembic = { state: "unknown" };
862
- }
863
- timings["worker-db-alembic"] = elapsedMs(started);
864
- started = monotonicNow();
865
1086
  let inventory = { state: "unknown" };
866
1087
  const listing = await listWorkerDatabases(ctx);
867
1088
  if (listing.kind === "ok") {
868
- const harness = await runPsql(deps, MAINTENANCE_DATABASE, HARNESS_COUNT_SQL, stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), options.signal);
869
- const harnessText = harness.stdout.trim();
870
- if (succeeded(harness) && /^\d+$/.test(harnessText)) {
1089
+ const harness = await runPsql(deps, MAINTENANCE_DATABASE, harnessListingSql(options.ciHarnessOwnerRole), stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), options.signal);
1090
+ let harnessListing = succeeded(harness) ? parseHarnessListing(harness.stdout) : null;
1091
+ // Only a failed activity request qualifies for fallback. Malformed successful
1092
+ // output remains unknown; never conceal it with an inventory retry.
1093
+ if (!succeeded(harness)) {
1094
+ const fallback = await runPsql(deps, MAINTENANCE_DATABASE, harnessListingSql(options.ciHarnessOwnerRole, false), stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), options.signal);
1095
+ harnessListing = succeeded(fallback) ? parseHarnessListing(fallback.stdout) : null;
1096
+ if (harnessListing)
1097
+ harnessListing.coverage = {
1098
+ total: harnessListing.count, activity: "unknown", inUse: null, ciOwned: harnessListing.coverage?.ciOwned ?? 0, covered: null, uncovered: null,
1099
+ };
1100
+ }
1101
+ if (harnessListing) {
871
1102
  const value = {
872
1103
  active: [],
873
1104
  leftovers: [],
874
1105
  unverifiable: [],
875
- harnessCount: Number(harnessText),
1106
+ harnessCount: harnessListing.count,
1107
+ harnessCoverage: harnessListing.coverage,
1108
+ harnessOwners: harnessListing.owners,
1109
+ harnessOwnerCount: harnessListing.ownerCount,
876
1110
  };
877
1111
  for (const entry of listing.rows) {
878
1112
  const ownership = classifyOwnership(entry, options.hostDigest);
@@ -894,6 +1128,10 @@ export async function inspectWorkerDatabaseReadiness(options, deps) {
894
1128
  const inventoryMs = elapsedMs(started);
895
1129
  for (const id of ["worker-db-leftovers", "worker-db-unverifiable", "worker-db-harness"])
896
1130
  timings[id] = inventoryMs;
1131
+ // Alembic is probed LAST so a slow or failing check can never cost the earlier rows.
1132
+ started = monotonicNow();
1133
+ const alembic = await inspectOfflineAlembic(options, ctx);
1134
+ timings["worker-db-alembic"] = elapsedMs(started);
897
1135
  return { role, boundary, alembic, inventory, timings };
898
1136
  }
899
1137
  // ---------------------------------------------------------------------------
@@ -908,14 +1146,16 @@ function safeJobIdForLog(jobId) {
908
1146
  * host operator and the runbook section; `bridgeapi_reachable` gets distinct
909
1147
  * wording because it is an unsafe boundary, not a missing prerequisite.
910
1148
  */
911
- export function formatWorkerDatabaseUnavailableLine(jobId, category) {
1149
+ export function formatWorkerDatabaseUnavailableLine(jobId, category, cause) {
912
1150
  const id = safeJobIdForLog(jobId);
913
1151
  if (category === "bridgeapi_reachable") {
914
1152
  return (`[executor] job ${id}: UNSAFE worker database boundary: the worker role can connect to bridgeapi; ` +
915
1153
  `no worker database was created; continuing with the sentinel database — host operator: see ${WORKER_DATABASE_RUNBOOK_SECTION}`);
916
1154
  }
917
1155
  const safeCategory = UNAVAILABLE_CATEGORIES.has(category) ? category : "unknown";
918
- return (`[executor] job ${id}: worker database unavailable (non-fatal): ${safeCategory}; ` +
1156
+ const remedy = cause === "ssl_refused" ? "; declare the repository’s required setting in worker_env" : "";
1157
+ const causeSuffix = isWorkerDatabaseMigrationCause(cause) ? ` (cause: ${cause})` : "";
1158
+ return (`[executor] job ${id}: worker database unavailable (non-fatal): ${safeCategory}${causeSuffix}${remedy}; ` +
919
1159
  `continuing with the sentinel database — host operator: see ${WORKER_DATABASE_RUNBOOK_SECTION}`);
920
1160
  }
921
1161
  /** The ONE bounded, non-fatal line for a teardown failure. */
@@ -518,7 +518,7 @@ const MAX_HOLD_BLOCKERS_IN_MESSAGE = 8;
518
518
  * worker HEAD equal to it; and an origin tip equal to both. Anything less is not
519
519
  * server confirmation, and the caller falls through to its existing checks.
520
520
  */
521
- function confirmedDeliveryHold(delivery, workerHeadSha, originSha) {
521
+ function confirmedDeliveryState(delivery, workerHeadSha, originSha) {
522
522
  if (!delivery || delivery.bound !== true || delivery.unavailable === true)
523
523
  return null;
524
524
  if (typeof delivery.attemptId !== "string" || !delivery.attemptId)
@@ -537,6 +537,26 @@ function confirmedDeliveryHold(delivery, workerHeadSha, originSha) {
537
537
  blockers: (delivery.blockers ?? []).map((b) => typeof b.step_id === "number" ? { kind: b.kind, step_id: b.step_id } : { kind: b.kind }),
538
538
  };
539
539
  }
540
+ /**
541
+ * BAPI-1563: the hold the server confirmed for THIS head, or null. Only an actual
542
+ * server hold outcome (`blocked`, `verification_failed`, `evidence_missing_or_stale`)
543
+ * is a hold. `awaiting_post_pr` and `complete` PERMIT publication and success, so
544
+ * they are never translated into a required-check or required-work failure here;
545
+ * a missing pull request is judged separately by {@link confirmedAwaitingWithoutPr}.
546
+ */
547
+ function confirmedDeliveryHold(delivery, workerHeadSha, originSha) {
548
+ const state = confirmedDeliveryState(delivery, workerHeadSha, originSha);
549
+ return state !== null && DELIVERY_HOLD_OUTCOMES.has(state.outcome) ? state : null;
550
+ }
551
+ /**
552
+ * BAPI-1426: an `awaiting_post_pr` attempt confirmed at THIS head. Its remaining
553
+ * work needs a pull request, so it is a hold only while none is attached. This is
554
+ * about the missing PR, not about verification: with a PR it is a success path.
555
+ */
556
+ function confirmedAwaitingWithoutPr(delivery, workerHeadSha, originSha) {
557
+ const state = confirmedDeliveryState(delivery, workerHeadSha, originSha);
558
+ return state !== null && state.outcome === "awaiting_post_pr" ? state : null;
559
+ }
540
560
  /**
541
561
  * BAPI-1426: the intentional checkpoint a managed ticket ends with when the
542
562
  * server holds its delivery. This is a `/fail`, never a success, and it never
@@ -547,7 +567,7 @@ function confirmedDeliveryHold(delivery, workerHeadSha, originSha) {
547
567
  * The message carries only public identifiers, the closed outcome token, a
548
568
  * truncated head, and blocker kinds with step ids — never evidence text.
549
569
  */
550
- function deliveryHoldFailure(job, branch, hold) {
570
+ function deliveryHoldFailure(job, branch, hold, observedPr) {
551
571
  const label = job.ticket_key ? `${job.ticket_key} (job ${job.id})` : `job ${job.id}`;
552
572
  const shown = hold.blockers.slice(0, MAX_HOLD_BLOCKERS_IN_MESSAGE);
553
573
  const blockerText = shown.length
@@ -567,8 +587,19 @@ function deliveryHoldFailure(job, branch, hold) {
567
587
  classification: "clean_exit",
568
588
  last_commit_sha: hold.preserved_head_sha,
569
589
  telemetry,
590
+ // BAPI-1563: a hold still reports the pull request the executor discovered.
591
+ ...(observedPr ? { observed_pr: observedPr } : {}),
570
592
  };
571
593
  }
594
+ /** BAPI-1563: the discovered pull request as a wire fact, or undefined when not fully known. */
595
+ function observedPrOf(pr) {
596
+ if (!pr.found || typeof pr.prNumber !== "number" || !Number.isInteger(pr.prNumber) || pr.prNumber <= 0) {
597
+ return undefined;
598
+ }
599
+ if (pr.headRefOid === null || !FULL_SHA_RE.test(pr.headRefOid) || pr.baseRef === null)
600
+ return undefined;
601
+ return { number: pr.prNumber, head_sha: pr.headRefOid, base_ref: pr.baseRef };
602
+ }
572
603
  /**
573
604
  * BAPI-1426: the delivery hold a finalization failure carries, or null. Read
574
605
  * from the failure's own structured marker, never from its message.
@@ -747,11 +778,32 @@ export async function validateWorkerFinalization(input) {
747
778
  // is attached, and before the attachment contract can call it missing.
748
779
  // BAPI-1516: a `ci_fix` is never a delivery hold, even when an outcome reaches
749
780
  // this seam directly; its success rests on the attachment contract below.
750
- const hold = job.job_type === "ci_fix"
751
- ? undefined
752
- : confirmedDeliveryHold(input.deliveryOutcome, trimmedHeadSha, remoteSha);
753
- if (hold && DELIVERY_HOLD_OUTCOMES.has(hold.outcome)) {
754
- return { ok: false, failure: deliveryHoldFailure(job, trimmedBranch, hold) };
781
+ const observedPr = observedPrOf(pr);
782
+ if (observedPr && input.onObservedPr) {
783
+ try {
784
+ input.onObservedPr({ number: observedPr.number, headSha: observedPr.head_sha, baseRef: observedPr.base_ref });
785
+ }
786
+ catch {
787
+ /* observational only */
788
+ }
789
+ }
790
+ // BAPI-1563: the verdict acted on is a FRESH one, read after the final head is
791
+ // proven on origin and the PR has been discovered. A failed or absent refresh
792
+ // keeps the earlier read; it never invents a verdict.
793
+ let deliveryOutcome = input.deliveryOutcome;
794
+ if (job.job_type !== "ci_fix" && input.refreshDeliveryOutcome) {
795
+ try {
796
+ const fresh = await input.refreshDeliveryOutcome();
797
+ if (fresh !== undefined)
798
+ deliveryOutcome = fresh;
799
+ }
800
+ catch {
801
+ /* keep the earlier read */
802
+ }
803
+ }
804
+ const hold = job.job_type === "ci_fix" ? null : confirmedDeliveryHold(deliveryOutcome, trimmedHeadSha, remoteSha);
805
+ if (hold) {
806
+ return { ok: false, failure: deliveryHoldFailure(job, trimmedBranch, hold, observedPr) };
755
807
  }
756
808
  let contract = evaluatePrContract(pr, trimmedHeadSha, covered);
757
809
  for (let attempt = 1; attempt < attempts && !contract.ok && contract.retryable; attempt++) {
@@ -761,12 +813,13 @@ export async function validateWorkerFinalization(input) {
761
813
  }
762
814
  // BAPI-1426: post-PR work needs a pull request. While neither the provider nor
763
815
  // the server shows one, a confirmed `awaiting_post_pr` attempt is a hold too.
816
+ const awaitingHold = job.job_type === "ci_fix" ? null : confirmedAwaitingWithoutPr(deliveryOutcome, trimmedHeadSha, remoteSha);
764
817
  if (!contract.ok &&
765
818
  contract.unverified !== true &&
766
819
  !pr.found &&
767
- hold?.outcome === "awaiting_post_pr" &&
768
- input.deliveryOutcome?.prNumber == null) {
769
- return { ok: false, failure: deliveryHoldFailure(job, trimmedBranch, hold) };
820
+ awaitingHold !== null &&
821
+ deliveryOutcome?.prNumber == null) {
822
+ return { ok: false, failure: deliveryHoldFailure(job, trimmedBranch, awaitingHold) };
770
823
  }
771
824
  if (!contract.ok && contract.unverified === true) {
772
825
  return {
@@ -784,6 +837,8 @@ export async function validateWorkerFinalization(input) {
784
837
  ok: true,
785
838
  prUrl: pr.url ?? undefined,
786
839
  prNumber: pr.prNumber,
840
+ // Only when a fresh assessment was requested, so the legacy success shape is unchanged.
841
+ ...(input.refreshDeliveryOutcome !== undefined && deliveryOutcome !== undefined ? { deliveryOutcome } : {}),
787
842
  // BAPI-1311: the verified origin tip — proven equal to the worker's HEAD above
788
843
  // whenever that HEAD was known. Only for a caller that asked for it.
789
844
  ...(input.exposePushedHead === true ? { pushedHeadSha: remoteSha } : {}),
@@ -111,6 +111,12 @@ export function renderWorkerGuardReason(category, family, form) {
111
111
  "made outside the worker. Do not run regenerate-plan or call its route; record the " +
112
112
  "step escalated with its reason and continue.");
113
113
  }
114
+ if (category === "operator-verb" && family === "acknowledge-gaps") {
115
+ return (`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). ` +
116
+ "Acknowledging the run's carried-gap list is the run owner's decision, made " +
117
+ "outside the worker. Do not run acknowledge-gaps or call its route; record what " +
118
+ "you could not verify in your phase result and continue.");
119
+ }
114
120
  if (category === "operator-verb") {
115
121
  return (`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). ` +
116
122
  "Resolving a verification hand-off is the run owner's decision, made outside the " +
@@ -1012,9 +1018,11 @@ function isClaudeWorkflowPrintLaunch(segment) {
1012
1018
  /**
1013
1019
  * The operator-only subcommands a worker may never run, and their route segments.
1014
1020
  * BAPI-1532 adds `regenerate-plan` beside `resolve-handoff`, with its own family so
1015
- * the denial names the verb that was attempted.
1021
+ * the denial names the verb that was attempted. BAPI-1562 adds `acknowledge-gaps`,
1022
+ * the owner's one acknowledgement of the run's carried-gap list (route segment
1023
+ * `/acknowledge-gaps`), the same way.
1016
1024
  */
1017
- const OPERATOR_ONLY_VERBS = ["resolve-handoff", "regenerate-plan"];
1025
+ const OPERATOR_ONLY_VERBS = ["resolve-handoff", "regenerate-plan", "acknowledge-gaps"];
1018
1026
  /** The packaged MCP-server package token after `npx` (any version suffix). */
1019
1027
  const BRIDGE_PACKAGE_TOKEN = /^@bridge_gpt\/mcp-server(?:@\S+)?$/;
1020
1028
  /** Package runners whose package argument launches the packaged CLI. */