@bridge_gpt/mcp-server 0.2.71 → 0.2.73

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 (198) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +22 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +7 -7
  5. package/build/bridge-permissions.js +31 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/ci-system-detection.js +50 -0
  9. package/build/ci-trigger-adapters.js +631 -0
  10. package/build/ci-trigger-install.js +106 -0
  11. package/build/claude-review-workflow.js +1 -1
  12. package/build/cli-help.js +6 -0
  13. package/build/codex-auto-recovery.js +126 -0
  14. package/build/codex-launcher-pin.js +33 -2
  15. package/build/codex-skill-adapter.js +5 -1
  16. package/build/command-host.js +33 -0
  17. package/build/commands.generated.js +7 -6
  18. package/build/conductor/bridge-api-client.js +1352 -50
  19. package/build/conductor/bring-up-facts.js +18 -5
  20. package/build/conductor/command-drift-production.js +42 -17
  21. package/build/conductor/command-drift.js +47 -0
  22. package/build/conductor/declare-blocked.js +554 -0
  23. package/build/conductor/doctor.js +187 -28
  24. package/build/conductor/driver-commands.js +141 -0
  25. package/build/conductor/driver-guard.js +277 -0
  26. package/build/conductor/driver-lapse.js +321 -0
  27. package/build/conductor/driver-register.js +176 -0
  28. package/build/conductor/driver-release.js +174 -0
  29. package/build/conductor/driver-session-state.js +315 -0
  30. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  31. package/build/conductor/epic-implementer-cli.js +213 -13
  32. package/build/conductor/epic-server-database.js +162 -0
  33. package/build/conductor/epic-server-guidance.js +278 -0
  34. package/build/conductor/epic-server-journal.js +239 -0
  35. package/build/conductor/epic-server-processes.js +324 -0
  36. package/build/conductor/epic-server-recipe.js +397 -0
  37. package/build/conductor/epic-server-runtime.js +1207 -0
  38. package/build/conductor/epic-server-sfcc.js +107 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +594 -0
  41. package/build/conductor/gate-discovery.js +281 -10
  42. package/build/conductor/gate-settings-review.js +525 -5
  43. package/build/conductor/git-hooks-uninstall.js +112 -0
  44. package/build/conductor/git-hooks.js +81 -15
  45. package/build/conductor/guided-repair.js +10 -1
  46. package/build/conductor/install-doctor.js +2 -4
  47. package/build/conductor/launch-need-probes.js +6 -53
  48. package/build/conductor/launch-plan.js +318 -121
  49. package/build/conductor/local-merge.js +12 -1
  50. package/build/conductor/merge-execution-contract.js +1 -1
  51. package/build/conductor/merged-child-check.js +2 -1
  52. package/build/conductor/prerequisite-inputs.js +1213 -0
  53. package/build/conductor/readiness-assessment.js +93 -0
  54. package/build/conductor/readiness-cli.js +30 -9
  55. package/build/conductor/readiness-prerequisites.js +77 -5
  56. package/build/conductor/readiness-sections.js +146 -126
  57. package/build/conductor/readiness.js +21 -3
  58. package/build/conductor/recovery-cli.js +236 -15
  59. package/build/conductor/recovery-operations.js +34 -4
  60. package/build/conductor/repair-contract.js +33 -0
  61. package/build/conductor/tools.js +36 -4
  62. package/build/conductor/wait-run-attention.js +115 -0
  63. package/build/conductor/wait-run-cli.js +300 -21
  64. package/build/conductor/worker-database-doctor-inspector.js +34 -2
  65. package/build/conductor/worker-setup-tally.js +27 -0
  66. package/build/credential-store.js +96 -21
  67. package/build/dependency-install-declarations.js +212 -0
  68. package/build/docs.generated.js +4 -4
  69. package/build/doctor.js +91 -8
  70. package/build/drive-epic-help.js +23 -4
  71. package/build/drive-epic.js +1841 -340
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +140 -0
  74. package/build/epic-capability-statement.js +107 -0
  75. package/build/epic-ci-workflow-drift.js +30 -15
  76. package/build/epic-ci-workflow-install.js +110 -42
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow.js +38 -12
  79. package/build/epic-implementer-bin.js +2184 -52
  80. package/build/epic-launch-context.js +607 -0
  81. package/build/epic-launch-profile.js +1 -1
  82. package/build/epic-server-record.js +273 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/cli.js +2 -0
  87. package/build/executor/completion-contract.js +24 -1
  88. package/build/executor/credentials.js +1 -1
  89. package/build/executor/delivery-observations.js +113 -0
  90. package/build/executor/delivery-outcome.js +30 -0
  91. package/build/executor/dependency-refresh-runner.js +132 -0
  92. package/build/executor/dependency-refresh.js +530 -0
  93. package/build/executor/deps.js +4 -0
  94. package/build/executor/env.js +119 -17
  95. package/build/executor/epic-server-context.js +141 -0
  96. package/build/executor/gate-qualification-job.js +127 -26
  97. package/build/executor/harness-coverage.js +19 -0
  98. package/build/executor/http-client.js +87 -6
  99. package/build/executor/index.js +2 -1
  100. package/build/executor/install-preflight.js +1 -1
  101. package/build/executor/job-runner.js +659 -87
  102. package/build/executor/likely-tests.js +94 -97
  103. package/build/executor/observation.js +8 -0
  104. package/build/executor/pre-pr-checks.js +363 -0
  105. package/build/executor/prompt-spec.js +127 -5
  106. package/build/executor/reconcile-overlap-job.js +5 -3
  107. package/build/executor/required-verification.js +28 -0
  108. package/build/executor/required-work-diagnostics.js +32 -0
  109. package/build/executor/required-work-ledger.js +955 -39
  110. package/build/executor/results.js +100 -0
  111. package/build/executor/service-discovery.js +42 -0
  112. package/build/executor/service-lifecycle.js +109 -2
  113. package/build/executor/service-uninstall.js +205 -0
  114. package/build/executor/service-unit.js +5 -3
  115. package/build/executor/terminal-mutation.js +8 -0
  116. package/build/executor/test-clock.js +3 -0
  117. package/build/executor/verification-hints.js +179 -0
  118. package/build/executor/worker-command.js +126 -5
  119. package/build/executor/worker-database-config.js +281 -0
  120. package/build/executor/worker-database-target.js +16 -12
  121. package/build/executor/worker-database.js +575 -116
  122. package/build/executor/worker-finalization.js +71 -10
  123. package/build/executor/worker-guard-hook.js +10 -2
  124. package/build/executor/worker-resources.js +25 -3
  125. package/build/executor/worker-verification-guidance.js +55 -5
  126. package/build/executor/worktree-inspection.js +42 -0
  127. package/build/executor/worktree.js +20 -1
  128. package/build/executor-launch.js +54 -2
  129. package/build/generated-assets-catalog.js +2 -2
  130. package/build/github-sign-in.js +1 -1
  131. package/build/index.js +1111 -381
  132. package/build/init.js +29 -14
  133. package/build/install-bridge-conductor-answers.js +465 -0
  134. package/build/install-bridge-conductor-apply.js +259 -0
  135. package/build/install-bridge-conductor-assessment.js +895 -0
  136. package/build/install-bridge-conductor-compact.js +161 -0
  137. package/build/install-bridge-conductor-contracts.js +63 -0
  138. package/build/install-bridge-conductor-gate.js +1383 -188
  139. package/build/install-bridge-conductor-setup.js +637 -92
  140. package/build/install-bridge-conductor.js +3163 -740
  141. package/build/install-bridge.js +601 -128
  142. package/build/install-maintenance.js +127 -0
  143. package/build/install-reexec.js +1 -1
  144. package/build/launcher-config-inspection.js +162 -1
  145. package/build/local-cleanup.js +59 -0
  146. package/build/mcp-grant-candidates.js +767 -0
  147. package/build/mcp-grant-doctor.js +63 -0
  148. package/build/mcp-grant.js +288 -0
  149. package/build/mcp-host-targets.js +8 -0
  150. package/build/mcp-identity.js +23 -0
  151. package/build/mcp-install-state.js +68 -2
  152. package/build/mcp-invoke.js +126 -13
  153. package/build/mcp-presets.js +107 -0
  154. package/build/mcp-provisioning.js +134 -2
  155. package/build/mcp-registration-doctor.js +31 -2
  156. package/build/mcp-server-invocation.js +6 -1
  157. package/build/merge-workflow-install.js +236 -111
  158. package/build/package-script-semantics.js +10 -0
  159. package/build/pipeline-utils.js +1 -1
  160. package/build/pipelines.generated.js +6 -6
  161. package/build/plan-discovery.js +97 -4
  162. package/build/plan-execution-ledger.js +248 -9
  163. package/build/plan-generation-io.js +262 -0
  164. package/build/plan-generation.js +424 -0
  165. package/build/plane/build-freshness.js +6 -1
  166. package/build/plane/cli.js +75 -9
  167. package/build/plane/plane-freshness.js +23 -7
  168. package/build/plane/preflight.js +50 -10
  169. package/build/plane/shutdown.js +19 -0
  170. package/build/plane/terminal-run-cleanup.js +23 -5
  171. package/build/plane/terminal-run-status.js +4 -0
  172. package/build/printed-remedy-commands.js +229 -15
  173. package/build/readiness-check.js +1 -1
  174. package/build/readiness-prerequisites.generated.js +311 -4
  175. package/build/readme.generated.js +1 -1
  176. package/build/repository-state-paths.js +38 -0
  177. package/build/repository-toolchains.js +50 -8
  178. package/build/run-unit-tests-launcher.js +8 -1
  179. package/build/setup-change-policy.js +32 -0
  180. package/build/setup-epic.js +1192 -198
  181. package/build/setup-progress.js +44 -0
  182. package/build/setup-question.js +180 -0
  183. package/build/start-tickets.js +4 -0
  184. package/build/test-command-detection.js +32 -88
  185. package/build/test-support/notes-fs.js +40 -0
  186. package/build/third-party-mcp-targets.js +30 -0
  187. package/build/ticket-delivery-enrollment.js +30 -8
  188. package/build/ticket-delivery-run-scope.js +128 -0
  189. package/build/upgrade-cli.js +85 -2
  190. package/build/v2-readiness-requirements.js +28 -1
  191. package/build/version.generated.js +3 -3
  192. package/build/worker-guard-hook-bin.js +2 -2
  193. package/build/worktrees.js +105 -0
  194. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  195. package/docs/EPIC-IMPLEMENTER.md +5 -0
  196. package/docs/epic-implementer/getting-started.md +42 -15
  197. package/docs/epic-implementer/self-hosting.md +14 -1
  198. package/package.json +2 -2
@@ -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).
@@ -11,7 +12,7 @@ import { monotonicNow, elapsedMs } from "../conductor/precheck-timings.js";
11
12
  * and `doctor.ts` consume.
12
13
  *
13
14
  * Client posture: every executor-side statement is one `psql` subprocess with an
14
- * explicit loopback target (`-h 127.0.0.1 -p 5432 -U bridge_epic_worker -d ...`),
15
+ * explicit loopback target (`-h 127.0.0.1 -p 5432 -U <configured role> -d ...`),
15
16
  * `-X -w`, and a REPLACING environment (`buildPsqlEnv`), so no ambient database
16
17
  * URL, password, service, `.pgpass`, or `.psqlrc` is ever used. Every
17
18
  * destructive statement passes through one guarded function that re-validates
@@ -20,13 +21,53 @@ import { monotonicNow, elapsedMs } from "../conductor/precheck-timings.js";
20
21
  import { spawn } from "node:child_process";
21
22
  import { randomBytes } from "node:crypto";
22
23
  import { constants as fsConstants } from "node:fs";
23
- import { access, mkdir } from "node:fs/promises";
24
+ import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
24
25
  import path from "node:path";
25
- import { parseAlembicRevisions, resolveRepositoryAlembicCommand } from "../plane/alembic-head.js";
26
+ import { parseAlembicRevisions } from "../plane/alembic-head.js";
26
27
  import { buildExecutorBaseWorkerEnv, hasWorkerEnvOption } from "./env.js";
27
- import { POSTGRES_IDENTIFIER_MAX_LENGTH, WORKER_DATABASE_HOST, WORKER_DATABASE_PORT, WORKER_DATABASE_PREFIX, WORKER_DATABASE_ROLE, isValidWorkerDatabaseName, validateWorkerDatabaseName, } from "./worker-database-target.js";
28
+ import { isWorkerDatabaseIdentifier, parseAlembicArgv, } from "./worker-database-config.js";
29
+ import { POSTGRES_IDENTIFIER_MAX_LENGTH, WORKER_DATABASE_HOST, WORKER_DATABASE_PORT, WORKER_DATABASE_PREFIX, isValidWorkerDatabaseName, validateWorkerDatabaseName, WorkerDatabaseNameError, } from "./worker-database-target.js";
28
30
  /** Runbook section every worker-database diagnostic points the host operator to. */
29
31
  export const WORKER_DATABASE_RUNBOOK_SECTION = "docs/claude/runbooks/local-db-safety.md#worker-databases";
32
+ /** File name of the marker under the executor state directory. */
33
+ export const WORKER_DATABASE_HOST_MARKER_FILE = "worker-database-provisioned.json";
34
+ /** The production marker. Holds `{"v":1,"role":"<role>"}` and nothing else. */
35
+ export function createFileWorkerDatabaseHostState(stateDir) {
36
+ const file = path.join(stateDir, WORKER_DATABASE_HOST_MARKER_FILE);
37
+ return {
38
+ async read() {
39
+ let text;
40
+ try {
41
+ text = await readFile(file, "utf8");
42
+ }
43
+ catch (error) {
44
+ return error.code === "ENOENT" ? { state: "absent" } : { state: "unreadable" };
45
+ }
46
+ try {
47
+ const value = JSON.parse(text);
48
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
49
+ const record = value;
50
+ if (Object.keys(record).sort().join(",") === "role,v" &&
51
+ record.v === 1 &&
52
+ isWorkerDatabaseIdentifier(record.role)) {
53
+ return { state: "present", role: record.role };
54
+ }
55
+ }
56
+ }
57
+ catch {
58
+ // fall through
59
+ }
60
+ return { state: "unreadable" };
61
+ },
62
+ async write(role) {
63
+ await mkdir(stateDir, { recursive: true, mode: 0o700 });
64
+ await writeFile(file, JSON.stringify({ v: 1, role }), { mode: 0o600 });
65
+ },
66
+ async clear() {
67
+ await rm(file, { force: true });
68
+ },
69
+ };
70
+ }
30
71
  export const WORKER_DATABASE_PROVISION_BUDGET_MS = 120_000;
31
72
  export const WORKER_DATABASE_DROP_BUDGET_MS = 20_000;
32
73
  export const WORKER_DATABASE_SWEEP_BUDGET_MS = 60_000;
@@ -45,8 +86,8 @@ export const WORKER_DATABASE_CLIENT_HOME_DIR = "pg-client-home";
45
86
  export const WORKER_DATABASE_METADATA_VERSION = 1;
46
87
  /** The maintenance database every executor-side statement connects to. */
47
88
  const MAINTENANCE_DATABASE = "postgres";
48
- /** The operational database the worker role must be refused on. */
49
- const OPERATIONAL_DATABASE = "bridgeapi";
89
+ /** Escape a validated identifier for use inside a regular expression. */
90
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
50
91
  /** The Python harness prefix; counted for doctor only, never a lifecycle candidate. */
51
92
  const HARNESS_DATABASE_PREFIX = "conductor_harness_";
52
93
  /** Bounded subprocess output captured by the default runner, per stream. */
@@ -64,6 +105,23 @@ const RANDOM_SUFFIX_PATTERN = /^[0-9a-f]{4,16}$/;
64
105
  const ISO_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
65
106
  const SAFE_JOB_ID_FOR_LOG = /^[A-Za-z0-9_-]{1,64}$/;
66
107
  const HEX_PATTERN = /^(?:[0-9a-f]{2})*$/;
108
+ const MIGRATION_CAUSES = new Set([
109
+ "multiple_heads",
110
+ "revision_missing",
111
+ "ssl_refused",
112
+ "connection_refused",
113
+ "permission_denied",
114
+ "timeout",
115
+ "other",
116
+ ]);
117
+ /** True only for a member of the closed {@link WorkerDatabaseMigrationCause} vocabulary. */
118
+ export function isWorkerDatabaseMigrationCause(value) {
119
+ return typeof value === "string" && MIGRATION_CAUSES.has(value);
120
+ }
121
+ /** Only this many leading bytes of stderr are ever inspected for a cause. */
122
+ const MIGRATION_CAUSE_STDERR_BYTES = 4_096;
123
+ /** Per-step cap for one offline Alembic inspection command (inside the stage budget). */
124
+ export const WORKER_DATABASE_ALEMBIC_INSPECTION_STEP_TIMEOUT_MS = 5_000;
67
125
  const UNAVAILABLE_CATEGORIES = new Set([
68
126
  "client_missing",
69
127
  "postgres_unavailable",
@@ -95,6 +153,7 @@ export function createDefaultWorkerDatabaseDeps(overrides) {
95
153
  platform: process.platform,
96
154
  clientHome: path.join(stateDir, WORKER_DATABASE_CLIENT_HOME_DIR),
97
155
  clientPath: typeof env.PATH === "string" && env.PATH.length > 0 ? env.PATH : "/usr/bin:/bin",
156
+ hostState: createFileWorkerDatabaseHostState(stateDir),
98
157
  ...rest,
99
158
  };
100
159
  }
@@ -253,7 +312,7 @@ export function buildPsqlEnv(deps) {
253
312
  };
254
313
  }
255
314
  /** The `psql` argument array: explicit loopback target, no psqlrc, never prompt. */
256
- export function buildPsqlArgs(database, sql) {
315
+ export function buildPsqlArgs(database, sql, role) {
257
316
  return [
258
317
  "-X",
259
318
  "-w",
@@ -267,17 +326,17 @@ export function buildPsqlArgs(database, sql) {
267
326
  "-p",
268
327
  WORKER_DATABASE_PORT,
269
328
  "-U",
270
- WORKER_DATABASE_ROLE,
329
+ role,
271
330
  "-d",
272
331
  database,
273
332
  "-c",
274
333
  sql,
275
334
  ];
276
335
  }
277
- function runPsql(deps, database, sql, timeoutMs, signal) {
336
+ function runPsql(deps, role, database, sql, timeoutMs, signal) {
278
337
  return deps.runProcess({
279
338
  file: "psql",
280
- args: buildPsqlArgs(database, sql),
339
+ args: buildPsqlArgs(database, sql, role),
281
340
  env: buildPsqlEnv(deps),
282
341
  timeoutMs: Math.max(1, timeoutMs),
283
342
  signal,
@@ -300,9 +359,11 @@ const succeeded = (r) => r.exitCode === 0 && !r.timedOut && !r.aborted && !r.spa
300
359
  * and the number of roles it is a MEMBER of. Running it as the role against
301
360
  * `postgres` is also the maintenance-connectivity proof.
302
361
  */
303
- const ROLE_INSPECTION_SQL = "SELECT r.rolcanlogin, r.rolcreatedb, r.rolsuper, r.rolcreaterole, r.rolreplication, r.rolbypassrls, " +
304
- "(SELECT count(*) FROM pg_auth_members m WHERE m.member = r.oid) " +
305
- `FROM pg_roles r WHERE r.rolname = ${sqlLiteral(WORKER_DATABASE_ROLE)}`;
362
+ function roleInspectionSql(role) {
363
+ return ("SELECT r.rolcanlogin, r.rolcreatedb, r.rolsuper, r.rolcreaterole, r.rolreplication, r.rolbypassrls, " +
364
+ "(SELECT count(*) FROM pg_auth_members m WHERE m.member = r.oid) " +
365
+ `FROM pg_roles r WHERE r.rolname = ${sqlLiteral(role)}`);
366
+ }
306
367
  function remaining(ctx) {
307
368
  return ctx.deadline - ctx.deps.now();
308
369
  }
@@ -322,11 +383,11 @@ function interruption(ctx, r) {
322
383
  * own fixed messages and the server's startup messages are matched; nothing here
323
384
  * is ever logged.
324
385
  */
325
- function classifyMaintenanceFailure(r) {
386
+ function classifyMaintenanceFailure(r, role) {
326
387
  if (r.spawnFailed)
327
388
  return "client_missing";
328
389
  const text = r.stderr;
329
- if (new RegExp(`role "${WORKER_DATABASE_ROLE}" does not exist`).test(text))
390
+ if (new RegExp(`role "${escapeRegExp(role)}" does not exist`).test(text))
330
391
  return "role_missing";
331
392
  if (/password authentication failed|no password supplied|authentication failed|pg_hba\.conf|permission denied for database "postgres"|is not permitted to log in/.test(text)) {
332
393
  return "role_misconfigured";
@@ -363,14 +424,14 @@ export function evaluateWorkerRoleRow(stdout) {
363
424
  return { kind: "ok" };
364
425
  }
365
426
  async function checkWorkerRole(ctx) {
366
- const r = await runPsql(ctx.deps, MAINTENANCE_DATABASE, ROLE_INSPECTION_SQL, stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), ctx.signal);
427
+ const r = await runPsql(ctx.deps, ctx.role, MAINTENANCE_DATABASE, roleInspectionSql(ctx.role), stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), ctx.signal);
367
428
  const interrupted = interruption(ctx, r);
368
429
  if (interrupted)
369
430
  return { kind: "unknown", category: interrupted };
370
431
  if (r.timedOut)
371
432
  return { kind: "unknown", category: "postgres_unavailable" };
372
433
  if (!succeeded(r)) {
373
- const category = classifyMaintenanceFailure(r);
434
+ const category = classifyMaintenanceFailure(r, ctx.role);
374
435
  return category === "role_missing" || category === "role_misconfigured"
375
436
  ? { kind: "unsafe", category }
376
437
  : { kind: "unknown", category };
@@ -378,40 +439,50 @@ async function checkWorkerRole(ctx) {
378
439
  return evaluateWorkerRoleRow(r.stdout);
379
440
  }
380
441
  /**
381
- * The recognized `bridgeapi` authorization denials, as `psql` prints them with
382
- * `LC_ALL=C`. A connection-startup failure carries no SQLSTATE in psql's output
383
- * (VERBOSITY does not apply before a session exists), so the message text is the
384
- * only representation available; the English text assumes the server's default
385
- * `lc_messages`. A localized server simply fails to match, which classifies as
386
- * `boundary_unknown` — the safe direction.
387
- * - 42501 insufficient_privilege: `FATAL: permission denied for database "bridgeapi"`
388
- * - 28000 an explicit pg_hba `reject` naming this host, role, AND `bridgeapi`.
442
+ * The recognized protected-database authorization denials, as `psql` prints them
443
+ * with `LC_ALL=C`. A connection-startup failure carries no SQLSTATE in psql's
444
+ * output (VERBOSITY does not apply before a session exists), so the message text
445
+ * is the only representation available; the English text assumes the server's
446
+ * default `lc_messages`. A localized server simply fails to match, which
447
+ * classifies as `boundary_unknown` — the safe direction.
448
+ * - 42501 insufficient_privilege: `FATAL: permission denied for database "<name>"`
449
+ * - 28000 an explicit pg_hba `reject` naming this host, role, AND the database.
389
450
  */
390
- const BRIDGEAPI_DENIAL_PATTERNS = [
391
- /FATAL:\s+permission denied for database "bridgeapi"(?=$|[\s.])/m,
392
- new RegExp(`FATAL:\\s+pg_hba\\.conf rejects connection for host "127\\.0\\.0\\.1", user "${WORKER_DATABASE_ROLE}", database "bridgeapi"(?=$|[\\s,.])`, "m"),
393
- ];
394
- /** Classify one `bridgeapi` probe. Only a recognized denial is proof of safety. */
395
- export function classifyBridgeapiProbe(r) {
451
+ function protectedDenialPatterns(role, database) {
452
+ const db = escapeRegExp(database);
453
+ return [
454
+ new RegExp(`FATAL:\\s+permission denied for database "${db}"(?=$|[\\s.])`, "m"),
455
+ new RegExp(`FATAL:\\s+pg_hba\\.conf rejects connection for host "127\\.0\\.0\\.1", user "${escapeRegExp(role)}", database "${db}"(?=$|[\\s,.])`, "m"),
456
+ ];
457
+ }
458
+ /** Classify one protected-database probe. Only a recognized denial is proof of safety. */
459
+ export function classifyProtectedDatabaseProbe(r, role, database) {
396
460
  if (r.spawnFailed || r.timedOut || r.aborted)
397
461
  return "unknown";
398
462
  if (r.exitCode === 0)
399
463
  return "reachable";
400
464
  if (r.exitCode === null)
401
465
  return "unknown";
402
- return BRIDGEAPI_DENIAL_PATTERNS.some((p) => p.test(r.stderr)) ? "denied" : "unknown";
466
+ return protectedDenialPatterns(role, database).some((p) => p.test(r.stderr)) ? "denied" : "unknown";
403
467
  }
404
- async function probeBridgeapi(ctx) {
405
- const r = await runPsql(ctx.deps, OPERATIONAL_DATABASE, "SELECT 1", stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), ctx.signal);
406
- const interrupted = interruption(ctx, r);
407
- if (interrupted)
408
- return { kind: "unknown", category: interrupted };
409
- const verdict = classifyBridgeapiProbe(r);
410
- if (verdict === "denied")
411
- return { kind: "ok" };
412
- if (verdict === "reachable")
413
- return { kind: "unsafe", category: "bridgeapi_reachable" };
414
- return { kind: "unknown", category: "boundary_unknown" };
468
+ /**
469
+ * Probe EVERY configured protected database. All must be denied; the first
470
+ * reachable one is unsafe, and the first unproven one is unknown. An empty list
471
+ * probes nothing.
472
+ */
473
+ async function probeProtectedDatabases(ctx, protectedDatabases) {
474
+ for (const database of protectedDatabases) {
475
+ const r = await runPsql(ctx.deps, ctx.role, database, "SELECT 1", stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), ctx.signal);
476
+ const interrupted = interruption(ctx, r);
477
+ if (interrupted)
478
+ return { kind: "unknown", category: interrupted };
479
+ const verdict = classifyProtectedDatabaseProbe(r, ctx.role, database);
480
+ if (verdict === "reachable")
481
+ return { kind: "unsafe", category: "bridgeapi_reachable" };
482
+ if (verdict !== "denied")
483
+ return { kind: "unknown", category: "boundary_unknown" };
484
+ }
485
+ return { kind: "ok" };
415
486
  }
416
487
  // ---------------------------------------------------------------------------
417
488
  // Names and ownership metadata
@@ -493,7 +564,106 @@ const LISTING_COLUMNS = "encode(convert_to(datname::text, 'UTF8'), 'hex'), " +
493
564
  "encode(convert_to(coalesce(shobj_description(oid, 'pg_database'), ''), 'UTF8'), 'hex')";
494
565
  const WORKER_LISTING_SQL = `SELECT ${LISTING_COLUMNS} FROM pg_database WHERE ${exactPrefixPredicate(WORKER_DATABASE_PREFIX)} ` +
495
566
  `ORDER BY datname LIMIT ${MAX_LISTED_DATABASES}`;
496
- const HARNESS_COUNT_SQL = `SELECT count(*) FROM pg_database WHERE ${exactPrefixPredicate(HARNESS_DATABASE_PREFIX)}`;
567
+ /** Most owners one harness listing returns (one representative database each). */
568
+ const MAX_HARNESS_OWNERS = 5;
569
+ /** A PostgreSQL role name the doctor and launch plan may display: ASCII, no whitespace or control characters. */
570
+ const HARNESS_OWNER_ROLE_PATTERN = /^[A-Za-z_][A-Za-z0-9_$-]{0,62}$/;
571
+ /** True only for a whole-string valid owner role name; nothing is trimmed into validity. */
572
+ export function isValidHarnessOwnerRole(value) {
573
+ return typeof value === "string" && HARNESS_OWNER_ROLE_PATTERN.test(value);
574
+ }
575
+ /**
576
+ * Harness databases with their owners. Totals are computed over the full set
577
+ * BEFORE the row limit: the exact database count, and the exact count of distinct
578
+ * VALID owners. The listing then ranks owners in byte order and returns one
579
+ * representative database per owner for the first five, so many databases owned
580
+ * by one role cannot hide another owner. Invalid owners are counted in the total
581
+ * only. Names and owners are hex-encoded so no separator or newline can split a
582
+ * row. At most five rows, far below the runner's capture limit.
583
+ */
584
+ /** Explicit CI-owner declaration is the authority; syntax validation alone grants nothing. */
585
+ export const HARNESS_CI_OWNER_ENV = "BAPI_HARNESS_CI_OWNER_ROLE";
586
+ function harnessListingSql(ciOwner, activity = true) {
587
+ const ci = isValidHarnessOwnerRole(ciOwner)
588
+ ? `pg_get_userbyid(datdba)::text = ${sqlLiteral(ciOwner)}` : "false";
589
+ const used = activity
590
+ ? "EXISTS (SELECT 1 FROM pg_stat_activity a WHERE a.datid = pg_database.oid AND a.backend_type = 'client backend')"
591
+ : "false";
592
+ 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 ` +
593
+ `WHERE ${exactPrefixPredicate(HARNESS_DATABASE_PREFIX)}), ` +
594
+ `v AS (SELECT n, o FROM h WHERE o ~ ${sqlLiteral(HARNESS_OWNER_ROLE_PATTERN.source)}), ` +
595
+ `t AS (SELECT (SELECT count(*) FROM h) AS total, (SELECT count(DISTINCT o) FROM v) AS owners, ` +
596
+ `(SELECT count(*) FROM h WHERE in_use) AS used, (SELECT count(*) FROM h WHERE ci_owned) AS ci, ` +
597
+ `(SELECT count(*) FROM h WHERE in_use OR ci_owned) AS covered), ` +
598
+ `r AS (SELECT n, o, row_number() OVER (PARTITION BY o ORDER BY n COLLATE "C") AS rn, ` +
599
+ `dense_rank() OVER (ORDER BY o COLLATE "C") AS orank FROM v), ` +
600
+ `x AS (SELECT n, o, orank FROM r WHERE rn = 1 AND orank <= ${MAX_HARNESS_OWNERS}) ` +
601
+ `SELECT t.total, t.owners, coalesce(encode(convert_to(x.n, 'UTF8'), 'hex'), ''), ` +
602
+ `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 ` +
603
+ `ORDER BY x.orank LIMIT ${MAX_HARNESS_OWNERS}`;
604
+ }
605
+ /**
606
+ * Parse the harness listing. Null on any malformed output: wrong field count, bad
607
+ * hex, a name outside the exact harness prefix, inconsistent totals, or an unsafe
608
+ * integer. Empty output is a successful count of zero. An owner that fails the role
609
+ * rule is dropped here too (defense in depth) and never returned.
610
+ */
611
+ export function parseHarnessListing(stdout) {
612
+ const lines = stdout.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
613
+ if (lines.length === 0)
614
+ return { count: 0, owners: [], ownerCount: 0 };
615
+ if (lines.length > MAX_HARNESS_OWNERS)
616
+ return null;
617
+ let total;
618
+ let ownerTotal;
619
+ const owners = new Set();
620
+ let coverage;
621
+ for (const line of lines) {
622
+ const fields = line.split("|");
623
+ if (fields.length !== 8)
624
+ return null;
625
+ const [totalText, ownersText, nameHex, ownerHex] = fields;
626
+ if (!/^\d{1,15}$/.test(totalText) || !/^\d{1,15}$/.test(ownersText))
627
+ return null;
628
+ const lineTotal = Number(totalText);
629
+ const lineOwners = Number(ownersText);
630
+ if (!Number.isSafeInteger(lineTotal) || !Number.isSafeInteger(lineOwners))
631
+ return null;
632
+ if (total !== undefined && (total !== lineTotal || ownerTotal !== lineOwners))
633
+ return null;
634
+ const counts = fields.slice(4);
635
+ if (counts.some((n) => !/^\d{1,15}$/.test(n)))
636
+ return null;
637
+ const [inUse, ciOwned, covered, uncovered] = counts.map(Number);
638
+ const parsed = sanitizeHarnessCoverage({ total: lineTotal, activity: "known", inUse, ciOwned, covered, uncovered });
639
+ if (!parsed || (coverage && JSON.stringify(coverage) !== JSON.stringify(parsed)))
640
+ return null;
641
+ coverage = parsed;
642
+ total = lineTotal;
643
+ ownerTotal = lineOwners;
644
+ if (!HEX_PATTERN.test(nameHex) || !HEX_PATTERN.test(ownerHex))
645
+ return null;
646
+ if (nameHex.length === 0 && ownerHex.length === 0)
647
+ continue;
648
+ if (nameHex.length === 0 || ownerHex.length === 0)
649
+ return null;
650
+ const name = Buffer.from(nameHex, "hex").toString("utf8");
651
+ if (!name.startsWith(HARNESS_DATABASE_PREFIX))
652
+ return null;
653
+ const owner = Buffer.from(ownerHex, "hex").toString("utf8");
654
+ if (Buffer.from(name, "utf8").toString("hex") !== nameHex ||
655
+ Buffer.from(owner, "utf8").toString("hex") !== ownerHex)
656
+ return null;
657
+ if (isValidHarnessOwnerRole(owner))
658
+ owners.add(owner);
659
+ }
660
+ if (total === undefined || ownerTotal === undefined)
661
+ return null;
662
+ if (ownerTotal > total || owners.size > ownerTotal)
663
+ return null;
664
+ const sorted = [...owners].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)).slice(0, MAX_HARNESS_OWNERS);
665
+ return { count: total, owners: sorted, ownerCount: ownerTotal, coverage };
666
+ }
497
667
  function singleDatabaseListingSql(name) {
498
668
  return `SELECT ${LISTING_COLUMNS} FROM pg_database WHERE datname = ${sqlLiteral(validateWorkerDatabaseName(name))}`;
499
669
  }
@@ -535,12 +705,12 @@ function classifyOwnership(entry, hostDigest) {
535
705
  return { kind: "same_host", metadata };
536
706
  }
537
707
  async function listWorkerDatabases(ctx) {
538
- const r = await runPsql(ctx.deps, MAINTENANCE_DATABASE, WORKER_LISTING_SQL, stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), ctx.signal);
708
+ const r = await runPsql(ctx.deps, ctx.role, MAINTENANCE_DATABASE, WORKER_LISTING_SQL, stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), ctx.signal);
539
709
  const interrupted = interruption(ctx, r);
540
710
  if (interrupted)
541
711
  return { kind: "unavailable", category: interrupted };
542
712
  if (!succeeded(r)) {
543
- return { kind: "unavailable", category: r.timedOut ? "postgres_unavailable" : classifyMaintenanceFailure(r) };
713
+ return { kind: "unavailable", category: r.timedOut ? "postgres_unavailable" : classifyMaintenanceFailure(r, ctx.role) };
544
714
  }
545
715
  const rows = parseListing(r.stdout);
546
716
  return rows ? { kind: "ok", rows } : { kind: "unavailable", category: "postgres_unavailable" };
@@ -565,18 +735,18 @@ function dropFailureCategory(r, signal) {
565
735
  * this connection and the server's own (superuser) workers, which a
566
736
  * least-privilege role may not signal (see `conductor_harness/db.py`). No retry.
567
737
  */
568
- async function guardedDropWorkerDatabase(name, deps, budgetMs, signal) {
738
+ async function guardedDropWorkerDatabase(name, role, deps, budgetMs, signal) {
569
739
  const validated = validateWorkerDatabaseName(name);
570
740
  const deadline = deps.now() + Math.max(1, budgetMs);
571
741
  const timeout = () => Math.max(1, deadline - deps.now());
572
742
  const terminateSql = "SELECT count(pg_terminate_backend(pid)) FROM pg_stat_activity " +
573
743
  `WHERE datname = ${sqlLiteral(validateWorkerDatabaseName(validated))} ` +
574
744
  "AND pid <> pg_backend_pid() AND backend_type = 'client backend'";
575
- const terminated = await runPsql(deps, MAINTENANCE_DATABASE, terminateSql, timeout(), signal);
745
+ const terminated = await runPsql(deps, role, MAINTENANCE_DATABASE, terminateSql, timeout(), signal);
576
746
  if (!succeeded(terminated))
577
747
  return { kind: "failed", category: dropFailureCategory(terminated, signal) };
578
748
  const dropSql = `DROP DATABASE IF EXISTS ${quoteWorkerIdentifier(validated)}`;
579
- const dropped = await runPsql(deps, MAINTENANCE_DATABASE, dropSql, timeout(), signal);
749
+ const dropped = await runPsql(deps, role, MAINTENANCE_DATABASE, dropSql, timeout(), signal);
580
750
  if (!succeeded(dropped))
581
751
  return { kind: "failed", category: dropFailureCategory(dropped, signal) };
582
752
  return { kind: "dropped" };
@@ -588,6 +758,28 @@ async function guardedDropWorkerDatabase(name, deps, budgetMs, signal) {
588
758
  function alembicFailureCategory(ctx, r) {
589
759
  return interruption(ctx, r) ?? (r.timedOut ? "timeout" : "migration_failed");
590
760
  }
761
+ /**
762
+ * Classify a failed Alembic subprocess into the closed cause vocabulary. Pure.
763
+ * Inspects only the first {@link MIGRATION_CAUSE_STDERR_BYTES} bytes of stderr for
764
+ * fixed phrases and returns a token — never any part of the input.
765
+ */
766
+ export function classifyWorkerDatabaseMigrationFailure(result) {
767
+ if (result.timedOut)
768
+ return "timeout";
769
+ const raw = typeof result.stderr === "string" ? result.stderr : "";
770
+ const text = Buffer.from(raw, "utf8").subarray(0, MIGRATION_CAUSE_STDERR_BYTES).toString("utf8").toLowerCase();
771
+ if (text.includes("multiple head revisions"))
772
+ return "multiple_heads";
773
+ if (text.includes("can't locate revision"))
774
+ return "revision_missing";
775
+ if (text.includes("server does not support ssl, but ssl was required"))
776
+ return "ssl_refused";
777
+ if (text.includes("connection refused") || text.includes("could not connect"))
778
+ return "connection_refused";
779
+ if (text.includes("permission denied") || text.includes("must be owner"))
780
+ return "permission_denied";
781
+ return "other";
782
+ }
591
783
  /**
592
784
  * The migration subprocess environment. BAPI-1521: delegated to the shared
593
785
  * builder so the compatibility-versus-declaration choice, and the declaration
@@ -595,8 +787,8 @@ function alembicFailureCategory(ctx, r) {
595
787
  * declaration can never name them), and only `PATH`/`HOME` are taken from the
596
788
  * client environment, as before.
597
789
  */
598
- function buildAlembicEnv(name, deps, workerEnvOption) {
599
- const env = buildExecutorBaseWorkerEnv({ PATH: deps.clientPath, HOME: deps.clientHome }, { workerDatabase: { name }, legacyNotice: false, ...workerEnvOption });
790
+ function buildAlembicEnv(name, config, deps, workerEnvOption) {
791
+ const env = buildExecutorBaseWorkerEnv({ PATH: deps.clientPath, HOME: deps.clientHome }, { workerDatabase: { name }, workerDatabaseConfig: config, legacyNotice: false, ...workerEnvOption });
600
792
  // Two worker-only switches the shared builder always sets; a migration never
601
793
  // needed them, and provisioning behavior is unchanged.
602
794
  delete env.BRIDGE_SKIP_PREPUSH;
@@ -604,9 +796,29 @@ function buildAlembicEnv(name, deps, workerEnvOption) {
604
796
  return env;
605
797
  }
606
798
  /**
607
- * Verify the worker role and the `bridgeapi` boundary, create and comment a
608
- * per-job database, and migrate it to the job worktree's head with the operator
609
- * checkout's Alembic. Every failure after creation drops what was created; a
799
+ * Resolve a migration launcher. A launcher containing a path separator resolves
800
+ * against the operator checkout and is probed for the executable bit; a bare
801
+ * name is left to the client `PATH`.
802
+ */
803
+ function resolveMigrationLauncher(launcher, operatorRepositoryRoot) {
804
+ if (!launcher.includes("/") && !launcher.includes("\\"))
805
+ return { file: launcher, probe: false };
806
+ return { file: path.resolve(operatorRepositoryRoot, launcher), probe: true };
807
+ }
808
+ /** Write the host-state marker once provisioning succeeds. A failed write never fails the job. */
809
+ async function recordProvisioned(deps, role) {
810
+ try {
811
+ await deps.hostState?.write(role);
812
+ }
813
+ catch {
814
+ // The marker only gates the startup sweep; a missed write must not cost a job its database.
815
+ }
816
+ }
817
+ /**
818
+ * Verify the worker role and every protected-database boundary, create and
819
+ * comment a per-job database, and migrate it with the declared migration command
820
+ * run in the job worktree. When `head_check` is `alembic`, the head is then
821
+ * verified with the same launcher and configuration option. Every failure after creation drops what was created; a
610
822
  * failed rollback reports `retainedName`. Emits exactly one bounded line through
611
823
  * `deps.diagnostic` on an unavailable result (plus the drop-failed line when a
612
824
  * database is retained), so callers must not log the same line again.
@@ -621,20 +833,27 @@ export async function provisionWorkerDatabase(options, deps) {
621
833
  const start = deps.now();
622
834
  const reserve = Math.min(WORKER_DATABASE_DROP_BUDGET_MS, Math.floor(budgetMs / 4));
623
835
  const finalDeadline = start + budgetMs;
624
- const ctx = { deps, signal: options.signal, deadline: finalDeadline - reserve };
625
- const unavailable = (category, retainedName) => {
626
- deps.diagnostic?.(formatWorkerDatabaseUnavailableLine(options.jobId, category));
836
+ const { config } = options;
837
+ const role = config.workerRole;
838
+ const ctx = { deps, role, signal: options.signal, deadline: finalDeadline - reserve };
839
+ const unavailable = (category, retainedName, cause) => {
840
+ deps.diagnostic?.(formatWorkerDatabaseUnavailableLine(options.jobId, category, cause));
841
+ const result = { kind: "unavailable", category };
842
+ if (cause)
843
+ result.cause = cause;
627
844
  if (retainedName) {
628
845
  deps.diagnostic?.(formatWorkerDatabaseDropFailedLine(options.jobId, retainedName));
629
- return { kind: "unavailable", category, retainedName };
846
+ result.retainedName = retainedName;
630
847
  }
631
- return { kind: "unavailable", category };
848
+ return result;
632
849
  };
633
- const rollback = async (name, category) => {
850
+ const rollback = async (name, category, cause) => {
634
851
  // A small floor keeps a rollback possible even when a runner overshot its timeout.
635
852
  const rollbackBudget = Math.max(Math.min(reserve, 5_000), finalDeadline - deps.now(), 1);
636
- const outcome = await guardedDropWorkerDatabase(name, deps, rollbackBudget);
637
- return outcome.kind === "dropped" ? unavailable(category) : unavailable(category, name);
853
+ const outcome = await guardedDropWorkerDatabase(name, role, deps, rollbackBudget);
854
+ // A cancelled job was not a migration failure, so it carries no cause.
855
+ const kept = category === "cancelled" ? undefined : cause;
856
+ return outcome.kind === "dropped" ? unavailable(category, undefined, kept) : unavailable(category, name, kept);
638
857
  };
639
858
  if (options.signal?.aborted)
640
859
  return unavailable("cancelled");
@@ -642,31 +861,36 @@ export async function provisionWorkerDatabase(options, deps) {
642
861
  return unavailable("create_failed");
643
862
  }
644
863
  // (a) role attributes and memberships — also the maintenance-connect proof.
645
- const role = await checkWorkerRole(ctx);
646
- if (role.kind !== "ok")
647
- return unavailable(role.category);
648
- // (b) the operational boundary.
649
- const boundary = await probeBridgeapi(ctx);
864
+ const roleCheck = await checkWorkerRole(ctx);
865
+ if (roleCheck.kind !== "ok")
866
+ return unavailable(roleCheck.category);
867
+ // (b) every protected database must refuse the worker role.
868
+ const boundary = await probeProtectedDatabases(ctx, config.protectedDatabases);
650
869
  if (boundary.kind !== "ok")
651
870
  return unavailable(boundary.category);
652
- // Alembic must exist before anything is created.
653
- const alembic = resolveRepositoryAlembicCommand(options.operatorRepositoryRoot, deps.platform);
654
- let alembicPresent = false;
655
- try {
656
- alembicPresent = await deps.isExecutable(alembic);
657
- }
658
- catch {
659
- alembicPresent = false;
871
+ // The migration launcher must exist before anything is created. A path-like
872
+ // launcher resolves against the operator checkout; a bare name is found on the
873
+ // client PATH at spawn time and cannot be probed here.
874
+ const migrate = config.migrateCommand;
875
+ const launcher = resolveMigrationLauncher(migrate.argv[0], options.operatorRepositoryRoot);
876
+ if (launcher.probe) {
877
+ let launcherPresent = false;
878
+ try {
879
+ launcherPresent = await deps.isExecutable(launcher.file);
880
+ }
881
+ catch {
882
+ launcherPresent = false;
883
+ }
884
+ if (!launcherPresent)
885
+ return unavailable("alembic_missing");
660
886
  }
661
- if (!alembicPresent)
662
- return unavailable("alembic_missing");
663
887
  // (c) create, then comment immediately.
664
888
  const name = buildWorkerDatabaseName(options.jobId, deps.randomSuffix());
665
889
  if (!name)
666
890
  return unavailable("create_failed");
667
891
  if (remaining(ctx) <= 0)
668
892
  return unavailable("timeout");
669
- const created = await runPsql(deps, MAINTENANCE_DATABASE, `CREATE DATABASE ${quoteWorkerIdentifier(name)}`, stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), options.signal);
893
+ const created = await runPsql(deps, role, MAINTENANCE_DATABASE, `CREATE DATABASE ${quoteWorkerIdentifier(name)}`, stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), options.signal);
670
894
  if (!succeeded(created)) {
671
895
  const interrupted = interruption(ctx, created);
672
896
  // exit 1 = the server rejected the statement (ON_ERROR_STOP): nothing exists.
@@ -683,41 +907,59 @@ export async function provisionWorkerDatabase(options, deps) {
683
907
  hostDigest: options.hostDigest,
684
908
  createdAt: new Date(deps.now()).toISOString(),
685
909
  });
686
- const commented = await runPsql(deps, MAINTENANCE_DATABASE, `COMMENT ON DATABASE ${quoteWorkerIdentifier(name)} IS ${sqlLiteral(metadata)}`, stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), options.signal);
910
+ const commented = await runPsql(deps, role, MAINTENANCE_DATABASE, `COMMENT ON DATABASE ${quoteWorkerIdentifier(name)} IS ${sqlLiteral(metadata)}`, stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), options.signal);
687
911
  if (!succeeded(commented))
688
912
  return rollback(name, interruption(ctx, commented) ?? "create_failed");
689
913
  // (d) migrate with the job worktree's migrations, then verify the head.
690
- const env = buildAlembicEnv(name, deps, hasWorkerEnvOption(options) ? { workerEnv: options.workerEnv } : {});
691
- const runAlembic = (args) => deps.runProcess({
692
- file: alembic,
693
- args,
914
+ const env = buildAlembicEnv(name, config, deps, hasWorkerEnvOption(options) ? { workerEnv: options.workerEnv } : {});
915
+ // Each command is capped by the configured per-command timeout and by what is
916
+ // left of the stage budget, whichever is smaller.
917
+ const commandCapMs = migrate.timeoutSeconds * 1000;
918
+ const runMigration = (args) => deps.runProcess({
919
+ file: launcher.file,
920
+ args: [...args],
694
921
  cwd: options.worktreePath,
695
922
  env,
696
- timeoutMs: stepTimeout(ctx, Number.MAX_SAFE_INTEGER),
923
+ timeoutMs: stepTimeout(ctx, commandCapMs),
697
924
  signal: options.signal,
698
925
  });
699
926
  if (remaining(ctx) <= 0)
700
927
  return rollback(name, "timeout");
701
- const upgraded = await runAlembic(["-c", "alembic.ini", "upgrade", "head"]);
702
- if (!succeeded(upgraded))
703
- return rollback(name, alembicFailureCategory(ctx, upgraded));
928
+ const upgraded = await runMigration(migrate.argv.slice(1));
929
+ if (!succeeded(upgraded)) {
930
+ return rollback(name, alembicFailureCategory(ctx, upgraded), classifyWorkerDatabaseMigrationFailure(upgraded));
931
+ }
932
+ // The head and offline-render checks are Alembic-specific: only an explicit
933
+ // `head_check: "alembic"` runs them, never a generic command.
934
+ const invocation = migrate.headCheck === "alembic" ? parseAlembicArgv(migrate.argv) : undefined;
935
+ if (migrate.headCheck === "alembic" && invocation === undefined)
936
+ return rollback(name, "migration_failed", "other");
937
+ if (invocation === undefined) {
938
+ if (options.signal?.aborted)
939
+ return rollback(name, "cancelled");
940
+ await recordProvisioned(deps, role);
941
+ return { kind: "provisioned", target: { name }, role };
942
+ }
943
+ const runAlembic = (args) => runMigration([...invocation.configArgs, ...args]);
704
944
  const outputs = [];
705
- for (const args of [["-c", "alembic.ini", "heads"], ["-c", "alembic.ini", "current"]]) {
945
+ for (const args of [["heads"], ["current"]]) {
706
946
  if (remaining(ctx) <= 0)
707
947
  return rollback(name, "timeout");
708
948
  const r = await runAlembic(args);
709
- if (!succeeded(r))
710
- return rollback(name, alembicFailureCategory(ctx, r));
949
+ if (!succeeded(r)) {
950
+ return rollback(name, alembicFailureCategory(ctx, r), classifyWorkerDatabaseMigrationFailure(r));
951
+ }
711
952
  outputs.push(r.stdout);
712
953
  }
713
954
  const heads = parseAlembicRevisions(outputs[0]);
714
955
  const current = parseAlembicRevisions(outputs[1]);
715
956
  if (!heads || heads.length !== 1 || !current || current.length !== 1 || heads[0] !== current[0]) {
716
- return rollback(name, "migration_failed");
957
+ return rollback(name, "migration_failed", heads && heads.length >= 2 ? "multiple_heads" : "other");
717
958
  }
718
959
  if (options.signal?.aborted)
719
960
  return rollback(name, "cancelled");
720
- return { kind: "provisioned", target: { name } };
961
+ await recordProvisioned(deps, role);
962
+ return { kind: "provisioned", target: { name }, role };
721
963
  }
722
964
  // ---------------------------------------------------------------------------
723
965
  // Teardown
@@ -729,9 +971,11 @@ export async function provisionWorkerDatabase(options, deps) {
729
971
  * the ownership comment in place for the next sweep or the operator, and emits
730
972
  * one bounded line through `deps.diagnostic`.
731
973
  */
732
- export async function dropWorkerDatabase(target, deps, options = {}) {
974
+ export async function dropWorkerDatabase(target, deps, options) {
733
975
  const name = validateWorkerDatabaseName(target?.name);
734
- const outcome = await guardedDropWorkerDatabase(name, deps, options.budgetMs ?? WORKER_DATABASE_DROP_BUDGET_MS, options.signal);
976
+ if (!isWorkerDatabaseIdentifier(options.role))
977
+ throw new Error("invalid worker database role");
978
+ const outcome = await guardedDropWorkerDatabase(name, options.role, deps, options.budgetMs ?? WORKER_DATABASE_DROP_BUDGET_MS, options.signal);
735
979
  if (outcome.kind === "dropped")
736
980
  return { kind: "dropped" };
737
981
  deps.diagnostic?.(formatWorkerDatabaseDropFailedLine(options.jobId ?? "unknown", name));
@@ -748,8 +992,11 @@ export async function dropWorkerDatabase(target, deps, options = {}) {
748
992
  * diagnostics: an unavailable sweep is routine on a host without the role.
749
993
  */
750
994
  export async function sweepOrphanedWorkerDatabases(options, deps) {
995
+ if (!isWorkerDatabaseIdentifier(options.role))
996
+ return { kind: "unavailable", category: "role_misconfigured" };
751
997
  const ctx = {
752
998
  deps,
999
+ role: options.role,
753
1000
  signal: options.signal,
754
1001
  deadline: deps.now() + Math.max(1, options.budgetMs ?? WORKER_DATABASE_SWEEP_BUDGET_MS),
755
1002
  };
@@ -786,7 +1033,7 @@ export async function sweepOrphanedWorkerDatabases(options, deps) {
786
1033
  break;
787
1034
  }
788
1035
  // Re-read the comment immediately before the destructive step.
789
- const reread = await runPsql(deps, MAINTENANCE_DATABASE, singleDatabaseListingSql(entry.name), stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), options.signal);
1036
+ const reread = await runPsql(deps, options.role, MAINTENANCE_DATABASE, singleDatabaseListingSql(entry.name), stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), options.signal);
790
1037
  if (!succeeded(reread)) {
791
1038
  incomplete = true;
792
1039
  break;
@@ -800,7 +1047,7 @@ export async function sweepOrphanedWorkerDatabases(options, deps) {
800
1047
  incomplete = true;
801
1048
  break;
802
1049
  }
803
- const outcome = await guardedDropWorkerDatabase(entry.name, deps, Math.min(WORKER_DATABASE_DROP_BUDGET_MS, remaining(ctx)), options.signal);
1050
+ const outcome = await guardedDropWorkerDatabase(entry.name, options.role, deps, Math.min(WORKER_DATABASE_DROP_BUDGET_MS, remaining(ctx)), options.signal);
804
1051
  if (outcome.kind === "dropped") {
805
1052
  dropped.push(entry.name);
806
1053
  }
@@ -818,13 +1065,115 @@ export async function sweepOrphanedWorkerDatabases(options, deps) {
818
1065
  // Read-only inspection for doctor
819
1066
  // ---------------------------------------------------------------------------
820
1067
  /**
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.
1068
+ * The offline Alembic environment: the SAME shared construction as
1069
+ * {@link buildAlembicEnv} but with the executor's sentinel database target and no
1070
+ * ambient environment — no operator `DATABASE_URL`, `PG*`/`POSTGRES_*`
1071
+ * credential, or unrelated secret. Only client-owned `PATH`/`HOME` are carried.
1072
+ */
1073
+ function buildOfflineAlembicEnv(deps, options) {
1074
+ const env = buildExecutorBaseWorkerEnv({ PATH: deps.clientPath, HOME: deps.clientHome }, {
1075
+ legacyNotice: false,
1076
+ workerDatabaseConfig: {
1077
+ mode: "disposable_postgres",
1078
+ workerRole: options.workerRole,
1079
+ protectedDatabases: options.protectedDatabases,
1080
+ envNames: options.envNames,
1081
+ },
1082
+ });
1083
+ delete env.BRIDGE_SKIP_PREPUSH;
1084
+ delete env.MAX_MCP_OUTPUT_TOKENS;
1085
+ return env;
1086
+ }
1087
+ /** Run one offline Alembic command and map interruption and failure to a row result. */
1088
+ async function runOfflineAlembicStep(ctx, file, cwd, env, args) {
1089
+ if (remaining(ctx) <= 0)
1090
+ return { kind: "row", row: { state: "unsafe", cause: "timeout" } };
1091
+ if (ctx.signal?.aborted)
1092
+ return { kind: "row", row: { state: "unknown" } };
1093
+ const r = await ctx.deps.runProcess({
1094
+ file,
1095
+ args,
1096
+ cwd,
1097
+ env,
1098
+ timeoutMs: stepTimeout(ctx, WORKER_DATABASE_ALEMBIC_INSPECTION_STEP_TIMEOUT_MS),
1099
+ signal: ctx.signal,
1100
+ });
1101
+ if (r.aborted || ctx.signal?.aborted || r.spawnFailed)
1102
+ return { kind: "row", row: { state: "unknown" } };
1103
+ if (r.timedOut)
1104
+ return { kind: "row", row: { state: "unsafe", cause: "timeout" } };
1105
+ if (r.exitCode === null)
1106
+ return { kind: "row", row: { state: "unknown" } };
1107
+ if (r.exitCode !== 0) {
1108
+ return { kind: "row", row: { state: "unsafe", cause: classifyWorkerDatabaseMigrationFailure(r) } };
1109
+ }
1110
+ return { kind: "ok", stdout: r.stdout };
1111
+ }
1112
+ /**
1113
+ * The two offline Alembic checks: `heads` (one head?) and, only after that,
1114
+ * `upgrade base:head --sql` (does the whole chain render?). Argument arrays, `--sql`
1115
+ * (offline mode), and the controlled environment keep this read-only; the
1116
+ * guarantee rests on the repository's offline `env.py`, not on process-level
1117
+ * network isolation. Rendered SQL is discarded at once and never stored.
1118
+ */
1119
+ async function inspectOfflineAlembic(options, ctx) {
1120
+ const { deps } = ctx;
1121
+ // Only an explicit Alembic `head_check` is inspected; the launcher and its
1122
+ // configuration option come from the declared command, not a hard-coded prefix.
1123
+ const invocation = options.migrateCommand?.headCheck === "alembic"
1124
+ ? parseAlembicArgv(options.migrateCommand.argv)
1125
+ : undefined;
1126
+ if (invocation === undefined)
1127
+ return { state: "unknown" };
1128
+ const launcher = resolveMigrationLauncher(invocation.launcher, options.operatorRepositoryRoot);
1129
+ const alembic = launcher.file;
1130
+ const configArgs = [...invocation.configArgs];
1131
+ try {
1132
+ if (launcher.probe && !(await deps.isExecutable(alembic)))
1133
+ return { state: "unsafe" };
1134
+ }
1135
+ catch {
1136
+ return { state: "unknown" };
1137
+ }
1138
+ try {
1139
+ const env = buildOfflineAlembicEnv(deps, options);
1140
+ const cwd = options.operatorRepositoryRoot;
1141
+ const heads = await runOfflineAlembicStep(ctx, alembic, cwd, env, [...configArgs, "heads"]);
1142
+ if (heads.kind === "row")
1143
+ return heads.row;
1144
+ const revisions = parseAlembicRevisions(heads.stdout);
1145
+ if (!revisions)
1146
+ return { state: "unsafe", cause: "other" };
1147
+ if (revisions.length >= 2)
1148
+ return { state: "unsafe", cause: "multiple_heads" };
1149
+ const rendered = await runOfflineAlembicStep(ctx, alembic, cwd, env, [
1150
+ ...configArgs,
1151
+ "upgrade",
1152
+ "base:head",
1153
+ "--sql",
1154
+ ]);
1155
+ if (rendered.kind === "row")
1156
+ return rendered.row;
1157
+ return { state: "healthy" };
1158
+ }
1159
+ catch {
1160
+ return { state: "unknown" };
1161
+ }
1162
+ }
1163
+ /**
1164
+ * Doctor's worker-database rows (or, with `scope: "launch"`, only the role and
1165
+ * boundary rows a launch advisory shows). STRICTLY read-only: only SELECT statements, a
1166
+ * connection attempt to each protected database, and exactly two offline Alembic
1167
+ * commands, only for a declared `head_check: "alembic"` — `<launcher> [-c <config>] heads`
1168
+ * and `<launcher> [-c <config>] upgrade base:head --sql` (argument arrays, `--sql` offline render, controlled non-ambient environment,
1169
+ * run last) — no CREATE, DROP, COMMENT, or session termination, and no directory
1170
+ * creation. Alembic's read-only behavior relies on the repository's offline
1171
+ * `env.py`, not on process-level network isolation.
824
1172
  */
825
1173
  export async function inspectWorkerDatabaseReadiness(options, deps) {
826
1174
  const ctx = {
827
1175
  deps,
1176
+ role: options.workerRole,
828
1177
  signal: options.signal,
829
1178
  deadline: deps.now() + Math.max(1, options.budgetMs ?? WORKER_DATABASE_SWEEP_BUDGET_MS),
830
1179
  };
@@ -844,35 +1193,43 @@ export async function inspectWorkerDatabaseReadiness(options, deps) {
844
1193
  boundary = { state: "unknown", category: "boundary_unknown" };
845
1194
  }
846
1195
  else {
847
- const b = await probeBridgeapi(ctx);
1196
+ const b = await probeProtectedDatabases(ctx, options.protectedDatabases);
848
1197
  boundary =
849
1198
  b.kind === "ok"
850
1199
  ? { state: "healthy" }
851
1200
  : { state: b.kind === "unsafe" ? "unsafe" : "unknown", category: b.category };
852
1201
  }
853
1202
  timings["worker-db-boundary"] = elapsedMs(started);
854
- started = monotonicNow();
855
- let alembic;
856
- try {
857
- const exists = await deps.isExecutable(resolveRepositoryAlembicCommand(options.operatorRepositoryRoot, deps.platform));
858
- alembic = { state: exists ? "healthy" : "unsafe" };
1203
+ // A launch advisory shows only the role and the boundary. The skipped probes
1204
+ // report the existing "unknown" state: they were not observed, never "healthy".
1205
+ if (options.scope === "launch") {
1206
+ return { role, boundary, alembic: { state: "unknown" }, inventory: { state: "unknown" }, timings };
859
1207
  }
860
- catch {
861
- alembic = { state: "unknown" };
862
- }
863
- timings["worker-db-alembic"] = elapsedMs(started);
864
1208
  started = monotonicNow();
865
1209
  let inventory = { state: "unknown" };
866
1210
  const listing = await listWorkerDatabases(ctx);
867
1211
  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)) {
1212
+ const harness = await runPsql(deps, options.workerRole, MAINTENANCE_DATABASE, harnessListingSql(options.ciHarnessOwnerRole), stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), options.signal);
1213
+ let harnessListing = succeeded(harness) ? parseHarnessListing(harness.stdout) : null;
1214
+ // Only a failed activity request qualifies for fallback. Malformed successful
1215
+ // output remains unknown; never conceal it with an inventory retry.
1216
+ if (!succeeded(harness)) {
1217
+ const fallback = await runPsql(deps, options.workerRole, MAINTENANCE_DATABASE, harnessListingSql(options.ciHarnessOwnerRole, false), stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), options.signal);
1218
+ harnessListing = succeeded(fallback) ? parseHarnessListing(fallback.stdout) : null;
1219
+ if (harnessListing)
1220
+ harnessListing.coverage = {
1221
+ total: harnessListing.count, activity: "unknown", inUse: null, ciOwned: harnessListing.coverage?.ciOwned ?? 0, covered: null, uncovered: null,
1222
+ };
1223
+ }
1224
+ if (harnessListing) {
871
1225
  const value = {
872
1226
  active: [],
873
1227
  leftovers: [],
874
1228
  unverifiable: [],
875
- harnessCount: Number(harnessText),
1229
+ harnessCount: harnessListing.count,
1230
+ harnessCoverage: harnessListing.coverage,
1231
+ harnessOwners: harnessListing.owners,
1232
+ harnessOwnerCount: harnessListing.ownerCount,
876
1233
  };
877
1234
  for (const entry of listing.rows) {
878
1235
  const ownership = classifyOwnership(entry, options.hostDigest);
@@ -894,6 +1251,10 @@ export async function inspectWorkerDatabaseReadiness(options, deps) {
894
1251
  const inventoryMs = elapsedMs(started);
895
1252
  for (const id of ["worker-db-leftovers", "worker-db-unverifiable", "worker-db-harness"])
896
1253
  timings[id] = inventoryMs;
1254
+ // Alembic is probed LAST so a slow or failing check can never cost the earlier rows.
1255
+ started = monotonicNow();
1256
+ const alembic = await inspectOfflineAlembic(options, ctx);
1257
+ timings["worker-db-alembic"] = elapsedMs(started);
897
1258
  return { role, boundary, alembic, inventory, timings };
898
1259
  }
899
1260
  // ---------------------------------------------------------------------------
@@ -908,14 +1269,16 @@ function safeJobIdForLog(jobId) {
908
1269
  * host operator and the runbook section; `bridgeapi_reachable` gets distinct
909
1270
  * wording because it is an unsafe boundary, not a missing prerequisite.
910
1271
  */
911
- export function formatWorkerDatabaseUnavailableLine(jobId, category) {
1272
+ export function formatWorkerDatabaseUnavailableLine(jobId, category, cause) {
912
1273
  const id = safeJobIdForLog(jobId);
913
1274
  if (category === "bridgeapi_reachable") {
914
- return (`[executor] job ${id}: UNSAFE worker database boundary: the worker role can connect to bridgeapi; ` +
1275
+ return (`[executor] job ${id}: UNSAFE worker database boundary: the worker role can connect to a protected database; ` +
915
1276
  `no worker database was created; continuing with the sentinel database — host operator: see ${WORKER_DATABASE_RUNBOOK_SECTION}`);
916
1277
  }
917
1278
  const safeCategory = UNAVAILABLE_CATEGORIES.has(category) ? category : "unknown";
918
- return (`[executor] job ${id}: worker database unavailable (non-fatal): ${safeCategory}; ` +
1279
+ const remedy = cause === "ssl_refused" ? "; declare the repository’s required setting in worker_env" : "";
1280
+ const causeSuffix = isWorkerDatabaseMigrationCause(cause) ? ` (cause: ${cause})` : "";
1281
+ return (`[executor] job ${id}: worker database unavailable (non-fatal): ${safeCategory}${causeSuffix}${remedy}; ` +
919
1282
  `continuing with the sentinel database — host operator: see ${WORKER_DATABASE_RUNBOOK_SECTION}`);
920
1283
  }
921
1284
  /** The ONE bounded, non-fatal line for a teardown failure. */
@@ -925,3 +1288,99 @@ export function formatWorkerDatabaseDropFailedLine(jobId, name) {
925
1288
  return (`[executor] job ${id}: ${subject} could not be dropped (non-fatal); its ownership comment is kept ` +
926
1289
  `for review — host operator: see ${WORKER_DATABASE_RUNBOOK_SECTION}`);
927
1290
  }
1291
+ // ---------------------------------------------------------------------------
1292
+ // BAPI-1546: guarded low-level primitives for the epic-server helper
1293
+ // ---------------------------------------------------------------------------
1294
+ //
1295
+ // The epic-server helper's optional per-turn databases use their OWN prefix, so
1296
+ // the executor's orphan sweep (which lists only the exact `bridge_worker_job_`
1297
+ // prefix above) never lists or drops one mid-turn. These primitives share the
1298
+ // role check, the loopback maintenance connection, the controlled client HOME,
1299
+ // and the terminate-then-drop path, but they never run Alembic: migration is the
1300
+ // helper recipe's own step. `provisionWorkerDatabase()` is not used by the helper.
1301
+ /** The epic-server helper's database prefix. Never the worker prefix. */
1302
+ export const EPIC_SERVER_DATABASE_PREFIX = "bridge_epic_server_";
1303
+ const EPIC_SERVER_DATABASE_NAME_PATTERN = /^bridge_epic_server_[a-z0-9_]+$/;
1304
+ /** True only for a whole, valid helper database name within PostgreSQL's identifier limit. */
1305
+ export function isValidEpicServerDatabaseName(name) {
1306
+ return typeof name === "string" && name.length <= 63 && EPIC_SERVER_DATABASE_NAME_PATTERN.test(name);
1307
+ }
1308
+ function quoteEpicServerIdentifier(name) {
1309
+ if (!isValidEpicServerDatabaseName(name))
1310
+ throw new WorkerDatabaseNameError();
1311
+ return `"${name}"`;
1312
+ }
1313
+ /**
1314
+ * Create a helper database and record its ownership comment immediately. A
1315
+ * failed comment drops the database again; `retained` is true only when that
1316
+ * rollback could not be confirmed.
1317
+ */
1318
+ export async function createEpicServerDatabase(name, role, comment, deps, budgetMs) {
1319
+ if (!isWorkerDatabaseIdentifier(role))
1320
+ return { kind: "failed", category: "role_misconfigured", retained: false };
1321
+ if (!isValidEpicServerDatabaseName(name) || comment.length > MAX_COMMENT_CHARS) {
1322
+ return { kind: "failed", category: "create_failed", retained: false };
1323
+ }
1324
+ const deadline = deps.now() + Math.max(1, budgetMs);
1325
+ const timeout = () => Math.max(1, Math.min(WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS, deadline - deps.now()));
1326
+ const created = await runPsql(deps, role, MAINTENANCE_DATABASE, `CREATE DATABASE ${quoteEpicServerIdentifier(name)}`, timeout());
1327
+ if (!succeeded(created)) {
1328
+ if (created.exitCode === 1 && !created.timedOut)
1329
+ return { kind: "failed", category: "create_failed", retained: false };
1330
+ if (created.spawnFailed || created.exitCode === 2)
1331
+ return { kind: "failed", category: "postgres_unavailable", retained: false };
1332
+ const dropped = await dropEpicServerDatabase(name, role, deps, Math.max(1, deadline - deps.now()));
1333
+ return { kind: "failed", category: created.timedOut ? "timeout" : "create_failed", retained: dropped.kind !== "ok" };
1334
+ }
1335
+ const commented = await runPsql(deps, role, MAINTENANCE_DATABASE, `COMMENT ON DATABASE ${quoteEpicServerIdentifier(name)} IS ${sqlLiteral(comment)}`, timeout());
1336
+ if (!succeeded(commented)) {
1337
+ const dropped = await dropEpicServerDatabase(name, role, deps, Math.max(1, deadline - deps.now()));
1338
+ return { kind: "failed", category: "create_failed", retained: dropped.kind !== "ok" };
1339
+ }
1340
+ return { kind: "ok" };
1341
+ }
1342
+ /** Terminate sessions on, then drop, exactly one valid helper database. */
1343
+ export async function dropEpicServerDatabase(name, role, deps, budgetMs) {
1344
+ if (!isWorkerDatabaseIdentifier(role))
1345
+ return { kind: "failed", category: "role_misconfigured", retained: true };
1346
+ if (!isValidEpicServerDatabaseName(name))
1347
+ return { kind: "failed", category: "drop_failed", retained: true };
1348
+ const deadline = deps.now() + Math.max(1, budgetMs);
1349
+ const timeout = () => Math.max(1, deadline - deps.now());
1350
+ const terminateSql = "SELECT count(pg_terminate_backend(pid)) FROM pg_stat_activity " +
1351
+ `WHERE datname = ${sqlLiteral(name)} AND pid <> pg_backend_pid() AND backend_type = 'client backend'`;
1352
+ const terminated = await runPsql(deps, role, MAINTENANCE_DATABASE, terminateSql, timeout());
1353
+ if (!succeeded(terminated))
1354
+ return { kind: "failed", category: dropFailureCategory(terminated, undefined) === "timeout" ? "timeout" : "drop_failed", retained: true };
1355
+ const dropped = await runPsql(deps, role, MAINTENANCE_DATABASE, `DROP DATABASE IF EXISTS ${quoteEpicServerIdentifier(name)}`, timeout());
1356
+ if (!succeeded(dropped))
1357
+ return { kind: "failed", category: dropped.timedOut ? "timeout" : "drop_failed", retained: true };
1358
+ return { kind: "ok" };
1359
+ }
1360
+ /** List helper databases (exact helper prefix only) with their comments. Read-only. */
1361
+ export async function listEpicServerDatabases(role, deps, budgetMs) {
1362
+ if (!isWorkerDatabaseIdentifier(role))
1363
+ return { kind: "unavailable" };
1364
+ const sql = `SELECT ${LISTING_COLUMNS} FROM pg_database WHERE ${exactPrefixPredicate(EPIC_SERVER_DATABASE_PREFIX)} ` +
1365
+ `ORDER BY datname LIMIT ${MAX_LISTED_DATABASES}`;
1366
+ const r = await runPsql(deps, role, MAINTENANCE_DATABASE, sql, Math.max(1, Math.min(WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS, budgetMs)));
1367
+ if (!succeeded(r))
1368
+ return { kind: "unavailable" };
1369
+ const rows = [];
1370
+ for (const raw of r.stdout.split(/\r?\n/)) {
1371
+ const line = raw.trim();
1372
+ if (line.length === 0)
1373
+ continue;
1374
+ const fields = line.split("|");
1375
+ if (fields.length !== 3)
1376
+ return { kind: "unavailable" };
1377
+ const [nameHex, hasComment, commentHex] = fields;
1378
+ if (!HEX_PATTERN.test(nameHex) || !HEX_PATTERN.test(commentHex))
1379
+ return { kind: "unavailable" };
1380
+ const name = Buffer.from(nameHex, "hex").toString("utf8");
1381
+ if (!isValidEpicServerDatabaseName(name))
1382
+ continue;
1383
+ rows.push({ name, comment: hasComment === "t" ? Buffer.from(commentHex, "hex").toString("utf8") : null });
1384
+ }
1385
+ return { kind: "ok", rows };
1386
+ }