@bridge_gpt/mcp-server 0.2.72 → 0.2.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +15 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-config.js +7 -1
  5. package/build/bridge-permissions.js +30 -0
  6. package/build/ci-system-detection.js +50 -0
  7. package/build/ci-trigger-adapters.js +631 -0
  8. package/build/ci-trigger-install.js +106 -0
  9. package/build/codex-launcher-pin.js +33 -2
  10. package/build/codex-skill-adapter.js +3 -1
  11. package/build/command-host.js +33 -0
  12. package/build/command-provisioning.js +4 -3
  13. package/build/commands.generated.js +7 -6
  14. package/build/conductor/bridge-api-client.js +867 -35
  15. package/build/conductor/bring-up-facts.js +18 -5
  16. package/build/conductor/command-drift-production.js +42 -17
  17. package/build/conductor/command-drift.js +48 -1
  18. package/build/conductor/declare-blocked.js +554 -0
  19. package/build/conductor/declared-extras.js +335 -0
  20. package/build/conductor/doctor.js +108 -21
  21. package/build/conductor/driver-commands.js +141 -0
  22. package/build/conductor/driver-guard.js +277 -0
  23. package/build/conductor/driver-lapse.js +321 -0
  24. package/build/conductor/driver-pass-output.js +104 -0
  25. package/build/conductor/driver-pass.js +571 -0
  26. package/build/conductor/driver-register.js +176 -0
  27. package/build/conductor/driver-release.js +174 -0
  28. package/build/conductor/driver-session-state.js +315 -0
  29. package/build/conductor/epic-branch-ci-inspection.js +281 -43
  30. package/build/conductor/epic-implementer-cli.js +199 -15
  31. package/build/conductor/epic-server-database.js +162 -0
  32. package/build/conductor/epic-server-guidance.js +278 -0
  33. package/build/conductor/epic-server-journal.js +239 -0
  34. package/build/conductor/epic-server-processes.js +324 -0
  35. package/build/conductor/epic-server-recipe.js +397 -0
  36. package/build/conductor/epic-server-runtime.js +1207 -0
  37. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  38. package/build/conductor/epic-server-sfcc.js +85 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +647 -0
  41. package/build/conductor/gate-discovery.js +196 -11
  42. package/build/conductor/gate-settings-review.js +261 -4
  43. package/build/conductor/launch-need-probes.js +6 -53
  44. package/build/conductor/launch-plan.js +313 -156
  45. package/build/conductor/prerequisite-inputs.js +879 -45
  46. package/build/conductor/readiness-assessment.js +16 -1
  47. package/build/conductor/readiness-cli.js +20 -9
  48. package/build/conductor/readiness-prerequisites.js +28 -9
  49. package/build/conductor/readiness-sections.js +133 -126
  50. package/build/conductor/readiness.js +1 -1
  51. package/build/conductor/recovery-cli.js +13 -2
  52. package/build/conductor/tools.js +6 -5
  53. package/build/conductor/wait-run-attention.js +2 -2
  54. package/build/conductor/wait-run-cli.js +208 -22
  55. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  56. package/build/conductor/worker-setup-tally.js +27 -0
  57. package/build/credential-delivery.js +280 -0
  58. package/build/credential-launch-safety.js +142 -0
  59. package/build/credential-materialization.js +91 -16
  60. package/build/credential-references-node-deps.js +29 -0
  61. package/build/credential-references.js +1394 -0
  62. package/build/credential-references.test-fixtures.js +211 -0
  63. package/build/credential-scan-conventions.js +145 -0
  64. package/build/credential-scan.js +517 -0
  65. package/build/credential-store.js +121 -1
  66. package/build/credentials-cli.js +252 -3
  67. package/build/dependency-install-declarations.js +102 -1
  68. package/build/docs.generated.js +10 -3
  69. package/build/doctor.js +95 -3
  70. package/build/drive-epic-help.js +21 -2
  71. package/build/drive-epic.js +2095 -375
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +157 -0
  74. package/build/epic-capability-statement.js +175 -0
  75. package/build/epic-ci-workflow-drift.js +77 -23
  76. package/build/epic-ci-workflow-install.js +137 -44
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow-v3.js +273 -0
  79. package/build/epic-ci-workflow.js +165 -18
  80. package/build/epic-implementer-bin.js +2204 -56
  81. package/build/epic-launch-context.js +702 -0
  82. package/build/epic-server-record.js +288 -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/completion-contract.js +8 -1
  87. package/build/executor/credential-delivery-step.js +168 -0
  88. package/build/executor/deps.js +3 -1
  89. package/build/executor/env.js +98 -23
  90. package/build/executor/epic-server-context.js +157 -0
  91. package/build/executor/gate-qualification-job.js +127 -26
  92. package/build/executor/guarded-fast-forward-push.js +13 -8
  93. package/build/executor/http-client.js +52 -5
  94. package/build/executor/job-runner.js +577 -81
  95. package/build/executor/observation.js +8 -0
  96. package/build/executor/permissions.js +85 -3
  97. package/build/executor/pre-pr-checks.js +363 -0
  98. package/build/executor/prompt-spec.js +149 -3
  99. package/build/executor/reconcile-overlap-job.js +5 -3
  100. package/build/executor/required-work-diagnostics.js +4 -2
  101. package/build/executor/required-work-ledger.js +936 -38
  102. package/build/executor/results.js +58 -0
  103. package/build/executor/terminal-mutation.js +8 -0
  104. package/build/executor/worker-command.js +72 -3
  105. package/build/executor/worker-database-config.js +281 -0
  106. package/build/executor/worker-database-target.js +16 -12
  107. package/build/executor/worker-database.js +320 -101
  108. package/build/executor/worker-finalization.js +7 -1
  109. package/build/executor/worker-resources.js +25 -3
  110. package/build/executor/worker-verification-guidance.js +18 -3
  111. package/build/executor/worktree.js +20 -1
  112. package/build/executor-launch.js +58 -4
  113. package/build/generated-assets-catalog.js +2 -2
  114. package/build/git-exclude-lock.js +187 -0
  115. package/build/index.js +824 -366
  116. package/build/init.js +26 -11
  117. package/build/install-bridge-conductor-answers.js +528 -0
  118. package/build/install-bridge-conductor-apply.js +288 -0
  119. package/build/install-bridge-conductor-assessment.js +1222 -0
  120. package/build/install-bridge-conductor-compact.js +186 -0
  121. package/build/install-bridge-conductor-contracts.js +72 -0
  122. package/build/install-bridge-conductor-gate.js +1312 -198
  123. package/build/install-bridge-conductor-setup.js +577 -83
  124. package/build/install-bridge-conductor.js +3381 -544
  125. package/build/install-bridge.js +280 -25
  126. package/build/install-doctor.js +38 -8
  127. package/build/install-maintenance.js +26 -3
  128. package/build/install-sfcc-detection.js +120 -0
  129. package/build/install-sfcc-setup.js +185 -0
  130. package/build/launcher-config-inspection.js +162 -1
  131. package/build/mcp-grant-candidates.js +779 -0
  132. package/build/mcp-grant-doctor.js +63 -0
  133. package/build/mcp-grant.js +288 -0
  134. package/build/mcp-host-targets.js +8 -0
  135. package/build/mcp-identity.js +23 -0
  136. package/build/mcp-invoke.js +292 -15
  137. package/build/mcp-presets.js +107 -0
  138. package/build/mcp-provisioning.js +155 -6
  139. package/build/mcp-registration-doctor.js +31 -2
  140. package/build/mcp-server-invocation.js +19 -1
  141. package/build/merge-workflow-install.js +243 -110
  142. package/build/pipelines.generated.js +7 -6
  143. package/build/plan-discovery.js +97 -4
  144. package/build/plan-execution-ledger.js +100 -7
  145. package/build/plan-generation-io.js +262 -0
  146. package/build/plan-generation.js +424 -0
  147. package/build/plane/build-freshness.js +6 -1
  148. package/build/plane/cli.js +75 -9
  149. package/build/plane/plane-freshness.js +17 -0
  150. package/build/plane/preflight.js +50 -10
  151. package/build/plane/shutdown.js +19 -0
  152. package/build/plane/status.js +8 -2
  153. package/build/plane/terminal-run-cleanup.js +18 -4
  154. package/build/printed-remedy-commands.js +211 -12
  155. package/build/project-root.js +40 -0
  156. package/build/readiness-check.js +77 -0
  157. package/build/readiness-prerequisites.generated.js +122 -14
  158. package/build/readme.generated.js +1 -1
  159. package/build/repository-state-paths.js +41 -0
  160. package/build/repository-toolchains.js +6 -3
  161. package/build/run-unit-tests-launcher.js +8 -1
  162. package/build/setup-epic.js +1305 -210
  163. package/build/setup-progress.js +44 -0
  164. package/build/setup-question.js +122 -4
  165. package/build/sfcc/credentials.js +3 -2
  166. package/build/sfcc/hostname.js +98 -2
  167. package/build/sfcc/tool-wrapper.js +6 -95
  168. package/build/start-tickets.js +193 -29
  169. package/build/test-support/executor-source-files.js +200 -0
  170. package/build/testing-config-client.js +25 -2
  171. package/build/third-party-mcp-targets.js +63 -2
  172. package/build/ticket-delivery-enrollment.js +9 -0
  173. package/build/upgrade-cli.js +85 -2
  174. package/build/v2-readiness-requirements.js +28 -1
  175. package/build/version.generated.js +3 -3
  176. package/build/with-credentials.js +208 -0
  177. package/build/worktree-credential-delivery.js +340 -0
  178. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  179. package/docs/epic-implementer/getting-started.md +3 -1
  180. package/docs/epic-implementer/self-hosting.md +14 -1
  181. package/package.json +2 -2
@@ -12,7 +12,7 @@ import { monotonicNow, elapsedMs } from "../conductor/precheck-timings.js";
12
12
  * and `doctor.ts` consume.
13
13
  *
14
14
  * Client posture: every executor-side statement is one `psql` subprocess with an
15
- * 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 ...`),
16
16
  * `-X -w`, and a REPLACING environment (`buildPsqlEnv`), so no ambient database
17
17
  * URL, password, service, `.pgpass`, or `.psqlrc` is ever used. Every
18
18
  * destructive statement passes through one guarded function that re-validates
@@ -21,13 +21,53 @@ import { monotonicNow, elapsedMs } from "../conductor/precheck-timings.js";
21
21
  import { spawn } from "node:child_process";
22
22
  import { randomBytes } from "node:crypto";
23
23
  import { constants as fsConstants } from "node:fs";
24
- import { access, mkdir } from "node:fs/promises";
24
+ import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
25
25
  import path from "node:path";
26
- import { parseAlembicRevisions, resolveRepositoryAlembicCommand } from "../plane/alembic-head.js";
26
+ import { parseAlembicRevisions } from "../plane/alembic-head.js";
27
27
  import { buildExecutorBaseWorkerEnv, hasWorkerEnvOption } from "./env.js";
28
- 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";
29
30
  /** Runbook section every worker-database diagnostic points the host operator to. */
30
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
+ }
31
71
  export const WORKER_DATABASE_PROVISION_BUDGET_MS = 120_000;
32
72
  export const WORKER_DATABASE_DROP_BUDGET_MS = 20_000;
33
73
  export const WORKER_DATABASE_SWEEP_BUDGET_MS = 60_000;
@@ -46,8 +86,8 @@ export const WORKER_DATABASE_CLIENT_HOME_DIR = "pg-client-home";
46
86
  export const WORKER_DATABASE_METADATA_VERSION = 1;
47
87
  /** The maintenance database every executor-side statement connects to. */
48
88
  const MAINTENANCE_DATABASE = "postgres";
49
- /** The operational database the worker role must be refused on. */
50
- const OPERATIONAL_DATABASE = "bridgeapi";
89
+ /** Escape a validated identifier for use inside a regular expression. */
90
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
51
91
  /** The Python harness prefix; counted for doctor only, never a lifecycle candidate. */
52
92
  const HARNESS_DATABASE_PREFIX = "conductor_harness_";
53
93
  /** Bounded subprocess output captured by the default runner, per stream. */
@@ -113,6 +153,7 @@ export function createDefaultWorkerDatabaseDeps(overrides) {
113
153
  platform: process.platform,
114
154
  clientHome: path.join(stateDir, WORKER_DATABASE_CLIENT_HOME_DIR),
115
155
  clientPath: typeof env.PATH === "string" && env.PATH.length > 0 ? env.PATH : "/usr/bin:/bin",
156
+ hostState: createFileWorkerDatabaseHostState(stateDir),
116
157
  ...rest,
117
158
  };
118
159
  }
@@ -271,7 +312,7 @@ export function buildPsqlEnv(deps) {
271
312
  };
272
313
  }
273
314
  /** The `psql` argument array: explicit loopback target, no psqlrc, never prompt. */
274
- export function buildPsqlArgs(database, sql) {
315
+ export function buildPsqlArgs(database, sql, role) {
275
316
  return [
276
317
  "-X",
277
318
  "-w",
@@ -285,17 +326,17 @@ export function buildPsqlArgs(database, sql) {
285
326
  "-p",
286
327
  WORKER_DATABASE_PORT,
287
328
  "-U",
288
- WORKER_DATABASE_ROLE,
329
+ role,
289
330
  "-d",
290
331
  database,
291
332
  "-c",
292
333
  sql,
293
334
  ];
294
335
  }
295
- function runPsql(deps, database, sql, timeoutMs, signal) {
336
+ function runPsql(deps, role, database, sql, timeoutMs, signal) {
296
337
  return deps.runProcess({
297
338
  file: "psql",
298
- args: buildPsqlArgs(database, sql),
339
+ args: buildPsqlArgs(database, sql, role),
299
340
  env: buildPsqlEnv(deps),
300
341
  timeoutMs: Math.max(1, timeoutMs),
301
342
  signal,
@@ -318,9 +359,11 @@ const succeeded = (r) => r.exitCode === 0 && !r.timedOut && !r.aborted && !r.spa
318
359
  * and the number of roles it is a MEMBER of. Running it as the role against
319
360
  * `postgres` is also the maintenance-connectivity proof.
320
361
  */
321
- const ROLE_INSPECTION_SQL = "SELECT r.rolcanlogin, r.rolcreatedb, r.rolsuper, r.rolcreaterole, r.rolreplication, r.rolbypassrls, " +
322
- "(SELECT count(*) FROM pg_auth_members m WHERE m.member = r.oid) " +
323
- `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
+ }
324
367
  function remaining(ctx) {
325
368
  return ctx.deadline - ctx.deps.now();
326
369
  }
@@ -340,11 +383,11 @@ function interruption(ctx, r) {
340
383
  * own fixed messages and the server's startup messages are matched; nothing here
341
384
  * is ever logged.
342
385
  */
343
- function classifyMaintenanceFailure(r) {
386
+ function classifyMaintenanceFailure(r, role) {
344
387
  if (r.spawnFailed)
345
388
  return "client_missing";
346
389
  const text = r.stderr;
347
- if (new RegExp(`role "${WORKER_DATABASE_ROLE}" does not exist`).test(text))
390
+ if (new RegExp(`role "${escapeRegExp(role)}" does not exist`).test(text))
348
391
  return "role_missing";
349
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)) {
350
393
  return "role_misconfigured";
@@ -381,14 +424,14 @@ export function evaluateWorkerRoleRow(stdout) {
381
424
  return { kind: "ok" };
382
425
  }
383
426
  async function checkWorkerRole(ctx) {
384
- 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);
385
428
  const interrupted = interruption(ctx, r);
386
429
  if (interrupted)
387
430
  return { kind: "unknown", category: interrupted };
388
431
  if (r.timedOut)
389
432
  return { kind: "unknown", category: "postgres_unavailable" };
390
433
  if (!succeeded(r)) {
391
- const category = classifyMaintenanceFailure(r);
434
+ const category = classifyMaintenanceFailure(r, ctx.role);
392
435
  return category === "role_missing" || category === "role_misconfigured"
393
436
  ? { kind: "unsafe", category }
394
437
  : { kind: "unknown", category };
@@ -396,40 +439,50 @@ async function checkWorkerRole(ctx) {
396
439
  return evaluateWorkerRoleRow(r.stdout);
397
440
  }
398
441
  /**
399
- * The recognized `bridgeapi` authorization denials, as `psql` prints them with
400
- * `LC_ALL=C`. A connection-startup failure carries no SQLSTATE in psql's output
401
- * (VERBOSITY does not apply before a session exists), so the message text is the
402
- * only representation available; the English text assumes the server's default
403
- * `lc_messages`. A localized server simply fails to match, which classifies as
404
- * `boundary_unknown` — the safe direction.
405
- * - 42501 insufficient_privilege: `FATAL: permission denied for database "bridgeapi"`
406
- * - 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.
407
450
  */
408
- const BRIDGEAPI_DENIAL_PATTERNS = [
409
- /FATAL:\s+permission denied for database "bridgeapi"(?=$|[\s.])/m,
410
- new RegExp(`FATAL:\\s+pg_hba\\.conf rejects connection for host "127\\.0\\.0\\.1", user "${WORKER_DATABASE_ROLE}", database "bridgeapi"(?=$|[\\s,.])`, "m"),
411
- ];
412
- /** Classify one `bridgeapi` probe. Only a recognized denial is proof of safety. */
413
- 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) {
414
460
  if (r.spawnFailed || r.timedOut || r.aborted)
415
461
  return "unknown";
416
462
  if (r.exitCode === 0)
417
463
  return "reachable";
418
464
  if (r.exitCode === null)
419
465
  return "unknown";
420
- 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";
421
467
  }
422
- async function probeBridgeapi(ctx) {
423
- const r = await runPsql(ctx.deps, OPERATIONAL_DATABASE, "SELECT 1", stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), ctx.signal);
424
- const interrupted = interruption(ctx, r);
425
- if (interrupted)
426
- return { kind: "unknown", category: interrupted };
427
- const verdict = classifyBridgeapiProbe(r);
428
- if (verdict === "denied")
429
- return { kind: "ok" };
430
- if (verdict === "reachable")
431
- return { kind: "unsafe", category: "bridgeapi_reachable" };
432
- 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" };
433
486
  }
434
487
  // ---------------------------------------------------------------------------
435
488
  // Names and ownership metadata
@@ -652,12 +705,12 @@ function classifyOwnership(entry, hostDigest) {
652
705
  return { kind: "same_host", metadata };
653
706
  }
654
707
  async function listWorkerDatabases(ctx) {
655
- 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);
656
709
  const interrupted = interruption(ctx, r);
657
710
  if (interrupted)
658
711
  return { kind: "unavailable", category: interrupted };
659
712
  if (!succeeded(r)) {
660
- return { kind: "unavailable", category: r.timedOut ? "postgres_unavailable" : classifyMaintenanceFailure(r) };
713
+ return { kind: "unavailable", category: r.timedOut ? "postgres_unavailable" : classifyMaintenanceFailure(r, ctx.role) };
661
714
  }
662
715
  const rows = parseListing(r.stdout);
663
716
  return rows ? { kind: "ok", rows } : { kind: "unavailable", category: "postgres_unavailable" };
@@ -682,18 +735,18 @@ function dropFailureCategory(r, signal) {
682
735
  * this connection and the server's own (superuser) workers, which a
683
736
  * least-privilege role may not signal (see `conductor_harness/db.py`). No retry.
684
737
  */
685
- async function guardedDropWorkerDatabase(name, deps, budgetMs, signal) {
738
+ async function guardedDropWorkerDatabase(name, role, deps, budgetMs, signal) {
686
739
  const validated = validateWorkerDatabaseName(name);
687
740
  const deadline = deps.now() + Math.max(1, budgetMs);
688
741
  const timeout = () => Math.max(1, deadline - deps.now());
689
742
  const terminateSql = "SELECT count(pg_terminate_backend(pid)) FROM pg_stat_activity " +
690
743
  `WHERE datname = ${sqlLiteral(validateWorkerDatabaseName(validated))} ` +
691
744
  "AND pid <> pg_backend_pid() AND backend_type = 'client backend'";
692
- const terminated = await runPsql(deps, MAINTENANCE_DATABASE, terminateSql, timeout(), signal);
745
+ const terminated = await runPsql(deps, role, MAINTENANCE_DATABASE, terminateSql, timeout(), signal);
693
746
  if (!succeeded(terminated))
694
747
  return { kind: "failed", category: dropFailureCategory(terminated, signal) };
695
748
  const dropSql = `DROP DATABASE IF EXISTS ${quoteWorkerIdentifier(validated)}`;
696
- const dropped = await runPsql(deps, MAINTENANCE_DATABASE, dropSql, timeout(), signal);
749
+ const dropped = await runPsql(deps, role, MAINTENANCE_DATABASE, dropSql, timeout(), signal);
697
750
  if (!succeeded(dropped))
698
751
  return { kind: "failed", category: dropFailureCategory(dropped, signal) };
699
752
  return { kind: "dropped" };
@@ -734,8 +787,8 @@ export function classifyWorkerDatabaseMigrationFailure(result) {
734
787
  * declaration can never name them), and only `PATH`/`HOME` are taken from the
735
788
  * client environment, as before.
736
789
  */
737
- function buildAlembicEnv(name, deps, workerEnvOption) {
738
- 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 });
739
792
  // Two worker-only switches the shared builder always sets; a migration never
740
793
  // needed them, and provisioning behavior is unchanged.
741
794
  delete env.BRIDGE_SKIP_PREPUSH;
@@ -743,9 +796,29 @@ function buildAlembicEnv(name, deps, workerEnvOption) {
743
796
  return env;
744
797
  }
745
798
  /**
746
- * Verify the worker role and the `bridgeapi` boundary, create and comment a
747
- * per-job database, and migrate it to the job worktree's head with the operator
748
- * 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
749
822
  * failed rollback reports `retainedName`. Emits exactly one bounded line through
750
823
  * `deps.diagnostic` on an unavailable result (plus the drop-failed line when a
751
824
  * database is retained), so callers must not log the same line again.
@@ -760,7 +833,9 @@ export async function provisionWorkerDatabase(options, deps) {
760
833
  const start = deps.now();
761
834
  const reserve = Math.min(WORKER_DATABASE_DROP_BUDGET_MS, Math.floor(budgetMs / 4));
762
835
  const finalDeadline = start + budgetMs;
763
- const ctx = { deps, signal: options.signal, deadline: finalDeadline - reserve };
836
+ const { config } = options;
837
+ const role = config.workerRole;
838
+ const ctx = { deps, role, signal: options.signal, deadline: finalDeadline - reserve };
764
839
  const unavailable = (category, retainedName, cause) => {
765
840
  deps.diagnostic?.(formatWorkerDatabaseUnavailableLine(options.jobId, category, cause));
766
841
  const result = { kind: "unavailable", category };
@@ -775,7 +850,7 @@ export async function provisionWorkerDatabase(options, deps) {
775
850
  const rollback = async (name, category, cause) => {
776
851
  // A small floor keeps a rollback possible even when a runner overshot its timeout.
777
852
  const rollbackBudget = Math.max(Math.min(reserve, 5_000), finalDeadline - deps.now(), 1);
778
- const outcome = await guardedDropWorkerDatabase(name, deps, rollbackBudget);
853
+ const outcome = await guardedDropWorkerDatabase(name, role, deps, rollbackBudget);
779
854
  // A cancelled job was not a migration failure, so it carries no cause.
780
855
  const kept = category === "cancelled" ? undefined : cause;
781
856
  return outcome.kind === "dropped" ? unavailable(category, undefined, kept) : unavailable(category, name, kept);
@@ -786,31 +861,36 @@ export async function provisionWorkerDatabase(options, deps) {
786
861
  return unavailable("create_failed");
787
862
  }
788
863
  // (a) role attributes and memberships — also the maintenance-connect proof.
789
- const role = await checkWorkerRole(ctx);
790
- if (role.kind !== "ok")
791
- return unavailable(role.category);
792
- // (b) the operational boundary.
793
- 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);
794
869
  if (boundary.kind !== "ok")
795
870
  return unavailable(boundary.category);
796
- // Alembic must exist before anything is created.
797
- const alembic = resolveRepositoryAlembicCommand(options.operatorRepositoryRoot, deps.platform);
798
- let alembicPresent = false;
799
- try {
800
- alembicPresent = await deps.isExecutable(alembic);
801
- }
802
- catch {
803
- 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");
804
886
  }
805
- if (!alembicPresent)
806
- return unavailable("alembic_missing");
807
887
  // (c) create, then comment immediately.
808
888
  const name = buildWorkerDatabaseName(options.jobId, deps.randomSuffix());
809
889
  if (!name)
810
890
  return unavailable("create_failed");
811
891
  if (remaining(ctx) <= 0)
812
892
  return unavailable("timeout");
813
- 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);
814
894
  if (!succeeded(created)) {
815
895
  const interrupted = interruption(ctx, created);
816
896
  // exit 1 = the server rejected the statement (ON_ERROR_STOP): nothing exists.
@@ -827,27 +907,42 @@ export async function provisionWorkerDatabase(options, deps) {
827
907
  hostDigest: options.hostDigest,
828
908
  createdAt: new Date(deps.now()).toISOString(),
829
909
  });
830
- 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);
831
911
  if (!succeeded(commented))
832
912
  return rollback(name, interruption(ctx, commented) ?? "create_failed");
833
913
  // (d) migrate with the job worktree's migrations, then verify the head.
834
- const env = buildAlembicEnv(name, deps, hasWorkerEnvOption(options) ? { workerEnv: options.workerEnv } : {});
835
- const runAlembic = (args) => deps.runProcess({
836
- file: alembic,
837
- 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],
838
921
  cwd: options.worktreePath,
839
922
  env,
840
- timeoutMs: stepTimeout(ctx, Number.MAX_SAFE_INTEGER),
923
+ timeoutMs: stepTimeout(ctx, commandCapMs),
841
924
  signal: options.signal,
842
925
  });
843
926
  if (remaining(ctx) <= 0)
844
927
  return rollback(name, "timeout");
845
- const upgraded = await runAlembic(["-c", "alembic.ini", "upgrade", "head"]);
928
+ const upgraded = await runMigration(migrate.argv.slice(1));
846
929
  if (!succeeded(upgraded)) {
847
930
  return rollback(name, alembicFailureCategory(ctx, upgraded), classifyWorkerDatabaseMigrationFailure(upgraded));
848
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]);
849
944
  const outputs = [];
850
- for (const args of [["-c", "alembic.ini", "heads"], ["-c", "alembic.ini", "current"]]) {
945
+ for (const args of [["heads"], ["current"]]) {
851
946
  if (remaining(ctx) <= 0)
852
947
  return rollback(name, "timeout");
853
948
  const r = await runAlembic(args);
@@ -863,7 +958,8 @@ export async function provisionWorkerDatabase(options, deps) {
863
958
  }
864
959
  if (options.signal?.aborted)
865
960
  return rollback(name, "cancelled");
866
- return { kind: "provisioned", target: { name } };
961
+ await recordProvisioned(deps, role);
962
+ return { kind: "provisioned", target: { name }, role };
867
963
  }
868
964
  // ---------------------------------------------------------------------------
869
965
  // Teardown
@@ -875,9 +971,11 @@ export async function provisionWorkerDatabase(options, deps) {
875
971
  * the ownership comment in place for the next sweep or the operator, and emits
876
972
  * one bounded line through `deps.diagnostic`.
877
973
  */
878
- export async function dropWorkerDatabase(target, deps, options = {}) {
974
+ export async function dropWorkerDatabase(target, deps, options) {
879
975
  const name = validateWorkerDatabaseName(target?.name);
880
- 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);
881
979
  if (outcome.kind === "dropped")
882
980
  return { kind: "dropped" };
883
981
  deps.diagnostic?.(formatWorkerDatabaseDropFailedLine(options.jobId ?? "unknown", name));
@@ -894,8 +992,11 @@ export async function dropWorkerDatabase(target, deps, options = {}) {
894
992
  * diagnostics: an unavailable sweep is routine on a host without the role.
895
993
  */
896
994
  export async function sweepOrphanedWorkerDatabases(options, deps) {
995
+ if (!isWorkerDatabaseIdentifier(options.role))
996
+ return { kind: "unavailable", category: "role_misconfigured" };
897
997
  const ctx = {
898
998
  deps,
999
+ role: options.role,
899
1000
  signal: options.signal,
900
1001
  deadline: deps.now() + Math.max(1, options.budgetMs ?? WORKER_DATABASE_SWEEP_BUDGET_MS),
901
1002
  };
@@ -932,7 +1033,7 @@ export async function sweepOrphanedWorkerDatabases(options, deps) {
932
1033
  break;
933
1034
  }
934
1035
  // Re-read the comment immediately before the destructive step.
935
- 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);
936
1037
  if (!succeeded(reread)) {
937
1038
  incomplete = true;
938
1039
  break;
@@ -946,7 +1047,7 @@ export async function sweepOrphanedWorkerDatabases(options, deps) {
946
1047
  incomplete = true;
947
1048
  break;
948
1049
  }
949
- 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);
950
1051
  if (outcome.kind === "dropped") {
951
1052
  dropped.push(entry.name);
952
1053
  }
@@ -969,8 +1070,16 @@ export async function sweepOrphanedWorkerDatabases(options, deps) {
969
1070
  * ambient environment — no operator `DATABASE_URL`, `PG*`/`POSTGRES_*`
970
1071
  * credential, or unrelated secret. Only client-owned `PATH`/`HOME` are carried.
971
1072
  */
972
- function buildOfflineAlembicEnv(deps) {
973
- const env = buildExecutorBaseWorkerEnv({ PATH: deps.clientPath, HOME: deps.clientHome }, { legacyNotice: false });
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
+ });
974
1083
  delete env.BRIDGE_SKIP_PREPUSH;
975
1084
  delete env.MAX_MCP_OUTPUT_TOKENS;
976
1085
  return env;
@@ -1009,19 +1118,27 @@ async function runOfflineAlembicStep(ctx, file, cwd, env, args) {
1009
1118
  */
1010
1119
  async function inspectOfflineAlembic(options, ctx) {
1011
1120
  const { deps } = ctx;
1012
- let alembic;
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];
1013
1131
  try {
1014
- alembic = resolveRepositoryAlembicCommand(options.operatorRepositoryRoot, deps.platform);
1015
- if (!(await deps.isExecutable(alembic)))
1132
+ if (launcher.probe && !(await deps.isExecutable(alembic)))
1016
1133
  return { state: "unsafe" };
1017
1134
  }
1018
1135
  catch {
1019
1136
  return { state: "unknown" };
1020
1137
  }
1021
1138
  try {
1022
- const env = buildOfflineAlembicEnv(deps);
1139
+ const env = buildOfflineAlembicEnv(deps, options);
1023
1140
  const cwd = options.operatorRepositoryRoot;
1024
- const heads = await runOfflineAlembicStep(ctx, alembic, cwd, env, ["-c", "alembic.ini", "heads"]);
1141
+ const heads = await runOfflineAlembicStep(ctx, alembic, cwd, env, [...configArgs, "heads"]);
1025
1142
  if (heads.kind === "row")
1026
1143
  return heads.row;
1027
1144
  const revisions = parseAlembicRevisions(heads.stdout);
@@ -1030,8 +1147,7 @@ async function inspectOfflineAlembic(options, ctx) {
1030
1147
  if (revisions.length >= 2)
1031
1148
  return { state: "unsafe", cause: "multiple_heads" };
1032
1149
  const rendered = await runOfflineAlembicStep(ctx, alembic, cwd, env, [
1033
- "-c",
1034
- "alembic.ini",
1150
+ ...configArgs,
1035
1151
  "upgrade",
1036
1152
  "base:head",
1037
1153
  "--sql",
@@ -1045,10 +1161,11 @@ async function inspectOfflineAlembic(options, ctx) {
1045
1161
  }
1046
1162
  }
1047
1163
  /**
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,
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,
1052
1169
  * run last) — no CREATE, DROP, COMMENT, or session termination, and no directory
1053
1170
  * creation. Alembic's read-only behavior relies on the repository's offline
1054
1171
  * `env.py`, not on process-level network isolation.
@@ -1056,6 +1173,7 @@ async function inspectOfflineAlembic(options, ctx) {
1056
1173
  export async function inspectWorkerDatabaseReadiness(options, deps) {
1057
1174
  const ctx = {
1058
1175
  deps,
1176
+ role: options.workerRole,
1059
1177
  signal: options.signal,
1060
1178
  deadline: deps.now() + Math.max(1, options.budgetMs ?? WORKER_DATABASE_SWEEP_BUDGET_MS),
1061
1179
  };
@@ -1075,23 +1193,28 @@ export async function inspectWorkerDatabaseReadiness(options, deps) {
1075
1193
  boundary = { state: "unknown", category: "boundary_unknown" };
1076
1194
  }
1077
1195
  else {
1078
- const b = await probeBridgeapi(ctx);
1196
+ const b = await probeProtectedDatabases(ctx, options.protectedDatabases);
1079
1197
  boundary =
1080
1198
  b.kind === "ok"
1081
1199
  ? { state: "healthy" }
1082
1200
  : { state: b.kind === "unsafe" ? "unsafe" : "unknown", category: b.category };
1083
1201
  }
1084
1202
  timings["worker-db-boundary"] = elapsedMs(started);
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 };
1207
+ }
1085
1208
  started = monotonicNow();
1086
1209
  let inventory = { state: "unknown" };
1087
1210
  const listing = await listWorkerDatabases(ctx);
1088
1211
  if (listing.kind === "ok") {
1089
- const harness = await runPsql(deps, MAINTENANCE_DATABASE, harnessListingSql(options.ciHarnessOwnerRole), stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), options.signal);
1212
+ const harness = await runPsql(deps, options.workerRole, MAINTENANCE_DATABASE, harnessListingSql(options.ciHarnessOwnerRole), stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), options.signal);
1090
1213
  let harnessListing = succeeded(harness) ? parseHarnessListing(harness.stdout) : null;
1091
1214
  // Only a failed activity request qualifies for fallback. Malformed successful
1092
1215
  // output remains unknown; never conceal it with an inventory retry.
1093
1216
  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);
1217
+ const fallback = await runPsql(deps, options.workerRole, MAINTENANCE_DATABASE, harnessListingSql(options.ciHarnessOwnerRole, false), stepTimeout(ctx, WORKER_DATABASE_PSQL_STEP_TIMEOUT_MS), options.signal);
1095
1218
  harnessListing = succeeded(fallback) ? parseHarnessListing(fallback.stdout) : null;
1096
1219
  if (harnessListing)
1097
1220
  harnessListing.coverage = {
@@ -1149,7 +1272,7 @@ function safeJobIdForLog(jobId) {
1149
1272
  export function formatWorkerDatabaseUnavailableLine(jobId, category, cause) {
1150
1273
  const id = safeJobIdForLog(jobId);
1151
1274
  if (category === "bridgeapi_reachable") {
1152
- 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; ` +
1153
1276
  `no worker database was created; continuing with the sentinel database — host operator: see ${WORKER_DATABASE_RUNBOOK_SECTION}`);
1154
1277
  }
1155
1278
  const safeCategory = UNAVAILABLE_CATEGORIES.has(category) ? category : "unknown";
@@ -1165,3 +1288,99 @@ export function formatWorkerDatabaseDropFailedLine(jobId, name) {
1165
1288
  return (`[executor] job ${id}: ${subject} could not be dropped (non-fatal); its ownership comment is kept ` +
1166
1289
  `for review — host operator: see ${WORKER_DATABASE_RUNBOOK_SECTION}`);
1167
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
+ }