Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.59.3.0 fix(minions): block workers on local configuration faults instead of restart-looping (#5602)
Garry Tan6bb88d128d70
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex efa54ade3a..0486b40e7b 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.59.2.0",+ "version": "0.59.3.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex b7c3908ca5..6a305556d6 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.59.2.0",+ "version": "0.59.3.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.gitignore b/.gitignoreindex 3bc8a98555..360bf3aad6 100644--- a/.gitignore+++ b/.gitignore@@ -11,7 +11,8 @@ bin/# Bun --compile temp artifacts. Each build emits a new hash-named .bun-build# file in cwd; glob catches all of them.*.bun-build-.gstack/+.gstack/*+!.gstack/redact-allowlistsupabase/.temp/.claude/skills/# admin/dist/ is the React SPA bundle. CLAUDE.md says it's committed fordiff --git a/.gstack/redact-allowlist b/.gstack/redact-allowlistnew file mode 100644index 0000000000..aad82b37c8--- /dev/null+++ b/.gstack/redact-allowlist@@ -0,0 +1,3 @@+# Exact spans the gstack credential pre-push guard must not flag.+# vendor/postgres/README.md is byte-exact upstream documentation (placeholder, not a credential).+postgres://username:password@host:portdiff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 2f2fe42b87..7b3057640c 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.59.2.0 -->+<!-- gbrain-runbook-stamp: 0.59.3.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 352a75e8ec..85ee0e8f8c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,61 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.59.3.0] - 2026-09-28++**A broken worker installation now asks for repair instead of repeatedly interrupting your jobs.**++Background workers check that they and the programs they launch can safely talk to+the database before taking work. If an installation is missing a required+capability, processing stops with a repair instruction. Its supervisor stays+available to report the problem rather than starting the same broken worker+again. Temporary connection problems still retry normally.++The database driver now ships with the application, so a global installation no+longer depends on the package manager remembering to apply a separate patch.+Workers also prefer their own installation when launching jobs, while checking+any explicitly selected alternative before using it.++If a configuration problem interrupts running work, the worker only returns a job+to the queue after execution has stopped and its ownership is still valid. When+that cannot be confirmed, the diagnostic says so: recovery may still consume a+stall allowance, and side effects may need inspection before retrying. This does+not impose memory limits on individual jobs or automatically replay failed work.++| Situation | Behavior |+| --- | --- |+| Installation cannot safely run jobs | Processing is blocked; repair and explicitly restart the owner. |+| Database connection is temporarily unavailable | Existing retry and backoff behavior remains active. |+| Supervisor is alive but not processing | Status reports readiness, startup stage and next retry separately from process liveness. |+| Shutdown or job release cannot be confirmed | Report the uncertainty; do not claim the job was safely returned. |++### To take advantage of v0.59.3.0++Run `gbrain upgrade`, verify the worker and any `GBRAIN_JOB_CHILD_CLI` override point+to the intended installation, and restart the affected supervisor or autopilot+service. Use `gbrain jobs supervisor status --json` or+`gbrain autopilot --status --json` to inspect `processing_ready` and+`processing_state`; `processing_stage` and `retry_at` explain a startup wait.+A live process alone does not establish progress.+The [worker recovery guide](docs/guides/minions-fix.md) covers each installation+and service owner. Inspect already failed jobs individually before retrying them.+An older supervisor keeps running upgraded workers until you restart it, but to roll a+worker back below v0.59.3.0, stop its v0.59.3.0 owner first; otherwise the owner's+120-second startup deadline keeps restarting the older worker.++### Itemized changes++- Bundle the cancellation-capable Postgres driver and share its runtime capability+ check with doctor and startup readiness.+- Preserve typed configuration failures through database probes and job-child+ results; distinguish them from temporary connectivity failures.+- Block both supervisor owners without a restart loop, retaining diagnostics and+ explicit repair/restart recovery. Keep the existing soft and hard crash budgets.+- Fence delayed job release on ownership and actual execution settlement; bound+ shutdown work and report unconfirmed cleanup instead of silently consuming jobs.+- Validate selected child compatibility, bound handshake output and deadlines,+ and keep process-group cleanup active after a direct child exits.+## [0.59.2.0] - 2026-09-28**When skill optimization gets nothing usable back from the optimizer model, it now says so instead of quietly reporting "no improvement", and every run tells you exactly which models it used and what they cost.**diff --git a/TODOS.md b/TODOS.mdindex c9d66b49b1..81ec6b4613 100644--- a/TODOS.md+++ b/TODOS.md@@ -2160,7 +2160,9 @@ checklist. The independent follow-ups below remain open.- [ ] **P3 — isolation test-gap follow-ups (pre-landing review).** **What:**(a) spawned-CLI negative tests for `jobs run-child` bootstrap guards (PGLite→ exit 13; missing job-id/env → exit 13) and for `jobs work` with- isolation on + an unresolvable child CLI (fail-fast exit 1) — both need a+ isolation on + an unresolvable child CLI (configuration exit 16; the+ incompatible-child case is already covered by+ `test/e2e/worker-readiness-cli.test.ts`) — both need areal engine bootstrap so they live in the e2e lane; (b) a behavioral (notstructural) test driving `withRefreshingLock` with a hung injected`handle.refresh` (signal aborted at timeout, no overlapping ticks); (c) adiff --git a/VERSION b/VERSIONindex 891f45f84d..5ebd215073 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.59.2.0+0.59.3.0diff --git a/bun.lock b/bun.lockindex b3357aa4d6..1075c40d19 100644--- a/bun.lock+++ b/bun.lock@@ -31,7 +31,6 @@"marked": "^18.0.2","openai": "^4.0.0","pgvector": "^0.2.0",- "postgres": "3.4.9","tree-sitter-wasms": "0.1.13","web-tree-sitter": "0.22.6","zod": "^4.3.6",@@ -52,9 +51,6 @@"trustedDependencies": ["@electric-sql/pglite",],- "patchedDependencies": {- "[email protected]": "patches/[email protected]",- },"overrides": {"@ai-sdk/provider-utils": "4.0.33","@hono/node-server": "^2.0.5",@@ -523,8 +519,6 @@"playwright-core": ["[email protected]", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg=="],- "postgres": ["[email protected]", "", {}, "sha512-GD3qdB0x1z9xgFI6cdRD6xu2Sp2WCOEoe3mtnyB5Ee0XrrL5Pe+e4CCnJrRMnL1zYtRDZmQQVbvOttLnKDLnaw=="],-"proxy-addr": ["[email protected]", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="],"pure-rand": ["[email protected]", "", {}, "sha512-IoM8YF/jY0hiugFo/wOWqfmarlE6J0wc6fDK1PhftMk7MGhVZl88sZimmqBBFomLOCSmcCCpsfj7wXASCpvK9A=="],diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex e955996be4..0b2e5e4edf 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -15,7 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`create --scopes read,write` narrows a token via the `scopes TEXT[]` column with mint-time validation — a typo'd scope refuses loudly, never silently denies or widens; `list` shows id + scopes columns with grandfathered rows rendered honestly; `revoke --id <uuid>` revokes exactly one row since names are not unique, and bulk revoke-by-name says when it hit several; `permissions set-takes-holders` MERGES into the permissions JSONB via `COALESCE(permissions,'{}'::jsonb) || $2::jsonb` — a whole-object replace would silently wipe the `source_id` federation grant), plus `gbrain auth register-client` and `gbrain auth revoke-client <client_id>` for OAuth 2.1 client lifecycle. `revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; clients without a `source_id` backfill to `'default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), and federated reads (`federated_read`) — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `--usage` joins per-client op-call counts via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)`. Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`.-- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and `maxCrashes: 5`. `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID, startup checks `kill -0 <pid>` before refusing to start (a stale lock from a crashed process does not block). (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution).+- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID, startup checks `kill -0 <pid>` before refusing to start (a stale lock from a crashed process does not block). (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`.- `src/commands/backup.ts` — trusted local `gbrain backup status|check`: status may reuse a recent warning; check forces a bounded remote readback sweep. Enabled missing/locked/degraded evidence does not return an all-clear. Quiet and disabled modes retain explicit zero-exit behavior. JSON separates configured repos from fresh verified recoverable repos and describes committed-file-only recovery. Remote MCP doctor never invokes this local Git path; see `docs/operations/backup-check.md` and `test/backup-cli.serial.test.ts`.diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 7711b4ce75..5739280cd8 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/doctor/checks/sync-failures.ts` — reads managed durable cursor/receipt state even when its compatibility ledger is absent. An unavailable read is unknown/warn, not healthy; local findings carry diagnostics and remote findings contain only source-scoped aggregates. Legacy remediation stays separate from explicit managed retry. Tests: `test/persistence-sync-failures.serial.test.ts`, `test/doctor-report-remote.serial.test.ts`.-- `src/commands/doctor.ts` — `gbrain doctor [--json] [--fast] [--fix] [--dry-run] [--index-audit] [--no-migrate]`: health checks. `--no-migrate` keeps doctor observational: the CLI connects with `probeOnly` so a clean-or-behind schema is reported as-is instead of being auto-migrated before the checks run. The file is a façade carrying `buildChecks`/`runDoctor` and output rendering; the check-function library lives in bundles under `src/commands/doctor/checks/` plus four tail-cluster modules under `src/commands/doctor/` (see that entry), all re-exported here so the full surface is unchanged — structural guards pin its source text via `test/helpers/doctor-source.ts`, never by reading this file alone. Checks include `jsonb_integrity` + `markdown_body_completeness` (reliability), `schema_version` (fails loudly when `version=0`, routes to `gbrain apply-migrations --yes`; a version AHEAD of this client's `LATEST_VERSION` warns "upgrade this client"; and when the ledger reads current, a read-only `detectMissingColumns` diff from `src/core/schema-verify.ts` runs INSIDE the ledger-current branch — a PgBouncer-swallowed ALTER TABLE can advance `config.version` over a physically narrower table, so missing live columns downgrade the ok to a warn naming them with the `gbrain init --migrate-only` hint; diff failure is best-effort and the ledger ok stands; positional wiring pinned by `test/doctor-schema-column-diff.test.ts`), `upgrade_errors` (async `checkUpgradeErrors(engine)` over `~/.gbrain/upgrade-errors.jsonl`: the warn downgrades to an EXPLICIT status-ok line — never silence — only when the past failure is provably superseded, i.e. the running binary is at/past the failed target version AND the schema verifies current via `engine.getConfig('version')`; a missing engine or unverifiable schema keeps the warn, fail-closed, because `self-upgrade` swaps the binary before `post-upgrade` runs migrations and the binary alone can lie; pinned by `test/doctor-upgrade-errors.test.ts` + `test/doctor-upgrade-errors-stale.test.ts`), `queue_health` (Postgres-only: stalled-forever active jobs started_at > 1h, waiting-depth-per-name > threshold default 10 via `GBRAIN_QUEUE_WAITING_THRESHOLD`, and dead-lettered subagent jobs with `last_error` matching the `prompt_too_long` classifier in last 24h), `sync_failures` (`[CODE=N, ...]` breakdown for unacked-warn + acked-ok; severity comes from the shared `decideSyncFailureSeverity` in `src/core/sync-failure-ledger.ts` so the LOCAL and REMOTE/thin-client doctor surfaces can never drift — a stuck bookmark escalates to FAIL once an OPEN failure has blocked past the staleness window or ≥10 files block, while already `auto_skipped` rows stay a visible WARN), `rls_event_trigger` (healthy `evtenabled` set is `('O','A')` only; fix hint `gbrain apply-migrations --force-retry 35`), `graph_coverage` (short-circuits to ok when `SELECT COUNT(*) FROM pages WHERE type IN ('entity','person','company','organization')` returns 0; WARN hint is `gbrain extract all`), `embedding_column_registry` (probes each declared column via Postgres `format_type(atttypid, atttypmod)` to catch dim mismatch with a paste-ready `gbrain config set embedding_columns '{...}'` hint, probes HNSW index presence via `pg_indexes`, computes default-column population via `COUNT(*) FILTER (WHERE <col> IS NOT NULL) / COUNT(*)` warning below 90% except empty brains where chunk_count=0 short-circuits to ok; PGLite parity via `executeRaw`), and `skill_brain_first` (walks SKILL.md via `autoDetectSkillsDirReadOnly`, calls `analyzeSkillBrainFirst()` from `src/core/skill-brain-first.ts` per file with structured `Check.issues[]`; warn states `missing_brain_first`/`brain_first_typo`, ok states `compliant_callout`/`compliant_phase`/`compliant_position`/`exempt_frontmatter`/`no_external`; snapshot+diff audit at `~/.gbrain/audit/skill-brain-first-YYYY-Www.jsonl`). `--fix` delegates inlined cross-cutting rules to `> **Convention:** see [path](../path).` callouts via `src/core/dry-fix.ts` (and MISSING_RULE_PATTERNS for the brain-first callout); `--fix --dry-run` previews. `--index-audit` (Postgres-only, informational, no auto-drop) reports zero-scan indexes from `pg_stat_user_indexes`. Every DB check runs under a progress phase; `markdown_body_completeness` runs under a 1s heartbeat. `runDoctor` uses `autoDetectSkillsDirReadOnly` (from `src/core/repo-root.ts`; install-path fallback so `cd ~ && gbrain doctor` finds bundled skills); `--fix` carries a D6 install-path safety gate that refuses auto-repair when `detected.source === 'install_path'` (would rewrite the bundled tree). The Lane D supervisor check at `doctor.ts:1011-1043` consumes `summarizeCrashes(events)` from `src/core/minions/handlers/supervisor-audit.ts` (warn at `>=1` real crash; ok message has `clean_exits_24h=N`; warn message has `runtime=A oom=B unknown=C legacy=D` per-cause breakdown) so OOM/runtime/unknown crashes are distinguishable from clean code=0 worker drains; cross-surface parity with `gbrain jobs supervisor status` is pinned by source-grep wiring assertions requiring the breakdown substrings in BOTH `doctor.ts` and `jobs.ts`. `checkSyncFreshness` (exported, in `runDoctor` local + `doctorReportRemote` thin-client) is a staleness probe: warns at 24h, fails at 72h or never-synced; future-`last_sync_at` warns ("clock skew") instead of falling through ok; env overrides `GBRAIN_SYNC_FRESHNESS_WARN_HOURS`/`GBRAIN_SYNC_FRESHNESS_FAIL_HOURS` (invalid fall back with once-per-process stderr warn via `_resolveSyncFreshnessHours`); failure messages embed `source.id` so the printed `gbrain sync --source <id>` matches. A source holding a LIVE, non-expired per-source sync lock (`inspectLock(engine, syncLockId(source.id))` from `src/core/db-lock.ts`) is reported as actively syncing (the message names the holder pid + host) and counted in `synced_recently_count`, NOT flagged stale — the live lock is the only honest in-progress signal (checkpoint banking can't distinguish in-progress from wedged: a blocked sync banks its files but writes no anchor). A blocked/failed sync's process has exited (no lock row) and a wedged holder stops refreshing (TTL lapses), so either falls through to the stale path and is never masked; the dynamic `db-lock` import is swallowed to a no-op on a stub engine or pre-lock-table brain, so this can only ADD an in-progress verdict, never suppress a real stale one. The in-progress note is appended to whatever verdict the buckets produce and is empty when nothing is syncing, so steady-state messages stay byte-for-byte unchanged. It has a `localOnly`-gated git short-circuit (`runDoctor` passes `localOnly: true`; `doctorReportRemote` runs in the HTTP MCP server `src/commands/serve-http.ts` and keeps default `false` so that path never walks DB-supplied `local_path` via subprocess — trust boundary). The local predicate mirrors sync's "do work?" gate (HEAD == `last_commit` AND working tree clean via `requireCleanWorkingTree: 'ignore-untracked'` so a quiet repo with only untracked dirs is `unchanged` not SEVERE, AND `chunker_version === CURRENT`); the inline SELECT carries `last_commit + chunker_version + newest_content_at`. The REMOTE path computes lag via `lagFromContentMs(newest_content_at, lastSync, now)` from the stored column, NO git subprocess; LOCAL fall-through and the `< 0` clock-skew check stay on raw wall-clock. Three-bucket count math populates `Check.details = {unchanged_count, synced_recently_count, stale_count}` with the invariant `sum === sources.length`. `checkCycleFreshness` is DELIBERATELY NOT git-short-circuited or content-relativized (`last_commit == HEAD` can't answer "did the full cycle complete?"; a sync can succeed while later cycle phases fail; different axis `last_full_cycle_at`). Pinned by `test/doctor.test.ts` (incl. the IRON-RULE guard banning stale verb names, the sync_freshness boundary matrix, the D4 guard verifying git probes are NEVER called when `localOnly` is unset/false, the three-bucket invariant, and the untracked-folders / remote-never-shells-out trust-boundary cases). `pglite_data_dir` check: fs-only check that runs when a PGLite brain FAILS to connect (`!fastMode && !engine && config.engine === 'pglite'`, placed after `orphan_clones`, before the DB-checks gate): `computePgliteDataDirCheck(dataDir, diagnosis)` (exported pure fn, `computeWorkerOomLoopCheck` convention) maps the `inspectPgliteDataDir` verdict to a Check — corruption-likely/looks-healthy-but-unopenable/unsupported-layout → `fail` naming `gbrain pglite-repair --dry-run`/`--yes` or the rebuild path, live-lock/missing-dir → `warn`; all `remediation_status: 'human_only'` (Minion remediation needs the DB that is down). Escalates when ≥2 repair attempts failed inside 7 days (unclean-shutdown genesis still active → engine-switch pointer) and reports retained backup-dir inventory (orphan_clones disk-visibility class). Registered in `doctor-categories.ts` OPS_CHECK_NAMES. Pinned by `test/doctor-pglite-datadir.test.ts`. silent-failure checks: `content_hash_duplicates` (single GROUP BY over `(source_id, content_hash)` with FILTER aggregates — never N² — flagging hash groups that hold BOTH a bare and a path-prefixed slug, the wrong-import-root pattern; warn carries sample pairs + the `pages delete` → `purge-deleted --older-than 0` remediation); `undeclared_db_only_pages` (per source with a local repo: markdown pages with no backing file outside every declared + derive-phase-default db_only prefix — the one check deliberately allowed to stat the repo); `db_only_collector_collision` (configured recipe `output_paths` inside a declared db_only dir — auto-gitignore means sync AND import silently skip the collector's files; same warning fires in sync's `manageGitignore` at config-write time). All warn-level, engine-parity pinned by `test/e2e/doctor-silent-death-parity.test.ts`; units in `test/doctor-silent-death-checks.test.ts`. `graph_signals_coverage` check wired into both `runDoctor` (local) and `doctorReportRemote` (HTTP/JSON thin-client path). Reads `search.graph_signals` config first, falls back to mode default; silent `ok` when disabled. Computes inbound link coverage on the page set; warns at <10% with `gbrain extract all` fix hint; `ok` at ≥30% ("fire on most queries") and 10-29% ("fire occasionally"), each with the percentage embedded. Pinned by cases in `test/doctor.test.ts`. `subagent_provider` check (layer 3 of 3). Resolves subagent model config in runtime order (`models.subagent` > `models.default` > `models.tier.subagent` > built-in default) and warns when the selected model lacks native tool-loop capability (message names the bad value + paste-ready fix `gbrain config set models.tier.subagent anthropic:claude-sonnet-4-6`); also warns when `models.default` would sneak `subagent` into a non-Anthropic provider via tier inheritance. OK when subagent tier resolves to Anthropic. Tests in `test/doctor.test.ts`. `computeWorkerOomLoopCheck(engine)` is the single authoritative OOM-loop signal, unioning supervised `summarizeCrashes(readRecentSupervisorEvents(24)).by_cause.rss_watchdog` (cross-week read via `readRecentSupervisorEvents` so a Monday window can't lose Sunday) + bare-worker `minion_jobs error_text='aborted: watchdog'` count (Postgres-only; the same source `queue_health` subcheck 3 reads). Cap comes from the latest `rss_watchdog_loop` breaker alert's `max_rss_mb`, else `resolveDefaultMaxRssMb()` fallback. fail at breaker-tripped or oomKills≥5, warn at ≥1, null otherwise. `computePoolReapHealthCheck(engine)` is the Postgres-only `pool_reap_health` check reading `readRecentPoolRecoveries(1)` — fail when reconnect failures>0 (reconnect throwing is the actionable signal), warn at ≥10 reaps/hr (pooler thrash), null otherwise. Both registered in `buildChecks` after the `supervisor` block. The `supervisor` causeStr carries `rss=N (see worker_oom_loop)` and `queue_health`'s watchdog message cross-references `worker_oom_loop`. `DoctorReport.top_issues` + the cause-ranked render header. `worker_oom_loop` + `pool_reap_health` registered under ops in `doctor-categories.ts`. Pinned by `test/doctor-worker-oom-loop.test.ts`, `test/doctor-pool-reap-health.test.ts`. `supervisor_singleton` check, a SEPARATE check from `supervisor` (same split precedent as the niceness check) so a singleton-divergence warn can't clobber the crash/liveness precedence. Runs only when a `started` supervisor event was seen in the last 24h and a live engine is available. Reads the queue-scoped DB lock row (`gbrain_cycle_locks WHERE id = supervisorLockId(queue)`) and compares the lock holder (`holder_host:holder_pid`) against the local pidfile holder via the pure `classifySupervisorSingleton`. `mismatch` → warn (a second supervisor may be running with a different `--max-rss`; message names both holders, the effective cap from the `started` event's `max_rss_mb`, and the fix `gbrain jobs supervisor stop`); `single` → ok (names holder + cap); `no_lock` → no check emitted. Best-effort try/catch (silent skip on brains without the lock table). Registered under ops in `doctor-categories.ts` as `supervisor_singleton`. Pinned by `test/supervisor-db-lock.test.ts` + `test/doctor.test.ts`. `checkBatchRetryHealth`: `batch_retry_health` check surfacing Supavisor circuit-breaker incidents. Wired into both `runDoctor` (local) and `doctorReportRemote` (thin-client). Reads last 24h. States: `ok` (zero exhausted in 24h OR <3 from a single site), `warn` (>=3 same-site OR >=5 cross-site), `fail` (>=20 sustained breaker). Surfaces bad `GBRAIN_BULK_*` env at doctor startup. Corrupt-JSONL tolerant. Paste-ready fix hints in every warn/fail message. Also reads `readRecentDbDisconnects(24)` and appends `Disconnect-call audit: N call(s) in 24h (most recent caller: <frame>).` to ALL three message paths so connection-incident signal is greppable from one `gbrain doctor --json` call (module-import wrapped in try/catch so older brains without the audit file degrade silently). Pinned by `test/doctor-batch-retry.test.ts` (10 cases). three checks wired into `runDoctor()` and the JSON envelope, all warn-only with paste-ready fix hints. (1) `checkSourceRoutingHealth(engine)` scans up to 200 pages on federated brains and flags pages whose `source_id` doesn't match what `resolveSourceWithTier()` would have picked for their `source_path`; single-source brains short-circuit to `ok`; the 200-page cap is total across the brain so doctor stays under 5s. (2) `checkOauthConfidentialHealth(engine)` probes registered confidential clients for `/token` reachability. (3) `checkAutopilotLockScope()` (pure, no engine) compares the resolved lock path to `$GBRAIN_HOME`; warns when set but the lock lives elsewhere, with a PID-safe inspection hint (`kill -0 <pid>` before deletion). Pinned by `test/doctor-v0_37_7_checks.test.ts`. `buildChecks(engine, args, dbSource, connectError?): Promise<Check[]>` exported as a test seam; the optional `connectError` is the connect failure captured by the CLI's dead-DB fallback, which the null-engine path turns into a SYNTHESIZED classified `connection` fail entry (so `checks[name=="connection"]` exists in every failure shape — smoke-test branches on it). The `connection` check's failure path classifies via `src/core/pg-access-classify.ts` into a redacted message + `details: {reason, transient, fix_hint}` naming `gbrain db-repair` (deliberately NOT `remediation[]`/`makeRemediationStep` — that lane feeds `--remediate`, whose Minion jobs need the very DB that's down; applicator boundary: `--remediate` = brain-DATA quality with a live engine, `db-repair` = DB ACCESS engine-free). The URL-only `pgbouncerPrepareCheck` helper and the engine-free `db_repair_recurrence` check run BOTH before the connection check and in the dead-DB filesystem lane; `pglite_scale` (engine-fit, warn at ≥1000 pages on pglite) runs in the DB phase. `computeDoctorReport(checks, extras?)` accepts optional `{engine, db_url_source}` which land as additive `DoctorReport.engine` / `DoctorReport.db_url_source` JSON fields (schema_version stays 2). `runDoctor` is a thin wrapper: `buildChecks → computeDoctorReport → render + process.exit`. All 10 `process.exit` sites stay in the wrapper; the two early-return paths (no engine, connection failure) return partial check lists instead of inline exits (observable output identical). Pinned by `test/doctor-behavioral.test.ts` (13 cases: pure aggregation math over `computeDoctorReport`, orchestrator cases for `--fast` skip set + `--json` flag + no-engine partial path + snapshot of load-bearing check names) and `test/doctor-cli-smoke.serial.test.ts` (1 subprocess case spawning `bun run src/cli.ts doctor --json` against a fresh PGLite tempdir, asserting schema_version=2 envelope, status enum, non-empty checks array — the render-path coverage buildChecks-only tests miss; quarantined `.serial` because PGLite write-locks don't play with parallel runners). three checks wired into `runDoctor()` and the JSON envelope: `oversized_pages` (warns on pages exceeding `content_sanity.bytes_warn`), `scraper_junk_pages` (warns on live DB pages matching any junk pattern that escaped ingest), and `content_sanity_audit_recent` (reads the last 7 days of audit events, aggregates by pattern+source). Default scans the 1000 most-recent pages; `--content-audit` opts into a full scan. All three warn-only with paste-ready fix hints (junk → `gbrain sources audit <id>` + `git rm` source-of-truth, oversize → split or accept). two checks wired into `runDoctor()` + the JSON envelope: `quarantined_pages` (counts pages carrying the `quarantine` marker via `engine.executeRaw` JSONB `?` existence, works on PGLite + Postgres; warn-only with a `gbrain quarantine list` hint) and `flagged_pages` (counts `content_flag` pages — searchable but odd; warn-only). Both skip gracefully (status ok, "Skipped") on engines/brains where the probe errors. Pinned by `test/doctor.test.ts`. `home_dir_in_worktree`: filesystem check walking up from `gbrainPath()` toward `$HOME` looking for a `.git` directory (main repo) or `.git` file (linked worktree pointer; Conductor + git-worktrees topology). Walk terminates at `$HOME` so a `.git` above the user's home doesn't false-positive. Honors `GBRAIN_HOME` (appends `.gbrain` to the override). Warn (not fail) with worktree-root path + paste-ready fix pointing at `GBRAIN_HOME` override or moving the brain. `--remediation-plan [--json] [--target-score N]` prints what would run (stable `id`, `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on`); `--remediate [--yes] [--target-score N] [--max-usd N]` submits each plan step as a Minion job in dependency order, re-checking score between steps. `--target-score N` defaults to 90; refuses to start when target exceeds `maxReachableScore()` and lists what's missing. `--max-usd N` is the cron-safety guard — submission refuses when the plan's `est_total_usd_cost` exceeds the cap. JSON envelope adds a `Check.remediation` field (additive, schema_version unchanged). Pinned by tests in `test/doctor.test.ts`. 4 checks: `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` (mitigation surface; math ships later), `voice_gate_health`. Schema health is a two-check pair: `schema_version` resolves through `schemaVersionHealth` (`src/core/schema-version-health.ts`, shared with the remote doctor report; a DB AHEAD of the client warns with an upgrade-this-client hint rather than suggesting migrations), and on ledger-current brains a read-only `schema_columns` check diffs live columns against the expected schema (`detectMissingColumns`, dynamically imported inside the ledger-current branch — positional guard in `test/doctor-schema-column-diff.test.ts`) and warns naming the missing columns with the `gbrain init --migrate-only` hint.+- `src/commands/doctor.ts` — `gbrain doctor [--json] [--fast] [--fix] [--dry-run] [--index-audit] [--no-migrate]`: health checks. `checkPostgresCancellationDriver` (`postgres_cancellation_driver`) inspects a real reserved runtime owner through the shared cancellation helper: unsupported `discard()` is a typed local failure with a repair link, connection/deadline failure is a warning, and PGLite is exempt. The bounded reserve releases late arrivals and does not make general engine connect require cancellation, preserving broken-install diagnostics. `--no-migrate` keeps doctor observational: the CLI connects with `probeOnly` so a clean-or-behind schema is reported as-is instead of being auto-migrated before the checks run. The file is a façade carrying `buildChecks`/`runDoctor` and output rendering; the check-function library lives in bundles under `src/commands/doctor/checks/` plus four tail-cluster modules under `src/commands/doctor/` (see that entry), all re-exported here so the full surface is unchanged — structural guards pin its source text via `test/helpers/doctor-source.ts`, never by reading this file alone. Checks include `jsonb_integrity` + `markdown_body_completeness` (reliability), `schema_version` (fails loudly when `version=0`, routes to `gbrain apply-migrations --yes`; a version AHEAD of this client's `LATEST_VERSION` warns "upgrade this client"; and when the ledger reads current, a read-only `detectMissingColumns` diff from `src/core/schema-verify.ts` runs INSIDE the ledger-current branch — a PgBouncer-swallowed ALTER TABLE can advance `config.version` over a physically narrower table, so missing live columns downgrade the ok to a warn naming them with the `gbrain init --migrate-only` hint; diff failure is best-effort and the ledger ok stands; positional wiring pinned by `test/doctor-schema-column-diff.test.ts`), `upgrade_errors` (async `checkUpgradeErrors(engine)` over `~/.gbrain/upgrade-errors.jsonl`: the warn downgrades to an EXPLICIT status-ok line — never silence — only when the past failure is provably superseded, i.e. the running binary is at/past the failed target version AND the schema verifies current via `engine.getConfig('version')`; a missing engine or unverifiable schema keeps the warn, fail-closed, because `self-upgrade` swaps the binary before `post-upgrade` runs migrations and the binary alone can lie; pinned by `test/doctor-upgrade-errors.test.ts` + `test/doctor-upgrade-errors-stale.test.ts`), `queue_health` (Postgres-only: stalled-forever active jobs started_at > 1h, waiting-depth-per-name > threshold default 10 via `GBRAIN_QUEUE_WAITING_THRESHOLD`, and dead-lettered subagent jobs with `last_error` matching the `prompt_too_long` classifier in last 24h), `sync_failures` (`[CODE=N, ...]` breakdown for unacked-warn + acked-ok; severity comes from the shared `decideSyncFailureSeverity` in `src/core/sync-failure-ledger.ts` so the LOCAL and REMOTE/thin-client doctor surfaces can never drift — a stuck bookmark escalates to FAIL once an OPEN failure has blocked past the staleness window or ≥10 files block, while already `auto_skipped` rows stay a visible WARN), `rls_event_trigger` (healthy `evtenabled` set is `('O','A')` only; fix hint `gbrain apply-migrations --force-retry 35`), `graph_coverage` (short-circuits to ok when `SELECT COUNT(*) FROM pages WHERE type IN ('entity','person','company','organization')` returns 0; WARN hint is `gbrain extract all`), `embedding_column_registry` (probes each declared column via Postgres `format_type(atttypid, atttypmod)` to catch dim mismatch with a paste-ready `gbrain config set embedding_columns '{...}'` hint, probes HNSW index presence via `pg_indexes`, computes default-column population via `COUNT(*) FILTER (WHERE <col> IS NOT NULL) / COUNT(*)` warning below 90% except empty brains where chunk_count=0 short-circuits to ok; PGLite parity via `executeRaw`), and `skill_brain_first` (walks SKILL.md via `autoDetectSkillsDirReadOnly`, calls `analyzeSkillBrainFirst()` from `src/core/skill-brain-first.ts` per file with structured `Check.issues[]`; warn states `missing_brain_first`/`brain_first_typo`, ok states `compliant_callout`/`compliant_phase`/`compliant_position`/`exempt_frontmatter`/`no_external`; snapshot+diff audit at `~/.gbrain/audit/skill-brain-first-YYYY-Www.jsonl`). `--fix` delegates inlined cross-cutting rules to `> **Convention:** see [path](../path).` callouts via `src/core/dry-fix.ts` (and MISSING_RULE_PATTERNS for the brain-first callout); `--fix --dry-run` previews. `--index-audit` (Postgres-only, informational, no auto-drop) reports zero-scan indexes from `pg_stat_user_indexes`. Every DB check runs under a progress phase; `markdown_body_completeness` runs under a 1s heartbeat. `runDoctor` uses `autoDetectSkillsDirReadOnly` (from `src/core/repo-root.ts`; install-path fallback so `cd ~ && gbrain doctor` finds bundled skills); `--fix` carries a D6 install-path safety gate that refuses auto-repair when `detected.source === 'install_path'` (would rewrite the bundled tree). The Lane D supervisor check at `doctor.ts:1011-1043` consumes `summarizeCrashes(events)` from `src/core/minions/handlers/supervisor-audit.ts` (warn at `>=1` real crash; ok message has `clean_exits_24h=N`; warn message has `runtime=A oom=B unknown=C legacy=D` per-cause breakdown) so OOM/runtime/unknown crashes are distinguishable from clean code=0 worker drains; cross-surface parity with `gbrain jobs supervisor status` is pinned by source-grep wiring assertions requiring the breakdown substrings in BOTH `doctor.ts` and `jobs.ts`. `checkSyncFreshness` (exported, in `runDoctor` local + `doctorReportRemote` thin-client) is a staleness probe: warns at 24h, fails at 72h or never-synced; future-`last_sync_at` warns ("clock skew") instead of falling through ok; env overrides `GBRAIN_SYNC_FRESHNESS_WARN_HOURS`/`GBRAIN_SYNC_FRESHNESS_FAIL_HOURS` (invalid fall back with once-per-process stderr warn via `_resolveSyncFreshnessHours`); failure messages embed `source.id` so the printed `gbrain sync --source <id>` matches. A source holding a LIVE, non-expired per-source sync lock (`inspectLock(engine, syncLockId(source.id))` from `src/core/db-lock.ts`) is reported as actively syncing (the message names the holder pid + host) and counted in `synced_recently_count`, NOT flagged stale — the live lock is the only honest in-progress signal (checkpoint banking can't distinguish in-progress from wedged: a blocked sync banks its files but writes no anchor). A blocked/failed sync's process has exited (no lock row) and a wedged holder stops refreshing (TTL lapses), so either falls through to the stale path and is never masked; the dynamic `db-lock` import is swallowed to a no-op on a stub engine or pre-lock-table brain, so this can only ADD an in-progress verdict, never suppress a real stale one. The in-progress note is appended to whatever verdict the buckets produce and is empty when nothing is syncing, so steady-state messages stay byte-for-byte unchanged. It has a `localOnly`-gated git short-circuit (`runDoctor` passes `localOnly: true`; `doctorReportRemote` runs in the HTTP MCP server `src/commands/serve-http.ts` and keeps default `false` so that path never walks DB-supplied `local_path` via subprocess — trust boundary). The local predicate mirrors sync's "do work?" gate (HEAD == `last_commit` AND working tree clean via `requireCleanWorkingTree: 'ignore-untracked'` so a quiet repo with only untracked dirs is `unchanged` not SEVERE, AND `chunker_version === CURRENT`); the inline SELECT carries `last_commit + chunker_version + newest_content_at`. The REMOTE path computes lag via `lagFromContentMs(newest_content_at, lastSync, now)` from the stored column, NO git subprocess; LOCAL fall-through and the `< 0` clock-skew check stay on raw wall-clock. Three-bucket count math populates `Check.details = {unchanged_count, synced_recently_count, stale_count}` with the invariant `sum === sources.length`. `checkCycleFreshness` is DELIBERATELY NOT git-short-circuited or content-relativized (`last_commit == HEAD` can't answer "did the full cycle complete?"; a sync can succeed while later cycle phases fail; different axis `last_full_cycle_at`). Pinned by `test/doctor.test.ts` (incl. the IRON-RULE guard banning stale verb names, the sync_freshness boundary matrix, the D4 guard verifying git probes are NEVER called when `localOnly` is unset/false, the three-bucket invariant, and the untracked-folders / remote-never-shells-out trust-boundary cases). `pglite_data_dir` check: fs-only check that runs when a PGLite brain FAILS to connect (`!fastMode && !engine && config.engine === 'pglite'`, placed after `orphan_clones`, before the DB-checks gate): `computePgliteDataDirCheck(dataDir, diagnosis)` (exported pure fn, `computeWorkerOomLoopCheck` convention) maps the `inspectPgliteDataDir` verdict to a Check — corruption-likely/looks-healthy-but-unopenable/unsupported-layout → `fail` naming `gbrain pglite-repair --dry-run`/`--yes` or the rebuild path, live-lock/missing-dir → `warn`; all `remediation_status: 'human_only'` (Minion remediation needs the DB that is down). Escalates when ≥2 repair attempts failed inside 7 days (unclean-shutdown genesis still active → engine-switch pointer) and reports retained backup-dir inventory (orphan_clones disk-visibility class). Registered in `doctor-categories.ts` OPS_CHECK_NAMES. Pinned by `test/doctor-pglite-datadir.test.ts`. silent-failure checks: `content_hash_duplicates` (single GROUP BY over `(source_id, content_hash)` with FILTER aggregates — never N² — flagging hash groups that hold BOTH a bare and a path-prefixed slug, the wrong-import-root pattern; warn carries sample pairs + the `pages delete` → `purge-deleted --older-than 0` remediation); `undeclared_db_only_pages` (per source with a local repo: markdown pages with no backing file outside every declared + derive-phase-default db_only prefix — the one check deliberately allowed to stat the repo); `db_only_collector_collision` (configured recipe `output_paths` inside a declared db_only dir — auto-gitignore means sync AND import silently skip the collector's files; same warning fires in sync's `manageGitignore` at config-write time). All warn-level, engine-parity pinned by `test/e2e/doctor-silent-death-parity.test.ts`; units in `test/doctor-silent-death-checks.test.ts`. `graph_signals_coverage` check wired into both `runDoctor` (local) and `doctorReportRemote` (HTTP/JSON thin-client path). Reads `search.graph_signals` config first, falls back to mode default; silent `ok` when disabled. Computes inbound link coverage on the page set; warns at <10% with `gbrain extract all` fix hint; `ok` at ≥30% ("fire on most queries") and 10-29% ("fire occasionally"), each with the percentage embedded. Pinned by cases in `test/doctor.test.ts`. `subagent_provider` check (layer 3 of 3). Resolves subagent model config in runtime order (`models.subagent` > `models.default` > `models.tier.subagent` > built-in default) and warns when the selected model lacks native tool-loop capability (message names the bad value + paste-ready fix `gbrain config set models.tier.subagent anthropic:claude-sonnet-4-6`); also warns when `models.default` would sneak `subagent` into a non-Anthropic provider via tier inheritance. OK when subagent tier resolves to Anthropic. Tests in `test/doctor.test.ts`. `computeWorkerOomLoopCheck(engine)` is the single authoritative OOM-loop signal, unioning supervised `summarizeCrashes(readRecentSupervisorEvents(24)).by_cause.rss_watchdog` (cross-week read via `readRecentSupervisorEvents` so a Monday window can't lose Sunday) + bare-worker `minion_jobs error_text='aborted: watchdog'` count (Postgres-only; the same source `queue_health` subcheck 3 reads). Cap comes from the latest `rss_watchdog_loop` breaker alert's `max_rss_mb`, else `resolveDefaultMaxRssMb()` fallback. fail at breaker-tripped or oomKills≥5, warn at ≥1, null otherwise. `computePoolReapHealthCheck(engine)` is the Postgres-only `pool_reap_health` check reading `readRecentPoolRecoveries(1)` — fail when reconnect failures>0 (reconnect throwing is the actionable signal), warn at ≥10 reaps/hr (pooler thrash), null otherwise. Both registered in `buildChecks` after the `supervisor` block. The `supervisor` causeStr carries `rss=N (see worker_oom_loop)` and `queue_health`'s watchdog message cross-references `worker_oom_loop`. `DoctorReport.top_issues` + the cause-ranked render header. `worker_oom_loop` + `pool_reap_health` registered under ops in `doctor-categories.ts`. Pinned by `test/doctor-worker-oom-loop.test.ts`, `test/doctor-pool-reap-health.test.ts`. `supervisor_singleton` check, a SEPARATE check from `supervisor` (same split precedent as the niceness check) so a singleton-divergence warn can't clobber the crash/liveness precedence. Runs only when a `started` supervisor event was seen in the last 24h and a live engine is available. Reads the queue-scoped DB lock row (`gbrain_cycle_locks WHERE id = supervisorLockId(queue)`) and compares the lock holder (`holder_host:holder_pid`) against the local pidfile holder via the pure `classifySupervisorSingleton`. `mismatch` → warn (a second supervisor may be running with a different `--max-rss`; message names both holders, the effective cap from the `started` event's `max_rss_mb`, and the fix `gbrain jobs supervisor stop`); `single` → ok (names holder + cap); `no_lock` → no check emitted. Best-effort try/catch (silent skip on brains without the lock table). Registered under ops in `doctor-categories.ts` as `supervisor_singleton`. Pinned by `test/supervisor-db-lock.test.ts` + `test/doctor.test.ts`. `checkBatchRetryHealth`: `batch_retry_health` check surfacing Supavisor circuit-breaker incidents. Wired into both `runDoctor` (local) and `doctorReportRemote` (thin-client). Reads last 24h. States: `ok` (zero exhausted in 24h OR <3 from a single site), `warn` (>=3 same-site OR >=5 cross-site), `fail` (>=20 sustained breaker). Surfaces bad `GBRAIN_BULK_*` env at doctor startup. Corrupt-JSONL tolerant. Paste-ready fix hints in every warn/fail message. Also reads `readRecentDbDisconnects(24)` and appends `Disconnect-call audit: N call(s) in 24h (most recent caller: <frame>).` to ALL three message paths so connection-incident signal is greppable from one `gbrain doctor --json` call (module-import wrapped in try/catch so older brains without the audit file degrade silently). Pinned by `test/doctor-batch-retry.test.ts` (10 cases). three checks wired into `runDoctor()` and the JSON envelope, all warn-only with paste-ready fix hints. (1) `checkSourceRoutingHealth(engine)` scans up to 200 pages on federated brains and flags pages whose `source_id` doesn't match what `resolveSourceWithTier()` would have picked for their `source_path`; single-source brains short-circuit to `ok`; the 200-page cap is total across the brain so doctor stays under 5s. (2) `checkOauthConfidentialHealth(engine)` probes registered confidential clients for `/token` reachability. (3) `checkAutopilotLockScope()` (pure, no engine) compares the resolved lock path to `$GBRAIN_HOME`; warns when set but the lock lives elsewhere, with a PID-safe inspection hint (`kill -0 <pid>` before deletion). Pinned by `test/doctor-v0_37_7_checks.test.ts`. `buildChecks(engine, args, dbSource, connectError?): Promise<Check[]>` exported as a test seam; the optional `connectError` is the connect failure captured by the CLI's dead-DB fallback, which the null-engine path turns into a SYNTHESIZED classified `connection` fail entry (so `checks[name=="connection"]` exists in every failure shape — smoke-test branches on it). The `connection` check's failure path classifies via `src/core/pg-access-classify.ts` into a redacted message + `details: {reason, transient, fix_hint}` naming `gbrain db-repair` (deliberately NOT `remediation[]`/`makeRemediationStep` — that lane feeds `--remediate`, whose Minion jobs need the very DB that's down; applicator boundary: `--remediate` = brain-DATA quality with a live engine, `db-repair` = DB ACCESS engine-free). The URL-only `pgbouncerPrepareCheck` helper and the engine-free `db_repair_recurrence` check run BOTH before the connection check and in the dead-DB filesystem lane; `pglite_scale` (engine-fit, warn at ≥1000 pages on pglite) runs in the DB phase. `computeDoctorReport(checks, extras?)` accepts optional `{engine, db_url_source}` which land as additive `DoctorReport.engine` / `DoctorReport.db_url_source` JSON fields (schema_version stays 2). `runDoctor` is a thin wrapper: `buildChecks → computeDoctorReport → render + process.exit`. All 10 `process.exit` sites stay in the wrapper; the two early-return paths (no engine, connection failure) return partial check lists instead of inline exits (observable output identical). Pinned by `test/doctor-behavioral.test.ts` (13 cases: pure aggregation math over `computeDoctorReport`, orchestrator cases for `--fast` skip set + `--json` flag + no-engine partial path + snapshot of load-bearing check names) and `test/doctor-cli-smoke.serial.test.ts` (1 subprocess case spawning `bun run src/cli.ts doctor --json` against a fresh PGLite tempdir, asserting schema_version=2 envelope, status enum, non-empty checks array — the render-path coverage buildChecks-only tests miss; quarantined `.serial` because PGLite write-locks don't play with parallel runners). three checks wired into `runDoctor()` and the JSON envelope: `oversized_pages` (warns on pages exceeding `content_sanity.bytes_warn`), `scraper_junk_pages` (warns on live DB pages matching any junk pattern that escaped ingest), and `content_sanity_audit_recent` (reads the last 7 days of audit events, aggregates by pattern+source). Default scans the 1000 most-recent pages; `--content-audit` opts into a full scan. All three warn-only with paste-ready fix hints (junk → `gbrain sources audit <id>` + `git rm` source-of-truth, oversize → split or accept). two checks wired into `runDoctor()` + the JSON envelope: `quarantined_pages` (counts pages carrying the `quarantine` marker via `engine.executeRaw` JSONB `?` existence, works on PGLite + Postgres; warn-only with a `gbrain quarantine list` hint) and `flagged_pages` (counts `content_flag` pages — searchable but odd; warn-only). Both skip gracefully (status ok, "Skipped") on engines/brains where the probe errors. Pinned by `test/doctor.test.ts`. `home_dir_in_worktree`: filesystem check walking up from `gbrainPath()` toward `$HOME` looking for a `.git` directory (main repo) or `.git` file (linked worktree pointer; Conductor + git-worktrees topology). Walk terminates at `$HOME` so a `.git` above the user's home doesn't false-positive. Honors `GBRAIN_HOME` (appends `.gbrain` to the override). Warn (not fail) with worktree-root path + paste-ready fix pointing at `GBRAIN_HOME` override or moving the brain. `--remediation-plan [--json] [--target-score N]` prints what would run (stable `id`, `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on`); `--remediate [--yes] [--target-score N] [--max-usd N]` submits each plan step as a Minion job in dependency order, re-checking score between steps. `--target-score N` defaults to 90; refuses to start when target exceeds `maxReachableScore()` and lists what's missing. `--max-usd N` is the cron-safety guard — submission refuses when the plan's `est_total_usd_cost` exceeds the cap. JSON envelope adds a `Check.remediation` field (additive, schema_version unchanged). Pinned by tests in `test/doctor.test.ts`. 4 checks: `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` (mitigation surface; math ships later), `voice_gate_health`. Schema health is a two-check pair: `schema_version` resolves through `schemaVersionHealth` (`src/core/schema-version-health.ts`, shared with the remote doctor report; a DB AHEAD of the client warns with an upgrade-this-client hint rather than suggesting migrations), and on ledger-current brains a read-only `schema_columns` check diffs live columns against the expected schema (`detectMissingColumns`, dynamically imported inside the ledger-current branch — positional guard in `test/doctor-schema-column-diff.test.ts`) and warns naming the missing columns with the `gbrain init --migrate-only` hint.- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts`, `verbs-reflex.ts`, `stale-mentions.ts`, `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface.diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex d2579ee860..5f6987377b 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/integrity.ts` — `gbrain integrity check|auto|review|extract`: bare-tweet detection, dead-link detection, three-bucket repair (auto-repair / review-queue / skip). `scanIntegrity()` is the shared library function called from `gbrain doctor` (sampled at limit=500) and `cmdCheck` (full scan). Batch-load fast path on Postgres uses a single SQL query (avoids the PgBouncer per-row round-trip timeout), gated by `engine.kind === 'postgres'` at the call site so PGLite never enters batch; fallback `catch` logs at `GBRAIN_DEBUG=1`. Batch projection is `SELECT ... ORDER BY source_id, slug` (NOT `SELECT DISTINCT ON (slug)`, which would collapse same-slug-different-source pages into one scan) so multi-source brains scan each `(source, slug)` row independently. Sequential and auto-repair loops use `listAllPageRefs()` to enumerate `(slug, source_id)` pairs and thread `sourceId` to `getPage`; batch + sequential paths report the same page count on multi-source brains.-- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the subcommand switch — `jobs work --help` can never start a daemon; only `--help`/`-h` are help tokens (bare `help` can be a job name); cli.ts routes it engine-free via `SELF_HELP_WITHOUT_ENGINE` + `CLI_ONLY_SELF_HELP`. `formatJobDetail` prints the effective wall-clock budget (`Timeout:`/`Deadline:` — 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer; `timeout_at` is in `JOB_DATE_FIELDS` for thin-client rehydration. `jobs stats` prints a `Backpressure (24h)` line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the shared `GBRAIN_WEDGED_QUEUE_WARN_MINUTES` threshold — the read-only visibility for maxPending single-flight suppression. Pinned by `test/jobs-subcommand-help.serial.test.ts`, `test/jobs-format-detail.test.ts`, `test/jobs-stats-backpressure.serial.test.ts`. `case 'work'` wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke --sigkill-rescue` is the SIGKILL-rescue guard. `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs `MAINTENANCE_PHASES` (mixed ∪ global) once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` only when no phase failed, no synthesis/pattern child is incomplete, no work was explicitly budget/triage-deferred, and the run was neither aborted nor lock-stolen; benign warning-only runs remain eligible. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status` consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output includes per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress. `parseJobIsolationFlag(args, env?)` (`--job-isolation`, space/= forms, `GBRAIN_JOB_ISOLATION` fallback, default inline); `case 'work'` resolves + fail-fast validates the child CLI invocation and warns when `--max-rss` is combined with isolation (watchdog covers the worker only); `case 'run-child'` is the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); the `db_dead` fatal text is verdict-aware (pool starved vs server unreachable). Generic `jobs submit` normalizes the job name once before trust, queueing, handler lookup, and audit; after the admission check and dry-run return, its explicit `ensureSchema()` preflight still runs before shell/handler validation so stale brains retain the canonical init/migration error precedence. On PGLite, `jobs submit embed-backfill` refuses with `no_worker_surface` and a paste-ready inline embed command before any queue access; `--dry-run` evaluates the same read-only feasibility gate and never says “Would submit” for an impossible job. `--follow` is the sole CLI exception because it starts and awaits the inline worker; padded names follow the same normalized path and cannot strand a row. The MCP `submit_job` operation applies the same gate (including dry-run), translates the expected refusal to branchable `OperationError('no_worker_surface')`, and never emits `internal_error` for this capability miss. The `sync` handler forwards `job.data.github_item` ({repo, number, kind}) into `performSync` for github-kind single-item webhook refreshes. `jobs work` registers the shell handler always; the startup line names the flag first (`--allow-shell-jobs` / `GBRAIN_ALLOW_SHELL_JOBS=1`); `jobs start` computes `allowShellJobs` as `--allow-shell-jobs || GBRAIN_ALLOW_SHELL_JOBS === '1'` — the same literal `handlers/shell.ts` and `buildChildArgs` check. `extract-atoms-drain` accepts a trusted `retryRequestId` in submitted params; a new job ID distinguishes a newly approved malformed-output provider attempt from provider-free publication replay. PGLite `jobs --follow` still requires exclusive owner access.+- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. `jobs-readiness.ts` orchestrates bounded driver-lane and selected-child readiness before worker schema/recovery, handler registration or claims. After `ensureSchema`, `maybeRunWorkerStartupRecovery(queue, process.env, true)` runs for both bare and supervised workers; the final worker `ready` event publishes readiness, and a worker handed an owner status channel (`GBRAIN_WORKER_STATUS_PATH` or `GBRAIN_WORKER_STATUS_TOKEN`, even partially) refuses admission if its status cannot be published, while a legacy supervised worker (`GBRAIN_SUPERVISED=1` from a pre-0.59.1 owner, no channel) publishes nothing and proceeds; typed faults report `configuration_blocked` and exit `WORKER_EXIT_CONFIGURATION`, while transient readiness failures admit no jobs and remain retryable. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the subcommand switch — `jobs work --help` can never start a daemon; only `--help`/`-h` are help tokens (bare `help` can be a job name); cli.ts routes it engine-free via `SELF_HELP_WITHOUT_ENGINE` + `CLI_ONLY_SELF_HELP`. `formatJobDetail` prints the effective wall-clock budget (`Timeout:`/`Deadline:` — 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer; `timeout_at` is in `JOB_DATE_FIELDS` for thin-client rehydration. `jobs stats` prints a `Backpressure (24h)` line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the shared `GBRAIN_WEDGED_QUEUE_WARN_MINUTES` threshold — the read-only visibility for maxPending single-flight suppression. Pinned by `test/jobs-subcommand-help.serial.test.ts`, `test/jobs-format-detail.test.ts`, `test/jobs-stats-backpressure.serial.test.ts`. `case 'work'` wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke --sigkill-rescue` is the SIGKILL-rescue guard. `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs `MAINTENANCE_PHASES` (mixed ∪ global) once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` only when no phase failed, no synthesis/pattern child is incomplete, no work was explicitly budget/triage-deferred, and the run was neither aborted nor lock-stolen; benign warning-only runs remain eligible. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status --json` adds `processing_ready`, lowercase `processing_state` (`starting`/`ready`/`configuration_blocked`, or `unknown`/`stopped` without current state), `reason_code`, `blocked_since` and worker/child identities without changing `running` or crash counters. A live local pidfile keeps this diagnostic engine-free; a missing pidfile retains the DB-lock fallback. It consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output includes per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress. `parseJobIsolationFlag(args, env?)` (`--job-isolation`, space/= forms, `GBRAIN_JOB_ISOLATION` fallback, default inline); `case 'work'` resolves the actual selected child and validates its bounded protocol/capability handshake and warns when `--max-rss` is combined with isolation (watchdog covers the worker only); `case 'run-child'` is the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); the `db_dead` fatal text is verdict-aware (pool starved vs server unreachable). Generic `jobs submit` normalizes the job name once before trust, queueing, handler lookup, and audit; after the admission check and dry-run return, its explicit `ensureSchema()` preflight still runs before shell/handler validation so stale brains retain the canonical init/migration error precedence. On PGLite, `jobs submit embed-backfill` refuses with `no_worker_surface` and a paste-ready inline embed command before any queue access; `--dry-run` evaluates the same read-only feasibility gate and never says “Would submit” for an impossible job. `--follow` is the sole CLI exception because it starts and awaits the inline worker; padded names follow the same normalized path and cannot strand a row. The MCP `submit_job` operation applies the same gate (including dry-run), translates the expected refusal to branchable `OperationError('no_worker_surface')`, and never emits `internal_error` for this capability miss. The `sync` handler forwards `job.data.github_item` ({repo, number, kind}) into `performSync` for github-kind single-item webhook refreshes. `jobs work` registers the shell handler always; the startup line names the flag first (`--allow-shell-jobs` / `GBRAIN_ALLOW_SHELL_JOBS=1`); `jobs start` computes `allowShellJobs` as `--allow-shell-jobs || GBRAIN_ALLOW_SHELL_JOBS === '1'` — the same literal `handlers/shell.ts` and `buildChildArgs` check. `extract-atoms-drain` accepts a trusted `retryRequestId` in submitted params; a new job ID distinguishes a newly approved malformed-output provider attempt from provider-free publication replay. PGLite `jobs --follow` still requires exclusive owner access.- `src/commands/jobs.ts:refreshGatewayForJob` + `src/core/ai/gateway.ts:refreshGatewayEnvFromFilePlane` — long-lived-worker staleness boundary, three tiers: (1) DB-plane model config re-resolves per gateway-refresh job (`reconfigureGatewayWithEngine`); (2) FILE-plane config (`~/.gbrain/config.json`, incl. provider API keys) re-folds per job via the env-ONLY `refreshGatewayEnvFromFilePlane` — never a full `configureGateway(buildGatewayConfig(loadConfig()))`, which would clobber DB-plane-merged fields (base_urls, chat options) with file-plane-only values; (3) true process env vars are fixed at worker start and need a restart. `gbrain config set *_api_key` writes the DB plane, which `loadConfigWithEngine()` deliberately never merges for key fields — those writes do NOT reach workers (TODO filed to reroute them to the file plane). `facts-absorb` sits in `GATEWAY_REFRESH_JOB_NAMES`; its handler converts execution-time `chat_unavailable` in a KEYED worker into a typed retryable failure (`factsAbsorbShouldRetry`) while a keyless worker completes the job as a calm skip. Pinned by `test/jobs-gateway-refresh.serial.test.ts`.diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.mdindex 6e5fdfbb10..1195f10e24 100644--- a/docs/architecture/key-files/core-minions-1.md+++ b/docs/architecture/key-files/core-minions-1.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/minions/` — Minions job queue: BullMQ-inspired, Postgres-native (queue, worker, backoff, types, protected-names, quiet-hours, stagger, handlers/shell). Private dream-inline-* queues carry an explicit lifecycle: owner job id + owner token + a renewable lease (columns on minion_jobs; `queue.ts` `reconcilePrivateQueue` terminalizes one queue through the normal cancelJobs bookkeeping and stamps every cancellation with the machine-readable `private_queue_reconciled:` reason family; `renewPrivateQueueLease` is MONOTONIC — GREATEST — so a default-horizon renewal can never shrink a creation-time lease; `reconcileOrphanedPrivateQueues` cancels only provably-orphaned queues: no healthy child lock, owner terminal/missing or lease expired; legacy unowned rows are left to Doctor/retriage; `classifyPrivateQueueForRecovery` is PUBLIC so the doctor orphan check buckets through the same verdict). Recovery runs on every lane that can strand a queue: supervisor beforeSpawn, bare `gbrain jobs work` startup (skipped under GBRAIN_SUPERVISED=1 — the supervisor already ran it; autopilot children never set the flag, so autopilot spawns/respawns recover too), and dream-cycle start (cycle.ts, next to the cycle lock reap — the ONLY lane on PGLite, which inlines every child). `deriveWedgeSignal` is queue-aware: a dream-inline queue is never 'wedged' (no shared worker can claim it) — it reports `private_queue: true` so jobs stats / get_job_stats / doctor all point at reconciliation instead of the impossible worker restart.+- `src/core/minions/` — Minions job queue: BullMQ-inspired, Postgres-native (queue, worker, backoff, types, protected-names, quiet-hours, stagger, handlers/shell). Private dream-inline-* queues carry an explicit lifecycle: owner job id + owner token + a renewable lease (columns on minion_jobs; `queue.ts` `reconcilePrivateQueue` terminalizes one queue through the normal cancelJobs bookkeeping and stamps every cancellation with the machine-readable `private_queue_reconciled:` reason family; `renewPrivateQueueLease` is MONOTONIC — GREATEST — so a default-horizon renewal can never shrink a creation-time lease; `reconcileOrphanedPrivateQueues` cancels only provably-orphaned queues: no healthy child lock, owner terminal/missing or lease expired; legacy unowned rows are left to Doctor/retriage; `classifyPrivateQueueForRecovery` is PUBLIC so the doctor orphan check buckets through the same verdict). Recovery runs in `gbrain jobs work` after driver/selected-child readiness and `ensureSchema`, for bare AND supervised workers (including autopilot spawns/respawns); the standalone parent does not recover queues in `beforeSpawn`. `maybeRunWorkerStartupRecovery(queue, process.env, true)` keeps this worker-owned ordering even under `GBRAIN_SUPERVISED=1`. Dream-cycle start also recovers (cycle.ts, next to the cycle lock reap — the ONLY lane on PGLite, which inlines every child). `deriveWedgeSignal` is queue-aware: a dream-inline queue is never 'wedged' (no shared worker can claim it) — it reports `private_queue: true` so jobs stats / get_job_stats / doctor all point at reconciliation instead of the impossible worker restart.- `src/core/minions/admission.ts` — submit-side queue admission control (the drain-side pool-starvation half is the job-isolation work; claim fairness is a filed TODO, deliberately out of scope). Three primitives resolved per name via `resolveAdmissionPolicy` (config `minions.*` > per-name defaults tables, 60s in-process cache, fail-open with a once-per-process stderr warn; env kill-switch `GBRAIN_MINIONS_ADMISSION=0` disables all three): PARAM-COALESCING (`PARAM_COALESCE_DEFAULT` — on for `subagent`; `computeParamHash` = sha256 of stable-stringified payload excluding only `__param_hash` itself — `__owner_client_id` is deliberately INCLUDED so owner lanes never cross; parentless + waiting-only + age-bounded to ttl/2), WAITING-TTL (`WAITING_TTL_DEFAULT_HOURS` — 48h for `subagent`; swept by `MinionQueue.handleWaitingTTL` through `cancelJobs(ids, {reason, rootStatuses:['waiting']})` so descendants cancel, child_done lands, aggregator parents resolve, and the reason stamps ROOT ids only; ≤500/tick oldest-first; warn-before-act is `runWaitingTtlTick` — first tick counts affected + stamps `TTL_NOTICE_SHOWN_KEY` with an ISO timestamp, sweeping starts only after `ttlNoticeGraceMs()` (1h default, env `GBRAIN_MINIONS_TTL_NOTICE_GRACE_MS`) elapses; `gbrain upgrade` prints the same one-shot notice and starts the same clock; legacy `'true'` flag values sweep immediately), and NAME-GLOBAL QUOTA (`QUOTA_MAX_WAITING_DEFAULT` EMPTY by operator decision — activates only via `minions.quota_max_waiting.<name>`; counts the name across ALL queues so per-run `dream-inline-*` fanout queues can't dodge it, EXACT under concurrency via a `minion_quota:<name>` advisory xact lock taken only when a quota is configured; throws typed `QueueQuotaExceededError`, checked everywhere via `isQueueQuotaExceededError` — dream submitters record a phase skip, synthesize rolls back the current transcript's fresh chunks, agent fanout cancels the whole tree, `submit_agent` maps to a structured `rate_limited` OperationError). `TTL_REASON_PREFIX` is the single source for the sweep's error_text prefix and the stats/doctor LIKE patterns; `safeConfigSegment` gates untrusted job names out of copy-pasteable config hints. Alerting rides `getStats` (`drained_completed/failed/dead/cancelled` keyed on finished_at + `waiting_now` + `oldest_waiting_minutes`), the `jobs stats` DIVERGENT-QUEUE / waiting-TTL screams (`GBRAIN_QUEUE_DIVERGENCE_RATIO`=2, `GBRAIN_QUEUE_DIVERGENCE_MIN_WAITING`=50; divergence compares intake vs COMPLETED so TTL-cancel storms can't masquerade as throughput) + `--json`, and doctor `checkQueueHealth`. Pinned by `test/minions-admission.test.ts` + `test/jobs-stats-divergence.serial.test.ts`.@@ -13,11 +13,11 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/budget-meter.ts` — atomic reserve/settle accounting. Per-client advisory lock plus client row lock protects current cap and outstanding holds. NULL cap means unlimited; a caller's existing finite ceiling still applies. Pending and expired unresolved holds count across UTC dates; TTL marks overdue rather than releasing liability. Unknown-bound holds prevent subsequent finite admission until reconciled. Settlement is idempotent and writes reservation state plus spend log in one transaction. Tests cover races, changed caps, unknown usage, late settlement and both engines.-- `src/core/minions/child-job-runner.ts` — parent-side runner: `runJobInChild(opts)` spawns the child (detached + tini when available, stdio inherit for handler logs, per-job lifecycle log lines), maps per-job abort → group SIGTERM now + group SIGKILL at +25s (`CHILD_KILL_GRACE_MS`, inside the 30s force-evict backstop), gives worker-shutdown children the drain window to finish AND report (a non-reporting shutdown kill throws `ChildWorkerShutdownError` → released, no attempt burned), classifies pre-exec spawn failure as `ChildSpawnInfraError` (released, no attempt burned), and bounds child pools via env (`GBRAIN_POOL_SIZE` default 3, `GBRAIN_DIRECT_POOL_SIZE=1`). Pinned by `test/child-job-runner.test.ts` (real children) + `test/worker-job-isolation.test.ts` (full parent path on PGLite).+- `src/core/minions/child-job-runner.ts` — parent-side runner: `runJobInChild(opts)` spawns the child (detached + tini when available, stdio inherit for handler logs, per-job lifecycle log lines), maps per-job abort → group SIGTERM now + group SIGKILL at +25s (`CHILD_KILL_GRACE_MS`, inside the 30s force-evict backstop), gives worker-shutdown children the drain window to finish AND report (a non-reporting shutdown kill throws `ChildWorkerShutdownError` with separate `executionStopped` evidence; group cleanup retains its kill backstop after direct-child exit, and unconfirmed cleanup must not authorize configuration release). `onExecutionStopped` publishes confirmed no-execution failures or supported Linux owned-group/observed-descendant stop evidence once, including normal exits; a handler outcome alone is not that proof. After direct-child exit, termination settles as soon as supported Linux cleanup proof confirms the owned groups gone (bounded backoff poll); without proof the group is SIGKILLed immediately and the stop stays unconfirmed; surviving members still receive the grace SIGKILL. The runner classifies missing/non-executable child paths as `LocalConfigurationError` and other pre-exec spawn failures as `ChildSpawnInfraError` (no attempt burned), and bounds child pools via env (`GBRAIN_POOL_SIZE` default 3, `GBRAIN_DIRECT_POOL_SIZE=1`). Pinned by `test/child-job-runner.test.ts` (real children) + `test/worker-job-isolation.test.ts` (full parent path on PGLite).-- `src/core/minions/child-worker-supervisor.ts` — shared spawn-and-respawn core reused by both `MinionSupervisor` (standalone `gbrain jobs supervisor` daemon) and `src/commands/autopilot.ts` (autopilot daemon), so the two consumers can't drift into parallel-loop bugs. Pure class: NO PID file, NO signal handlers, NO `process.exit`, NO health check. Lifecycle events fire via injected `onEvent: (ChildSupervisorEvent) => void`. Exit classifier: `code === 0` leaves `crashCount` UNCHANGED (preserves flap detection across mixed exit sequences); `code != 0` follows `runDuration > stableRunResetMs ? 1 : ++crashCount`. Clean-restart budget: sliding window of code=0 exits; when count exceeds `cleanRestartBudget` (default 10) inside `cleanRestartWindowMs` (default 60s), emits `health_warn { reason: 'clean_restart_budget_exceeded' }` and applies `cleanRestartBudgetBackoffMs` (default 1s). The exit classifier special-cases `WORKER_EXIT_RSS_WATCHDOG` — `likely_cause='rss_watchdog'`, and that exit does NOT bump `crashCount` (routes to its own breaker); a dedicated `_watchdogExitTimestamps` sliding window trips a loud `rss_watchdog_loop` health_warn naming the cap when N watchdog exits land inside the window, INDEPENDENT of the stable-run reset (which would otherwise hide a >5-min-run watchdog drain loop). Opts `watchdogLoopBudget` (3), `watchdogLoopWindowMs` (600000), `watchdogBackoffMs` (30000); `ChildSupervisorEvent` extended. Public read-only accessors `childAlive`, `inBackoff`, `crashCount`; `killChild(signal)` gates on liveness (`exitCode === null && signalCode === null`), NOT `.killed` — `.killed` flips true once a signal is *sent*, so a `!this._child.killed` guard would make a follow-up SIGKILL after an ignored SIGTERM a silent no-op. `restartCurrentChild(graceMs)` (wedge self-heal) captures the CURRENT child ref, SIGTERM→grace→SIGKILLs THAT ref (never the respawn — closes the timer-kills-fresh-worker race), and flags `_intentionalRestart` so the exit is `likelyCause='wedge_restart'`, leaves `crashCount` UNTOUCHED (never trips `max_crashes`; like `rss_watchdog`), and respawns immediately (`backoff ms:0 reason='wedge_restart'`). `awaitChildExit(timeoutMs)` short-circuits when `child.exitCode !== null || child.signalCode !== null` so fast-SIGTERM responders don't cause a 35s shutdown hang. Degraded-retry: the `run()` loop does not fire `onMaxCrashesExceeded` at the soft `maxCrashes`; it announces `health_warn { reason: 'crash_budget_degraded' }` once per episode and keeps respawning with capped backoff (the 60s cap makes it a paced retry, not a hot loop), re-arming after a stable-run reset drops the count. Permanent give-up fires only at `hardStopMaxCrashes` (default `maxCrashes × HARD_STOP_CRASH_MULTIPLIER` = 10×; `0` disables). Test hooks `_backoffFloorMs`, `_now`. `supervisor-audit.ts` carries `rss_watchdog` as a non-clean cause + its own `CrashSummary.by_cause` bucket, and `wedge_restart` to `CLEAN_EXIT_CAUSES` (a self-heal, not a crash; denylist preserved so future causes route to `legacy`). Pinned by `test/child-worker-supervisor.test.ts` (12 cases).+- `src/core/minions/child-worker-supervisor.ts` — shared spawn-and-respawn core reused by both `MinionSupervisor` (standalone `gbrain jobs supervisor` daemon) and `src/commands/autopilot.ts` (autopilot daemon), so the two consumers can't drift into parallel-loop bugs. Pure spawn-loop class: NO PID file, NO signal handlers, NO `process.exit`, NO health check. `WORKER_EXIT_CONFIGURATION` and the generation-scoped `OwnerProcessingState` channel block spawning before generic crash accounting; `configurationBlocked` also prevents intentional watchdog/wedge restarts. The owner remains alive with additive readiness diagnostics until explicit restart after repair. Startup stages and retry deadlines remain visible, and missing readiness is bounded by the startup timeout and forced-stop backstop before ordinary crash-budget handling. The shared `processing-state.ts` validates bounded/redacted identities, correlates worker updates to the active runtime token, and does not turn a missing status file into readiness. Lifecycle events fire via injected `onEvent: (ChildSupervisorEvent) => void`. Exit classifier: `code === 0` leaves `crashCount` UNCHANGED (preserves flap detection across mixed exit sequences); `code != 0` follows `runDuration > stableRunResetMs ? 1 : ++crashCount`. Clean-restart budget: sliding window of code=0 exits; when count exceeds `cleanRestartBudget` (default 10) inside `cleanRestartWindowMs` (default 60s), emits `health_warn { reason: 'clean_restart_budget_exceeded' }` and applies `cleanRestartBudgetBackoffMs` (default 1s). The exit classifier special-cases `WORKER_EXIT_RSS_WATCHDOG` — `likely_cause='rss_watchdog'`, and that exit does NOT bump `crashCount` (routes to its own breaker); a dedicated `_watchdogExitTimestamps` sliding window trips a loud `rss_watchdog_loop` health_warn naming the cap when N watchdog exits land inside the window, INDEPENDENT of the stable-run reset (which would otherwise hide a >5-min-run watchdog drain loop). Opts `watchdogLoopBudget` (3), `watchdogLoopWindowMs` (600000), `watchdogBackoffMs` (30000); `ChildSupervisorEvent` extended. Public read-only accessors `childAlive`, `inBackoff`, `crashCount`; `killChild(signal)` gates on liveness (`exitCode === null && signalCode === null`), NOT `.killed` — `.killed` flips true once a signal is *sent*, so a `!this._child.killed` guard would make a follow-up SIGKILL after an ignored SIGTERM a silent no-op. `restartCurrentChild(graceMs)` (wedge self-heal) captures the CURRENT child ref, SIGTERM→grace→SIGKILLs THAT ref (never the respawn — closes the timer-kills-fresh-worker race), and flags `_intentionalRestart` so the exit is `likelyCause='wedge_restart'`, leaves `crashCount` UNTOUCHED (never trips `max_crashes`; like `rss_watchdog`), and respawns immediately (`backoff ms:0 reason='wedge_restart'`). `awaitChildExit(timeoutMs)` short-circuits when `child.exitCode !== null || child.signalCode !== null` so fast-SIGTERM responders don't cause a 35s shutdown hang. Degraded-retry: the `run()` loop does not fire `onMaxCrashesExceeded` at the soft `maxCrashes`; it announces `health_warn { reason: 'crash_budget_degraded' }` once per episode and keeps respawning with capped backoff (the 60s cap makes it a paced retry, not a hot loop), re-arming after a stable-run reset drops the count. Permanent give-up fires only at `hardStopMaxCrashes` (default `maxCrashes × HARD_STOP_CRASH_MULTIPLIER` = 10×; `0` disables). Test hooks `_backoffFloorMs`, `_now`. `supervisor-audit.ts` carries `rss_watchdog` as a non-clean cause + its own `CrashSummary.by_cause` bucket, and `wedge_restart` to `CLEAN_EXIT_CAUSES` (a self-heal, not a crash; denylist preserved so future causes route to `legacy`). Pinned by `test/child-worker-supervisor.test.ts` (12 cases).-- `src/core/minions/db-probe.ts` — hermetic DB-liveness probe with pool-starvation disambiguation: `runDbProbe(deps)` probes the read pool (signal-cancelled at `timeoutMs`), on failure probes the DIRECT lane (`DIRECT_PROBE_TIMEOUT_MS`, only when dual-pool is genuinely active) and returns a verdict — `pool_starved` ("server IS reachable; fault is in the transaction-pooler path — client pool exhaustion or a pooler-layer fault", deliberately an honest disjunction), `server_unreachable`, or `unknown`. Gauge counts render as a labeled tracked SUBSET; no waiter/available arithmetic. Pinned by `test/db-probe.test.ts`.+- `src/core/minions/db-probe.ts` — hermetic DB-liveness probe with pool-starvation disambiguation: `runDbProbe(deps)` probes the read pool (signal-cancelled at `timeoutMs`), on failure probes the DIRECT lane (`DIRECT_PROBE_TIMEOUT_MS`, only when dual-pool is genuinely active) and returns a verdict — `pool_starved` ("server IS reachable; fault is in the transaction-pooler path — client pool exhaustion or a pooler-layer fault", deliberately an honest disjunction), `server_unreachable`, `unknown`, or typed `client_misconfigured`. `runDbReadinessProbe` checks every required lane even after read success; a `LocalConfigurationError` on either lane wins over outage classification. Ordinary abort/network/timeout errors stay transient. Gauge counts render as a labeled tracked SUBSET; no waiter/available arithmetic. Pinned by `test/db-probe.test.ts`.- `src/core/minions/delegated-admission.ts` + `delegated-tools.ts` — queue admission locks the client row through validation, idempotency/coalescing, counting all nonterminal owned jobs across queues, and insertion. Returning an identical existing job adds no slot. Every delegated tool execution, including replay and one-shot writes, rechecks the current intersection and rebuilds the operation context with its current source/path bounds and authenticated read-source ceiling, including explicit per-call source overrides. Remote-owned writes cannot overwrite private existing pages (including dedup redirects), append their timeline, or run trusted-workspace auto-link/timeline hooks. One-shot remote-owned writes keep links as literal text without probing hidden target existence or counts; trusted local behavior is preserved. Trusted owner fields are separate from user parameters. Replay cannot replace identity or original bounds; valid owned replays and terminal-job retries consume a slot under the same client lock. Legacy terminal jobs missing a stored ceiling require fresh authenticated submission.@@ -57,11 +57,11 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/handlers/subagent.ts` — LLM-loop handler. Two-phase tool persistence (pending → complete/failed), replay reconciliation for mid-dispatch crashes, dual-signal abort (`ctx.signal` + `ctx.shutdownSignal`), Anthropic prompt caching on system + tool defs. `makeSubagentHandler({engine, client?, ...})` factory; `MessagesClient` is an injectable interface the real SDK implements structurally. Per-turn output cap resolves via `resolveMaxOutputTokens` (`data.max_tokens` → `agent.max_output_tokens` config → 8192 default); a `stop_reason: 'max_tokens'` final turn surfaces as `SubagentStopReason 'max_tokens'` (not a silent `end_turn`), and a max_tokens stop mid-tool-round injects a truncation note into the tool-result turn so the model re-issues the dropped call. Throws `RateLeaseUnavailableError` (renewable) when rate-lease capacity is full. Both loop paths (the direct Anthropic SDK turn loop and the gateway toolLoop's `acquireTurnPermit`) heartbeat the held lease at ttl/3 for the duration of each provider call — single-flight renewals so a stalled renewal never stacks behind a starved pool; a FALSE renewal means the lease row was pruned/stolen (the slot is already re-admitted), so the in-flight call aborts and converts to a lease-full requeue instead of running above `maxConcurrent`. Anthropic 400 `prompt is too long` responses (status 400 + body matches `/prompt is too long|prompt_too_long|context.*length/i`) classify as `UnrecoverableError` so the job goes straight to `dead` on first attempt instead of stalling three times. Catches both initial-prompt overflow and turn-N tool-loop accumulation that `synthesize.ts`'s chunker can't bound ahead of time. terminal-state short-circuit on resume. When a stored message thread already ends in `stop_reason: 'end_turn'`, the handler returns `{ ok: true }` immediately instead of issuing another `messages.create` call (re-prompting past `end_turn` would get a 400 and dead-letter an already-successful job). Pinned by `test/subagent-handler.test.ts`. Oneshot dispatch: `data.mode === 'oneshot'` on a FRESH job (zero persisted messages) routes to `runSubagentOneshot` (subagent-oneshot.ts) before either loop; a validation fallback re-enters the loops in the SAME job, stamped `synth_mode_used: 'agentic_fallback'` + `fallback_reason`. Write accounting (`finalizeWriteAccounting` in subagent-persistence.ts): every job's result carries pages_attempted/written/failed derived from the tool-execution ledger (settled rows only); `data.require_writes` jobs (dream synthesize + patterns fan-outs) require at least one settled successful page write; zero successes, including a clean prose-only finish or pending-only ledger, throw UnrecoverableError. Optional-write jobs can still complete without writing. `resolveMaxOutputTokens` takes the model: thinking-by-default models (Claude 5 by name or recipe-declared `thinking_by_default` such as DeepSeek v4, via the gateway's shared `isThinkingModel`) default to 32000 when neither per-job nor config caps are set. Gateway-path `onToolCallStart` has a uniq_subagent_tools_use_id backstop: a provider repeating a tool id across turns persists under a `#m<idx>o<ordinal>`-suffixed debug id (second violation reconciles to the existing row's gbrain_tool_use_id) instead of dead-lettering the job. Persistence helpers live in subagent-persistence.ts (pure peel; `__testing` unchanged). Tool-execution rows carry NO job-wide unique on the raw provider `tool_use_id` (migration v131 drops `uniq_subagent_tools_use_id`: providers like claude-cli legitimately re-mint the same short id every turn, and a collision would dead-letter the job); row identity is the stable `(job_id, message_idx, ordinal)` unique, and readers/settlement resolve an execution by `(message_idx, tool_use_id)`. Settle writes (complete/failed) target exactly ONE row — the call's own ordinal first, then a legacy ordinal=NULL row, never a row that already settled complete (a broader status disjunct could only capture a same-id sibling's row); pending inserts guard legacy NULL-ordinal rows via NOT EXISTS and use the stable-id `ON CONFLICT` as the zombie-worker backstop. Replay/reconcile resolve an execution by persisted ordinal first (validated against the raw id), then by `(message_idx, tool_use_id)` only when the id is unique within the turn, then the same-tool legacy positional fallback. Mixed-version window: a still-running pre-v131 `gbrain jobs work` daemon errors on tool persistence after the migration until it restarts (its two-phase writes targeted the dropped constraint)-- `src/core/minions/handlers/supervisor-audit.ts` — supervisor lifecycle JSONL audit at `~/.gbrain/audit/supervisor-YYYY-Www.jsonl` (ISO-week rotation; shares `computeIsoWeekName()` with `shell-audit.ts`). `writeSupervisorEvent(emission, supervisorPid)` appends one line per event (`started`, `worker_spawned`, `worker_exited`, `backoff`, `health_warn`, `health_error`, `max_crashes_exceeded`, `shutting_down`, `stopped`, `worker_spawn_failed`). `readSupervisorEvents({sinceMs})` is the readback for `gbrain doctor`. Exports `isCrashExit(event)`, `summarizeCrashes(events)`, `CrashSummary` type, and `CLEAN_EXIT_CAUSES` denylist (`'clean_exit' | 'graceful_shutdown'`). Single shared point — both `gbrain doctor` (supervisor check) and `gbrain jobs supervisor status` import from here so the two surfaces can't drift. `isCrashExit` classifies a single `worker_exited` against the denylist: clean/graceful are NON-crashes; everything else (incl. any future `likely_cause` from `child-worker-supervisor.ts`) is a crash; audit lines lacking `likely_cause` fall back to `code !== 0`. `summarizeCrashes` returns `{total, by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}, clean_exits}` — the `legacy` bucket catches both old fallback entries AND unrecognized future causes (fail-loud, not silent underreport); denylist-over-allowlist is deliberate. Pinned by `test/supervisor-audit.test.ts` (14 cases) and 4 source-grep wiring assertions in `test/doctor.test.ts`.+- `src/core/minions/handlers/supervisor-audit.ts` — supervisor lifecycle JSONL audit at `~/.gbrain/audit/supervisor-YYYY-Www.jsonl` (ISO-week rotation; shares `computeIsoWeekName()` with `shell-audit.ts`). `writeSupervisorEvent(emission, supervisorPid)` appends one line per event (`started`, `worker_spawned`, `worker_exited`, `backoff`, `health_warn`, `health_error`, `max_crashes_exceeded`, `shutting_down`, `stopped`, `worker_spawn_failed`). `readSupervisorEvents({sinceMs})` is the readback for `gbrain doctor`. Exports `isCrashExit(event)`, `summarizeCrashes(events)`, `CrashSummary` type, and `CLEAN_EXIT_CAUSES` denylist (`'clean_exit' | 'graceful_shutdown' | 'wedge_restart' | 'configuration_blocked'`). Single shared point — both `gbrain doctor` (supervisor check) and `gbrain jobs supervisor status` import from here so the two surfaces can't drift. `isCrashExit` classifies a single `worker_exited` against the denylist: clean/graceful, deliberate wedge restarts and configuration blocks are NON-crashes; everything else (incl. any future `likely_cause` from `child-worker-supervisor.ts`) is a crash; audit lines lacking `likely_cause` fall back to `code !== 0`. `summarizeCrashes` returns `{total, by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}, clean_exits}` — the `legacy` bucket catches both old fallback entries AND unrecognized future causes (fail-loud, not silent underreport); denylist-over-allowlist is deliberate. Pinned by `test/supervisor-audit.test.ts` (14 cases) and 4 source-grep wiring assertions in `test/doctor.test.ts`.- `src/core/minions/job-context.ts` — shared `buildJobContext(engine, queue, job, lockToken, signal, shutdownSignal)` (extracted verbatim from executeJob) so inline mode and the run-child child wire identical token-fenced DB callbacks.-- `src/core/minions/job-isolation.ts` — per-job process-isolation protocol: atomic outcome-file codec (`writeChildOutcomeFile` tmp+rename, `decodeChildOutcomeFile` with a 32MiB cap that throws `UnrecoverableError` — oversize results die loudly on attempt 1, decode errors report byte counts never content), `encodeHandlerError`/`reconstructHandlerError` preserving the two `instanceof` classes executeJob branches on (UnrecoverableError, RateLeaseUnavailableError), the child argv/env contract (`CHILD_ENV`, `buildChildArgs`), `resolveChildCliInvocation` (env override → compiled binary → bun-dev fallback → null for fail-fast), and `killProcessGroup(pid, sig)` — children are spawned detached (own group) because SIGKILL on a tini pid alone orphans the handler grandchild, and Bun rejects negative pids in process.kill (oven-sh/bun#15791) so group signaling falls back to POSIX /bin/kill. Pinned by `test/job-isolation-protocol.test.ts` (incl. real-process grandchild-death). `buildChildArgs(jobId, env = process.env)` appends `--allow-shell-jobs` when `env.GBRAIN_ALLOW_SHELL_JOBS === '1'` (child-job-runner passes its spawning env), because the per-job child re-runs the cwd-.env preflight in the worker's cwd and would otherwise lose the opt-in; `jobs run-child` re-asserts the env from that flag. Pinned by `test/job-isolation-allow-shell-jobs.test.ts`. `child-job-runner.ts` passes `opts.env ?? process.env` as the base env, so `GBRAIN_ALLOW_SHELL_JOBS === '1'` in it appends `--allow-shell-jobs` (any other value does not); pinned by the pass-through case in `test/child-job-runner.test.ts`.+- `src/core/minions/job-isolation.ts` — per-job process-isolation protocol: atomic outcome-file codec (`writeChildOutcomeFile` tmp+rename, `decodeChildOutcomeFile` with a 32MiB cap that throws `UnrecoverableError` — oversize results die loudly on attempt 1, decode errors report byte counts never content), `encodeHandlerError`/`reconstructHandlerError` preserving `UnrecoverableError`, `RateLeaseUnavailableError`, and allowlisted `LocalConfigurationError` reason codes; configuration messages are reconstructed locally rather than trusting child text, the child argv/env contract (`CHILD_ENV`, `buildChildArgs`), `resolveChildCliInvocation` (explicit `GBRAIN_JOB_CHILD_CLI` override → current worker entrypoint/compiled executable → PATH fallback → null for fail-fast), and the bounded selected-runtime handshake in `child-readiness.ts` (protocol/features plus version-skew reporting; 20s deadline and combined 64KiB stdout/stderr cap; only complete allowlisted replies prove configuration failure). `killProcessGroup(pid, sig)` — children are spawned detached (own group) because SIGKILL on a tini pid alone orphans the handler grandchild, and Bun rejects negative pids in process.kill (oven-sh/bun#15791) so group signaling falls back to POSIX /bin/kill. Pinned by `test/job-isolation-protocol.test.ts` (incl. real-process grandchild-death). `buildChildArgs(jobId, env = process.env)` appends `--allow-shell-jobs` when `env.GBRAIN_ALLOW_SHELL_JOBS === '1'` (child-job-runner passes its spawning env), because the per-job child re-runs the cwd-.env preflight in the worker's cwd and would otherwise lose the opt-in; `jobs run-child` re-asserts the env from that flag. Pinned by `test/job-isolation-allow-shell-jobs.test.ts`. `child-job-runner.ts` passes `opts.env ?? process.env` as the base env, so `GBRAIN_ALLOW_SHELL_JOBS === '1'` in it appends `--allow-shell-jobs` (any other value does not); pinned by the pass-through case in `test/child-job-runner.test.ts`.- `src/core/minions/lock-renewal-tick.ts` — Pure function behind `MinionWorker.launchJob`'s setInterval body, structured so a renewal failure can never surface as an unhandledRejection, carrying the verify-before-evict doctrine. Exports `runLockRenewalTick(deps, state) → Promise<TickResult>` + `resolveLockRenewalKnobs(env, lockDuration, intervalMs?) → LockRenewalKnobs` + `RenewalCallTimeoutError` + `LockRenewalTelemetryCtx`. Doctrine: a thrown/timed-out renewal is NOT evidence of loss — when the NEXT tick would land past the soft deadline (`lease - safetyMargin`, cadence-aware: `sinceLastSuccess + intervalMs >= deadline`), the tick runs ONE bounded fenced VERIFY renewal. Fenced-true → starved-but-ours, lease re-extended, counter reset (audit `success_after_failure` with `via: 'verify'`); fenced-false → CERTAIN loss → `lock_lost` (the only certain signal); verify unreachable → defer + reconnect-once (audit `failure` with `deadline_deferred: true`), aborting only past `hardEvictMs` — a LOCAL decision under uncertainty bounding blind external side effects during a total outage. Four env knobs, positive-int parsed with stderr-warn-once + default fallback, then RELATIONALLY validated (margin < lease/2, callTimeout ≤ cadence, hardEvict ≥ soft deadline — warn-once clamps): `GBRAIN_LOCK_RENEWAL_MAX_FAILURES` (default 3, audit-labeling only), `GBRAIN_LOCK_RENEWAL_CALL_TIMEOUT_MS` (default `min(lease/3, 15s)`), `GBRAIN_LOCK_RENEWAL_SAFETY_MARGIN_MS` (default `min(lease/6, 30s)`), `GBRAIN_LOCK_RENEWAL_HARD_EVICT_MS` (default `2×lease`, floored to the soft deadline; setting it TO the deadline approximates abort-at-deadline). Telemetry: tick lateness (`now - lastTickFiredAt - intervalMs`, the primary local-starvation signal — interval callbacks COALESCE under a blocked loop so missed-tick counters can't measure starvation), `overlapSkips` (tickInFlight re-entrancy skips only), failure-cause classification via the named `RenewalCallTimeoutError` (`call-timeout` | `refused` | `fenced-lost`), optional `deps.loadSnapshot` (try/caught — telemetry must never throw into control flow) and `deps.onRenewalSuccess` (worker resets its event-loop-delay histogram). Elapsed-time arithmetic runs on the injected `deps.now`, which production binds to `performance.now()` (monotonic) — the local clock only schedules WHEN to verify, never WHETHER to evict. The race timeout also aborts the in-flight call via AbortSignal threaded to `renewLock` (best-effort — the fence is the correctness authority). The tick checks `state.cancelled()` at every await boundary (entry, post-resolve, post-throw, post-verify). Result is a tagged union: `should_abort` carries `{cause, latenessMs, sinceLastSuccessMs, overlapSkips, load1?, cores?}` and `lock_lost` carries `{cause: 'fenced-lost', via: 'renewal'|'verify'}`; the worker stashes the result as per-launch `abortMeta` so the grace-evict log (30s later) reports the classified cause. The in-tick verify is reconciled in-code with queue.ts's no-background-retry rationale: it is synchronous, cancelled()-guarded, and callTimeoutMs-bounded — both UPDATEs are same-token idempotent lease extensions, so a fenced row cannot gain two holders. Pinned by `test/worker-lock-renewal.test.ts` (hermetic state-machine suite incl. a fake-time starvation replay, the cadence-quantization pin, hard-backstop timelines, relational-clamp cases) + `test/e2e/worker-lock-renewal-starvation.test.ts` (real-PG foundations). `LockRenewalDeps.renewLock` carries an optional per-call `{signal}`; the timeout race aborts it so the losing UPDATE releases its slot.diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.mdindex 489dcd445f..c2642e48d8 100644--- a/docs/architecture/key-files/core-minions-2.md+++ b/docs/architecture/key-files/core-minions-2.md@@ -5,13 +5,13 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/run-child.ts` — `runChildJobEntry(engine, opts, injectables)`: the `jobs run-child` core. Re-reads the job row and validates status+token (exit 14 on mismatch, handler never runs), builds the shared token-fenced context against the CHILD's engine, runs the handler, writes ONE atomic outcome file (handler failure = reported outcome = exit 0; only write-failure exits 15). Installs a SIGTERM→shutdownSignal-ONLY handler (inline signal-separation parity: ctx.signal stays live so cooperative handlers finish + report inside the drain window; the parent's group SIGKILL at drain end is the backstop) and a parent-liveness watchdog polling `process.kill(parentPid, 0)` (ppid checks are dead code under tini) that aborts BOTH signals on parent death with a hard exit after grace. No worker machinery (parent owns liveness). Pinned by `test/run-child-entry.test.ts`.-- `src/core/minions/spawn-helpers.ts` — pure `detectTini()` + `buildSpawnInvocation()` consumed by both `supervisor.ts` and `autopilot.ts` (one implementation for both spawn sites; tini wrapping is testable without `mock.module()`, rule R2 of `scripts/check-test-isolation.sh`). `detectTini()` calls `execFileSync('which', ['tini'])` with explicit `env: process.env` so Bun sees runtime PATH mutations. `buildSpawnInvocation(tiniPath, cmd, args)` returns `{cmd, args}` with tini prepended when present, or the bare invocation otherwise. Pinned by `test/spawn-helpers.test.ts` (5) and `test/supervisor-tini.test.ts` (4).+- `src/core/minions/spawn-helpers.ts` — pure `detectTini()` + `buildSpawnInvocation()` consumed by both `supervisor.ts` and `autopilot.ts` (one implementation for both spawn sites; tini wrapping is testable without `mock.module()`, rule R2 of `scripts/check-test-isolation.sh`). `detectTini()` calls `execFileSync('which', ['tini'])` with explicit `env: process.env` so Bun sees runtime PATH mutations. `buildSpawnInvocation(tiniPath, cmd, args)` returns `{cmd, args}` with `tini -s --` prepended when present, or the bare invocation otherwise. Subreaper mode also serves job children; it does not imply PID 1 or containment of descendants that escape the process group. Pinned by `test/spawn-helpers.test.ts` (5) and `test/supervisor-tini.test.ts` (4).- `src/core/minions/submission-authority.ts` — versioned authority kept outside caller job data. Submission normalization and worker revalidation bind remote jobs to immutable principal/grant/source/payload ceilings; application authority preserves trusted internal work. `src/core/minions/authorize-legacy.ts` provides explicit local preview and transactional snapshot comparison for selected historical rows. `src/core/minions/source-filesystem.ts` provides reentrant canonical root/worktree locking and descriptor-based confined reads/writes. Both worker modes enforce the same authority gate. Upgrade protocol: `docs/guides/authorization-upgrade.md`.- `src/core/minions/supervisor-pid.ts` — `readSupervisorPid(pidFile) → {pid, running}`: the shared `existsSync → readFileSync → parseInt → process.kill(pid,0)` PID-file + liveness reader shared by `jobs.ts` (supervisor status), `jobs.ts` (stats), and `doctor.ts`. EPERM from the liveness probe counts as running. Pinned by `test/supervisor-pid.test.ts`.-- `src/core/minions/supervisor.ts` — MinionSupervisor process manager. Spawns `gbrain jobs work` as a child, restarts on crash with exponential backoff, periodic health check. `consecutiveHealthFailures` counter; on 3 consecutive failures emits `health_warn` with `reason: 'db_connection_degraded'` and calls `engine.reconnect()` to swap in a fresh pool, then resets. Worker exit classifier emits `likely_cause` on `worker_exited` events: `oom_or_external_kill` (SIGKILL), `graceful_shutdown` (SIGTERM), `runtime_error` (code 1), `clean_exit` (code 0), `unknown`. Consumes `detectTini()` + `buildSpawnInvocation()` from `src/core/minions/spawn-helpers.ts` to wrap the worker subtree in tini-as-PID-1 when tini is on `PATH` (handles native-addon zombie reaping the in-process SIGCHLD reaper can't reach); exposes `isTiniDetected` read-only accessor. The spawn-and-respawn loop is the shared `ChildWorkerSupervisor` core: MinionSupervisor composes it via `runSuperviseLoop()` → `new ChildWorkerSupervisor({...})` and maps `ChildSupervisorEvent` back through `emit()` SupervisorEvent (JSONL audit consumers see byte-compatible output). PID lock, signal handlers, health check, and `process.exit` on the HARD crash ceiling stay in MinionSupervisor. Crossing the SOFT budget (`maxCrashes`) does not permanently give up: the core drops into degraded retry (capped backoff + a `crash_budget_degraded` health_warn) and self-heals when a respawn runs stably; permanent `process.exit(MAX_CRASHES)` fires only at the hard ceiling `resolveHardStopMaxCrashes(maxCrashes)` (default `maxCrashes × 10`, env `GBRAIN_SUPERVISOR_HARD_STOP_CRASHES`, `0` = never). Separately, `gbrain jobs supervisor status` + `gbrain doctor` detect a live supervisor through this queue lock (`inspectLock` + `isLockHolderLive`, freshness-keyed so PID reuse can't false-positive) when the `$HOME`-derived pidfile is absent, so a split-`$HOME` deployment does not read a healthy supervisor as "not running". `code=0` leaves `crashCount` untouched (so a worker alternating real crashes + watchdog drains still trips `max_crashes`); `cleanRestartBudget` (default 10 restarts per 60s) caps the macOS/non-Linux-fallback tight-loop via `health_warn { reason: 'clean_restart_budget_exceeded' }` + backoff. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Progress watchdog: `healthCheck()` restarts an alive-but-wedged child via `childSupervisor.restartCurrentChild(35_000)` when a queue has claimable work, 0 live-lock active jobs, and stale completions across `wedgeRestartChecks` (default 3) consecutive checks past `wedgeRestartMinutes` (default 15, 0 disables) + a `startupGraceMs` window; bounded by `wedgeRestartLoopBudget` (default 3 / `wedgeRestartLoopWindowMs`) which switches to a one-shot `wedge_restart_loop` alert. The wedge query is the exported `queryWedgeSignals(engine, queue, handlerNames)` — name+queue-scoped, `active_healthy` = live-lock only (an expired-lock active row does NOT mask the wedge), due-delayed counted. Claimable names are derived at start via a throwaway `registerBuiltinHandlers` worker (its new `quiet` opt). Flags `--wedge-restart-minutes` / `--wedge-restart-checks` + env `GBRAIN_WEDGE_RESTART_MINUTES` / `GBRAIN_WEDGE_RESTART_CHECKS`. The worker argv is built by the exported pure `buildWorkerArgs(opts)` (appends `--nice N` when `opts.nice_requested` is set, alongside `--concurrency`/`--queue`/`--max-rss`); the niceness apply RESULT (`nice_requested`/`nice_effective`/`nice_error`, computed by the CLI in jobs.ts — the supervisor doesn't call setPriority) rides on the `started`/`worker_spawned` audit emissions. Queue-scoped singleton: the real authority is a DB lock (`tryAcquireDbLock` from `src/core/db-lock.ts`) keyed on `supervisorLockId(queue)` = `gbrain-supervisor:<queue>` — keyed on the QUEUE ALONE because the lock row lives inside the target database, so the (database) half of the mutex is physical, not part of the key (mixing in a config-derived DB identity would let two supervisors on the same physical DB via different-but-equivalent URLs compute different ids and both acquire). Two supervisors with different `$HOME`/`--pid-file` against the same `(database, queue)` cannot both run with conflicting `--max-rss`: the second exits `LOCK_HELD`. The pidfile-cleanup `process.on('exit')` listener is installed BEFORE the DB-lock acquisition so the `LOCK_HELD` early-exit can't strand the pidfile this process just created. The default pidfile is brain-scoped (`supervisor-<brainId>.pid`) so different brains under one HOME don't false-block. The lock refreshes on its own `setInterval` (TTL 5min, refresh 60s, max 3 failures = 180s < TTL); a refresh that THROWS past the threshold exits `LOCK_LOST` (code 4) rather than risk a split-brain, while a fenced refresh returning `false` (0 rows matched — the lock was stolen or force-cleared) is treated as CERTAIN loss, not a blip: the supervisor emits `health_error { reason: 'supervisor_lock_lost' }` and exits `LOCK_LOST` immediately (counting it toward the failure threshold would let two supervisors drain the same queue for up to two more refresh windows). `shutdown()` releases the lock so a clean restart re-acquires immediately. The `started` audit records `max_rss_mb` so `gbrain doctor`'s `supervisor_singleton` check can surface the effective cap. Exports `supervisorLockId()` and the pure `classifySupervisorSingleton({lockLive, lockHolderHost, lockHolderPid, localHost, localPid}) → 'no_lock'|'single'|'mismatch'` (host+pid compare, bare pid meaningless cross-host) that doctor consumes. Pinned by `test/supervisor.test.ts` (16 cases), `test/supervisor-tini.test.ts`, `test/supervisor-wedge.test.ts`, `test/supervisor-build-worker-args.test.ts`, and `test/supervisor-db-lock.test.ts`. `SupervisorOpts.jobIsolation` passes `--job-isolation process` to the spawned worker via a CONDITIONAL `buildWorkerArgs` push (inline argv stays byte-identical). `queryWedgeSignals`/`probeQueueState` thread a per-probe AbortSignal; the probe timeout cancels the losing query (pool-slot release under exhaustion). `buildWorkerArgs` also appends `--allow-shell-jobs` when `opts.allowShellJobs` (conditional push like `--job-isolation`, so existing argv stays byte-identical; pinned by `test/supervisor-build-worker-args.test.ts`). Rationale: the worker's startup cwd-.env quarantine drops `GBRAIN_ALLOW_SHELL_JOBS` whenever a .env in the worker's cwd assigns it, so the env copy in `runSuperviseLoop` alone could silently disable shell jobs; `jobs work` parses the flag and re-sets `process.env.GBRAIN_ALLOW_SHELL_JOBS='1'` after preflight (read sites in jobs.ts / handlers/shell.ts unchanged). `allowShellJobs` sets the env var on the child AND pushes `--allow-shell-jobs`.+- `src/core/minions/supervisor.ts` — MinionSupervisor process manager. Spawns `gbrain jobs work` as a child, retries ordinary crashes with exponential backoff and runs periodic health checks. The default launcher prefers the current source/compiled CLI over PATH; internal `cliArgsPrefix` carries source-entrypoint arguments while explicit `--cli-path` remains authoritative. Private-queue recovery belongs to the ready worker, not the parent spawn hook. A typed local configuration fault leaves the owner alive but blocks respawns, recovery and progress-watchdog actions; repair plus explicit owner restart is required. `OwnerProcessingState` supplies additive live readiness and redacted runtime identities. `consecutiveHealthFailures` counter; on 3 consecutive failures emits `health_warn` with `reason: 'db_connection_degraded'` and calls `engine.reconnect()` to swap in a fresh pool, then resets. Worker exit classifier emits `likely_cause` on `worker_exited` events: `oom_or_external_kill` (SIGKILL), `graceful_shutdown` (SIGTERM), `runtime_error` (code 1), `clean_exit` (code 0), `unknown`. Consumes `detectTini()` + `buildSpawnInvocation()` from `src/core/minions/spawn-helpers.ts` to wrap the worker subtree in `tini -s` subreaper mode when tini is on `PATH` (without assuming PID 1) (handles native-addon zombie reaping the in-process SIGCHLD reaper can't reach); exposes `isTiniDetected` read-only accessor. The spawn-and-respawn loop is the shared `ChildWorkerSupervisor` core: MinionSupervisor composes it via `runSuperviseLoop()` → `new ChildWorkerSupervisor({...})` and maps `ChildSupervisorEvent` back through `emit()` SupervisorEvent (JSONL audit consumers see byte-compatible output). PID lock, signal handlers, health check, and `process.exit` on the HARD crash ceiling stay in MinionSupervisor. Crossing the SOFT budget (`maxCrashes`) does not permanently give up: the core drops into degraded retry (capped backoff + a `crash_budget_degraded` health_warn) and self-heals when a respawn runs stably; permanent `process.exit(MAX_CRASHES)` fires only at the hard ceiling `resolveHardStopMaxCrashes(maxCrashes)` (default `maxCrashes × 10`, env `GBRAIN_SUPERVISOR_HARD_STOP_CRASHES`, `0` = never). Separately, `gbrain jobs supervisor status` + `gbrain doctor` detect a live supervisor through this queue lock (`inspectLock` + `isLockHolderLive`, freshness-keyed so PID reuse can't false-positive) when the `$HOME`-derived pidfile is absent, so a split-`$HOME` deployment does not read a healthy supervisor as "not running". `code=0` leaves `crashCount` untouched (so a worker alternating real crashes + watchdog drains still trips `max_crashes`); `cleanRestartBudget` (default 10 restarts per 60s) caps the macOS/non-Linux-fallback tight-loop via `health_warn { reason: 'clean_restart_budget_exceeded' }` + backoff. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Progress watchdog: `healthCheck()` restarts an alive-but-wedged child via `childSupervisor.restartCurrentChild(35_000)` when a queue has claimable work, 0 live-lock active jobs, and stale completions across `wedgeRestartChecks` (default 3) consecutive checks past `wedgeRestartMinutes` (default 15, 0 disables) + a `startupGraceMs` window; bounded by `wedgeRestartLoopBudget` (default 3 / `wedgeRestartLoopWindowMs`) which switches to a one-shot `wedge_restart_loop` alert. The wedge query is the exported `queryWedgeSignals(engine, queue, handlerNames)` — name+queue-scoped, `active_healthy` = live-lock only (an expired-lock active row does NOT mask the wedge), due-delayed counted. Claimable names are derived at start via a throwaway `registerBuiltinHandlers` worker (its new `quiet` opt). Flags `--wedge-restart-minutes` / `--wedge-restart-checks` + env `GBRAIN_WEDGE_RESTART_MINUTES` / `GBRAIN_WEDGE_RESTART_CHECKS`. The worker argv is built by the exported pure `buildWorkerArgs(opts)` (appends `--nice N` when `opts.nice_requested` is set, alongside `--concurrency`/`--queue`/`--max-rss`); the niceness apply RESULT (`nice_requested`/`nice_effective`/`nice_error`, computed by the CLI in jobs.ts — the supervisor doesn't call setPriority) rides on the `started`/`worker_spawned` audit emissions. Queue-scoped singleton: the real authority is a DB lock (`tryAcquireDbLock` from `src/core/db-lock.ts`) keyed on `supervisorLockId(queue)` = `gbrain-supervisor:<queue>` — keyed on the QUEUE ALONE because the lock row lives inside the target database, so the (database) half of the mutex is physical, not part of the key (mixing in a config-derived DB identity would let two supervisors on the same physical DB via different-but-equivalent URLs compute different ids and both acquire). Two supervisors with different `$HOME`/`--pid-file` against the same `(database, queue)` cannot both run with conflicting `--max-rss`: the second exits `LOCK_HELD`. The pidfile-cleanup `process.on('exit')` listener is installed BEFORE the DB-lock acquisition so the `LOCK_HELD` early-exit can't strand the pidfile this process just created. The default pidfile is brain-scoped (`supervisor-<brainId>.pid`) so different brains under one HOME don't false-block. The lock refreshes on its own `setInterval` (TTL 5min, refresh 60s, max 3 failures = 180s < TTL); a refresh that THROWS past the threshold exits `LOCK_LOST` (code 4) rather than risk a split-brain, while a fenced refresh returning `false` (0 rows matched — the lock was stolen or force-cleared) is treated as CERTAIN loss, not a blip: the supervisor emits `health_error { reason: 'supervisor_lock_lost' }` and exits `LOCK_LOST` immediately (counting it toward the failure threshold would let two supervisors drain the same queue for up to two more refresh windows). `shutdown()` releases the lock so a clean restart re-acquires immediately. The `started` audit records `max_rss_mb` so `gbrain doctor`'s `supervisor_singleton` check can surface the effective cap. Exports `supervisorLockId()` and the pure `classifySupervisorSingleton({lockLive, lockHolderHost, lockHolderPid, localHost, localPid}) → 'no_lock'|'single'|'mismatch'` (host+pid compare, bare pid meaningless cross-host) that doctor consumes. Pinned by `test/supervisor.test.ts` (16 cases), `test/supervisor-tini.test.ts`, `test/supervisor-wedge.test.ts`, `test/supervisor-build-worker-args.test.ts`, and `test/supervisor-db-lock.test.ts`. `SupervisorOpts.jobIsolation` passes `--job-isolation process` to the spawned worker via a CONDITIONAL `buildWorkerArgs` push (inline argv stays byte-identical). `queryWedgeSignals`/`probeQueueState` thread a per-probe AbortSignal; the probe timeout cancels the losing query (pool-slot release under exhaustion). `buildWorkerArgs` also appends `--allow-shell-jobs` when `opts.allowShellJobs` (conditional push like `--job-isolation`, so existing argv stays byte-identical; pinned by `test/supervisor-build-worker-args.test.ts`). Rationale: the worker's startup cwd-.env quarantine drops `GBRAIN_ALLOW_SHELL_JOBS` whenever a .env in the worker's cwd assigns it, so the env copy in `runSuperviseLoop` alone could silently disable shell jobs; `jobs work` parses the flag and re-sets `process.env.GBRAIN_ALLOW_SHELL_JOBS='1'` after preflight (read sites in jobs.ts / handlers/shell.ts unchanged). `allowShellJobs` sets the env var on the child AND pushes `--allow-shell-jobs`.- `src/core/minions/tool-write-identity.ts` — Binds a journal mutation to the persisted subagent execution coordinates with a deterministic UUIDv8 before dispatch. Legacy, gateway and oneshot replay preserve the same logical request across process restart; explicit caller IDs remain authoritative. Pending receipts leave tool ledgers pending for retry and never count as written pages.@@ -23,8 +23,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/wait-for-completion.ts` — poll-until-terminal helper for CLI callers. `TimeoutError` does NOT cancel the job; `AbortSignal` exits without throwing. Default `pollMs`: 1000 on Postgres, 250 on PGLite inline.-- `src/core/minions/worker-exit-codes.ts` — single source of truth for reserved worker process exit codes, shared by the worker (sets them) and supervisor/CLI (classify them). Exports `WORKER_EXIT_RSS_WATCHDOG = 12`. The RSS watchdog drain must be self-identifying: a code-0 exit is indistinguishable from a healthy queue-drain, so a `code===0 → clean_exit` classifier would never count it and a respawn loop would stay invisible. A distinct code makes the drain `likely_cause=rss_watchdog`. Code 12 is deliberately outside {0 clean, 1 runtime_error} and the 128+N signal range. Also reserves the `jobs run-child` codes: 13 usage/PGLite, 14 not-claimed/token-mismatch, 15 result-write-failed (result-file presence, not the exit code, classifies the normal path).+- `src/core/minions/worker-exit-codes.ts` — single source of truth for reserved worker process exit codes, shared by the worker (sets them) and supervisor/CLI (classify them). Exports `WORKER_EXIT_RSS_WATCHDOG = 12` and `WORKER_EXIT_CONFIGURATION = 16`; the latter blocks the owning supervisor before generic crash accounting and requires repair plus explicit restart. The RSS watchdog drain must be self-identifying: a code-0 exit is indistinguishable from a healthy queue-drain, so a `code===0 → clean_exit` classifier would never count it and a respawn loop would stay invisible. A distinct code makes the drain `likely_cause=rss_watchdog`. Code 12 is deliberately outside {0 clean, 1 runtime_error} and the 128+N signal range. Also reserves the `jobs run-child` codes: 13 usage/PGLite, 14 not-claimed/token-mismatch, 15 result-write-failed (result-file presence, not the exit code, classifies the normal path).- `src/core/minions/worker-registry.ts` — live worker registry backing niceness observability. Each running `gbrain jobs work` self-registers `worker-<pid>.json` under `gbrainPath('workers')` (brain-isolated via `GBRAIN_HOME`; entries tagged with `currentBrainId()` so multiple DBs under one home don't cross-report). `registerWorker(info)` is best-effort (never blocks the worker) and returns a cleanup fn the caller wires to BOTH the shutdown `finally` AND `process.on('exit')` (the unhealthy `process.exit(1)` bypasses the awaited finally). `readWorkers(getNice?)` enumerates the dir, drops confirmed-dead pids (`classifyLiveness`: ESRCH = dead/prune, EPERM = alive/keep), applies a pid-reuse start-time guard (zone-free `ps -o etime=` parsed by `parseEtimeToMs`, start = now - elapsed; rejects a pid that started >5s after the entry was written), and re-measures each live worker's niceness now. Reports the worker's REAL pid, sidestepping the tini-wrapper-pid problem. Pinned by `test/worker-registry.serial.test.ts`.-- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). Aborted jobs call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`); `shutdownAbort` (instance field) fires on SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` (shell handler listens; non-shell handlers don't). Per-job timeout fires `abort.abort(new Error('timeout'))` then a 30s grace-then-evict safety net force-evicts the job from `inFlight` and marks it dead if the handler ignores the abort signal (the generic abort listener fires for ANY abort reason). The `launchJob` lock-renewal block is a thin sync wrapper around the pure `runLockRenewalTick` from `src/core/minions/lock-renewal-tick.ts` (NEVER `setInterval(async () => await renewLock(...))` — that shape surfaces an unhandledRejection during PgBouncer rotation). Guarantees: (1) `cancelled` flag captured in the timer closure stops in-flight IIFEs writing misleading audit events after the job ended; (2) re-entrancy guard `tickInFlight` (skips counted as `overlapSkips` telemetry) + per-call `Promise.race` timeout with best-effort AbortSignal cancellation; (3) verify-before-evict: eviction requires a fenced-false (certain loss) or the `hardEvictMs` backstop — never bare local arithmetic; the per-job lease (`job.lock_duration_ms ?? opts.lockDuration`) drives the renewal state, and the cadence clamps to `min(lease/2, 60s)`; (4) explicit `.catch()` on the stored `executeJob(...).finally(...)` promise closes the second unhandledRejection vector; (5) exported `INFRASTRUCTURE_ABORT_REASONS = new Set(['lock-renewal-failed', 'lock-lost'])` so executeJob's catch skips `failJob` for these (PgBouncer blips don't dead-letter healthy jobs; the stall detector reclaims); (6) inFlight generation-safety — force-evict and the handler's finally delete the inFlight entry ONLY when it still carries their own lockToken (the token is the generation; an evicted execution's late delete cannot remove a same-worker re-claim's entry); (7) eviction observability — the worker keeps a `perf_hooks.monitorEventLoopDelay` histogram (reset on every successful renewal, sampled ns→ms at eviction) plus raw loadavg, and both the abort and grace-evict log lines carry cause / since-last-success / tick-lateness / overlap-skips / load / event-loop-delay from the stashed `abortMeta`. CI guard `scripts/check-worker-lock-renewal-shape.sh` (in `bun run verify`) asserts the bug pattern stays absent AND `launchJob` keeps calling `runLockRenewalTick`. Engine-ownership invariant: `start()` does NOT call `engine.disconnect()` on shutdown — the CLI handler in `src/commands/jobs.ts case 'work'` owns engine lifecycle via try/finally with loud error logging. RSS watchdog uses non-file-backed pages on Linux: exported `parseRssFromProcStatus(status)` (pure parser; field-presence regex so `RssAnon: 0 + RssShmem: 512` parses correctly) and `getAccurateRss(readStatus?)` (reads `/proc/self/status` for `RssAnon + RssShmem`, falls back to `process.memoryUsage().rss` on macOS / restricted containers / kernel <4.5); the default `getRss` in `WorkerOpts` is `getAccurateRss`. `checkMemoryLimit` tracks peak RSS, fires an 80%-of-cap soft-warn (once per crossing, carrying peak + in-flight job kinds), and on exceed sets `_rssWatchdogTriggered=true` (exposed via `get rssWatchdogTriggered()`) so `jobs work`'s finally can `process.exit(WORKER_EXIT_RSS_WATCHDOG)` after disconnect (drain self-identifying instead of an opaque code-0 exit). The poll loop wraps `claim` in try/catch: on a retryable conn error it reconnects ONCE and continues to the next tick rather than blind-retrying (a retry after `UPDATE...RETURNING` committed but the socket died would double-claim). `LockRenewalDeps` is wired with `reconnect` when the engine supports it. The self-health DB-liveness probe runs EVEN under a supervisor (`GBRAIN_SUPERVISED=1`): the outer guard is `if (this.opts.healthCheckInterval > 0)` and only the STALL-detection block is wrapped in `if (!isSupervisedChild)` — so a supervised worker whose own pool dies self-exits `unhealthy(db_dead)` after `dbFailExitAfter` probes (the supervisor watches a different connection and can't see this worker's dead pool), while the supervisor's progress watchdog owns forward-progress. Pinned by the `test/worker-lock-renewal.test.ts` hermetic suite, `test/audit/lock-renewal-audit.test.ts`, `test/scripts/check-worker-lock-renewal-shape.test.ts`, `test/worker-shutdown-disconnect.test.ts` (asserts `disconnectSpy).not.toHaveBeenCalled()`), `test/worker-rss.test.ts` (11), `test/worker-supervised-db-probe.test.ts` (3). Per-job process isolation: `MinionWorkerOpts.jobIsolation` (`inline`|`process`) + `childCliInvocation`/`childTiniPath` swap `handler(context)` for `runJobInChild(...)` in executeJob — every reporting branch (completeJob, failJob, lease release, infra no-burn) is reused on the child outcome; when isolated the parent-side context is not built at all. Three extra no-burn child classes in the catch: `ChildSpawnInfraError` + `ChildWorkerShutdownError` (released, no attempt burned) and `ChildNotClaimedError` (the child proved the claim was already gone — reclaimed/cancelled before the handler ran — so nothing is recorded against it). The health probe delegates to `runDbProbe` (db-probe.ts) with a cancellation signal on every probe and emits a `verdict` (`pool_starved`/`server_unreachable`/`unknown`) on the `db_dead` unhealthy payload. `getHandler(name)` is the read-only registry accessor run-child uses.+- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). The `ready` event follows final startup checks; listener failure stops startup before claims or timers. The renewal adapter latches typed configuration faults before the generic retry tick consumes them, including deadline verification. Configuration shutdown stops claims, tracks actual executions separately from scheduling slots, and releases only confirmed stopped work through `MinionQueue.releaseConfigurationJob` within one bounded shutdown envelope. The active/token-fenced release returns `released`, `no_op` or `unconfirmed`, leaves attempt/stall counters unchanged, and delays released work for 30 seconds; an unconfirmed stop or DB write falls back to lease expiry. Outstanding claims register their token before the post-claim configuration check so late claims cannot launch handlers. Aborted jobs call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`); `shutdownAbort` (instance field) fires on SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` (shell handler listens; non-shell handlers don't). Per-job timeout fires `abort.abort(new Error('timeout'))` then a 30s grace-then-evict safety net force-evicts the job from `inFlight` and marks it dead if the handler ignores the abort signal (the generic abort listener fires for ANY abort reason). The `launchJob` lock-renewal block is a thin sync wrapper around the pure `runLockRenewalTick` from `src/core/minions/lock-renewal-tick.ts` (NEVER `setInterval(async () => await renewLock(...))` — that shape surfaces an unhandledRejection during PgBouncer rotation). Guarantees: (1) `cancelled` flag captured in the timer closure stops in-flight IIFEs writing misleading audit events after the job ended; (2) re-entrancy guard `tickInFlight` (skips counted as `overlapSkips` telemetry) + per-call `Promise.race` timeout with best-effort AbortSignal cancellation; (3) verify-before-evict: eviction requires a fenced-false (certain loss) or the `hardEvictMs` backstop — never bare local arithmetic; the per-job lease (`job.lock_duration_ms ?? opts.lockDuration`) drives the renewal state, and the cadence clamps to `min(lease/2, 60s)`; (4) explicit `.catch()` on the stored `executeJob(...).finally(...)` promise closes the second unhandledRejection vector; (5) exported `INFRASTRUCTURE_ABORT_REASONS = new Set(['lock-renewal-failed', 'lock-lost'])` so executeJob's catch skips `failJob` for these (PgBouncer blips don't dead-letter healthy jobs; the stall detector reclaims); worker configuration shutdown is not in this set — it is gated separately by the typed `configurationError` latch; (6) inFlight generation-safety — force-evict and the handler's finally delete the inFlight entry ONLY when it still carries their own lockToken (the token is the generation; an evicted execution's late delete cannot remove a same-worker re-claim's entry); (7) eviction observability — the worker keeps a `perf_hooks.monitorEventLoopDelay` histogram (reset on every successful renewal, sampled ns→ms at eviction) plus raw loadavg, and both the abort and grace-evict log lines carry cause / since-last-success / tick-lateness / overlap-skips / load / event-loop-delay from the stashed `abortMeta`. CI guard `scripts/check-worker-lock-renewal-shape.sh` (in `bun run verify`) asserts the bug pattern stays absent AND `launchJob` keeps calling `runLockRenewalTick`. Engine-ownership invariant: `start()` does NOT call `engine.disconnect()` on shutdown — the CLI handler in `src/commands/jobs.ts case 'work'` owns engine lifecycle via try/finally with loud error logging. RSS watchdog uses non-file-backed pages on Linux: exported `parseRssFromProcStatus(status)` (pure parser; field-presence regex so `RssAnon: 0 + RssShmem: 512` parses correctly) and `getAccurateRss(readStatus?)` (reads `/proc/self/status` for `RssAnon + RssShmem`, falls back to `process.memoryUsage().rss` on macOS / restricted containers / kernel <4.5); the default `getRss` in `WorkerOpts` is `getAccurateRss`. `checkMemoryLimit` tracks peak RSS, fires an 80%-of-cap soft-warn (once per crossing, carrying peak + in-flight job kinds), and on exceed sets `_rssWatchdogTriggered=true` (exposed via `get rssWatchdogTriggered()`) so `jobs work`'s finally can `process.exit(WORKER_EXIT_RSS_WATCHDOG)` after disconnect (drain self-identifying instead of an opaque code-0 exit). The poll loop wraps `claim` in try/catch: on a retryable conn error it reconnects ONCE and continues to the next tick rather than blind-retrying (a retry after `UPDATE...RETURNING` committed but the socket died would double-claim). `LockRenewalDeps` is wired with `reconnect` when the engine supports it. The self-health DB-liveness probe runs EVEN under a supervisor (`GBRAIN_SUPERVISED=1`): the outer guard is `if (this.opts.healthCheckInterval > 0)` and only the STALL-detection block is wrapped in `if (!isSupervisedChild)` — so a supervised worker whose own pool dies self-exits `unhealthy(db_dead)` after `dbFailExitAfter` probes (the supervisor watches a different connection and can't see this worker's dead pool), while the supervisor's progress watchdog owns forward-progress. Pinned by the `test/worker-lock-renewal.test.ts` hermetic suite, `test/audit/lock-renewal-audit.test.ts`, `test/scripts/check-worker-lock-renewal-shape.test.ts`, `test/worker-shutdown-disconnect.test.ts` (asserts `disconnectSpy).not.toHaveBeenCalled()`), `test/worker-rss.test.ts` (11), `test/worker-supervised-db-probe.test.ts` (3). Per-job process isolation: `MinionWorkerOpts.jobIsolation` (`inline`|`process`) + `childCliInvocation`/`childTiniPath` swap `handler(context)` for `runJobInChild(...)` in executeJob — every reporting branch (completeJob, failJob, lease release, infra no-burn) is reused on the child outcome; when isolated the parent-side context is not built at all. Three extra no-burn child classes in the catch: `ChildSpawnInfraError` + `ChildWorkerShutdownError` (released, no attempt burned) and `ChildNotClaimedError` (the child proved the claim was already gone — reclaimed/cancelled before the handler ran — so nothing is recorded against it). The health probe delegates to `runDbProbe` (db-probe.ts) with a cancellation signal on every probe and emits a `verdict` (`pool_starved`/`server_unreachable`/`unknown`/`client_misconfigured`); typed configuration faults block immediately instead of burning the transient DB failure threshold. `getHandler(name)` is the read-only registry accessor run-child uses.diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex 257a112226..398964211e 100644--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `patches/[email protected]` — pinned ESM/CommonJS driver ownership and cancellation repair consumed by `PostgresEngine.runUnsafe`. Abortable reservations settle atomically; shared transaction queues isolate cancellable SQL from tagged/savepoint siblings while preserving unfenced pipelining. See [PostgreSQL cancellation ownership](../postgres-cancellation.md) for settlement, deadline, transport and clean-install invariants. Pinned by `test/e2e/persistence-chaos.test.ts`.+- `patches/[email protected]` — auditable delta for the driver ownership and cancellation repair already applied to the shipped `vendor/postgres` ESM/CommonJS/workerd source (not an install hook; `bash vendor/update-postgres.sh --check` verifies it), consumed by `PostgresEngine.runUnsafe` through `#postgres`. Abortable reservations settle atomically; shared transaction queues isolate cancellable SQL from tagged/savepoint siblings while preserving unfenced pipelining. See [PostgreSQL cancellation ownership](../postgres-cancellation.md) for settlement, deadline, transport and clean-install invariants. Pinned by `test/e2e/persistence-chaos.test.ts`.- `src/core/pglite-resetwal.ts` — pg_resetwal for PGLite NodeFS data dirs, in TypeScript (a port of the electric-sql/pglite pg_resetwal contribution, PR #994, Apache-2.0). Validates the PG17 pg_control layout fail-closed (`WalResetUnsupportedError` on any unsupported shape — PG_VERSION ≠ 17, control ≠ 8192 bytes, control version ≠ 1700, bad seg/block size), removes stale postmaster.pid + old WAL segments + archive_status/summaries entries, writes a replacement shutdown-checkpoint WAL segment + CRC32C'd pg_control. Both file writes are atomic + durable (tmp cleared then opened `'wx'` so a pre-planted symlink at the predictable tmp name can never redirect the write, + fsync(tmp) + rename + fsync(parent dir)); write order is segment-first/control-last so a mid-write kill leaves a state that still fails startup and the next attempt re-runs (idempotent — a torn pair can never claim success). WAL segment size is capped at 64MB (pglite ships 16MB; the Postgres-general 1GB bound would let a corrupt-but-plausible control field drive a 1GB allocation on the repair path). Exports the shared PG17 layout literals (`PG_CONTROL_FILE_SIZE`, `isWalSegmentName`) consumed by pglite-repair.ts. LAYOUT COUPLING: any pglite bump past PG17 must revisit this file together with the `./vector` export blocker (TODOS.md "pglite upgrade blocker" entry). Pinned by `test/pglite-resetwal.test.ts`.@@ -11,7 +11,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/pool-gauge.ts` — `CheckoutGauge`: approximate in-flight counters at the engine's raw/direct/reserved/tx seams, surfaced via duck-typed `PostgresEngine.getPoolDiagnostics()` (no BrainEngine change, no PGLite stub). HONESTY CONTRACT in the module doc: tagged-template traffic is untracked; consumers must label counts as a subset and never derive waiter/available figures. Fail-open (clamped release, try/finally around sync-throwing runUnsafe). Consumed by db-probe.ts. Pinned by `test/pool-gauge.test.ts`.-- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/postgres-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full public surface. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (an `unnest(${arr}::text[])` array-literal path would crash Postgres with "malformed array literal" on free text such as calendar/Zoom context) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `disconnect()` runs `drainBackgroundWorkBeforeDisconnect()` before pool teardown (engine parity with PGLiteEngine — mode `'disconnect'`, so residual telemetry buffers drop symmetrically on both engines; guarded so a never-connected/already-torn-down engine skips the drain). `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection. `getEmbeddingsByChunkIds` uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` routes text-embedding writes through the column registry (both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; so a registry-routed brain never writes with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — a superset of PGLite's probe set: the shared column-only forward-reference cases (`files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`/`archived_at`/`archive_expires_at`, `timeline_entries.event_page_id`) plus Postgres-blob-only probes for state the PGLite blob doesn't carry (`dream_verdicts.expires_at` — see the forward-reference-bootstrap.ts entry); the entire probe path runs on the DDL connection threaded from `initSchema` (so concurrent bootstraps cannot race on a Supabase pooler). `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-ownership.test.ts`. `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` do not hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). Test seam `__resetFactsEmbeddingCastCacheForTest()` clears the per-engine cache. `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds do not pin the worker's shared read pool — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`. `getRawData` joins `pages` and adds `p.deleted_at IS NULL` unless `opts.includeDeleted` (the `alive` fragment next to `privacy` in all six branches) so raw session metadata follows the page soft-delete; PGLite mirrors it with one `where.push`; pinned by the standalone getRawData describe in `test/e2e/engine-parity.test.ts` (PGLite arm always runs; Postgres arm when DATABASE_URL is set). `includeDeleted` is NOT on the shared `PageReadScope` (only getRawData honors it) — it is declared per-method as `getRawData(slug, source?, opts?: PageReadScope & { includeDeleted?: boolean })` in engine.ts and both engines; resolved only by trusted callers (export, engine migration; the ingest probe passes it but only ever runs against a live page), never from MCP parameters (`get_raw_data` builds its scope from `readPolicyOpts(ctx)`).+- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). The package-private `#postgres` import maps directly to the shipped cancellation-capable `vendor/postgres` source (the same source is embedded by compiled builds); `vendor/README.md` and the hash-verifying updater own provenance and regeneration. `postgres-engine/cancellation.ts` shares actual reserved-owner capability detection, typed `postgres_cancellation_unavailable` errors, and abort-bounded reservation with late-owner release; unsignalled diagnostic queries remain usable. Signalled SQL must retain cancellation/discard safety, including through transaction-mode poolers. The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/postgres-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full public surface. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (an `unnest(${arr}::text[])` array-literal path would crash Postgres with "malformed array literal" on free text such as calendar/Zoom context) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `disconnect()` runs `drainBackgroundWorkBeforeDisconnect()` before pool teardown (engine parity with PGLiteEngine — mode `'disconnect'`, so residual telemetry buffers drop symmetrically on both engines; guarded so a never-connected/already-torn-down engine skips the drain). `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection. `getEmbeddingsByChunkIds` uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` routes text-embedding writes through the column registry (both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; so a registry-routed brain never writes with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — a superset of PGLite's probe set: the shared column-only forward-reference cases (`files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`/`archived_at`/`archive_expires_at`, `timeline_entries.event_page_id`) plus Postgres-blob-only probes for state the PGLite blob doesn't carry (`dream_verdicts.expires_at` — see the forward-reference-bootstrap.ts entry); the entire probe path runs on the DDL connection threaded from `initSchema` (so concurrent bootstraps cannot race on a Supabase pooler). `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-ownership.test.ts`. `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` do not hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). Test seam `__resetFactsEmbeddingCastCacheForTest()` clears the per-engine cache. `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds do not pin the worker's shared read pool — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`. `getRawData` joins `pages` and adds `p.deleted_at IS NULL` unless `opts.includeDeleted` (the `alive` fragment next to `privacy` in all six branches) so raw session metadata follows the page soft-delete; PGLite mirrors it with one `where.push`; pinned by the standalone getRawData describe in `test/e2e/engine-parity.test.ts` (PGLite arm always runs; Postgres arm when DATABASE_URL is set). `includeDeleted` is NOT on the shared `PageReadScope` (only getRawData honors it) — it is declared per-method as `getRawData(slug, source?, opts?: PageReadScope & { includeDeleted?: boolean })` in engine.ts and both engines; resolved only by trusted callers (export, engine migration; the ingest probe passes it but only ever runs against a live page), never from MCP parameters (`get_raw_data` builds its scope from `readPolicyOpts(ctx)`).- `src/core/supabase-admin.ts` — Supabase Management-API client (`listProjects`, `discoverPoolerUrl`, `extractProjectRef` — refs are lowercase ALPHANUMERIC, `[a-z0-9]+`). Consumed by the `init --prefer-postgres` ladder's rung 2 (DISCOVERY only — project creation stays dashboard guidance; discovered URLs are candidates, connect-probed before persisting) and by the classifier's Supabase hints. The access token is never persisted, logged, or written to receipts/config.diff --git a/docs/architecture/postgres-cancellation.md b/docs/architecture/postgres-cancellation.mdindex d59585ddcd..6f7178426e 100644--- a/docs/architecture/postgres-cancellation.md+++ b/docs/architecture/postgres-cancellation.md@@ -1,6 +1,6 @@# PostgreSQL cancellation ownership-GBrain pins `postgres` to 3.4.9 and applies `patches/[email protected]` through Bun's `patchedDependencies`. The patch covers the ESM and CommonJS entrypoints and their shared types. Keep both implementations equivalent, and verify a clean frozen-lockfile install after changing the patch. An edited `node_modules` directory is not a distributable fix.+GBrain ships the exact `postgres` 3.4.9 source with `patches/[email protected]` already applied under `vendor/postgres`. The package-private `#postgres` import resolves directly to those bytes, so global installs do not depend on Bun applying transitive `patchedDependencies`. The patch covers the ESM, CommonJS and workerd entrypoints and their shared types. Keep the implementations equivalent, run `bash vendor/update-postgres.sh --check`, and verify isolated package and compiled installations after changing the patch. See [driver provenance and update instructions](../../vendor/README.md). An edited `node_modules` directory is not a distributable fix.## Dispatch and settlement@@ -29,3 +29,11 @@ Direct PostgreSQL closes the cancellation connection after handling the request.`test/e2e/persistence-chaos.test.ts` exercises active, queued, delayed and failed cancellation; transaction siblings; stale ownership; atomic reservation settlement; reconnects; completed cursors; and real socket backpressure in both module formats. Its optional PgBouncer case requires `GBRAIN_PGBOUNCER_URL` and `GBRAIN_PGBOUNCER_DIRECT_URL`, uses a dedicated test database, and verifies another client can reuse the same server backend without receiving a late cancellation.Keep the response-mapping, actual-settlement and unchanged persistence latency checks alongside these protocol tests. Global `max_pipeline: 1`, serializer fallbacks and blind retries are not substitutes for ownership isolation.++## Worker admission and configuration shutdown++Workers check the actual driver lanes and selected child executable before admitting jobs. Final database/schema checks precede the worker's `ready` event. A supervised worker must publish readiness through its current owner channel; a missing or unwritable channel does not authorize claims. An unconfirmed startup remains subject to the owner's bounded startup timeout and existing transient crash budget, rather than disabling its watchdog indefinitely.++A typed local configuration fault stops admission and starts one bounded drain. The queue releases only active claims whose lock token still matches and whose execution is confirmed stopped, without incrementing attempts or stalls. A completed handler outcome is not process-stop evidence: normal completion can still be recorded, but a failed completion write cannot authorize configuration release while descendants remain live.++For isolated jobs, stop evidence comes from a confirmed no-execution spawn failure or direct-child exit plus supported Linux process-group checks. The bounded `/proc` snapshots cover known owned groups and observed descendants. Failed or unsupported scans, surviving members, unknown tini child groups and observed escapes remain unconfirmed. These checks do not contain arbitrary historical descendants that escaped before observation; other platforms retain lease-expiry fallback rather than claiming equivalent process-tree proof. See [release-unconfirmed recovery](../guides/minions-fix.md#release-unconfirmed).diff --git a/docs/guides/minions-deployment.md b/docs/guides/minions-deployment.mdindex 35cc7ff57e..6096f9d97b 100644--- a/docs/guides/minions-deployment.md+++ b/docs/guides/minions-deployment.md@@ -64,6 +64,16 @@ An agent seeing exit=2 can safely treat it as "one is already running";exit=4 as "restart me — the DB lock refresh failed"; exit=1 should pagea human.+A local configuration fault does not produce a supervisor exit code. When+the worker finds that its installation or selected job child cannot run jobs+safely (for example, a driver without the required cancellation support or an+incompatible `GBRAIN_JOB_CHILD_CLI`), it exits with code 16. The supervisor then+stays alive without respawning it, and `status --json` reports+`processing_state: "configuration_blocked"` with a `reason_code`. Repair the+installation, then explicitly restart the supervisor; see+[Minions fix](minions-fix.md). A running supervisor is not proof of progress,+so check `processing_ready` as well as `running`.+### Lowering scheduling priority (`--nice`)When the worker pool runs at full concurrency on a machine you also use@@ -147,12 +157,17 @@ Sizing notes:- **Security note:** the child receives the job's lock token via env. It isa *fencing* token (split-brain protection), not a secret — same-user envalready contains the database URL.-- **Child CLI resolution:** the worker fail-fast validates the child CLI at- startup (compiled `gbrain` binary, bun-dev fallback, or the- `GBRAIN_JOB_CHILD_CLI` env override — the ops/test escape hatch). Three- consecutive child spawn/bootstrap failures self-exit the worker as- unhealthy (a deterministically broken child CLI) for process-manager- restart instead of burning attempts across the queue.+- **Child CLI resolution:** the worker selects the child CLI in this order:+ the `GBRAIN_JOB_CHILD_CLI` env override (the ops/test escape hatch), then+ its own compiled executable or source entrypoint, then `gbrain` on PATH.+ Before claiming any job it checks that the selected child exists and passes+ a compatibility handshake. A missing, non-executable or incompatible child+ is a configuration fault: the worker exits with code 16 and its supervisor+ stays up, blocked, instead of respawning it (see+ [Minions fix](minions-fix.md#configuration-blocked)). Three consecutive+ transient child spawn/bootstrap failures still self-exit the worker as+ unhealthy for process-manager restart instead of burning attempts across+ the queue.### Which supervisor when?@@ -211,7 +226,7 @@ gbrain jobs supervisor start --detach --json# Check health (machine-parseable JSON, no log scraping)gbrain jobs supervisor status --json-# → {"running":true,"supervisor_pid":1234,"last_start":"2026-04-23T15:30:22Z","crashes_24h":0, ...}+# → {"running":true,"processing_ready":true,"processing_state":"ready","supervisor_pid":1234,"last_start":"2026-04-23T15:30:22Z","crashes_24h":0, ...}# Stop cleanly (SIGTERM + 35s drain + SIGKILL fallback)gbrain jobs supervisor stop@@ -405,8 +420,8 @@ over relying on hard kills.## Smoke test```bash-# Supervisor alive?-gbrain jobs supervisor status --json | jq .running+# Supervisor alive, and admitting work?+gbrain jobs supervisor status --json | jq '{running, processing_ready, processing_state, reason_code}'# Aggregate queue health.gbrain jobs statsdiff --git a/docs/guides/minions-fix.md b/docs/guides/minions-fix.mdindex 6a1ccc0c3c..658c62f57f 100644--- a/docs/guides/minions-fix.md+++ b/docs/guides/minions-fix.md@@ -1,6 +1,417 @@-# Minions fix: repairing a half-migrated install+# Minions fix: repairing a blocked worker or half-migrated install-**tl;dr:** Minions self-heals on upgrade. If an install is only partially+**Say to your agent:** *"Use `gbrain jobs supervisor status --json` and+`gbrain doctor --no-migrate` to find why my worker stopped. Show me the affected+installation and proposed repair before changing anything or retrying jobs."*++A local driver or child-CLI configuration failure is not a database outage.+Repair the installation that actually runs the worker, then explicitly restart+its owner. Repeated restarts or replaying the queue do not repair a missing+driver capability.++For a **half-migrated install** (no completed migration, autopilot still inline,+or cron jobs still on `agentTurn`), use the [migration repair](#migration-repair)+below. Do not use migrations as a substitute for repairing a broken driver.++## Identify the owner and installation first++Work in the same account, brain, `GBRAIN_HOME`, configuration and environment as+the affected owner. A healthy `gbrain` in an interactive shell does not prove a+service uses that executable. Preserve queue, concurrency, CLI-path and other+existing launch options throughout the repair.++| Owner | Inspect | Stop processing before repair | Explicit restart after verification |+|---|---|---|---|+| Foreground `gbrain jobs work` | Its startup output and terminal | Ctrl-C in that terminal; wait for shutdown | Run the same `gbrain jobs work` invocation again |+| Standalone jobs supervisor | `gbrain jobs supervisor status --json` | `gbrain jobs supervisor stop --json` | `gbrain jobs supervisor start --detach --json` with the original options |+| Autopilot under user systemd | `gbrain autopilot --status --json`; `systemctl --user status gbrain-autopilot.service` | `systemctl --user stop gbrain-autopilot.service` | `systemctl --user start gbrain-autopilot.service` |+| Autopilot under launchd | `gbrain autopilot --status --json`; `launchctl print "gui/$(id -u)/com.gbrain.autopilot"` | `launchctl bootout "gui/$(id -u)/com.gbrain.autopilot"` | `launchctl bootstrap "gui/$(id -u)" "$HOME/Library/LaunchAgents/com.gbrain.autopilot.plist"` |++These are the default user-service names. If the installation uses a different+service definition, use its actual name and recorded launcher. For a foreground+autopilot or a container/cron owner, stop and restart that owner through its+existing launcher; do not start a competing standalone supervisor. A timed-out+stop is not confirmation that work has stopped. Inspect remaining processes+before proceeding.++For systemd, inspect `systemctl --user cat gbrain-autopilot.service`. For+launchd, inspect the installed plist's `ProgramArguments`. Follow any wrapper+to the exact executable or checkout it invokes. Do not paste environment+files, credentials or database URLs into a public report.++### Upgrade and rollback ordering++Upgrading while an older owner (0.59.0.0 or earlier) is still running keeps+working: that owner respawns the upgraded worker, which processes jobs without+publishing readiness status. Restart the owner when convenient to get readiness+reporting and configuration blocking. Rolling a worker back below 0.59.3.0+under a 0.59.3.0 or later owner is different: the older worker never reports+readiness, so the owner's 120-second startup deadline stops and restarts it+repeatedly. Stop the owner first, roll back, then start the owner from the+rolled-back installation.++## Interpret the failure before choosing a repair++Workers check readiness before queue recovery or claiming jobs. In process+isolation, readiness also checks the selected job-child CLI. Periodic probes+continue to distinguish local configuration failures from database failures.++| Finding | Meaning | Action |+|---|---|---|+| `client_misconfigured` with `postgres_cancellation_unavailable` | The actual Postgres connection owner lacks the cancellation capability required for signalled SQL | Repair the worker's driver installation; also verify the selected job-child installation |+| `child_executable_invalid` | The selected child executable cannot be used | Follow [child executable repair](#child-executable-invalid) |+| `child_protocol_incompatible` | The selected child does not implement the required worker protocol/capabilities | Follow [child protocol repair](#child-protocol-incompatible) |+| `pool_starved` | The read lane failed while the direct lane answered | Follow [transient or slow retry diagnosis](#transient-or-slow-retry); do not label this a missing driver patch |+| `server_unreachable` | The database probes failed without evidence of a local capability failure | Diagnose reachability and allow bounded [transient retries](#transient-or-slow-retry) |+| `unknown` | The available probe evidence cannot distinguish the cause, for example without a direct lane | Inspect the diagnostic detail; do not guess a permanent configuration fault |++A reservation timeout, network error or ordinary cancellation alone does not+prove the driver is incompatible. A typed local capability fault on either+lane takes precedence over a generic outage diagnosis. PGLite does not require+the Postgres cancellation capability and does not use the standalone Postgres+supervisor.++### Configuration blocked++**Liveness is not readiness.** A supervisor or autopilot can be alive and+heartbeating while configuration-blocked and unable to start work. Read the+additive `processing_ready`, `processing_state`, `processing_stage`, `retry_at`,+`reason_code`, `blocked_since`, `worker_identity` and `child_identity` fields as+well as the existing running/freshness status.+`processing_state: configuration_blocked` means no+processing even when the liveness command exits successfully. Missing readiness+data is not evidence of readiness; standalone supervisor status reports+`unknown` for a live owner without that data and `stopped` when not running.+A blocked owner stays blocked: repairing files in place does not silently+resume processing. Repair, verify, then explicitly restart the owner.++These are **illustrative subsets**, not complete status responses. A healthy+standalone supervisor can report:++```json+{+ "running": true,+ "processing_ready": true,+ "processing_state": "ready",+ "processing_stage": "ready",+ "retry_at": null,+ "reason_code": null,+ "blocked_since": null,+ "worker_identity": { "executable": "/opt/gbrain/gbrain", "version": "1.2.3" },+ "child_identity": { "executable": "/opt/gbrain/gbrain", "version": "1.2.3", "protocol_version": 1 }+}+```++The same live owner can instead be blocked by a stale child override:++```json+{+ "running": true,+ "processing_ready": false,+ "processing_state": "configuration_blocked",+ "processing_stage": "configuration_blocked",+ "retry_at": null,+ "reason_code": "child_protocol_incompatible",+ "blocked_since": "2026-01-01T12:00:00.000Z",+ "worker_identity": { "executable": "/opt/gbrain/gbrain", "version": "1.2.3" },+ "child_identity": { "executable": "/opt/gbrain-old/gbrain", "version": "unknown" }+}+```++`unknown` does not identify an installed version; it means the handshake did+not establish one. Identities may also be `null` when unavailable. Autopilot+retains its own freshness `state` instead of the supervisor's `running` field;+its additive processing fields must be checked separately. Neither example+proves that queued jobs have completed.++### Transient or slow retry++Ordinary crashes still use the soft retry budget (`--max-crashes`) and capped+backoff. Crossing that budget means degraded retries, not a permanent stop.+The separate hard crash ceiling is terminal. A known local configuration fault+blocks immediately rather than consuming those generic crash budgets; a long+network outage is not reclassified as a local fault merely because it lasts.++`processing_state` remains the coarse `starting`, `ready` or+`configuration_blocked` verdict. `processing_stage` explains the current wait:++| `processing_stage` | What to inspect |+|---|---|+| `startup_readiness` | The owner is awaiting worker readiness; inspect subsequent stage updates and startup logs |+| `database_readiness` | Required database lanes are being checked; inspect connectivity and pool availability |+| `child_readiness` | The selected child is being checked; inspect its recorded identity and explicit override |+| `worker_startup` | Worker startup is not yet complete; wait for the actual `ready` transition |+| `ready` | Startup readiness completed; verify real queue progress separately |+| `startup_timeout` | Readiness exceeded the owner's startup budget; inspect logs, not a guessed permanent-fault diagnosis |+| `retry_backoff` | The owner is delaying another attempt; inspect `retry_at` |+| `configuration_blocked` | Automatic retries are disabled; repair and explicitly restart the owner |+| `stopped` | The worker is not processing; inspect owner liveness and why it stopped |++During `retry_backoff`, `retry_at` is the owner's next scheduled retry timestamp+in ISO format, or `null` when no timestamp is available. It is not a guarantee+that the database will be healthy or a job will run at that time. For example,+this live supervisor is waiting, not configuration-blocked:++```json+{+ "running": true,+ "processing_ready": false,+ "processing_state": "starting",+ "processing_stage": "retry_backoff",+ "retry_at": "2026-01-01T12:01:00.000Z",+ "reason_code": null+}+```++A configuration block has `retry_at: null` and still requires manual restart+after repair. A null timestamp alone does not mean blocked: a probe can still+be running. If the standalone owner has no current status record, both state+and stage fall back to `unknown` when alive or `stopped` when not running;+those fallback labels are not extra worker protocol states.++If readiness is still starting or the latest log says it is temporarily+unavailable, compare successive owner-status observations and the owner's+logs. A single slow probe or an expired handshake deadline is not a permanent+fault. Check `gbrain engine status --probe` with the actual launcher; distinguish+database/network failure from pool saturation. Restore connectivity or reduce+the identified competing work with approval, then let the existing owner retry.+Do not repeatedly start new supervisors to accelerate backoff. A foreground+worker that has exited needs an explicit rerun; it has no owner to retry it.++If status remains `unknown`, verify the owner account, `GBRAIN_HOME` and PID-file+selection before concluding the worker is ready or stopped. Missing diagnostics+do not authorize clearing a configuration block. Never reset crash/stall+counters or replay jobs merely because recovery is slow.++If the worker says readiness status could not be published, no jobs were+admitted. Check that its original owner is still running under the expected+account and that the owner's runtime directory is writable. Repair that path+and explicitly restart the owner; do not fabricate status files or copy an old+worker's internal status environment into a new process.++## Repair the installation that owns the failure++### Postgres cancellation unavailable++Stop the affected owner using the table above. Obtain approval for installation+changes separately from diagnostic commands. Choose the matching branch:++- **Bun global install:** reinstall a known-good GBrain release under the same+ account and Bun installation used by the service. The canonical GitHub path+ is `bun install -g github:garrytan/gbrain`; use an approved release ref when+ pinning. Do not substitute the unrelated npm package or change another+ account's global installation.+- **Checkout install:** switch that checkout to the approved fixed revision,+ then run `bun install` in that checkout. If the service uses a linked CLI,+ verify its link still points there. Updating Git without refreshing stale+ dependencies is not enough.+- **Compiled executable:** replace the exact executable named by the service+ with the approved fixed build. Updating a separate source checkout does not+ change an already compiled executable.++GBrain ships its cancellation-capable Postgres.js 3.4.9 in `vendor/postgres`,+with the upstream license. The package-private `#postgres` import maps directly+to that source; compiled builds embed the same resolved driver. The cancellation+changes are recorded in `patches/[email protected]`. This avoids relying on+transitive local dependencies or a consuming global installation to reapply+GBrain's dependency patch. Repair the GBrain package+as a unit, not by installing stock `postgres` over it or editing another+installation's `node_modules`.++Maintainers should follow [driver provenance and update instructions](../../vendor/README.md)+and use `bash vendor/update-postgres.sh --check` to verify the vendored bytes.+A version string is not a substitute for validating the actual reserved+connection's capability.++Do not bypass the readiness check, remove AbortSignals or use an unsignalled+timeout race as a workaround. Safe cancellation must stop the underlying SQL+and discard its connection when required, not just abandon the caller's wait.++The default job-child CLI follows the current worker's installation. An explicit+`GBRAIN_JOB_CHILD_CLI` override remains authoritative and can keep selecting a+stale executable after the worker has been repaired. Check it in the service's+environment, not just the interactive shell. A compatible version difference+is diagnostic information; a protocol or required-capability mismatch blocks+startup. Do not clear an intentional override without the operator's approval.++### Child executable invalid++For `child_executable_invalid`, stop the original owner and compare its recorded+`child_identity.executable` with `GBRAIN_JOB_CHILD_CLI` in that owner's+environment. Check that the selected file exists and is executable by that+account. A path in a different interactive shell is not a repair. Use the+matching global, checkout or compiled-install branch above; change a stale+override or permissions only with approval. Then run the diagnostics below+against both installations and explicitly restart the original owner. Do not+fall back to a different PATH executable without explaining the change.++### Child protocol incompatible++For `child_protocol_incompatible`, repair the selected child with a compatible+GBrain release, not just the parent worker. A completed malformed reply or+missing required protocol/capability can cause this diagnosis; a timeout alone+does not. Inspect the explicit override first. Compare each executable's+reported version, but do not treat equal versions as proof of compatibility or+different versions as proof of failure. The automatic startup handshake is the+protocol/capability check. Keep the block in place until repair and explicit+owner restart; do not invoke the hidden handshake command as a public repair+API or bypass its guard.++## Verify, restart and watch actual progress++### Read-only readiness diagnostics++Run this Bash block under the owner's account, working directory and environment,+including its `GBRAIN_HOME`, brain selection and `GBRAIN_JOB_CHILD_CLI` if set.+Edit the absolute launcher and owner-status array first. For a checkout, use+`actual_cli=(/absolute/path/to/bun /absolute/path/to/gbrain/src/cli.ts)`.+Use the CLI itself, not the service start wrapper: a wrapper may ignore the+diagnostic arguments and start processing instead.+For autopilot, replace the status array with+`owner_status=(autopilot --status --json)`. For a standalone supervisor, retain+its actual `--queue` and `--pid-file` options. Do not source an arbitrary service+file as shell code or print its secrets.++```bash+(+ actual_cli=(/absolute/path/to/gbrain)+ owner_status=(jobs supervisor status --json)+ brain_args=()+ diagnostic_failed=0++ if [[ ! -x "${actual_cli[0]}" ]]; then+ printf 'Set actual_cli to the executable used by this owner.\n' >&2+ exit 2+ fi++ run_check() {+ local label="$1" code+ shift+ printf '\n--- %s ---\n' "$label"+ if "$@"; then code=0; else code=$?; diagnostic_failed=1; fi+ printf '\n[%s: exit %s]\n' "$label" "$code"+ }++ printf 'Worker invocation:'+ printf ' %q' "${actual_cli[@]}"+ printf '\n'+ run_check 'Worker version' "${actual_cli[@]}" --version+ run_check 'Owner status' "${actual_cli[@]}" "${brain_args[@]}" "${owner_status[@]}"+ run_check 'Worker doctor' "${actual_cli[@]}" "${brain_args[@]}" doctor --no-migrate --json+ run_check 'Database reachability' "${actual_cli[@]}" "${brain_args[@]}" engine status --probe++ if [[ -n "${GBRAIN_JOB_CHILD_CLI:-}" ]]; then+ printf '\nExplicit child invocation: %q\n' "$GBRAIN_JOB_CHILD_CLI"+ child_executable=$(command -v -- "$GBRAIN_JOB_CHILD_CLI") || child_executable=''+ if [[ -n "$child_executable" && -x "$child_executable" ]]; then+ printf 'Resolved child executable: %q\n' "$child_executable"+ run_check 'Selected child version' "$child_executable" --version+ run_check 'Selected child doctor' "$child_executable" "${brain_args[@]}" doctor --no-migrate --json+ else+ printf 'Selected child is missing or not executable by this account.\n' >&2+ diagnostic_failed=1+ fi+ else+ printf '\nNo explicit child override in this environment; compare child_identity with the worker installation.\n'+ fi+ exit "$diagnostic_failed"+)+```++If the original worker is foreground-only, use `owner_status=()` and omit the+`run_check 'Owner status'` line: there is no owning daemon status to query. Inspect+that worker's terminal diagnostics instead. Set `brain_args=(--brain example-brain)`+only when that matches the owner's original selection; otherwise leave it empty.++This block does not install, migrate, restart, claim or retry work. Nonzero+diagnostic exits are printed and retained in the block's final exit code, not+treated as proof that the next check cannot run. `doctor --no-migrate` reports+the current schema without applying migrations; do not add `--fix` or replace+it with plain `doctor` in this diagnostic block.+Supervisor status also skips schema migration when it needs a database lookup+because the local PID file is absent. These are observational commands, not a+filesystem-forensic read-only mode: opening an embedded database can touch its+raw database files or WAL, just as `doctor --no-migrate` can.+An exit of zero from the block is not a readiness verdict: owner status keeps+its liveness exit semantics, so a blocked owner can still return zero. Check+`processing_ready`, `processing_state` and the identity match below explicitly.++**Verify the identity match before interpreting health:** compare the printed+worker invocation and version with `worker_identity` in owner status. With a+source launcher, compare its CLI source path, not just the Bun executable. If+an override is set, compare its path and separately printed version with+`child_identity`; an absent/`unknown` identity is an unresolved check, not a+match. Follow symlinks or wrappers to the recorded installation if the spellings+differ. If status names another installation, stop and correct the diagnostic+context rather than repairing the one found by your interactive PATH.++These public diagnostics gather readiness evidence; they do not run or bypass+the internal protocol. The worker's automatic startup handshake validates the+selected child's protocol and database readiness before any claims. A parent's+doctor result does not certify a different child installation. With a live+PGLite owner, a separate DB-backed doctor may be unable to acquire the exclusive+file lock; report that limitation rather than stopping the owner automatically+or declaring the check passed. Review output locally and redact private paths,+URLs and credentials before sharing it.++An ordinary successful SQL query alone is not proof that cancellation works.+Doctor and database-repair diagnostics remain usable with a broken driver;+they must be able to explain the local failure. For a reachability failure,+follow [engine detection and access repair](../ENGINES.md#engine-detection-and-access-repair)+instead of repeatedly reinstalling.++After verification, explicitly restart only the original owner using the+table above. Confirm readiness, then inspect queue progress:++```bash+gbrain jobs stats --json+gbrain jobs list+```++Compare successive observations: completed jobs should increase when work is+available, without recurring worker restarts or growing stall counts. An empty+queue is valid; do not create paid or side-effecting work just to make a counter+move. A live process alone does not establish recovery.++**Say to your agent:** *"Verify the repaired worker and its selected child CLI,+restart only the original owner with my approval, and show whether existing+jobs complete without new restarts or stalls. Do not replay failed jobs."*++## In-flight work and limits of recovery++A local fault discovered after startup stops new claims first. Confirmed+stopped work can be returned to delayed state through an active-job and+ownership-token check, without charging an attempt or stall solely for this+configuration shutdown. A stale token must not overwrite a completed,+cancelled or newly owned job.++### Release-unconfirmed++**Unconfirmed shutdown or release is not a successful requeue.** An inline+handler may ignore cancellation; a child may leave descendants; a cleanup+signal or database release may fail. If execution stop or token-fenced release+cannot be confirmed within the shutdown budget, lease expiry is the fallback.+That fallback can still incur stalls, and surviving work may still perform+side effects. Inspect the per-job result before deciding what to retry.++Process-group cleanup and optional tini subreaper mode improve cleanup on+supported systems. Positive stop verification currently uses bounded Linux+`/proc` checks of known groups and observed descendants; unavailable or failed+checks retain the unconfirmed fallback. They do not guarantee containment of+descendants that escaped before observation, and running under tini does not+make every process PID 1. Per-child hard RSS enforcement remains a separate TODO; this repair+does not control every large job's memory use or eliminate autopilot's own+memory footprint.++Inspect dead-lettered and failed jobs individually. At-least-once execution+means a job can have performed side effects before it stopped. Do not reset+stall counts, retry all dead letters or replay the queue as part of installation+repair. Retry only explicitly selected work after reviewing its effects and+obtaining approval.++## Migration repair++Minions self-heals on upgrade. If an install is only partiallyset up (no `~/.gbrain/preferences.json`, autopilot still inline, cron jobsstill on `agentTurn`), run:diff --git a/llms-full.txt b/llms-full.txtindex 8054683709..c3d569beab 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -7714,9 +7714,420 @@ end-to-end sync test (4c), push a real change and verify it appears in search.Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/minions-fix.md-# Minions fix: repairing a half-migrated install+# Minions fix: repairing a blocked worker or half-migrated install++**Say to your agent:** *"Use `gbrain jobs supervisor status --json` and+`gbrain doctor --no-migrate` to find why my worker stopped. Show me the affected+installation and proposed repair before changing anything or retrying jobs."*++A local driver or child-CLI configuration failure is not a database outage.+Repair the installation that actually runs the worker, then explicitly restart+its owner. Repeated restarts or replaying the queue do not repair a missing+driver capability.++For a **half-migrated install** (no completed migration, autopilot still inline,+or cron jobs still on `agentTurn`), use the [migration repair](#migration-repair)+below. Do not use migrations as a substitute for repairing a broken driver.++## Identify the owner and installation first++Work in the same account, brain, `GBRAIN_HOME`, configuration and environment as+the affected owner. A healthy `gbrain` in an interactive shell does not prove a+service uses that executable. Preserve queue, concurrency, CLI-path and other+existing launch options throughout the repair.++| Owner | Inspect | Stop processing before repair | Explicit restart after verification |+|---|---|---|---|+| Foreground `gbrain jobs work` | Its startup output and terminal | Ctrl-C in that terminal; wait for shutdown | Run the same `gbrain jobs work` invocation again |+| Standalone jobs supervisor | `gbrain jobs supervisor status --json` | `gbrain jobs supervisor stop --json` | `gbrain jobs supervisor start --detach --json` with the original options |+| Autopilot under user systemd | `gbrain autopilot --status --json`; `systemctl --user status gbrain-autopilot.service` | `systemctl --user stop gbrain-autopilot.service` | `systemctl --user start gbrain-autopilot.service` |+| Autopilot under launchd | `gbrain autopilot --status --json`; `launchctl print "gui/$(id -u)/com.gbrain.autopilot"` | `launchctl bootout "gui/$(id -u)/com.gbrain.autopilot"` | `launchctl bootstrap "gui/$(id -u)" "$HOME/Library/LaunchAgents/com.gbrain.autopilot.plist"` |++These are the default user-service names. If the installation uses a different+service definition, use its actual name and recorded launcher. For a foreground+autopilot or a container/cron owner, stop and restart that owner through its+existing launcher; do not start a competing standalone supervisor. A timed-out+stop is not confirmation that work has stopped. Inspect remaining processes+before proceeding.++For systemd, inspect `systemctl --user cat gbrain-autopilot.service`. For+launchd, inspect the installed plist's `ProgramArguments`. Follow any wrapper+to the exact executable or checkout it invokes. Do not paste environment+files, credentials or database URLs into a public report.++### Upgrade and rollback ordering++Upgrading while an older owner (0.59.0.0 or earlier) is still running keeps+working: that owner respawns the upgraded worker, which processes jobs without+publishing readiness status. Restart the owner when convenient to get readiness+reporting and configuration blocking. Rolling a worker back below 0.59.3.0+under a 0.59.3.0 or later owner is different: the older worker never reports+readiness, so the owner's 120-second startup deadline stops and restarts it+repeatedly. Stop the owner first, roll back, then start the owner from the+rolled-back installation.++## Interpret the failure before choosing a repair++Workers check readiness before queue recovery or claiming jobs. In process+isolation, readiness also checks the selected job-child CLI. Periodic probes+continue to distinguish local configuration failures from database failures.++| Finding | Meaning | Action |+|---|---|---|+| `client_misconfigured` with `postgres_cancellation_unavailable` | The actual Postgres connection owner lacks the cancellation capability required for signalled SQL | Repair the worker's driver installation; also verify the selected job-child installation |+| `child_executable_invalid` | The selected child executable cannot be used | Follow [child executable repair](#child-executable-invalid) |+| `child_protocol_incompatible` | The selected child does not implement the required worker protocol/capabilities | Follow [child protocol repair](#child-protocol-incompatible) |+| `pool_starved` | The read lane failed while the direct lane answered | Follow [transient or slow retry diagnosis](#transient-or-slow-retry); do not label this a missing driver patch |+| `server_unreachable` | The database probes failed without evidence of a local capability failure | Diagnose reachability and allow bounded [transient retries](#transient-or-slow-retry) |+| `unknown` | The available probe evidence cannot distinguish the cause, for example without a direct lane | Inspect the diagnostic detail; do not guess a permanent configuration fault |++A reservation timeout, network error or ordinary cancellation alone does not+prove the driver is incompatible. A typed local capability fault on either+lane takes precedence over a generic outage diagnosis. PGLite does not require+the Postgres cancellation capability and does not use the standalone Postgres+supervisor.++### Configuration blocked++**Liveness is not readiness.** A supervisor or autopilot can be alive and+heartbeating while configuration-blocked and unable to start work. Read the+additive `processing_ready`, `processing_state`, `processing_stage`, `retry_at`,+`reason_code`, `blocked_since`, `worker_identity` and `child_identity` fields as+well as the existing running/freshness status.+`processing_state: configuration_blocked` means no+processing even when the liveness command exits successfully. Missing readiness+data is not evidence of readiness; standalone supervisor status reports+`unknown` for a live owner without that data and `stopped` when not running.+A blocked owner stays blocked: repairing files in place does not silently+resume processing. Repair, verify, then explicitly restart the owner.++These are **illustrative subsets**, not complete status responses. A healthy+standalone supervisor can report:++```json+{+ "running": true,+ "processing_ready": true,+ "processing_state": "ready",+ "processing_stage": "ready",+ "retry_at": null,+ "reason_code": null,+ "blocked_since": null,+ "worker_identity": { "executable": "/opt/gbrain/gbrain", "version": "1.2.3" },+ "child_identity": { "executable": "/opt/gbrain/gbrain", "version": "1.2.3", "protocol_version": 1 }+}+```++The same live owner can instead be blocked by a stale child override:++```json+{+ "running": true,+ "processing_ready": false,+ "processing_state": "configuration_blocked",+ "processing_stage": "configuration_blocked",+ "retry_at": null,+ "reason_code": "child_protocol_incompatible",+ "blocked_since": "2026-01-01T12:00:00.000Z",+ "worker_identity": { "executable": "/opt/gbrain/gbrain", "version": "1.2.3" },+ "child_identity": { "executable": "/opt/gbrain-old/gbrain", "version": "unknown" }+}+```++`unknown` does not identify an installed version; it means the handshake did+not establish one. Identities may also be `null` when unavailable. Autopilot+retains its own freshness `state` instead of the supervisor's `running` field;+its additive processing fields must be checked separately. Neither example+proves that queued jobs have completed.++### Transient or slow retry++Ordinary crashes still use the soft retry budget (`--max-crashes`) and capped+backoff. Crossing that budget means degraded retries, not a permanent stop.+The separate hard crash ceiling is terminal. A known local configuration fault+blocks immediately rather than consuming those generic crash budgets; a long+network outage is not reclassified as a local fault merely because it lasts.++`processing_state` remains the coarse `starting`, `ready` or+`configuration_blocked` verdict. `processing_stage` explains the current wait:++| `processing_stage` | What to inspect |+|---|---|+| `startup_readiness` | The owner is awaiting worker readiness; inspect subsequent stage updates and startup logs |+| `database_readiness` | Required database lanes are being checked; inspect connectivity and pool availability |+| `child_readiness` | The selected child is being checked; inspect its recorded identity and explicit override |+| `worker_startup` | Worker startup is not yet complete; wait for the actual `ready` transition |+| `ready` | Startup readiness completed; verify real queue progress separately |+| `startup_timeout` | Readiness exceeded the owner's startup budget; inspect logs, not a guessed permanent-fault diagnosis |+| `retry_backoff` | The owner is delaying another attempt; inspect `retry_at` |+| `configuration_blocked` | Automatic retries are disabled; repair and explicitly restart the owner |+| `stopped` | The worker is not processing; inspect owner liveness and why it stopped |++During `retry_backoff`, `retry_at` is the owner's next scheduled retry timestamp+in ISO format, or `null` when no timestamp is available. It is not a guarantee+that the database will be healthy or a job will run at that time. For example,+this live supervisor is waiting, not configuration-blocked:++```json+{+ "running": true,+ "processing_ready": false,+ "processing_state": "starting",+ "processing_stage": "retry_backoff",+ "retry_at": "2026-01-01T12:01:00.000Z",+ "reason_code": null+}+```++A configuration block has `retry_at: null` and still requires manual restart+after repair. A null timestamp alone does not mean blocked: a probe can still+be running. If the standalone owner has no current status record, both state+and stage fall back to `unknown` when alive or `stopped` when not running;+those fallback labels are not extra worker protocol states.++If readiness is still starting or the latest log says it is temporarily+unavailable, compare successive owner-status observations and the owner's+logs. A single slow probe or an expired handshake deadline is not a permanent+fault. Check `gbrain engine status --probe` with the actual launcher; distinguish+database/network failure from pool saturation. Restore connectivity or reduce+the identified competing work with approval, then let the existing owner retry.+Do not repeatedly start new supervisors to accelerate backoff. A foreground+worker that has exited needs an explicit rerun; it has no owner to retry it.++If status remains `unknown`, verify the owner account, `GBRAIN_HOME` and PID-file+selection before concluding the worker is ready or stopped. Missing diagnostics+do not authorize clearing a configuration block. Never reset crash/stall+counters or replay jobs merely because recovery is slow.++If the worker says readiness status could not be published, no jobs were+admitted. Check that its original owner is still running under the expected+account and that the owner's runtime directory is writable. Repair that path+and explicitly restart the owner; do not fabricate status files or copy an old+worker's internal status environment into a new process.++## Repair the installation that owns the failure++### Postgres cancellation unavailable++Stop the affected owner using the table above. Obtain approval for installation+changes separately from diagnostic commands. Choose the matching branch:++- **Bun global install:** reinstall a known-good GBrain release under the same+ account and Bun installation used by the service. The canonical GitHub path+ is `bun install -g github:garrytan/gbrain`; use an approved release ref when+ pinning. Do not substitute the unrelated npm package or change another+ account's global installation.+- **Checkout install:** switch that checkout to the approved fixed revision,+ then run `bun install` in that checkout. If the service uses a linked CLI,+ verify its link still points there. Updating Git without refreshing stale+ dependencies is not enough.+- **Compiled executable:** replace the exact executable named by the service+ with the approved fixed build. Updating a separate source checkout does not+ change an already compiled executable.++GBrain ships its cancellation-capable Postgres.js 3.4.9 in `vendor/postgres`,+with the upstream license. The package-private `#postgres` import maps directly+to that source; compiled builds embed the same resolved driver. The cancellation+changes are recorded in `patches/[email protected]`. This avoids relying on+transitive local dependencies or a consuming global installation to reapply+GBrain's dependency patch. Repair the GBrain package+as a unit, not by installing stock `postgres` over it or editing another+installation's `node_modules`.++Maintainers should follow [driver provenance and update instructions](../../vendor/README.md)+and use `bash vendor/update-postgres.sh --check` to verify the vendored bytes.+A version string is not a substitute for validating the actual reserved+connection's capability.++Do not bypass the readiness check, remove AbortSignals or use an unsignalled+timeout race as a workaround. Safe cancellation must stop the underlying SQL+and discard its connection when required, not just abandon the caller's wait.++The default job-child CLI follows the current worker's installation. An explicit+`GBRAIN_JOB_CHILD_CLI` override remains authoritative and can keep selecting a+stale executable after the worker has been repaired. Check it in the service's+environment, not just the interactive shell. A compatible version difference+is diagnostic information; a protocol or required-capability mismatch blocks+startup. Do not clear an intentional override without the operator's approval.++### Child executable invalid++For `child_executable_invalid`, stop the original owner and compare its recorded+`child_identity.executable` with `GBRAIN_JOB_CHILD_CLI` in that owner's+environment. Check that the selected file exists and is executable by that+account. A path in a different interactive shell is not a repair. Use the+matching global, checkout or compiled-install branch above; change a stale+override or permissions only with approval. Then run the diagnostics below+against both installations and explicitly restart the original owner. Do not+fall back to a different PATH executable without explaining the change.++### Child protocol incompatible++For `child_protocol_incompatible`, repair the selected child with a compatible+GBrain release, not just the parent worker. A completed malformed reply or+missing required protocol/capability can cause this diagnosis; a timeout alone+does not. Inspect the explicit override first. Compare each executable's+reported version, but do not treat equal versions as proof of compatibility or+different versions as proof of failure. The automatic startup handshake is the+protocol/capability check. Keep the block in place until repair and explicit+owner restart; do not invoke the hidden handshake command as a public repair+API or bypass its guard.++## Verify, restart and watch actual progress++### Read-only readiness diagnostics++Run this Bash block under the owner's account, working directory and environment,+including its `GBRAIN_HOME`, brain selection and `GBRAIN_JOB_CHILD_CLI` if set.+Edit the absolute launcher and owner-status array first. For a checkout, use+`actual_cli=(/absolute/path/to/bun /absolute/path/to/gbrain/src/cli.ts)`.+Use the CLI itself, not the service start wrapper: a wrapper may ignore the+diagnostic arguments and start processing instead.+For autopilot, replace the status array with+`owner_status=(autopilot --status --json)`. For a standalone supervisor, retain+its actual `--queue` and `--pid-file` options. Do not source an arbitrary service+file as shell code or print its secrets.++```bash+(+ actual_cli=(/absolute/path/to/gbrain)+ owner_status=(jobs supervisor status --json)+ brain_args=()+ diagnostic_failed=0++ if [[ ! -x "${actual_cli[0]}" ]]; then+ printf 'Set actual_cli to the executable used by this owner.\n' >&2+ exit 2+ fi++ run_check() {+ local label="$1" code+ shift+ printf '\n--- %s ---\n' "$label"+ if "$@"; then code=0; else code=$?; diagnostic_failed=1; fi+ printf '\n[%s: exit %s]\n' "$label" "$code"+ }++ printf 'Worker invocation:'+ printf ' %q' "${actual_cli[@]}"+ printf '\n'+ run_check 'Worker version' "${actual_cli[@]}" --version+ run_check 'Owner status' "${actual_cli[@]}" "${brain_args[@]}" "${owner_status[@]}"+ run_check 'Worker doctor' "${actual_cli[@]}" "${brain_args[@]}" doctor --no-migrate --json+ run_check 'Database reachability' "${actual_cli[@]}" "${brain_args[@]}" engine status --probe++ if [[ -n "${GBRAIN_JOB_CHILD_CLI:-}" ]]; then+ printf '\nExplicit child invocation: %q\n' "$GBRAIN_JOB_CHILD_CLI"+ child_executable=$(command -v -- "$GBRAIN_JOB_CHILD_CLI") || child_executable=''+ if [[ -n "$child_executable" && -x "$child_executable" ]]; then+ printf 'Resolved child executable: %q\n' "$child_executable"+ run_check 'Selected child version' "$child_executable" --version+ run_check 'Selected child doctor' "$child_executable" "${brain_args[@]}" doctor --no-migrate --json+ else+ printf 'Selected child is missing or not executable by this account.\n' >&2+ diagnostic_failed=1+ fi+ else+ printf '\nNo explicit child override in this environment; compare child_identity with the worker installation.\n'+ fi+ exit "$diagnostic_failed"+)+```++If the original worker is foreground-only, use `owner_status=()` and omit the+`run_check 'Owner status'` line: there is no owning daemon status to query. Inspect+that worker's terminal diagnostics instead. Set `brain_args=(--brain example-brain)`+only when that matches the owner's original selection; otherwise leave it empty.++This block does not install, migrate, restart, claim or retry work. Nonzero+diagnostic exits are printed and retained in the block's final exit code, not+treated as proof that the next check cannot run. `doctor --no-migrate` reports+the current schema without applying migrations; do not add `--fix` or replace+it with plain `doctor` in this diagnostic block.+Supervisor status also skips schema migration when it needs a database lookup+because the local PID file is absent. These are observational commands, not a+filesystem-forensic read-only mode: opening an embedded database can touch its+raw database files or WAL, just as `doctor --no-migrate` can.+An exit of zero from the block is not a readiness verdict: owner status keeps+its liveness exit semantics, so a blocked owner can still return zero. Check+`processing_ready`, `processing_state` and the identity match below explicitly.++**Verify the identity match before interpreting health:** compare the printed+worker invocation and version with `worker_identity` in owner status. With a+source launcher, compare its CLI source path, not just the Bun executable. If+an override is set, compare its path and separately printed version with+`child_identity`; an absent/`unknown` identity is an unresolved check, not a+match. Follow symlinks or wrappers to the recorded installation if the spellings+differ. If status names another installation, stop and correct the diagnostic+context rather than repairing the one found by your interactive PATH.++These public diagnostics gather readiness evidence; they do not run or bypass+the internal protocol. The worker's automatic startup handshake validates the+selected child's protocol and database readiness before any claims. A parent's+doctor result does not certify a different child installation. With a live+PGLite owner, a separate DB-backed doctor may be unable to acquire the exclusive+file lock; report that limitation rather than stopping the owner automatically+or declaring the check passed. Review output locally and redact private paths,+URLs and credentials before sharing it.++An ordinary successful SQL query alone is not proof that cancellation works.+Doctor and database-repair diagnostics remain usable with a broken driver;+they must be able to explain the local failure. For a reachability failure,+follow [engine detection and access repair](../ENGINES.md#engine-detection-and-access-repair)+instead of repeatedly reinstalling.++After verification, explicitly restart only the original owner using the+table above. Confirm readiness, then inspect queue progress:++```bash+gbrain jobs stats --json+gbrain jobs list+```++Compare successive observations: completed jobs should increase when work is+available, without recurring worker restarts or growing stall counts. An empty+queue is valid; do not create paid or side-effecting work just to make a counter+move. A live process alone does not establish recovery.++**Say to your agent:** *"Verify the repaired worker and its selected child CLI,+restart only the original owner with my approval, and show whether existing+jobs complete without new restarts or stalls. Do not replay failed jobs."*++## In-flight work and limits of recovery++A local fault discovered after startup stops new claims first. Confirmed+stopped work can be returned to delayed state through an active-job and+ownership-token check, without charging an attempt or stall solely for this+configuration shutdown. A stale token must not overwrite a completed,+cancelled or newly owned job.++### Release-unconfirmed++**Unconfirmed shutdown or release is not a successful requeue.** An inline+handler may ignore cancellation; a child may leave descendants; a cleanup+signal or database release may fail. If execution stop or token-fenced release+cannot be confirmed within the shutdown budget, lease expiry is the fallback.+That fallback can still incur stalls, and surviving work may still perform+side effects. Inspect the per-job result before deciding what to retry.++Process-group cleanup and optional tini subreaper mode improve cleanup on+supported systems. Positive stop verification currently uses bounded Linux+`/proc` checks of known groups and observed descendants; unavailable or failed+checks retain the unconfirmed fallback. They do not guarantee containment of+descendants that escaped before observation, and running under tini does not+make every process PID 1. Per-child hard RSS enforcement remains a separate TODO; this repair+does not control every large job's memory use or eliminate autopilot's own+memory footprint.++Inspect dead-lettered and failed jobs individually. At-least-once execution+means a job can have performed side effects before it stopped. Do not reset+stall counts, retry all dead letters or replay the queue as part of installation+repair. Retry only explicitly selected work after reviewing its effects and+obtaining approval.++## Migration repair-**tl;dr:** Minions self-heals on upgrade. If an install is only partially+Minions self-heals on upgrade. If an install is only partiallyset up (no `~/.gbrain/preferences.json`, autopilot still inline, cron jobsstill on `agentTurn`), run:diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 14b58cc37a..390ffad8cf 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.59.2.0",+ "version": "0.59.3.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex b8b8d1c8b5..c15ef2240c 100644--- a/package.json+++ b/package.json@@ -2,6 +2,13 @@"name": "gbrain","description": "Postgres-native personal knowledge brain with hybrid RAG search","type": "module",+ "imports": {+ "#postgres": {+ "types": "./vendor/postgres/types/index.d.ts",+ "require": "./vendor/postgres/cjs/src/index.js",+ "default": "./vendor/postgres/src/index.js"+ }+ },"main": "src/core/index.ts","bin": {"gbrain": "src/cli.ts"@@ -159,7 +166,6 @@"marked": "^18.0.2","openai": "^4.0.0","pgvector": "^0.2.0",- "postgres": "3.4.9","tree-sitter-wasms": "0.1.13","web-tree-sitter": "0.22.6","zod": "^4.3.6"@@ -182,7 +188,7 @@"bun": ">=1.3.11"},"license": "MIT",- "version": "0.59.2.0",+ "version": "0.59.3.0","overrides": {"@ai-sdk/provider-utils": "4.0.33","@hono/node-server": "^2.0.5",@@ -195,8 +201,5 @@"ip-address": "^10.3.1","qs": "6.16.0","js-yaml": "^3.15.2"- },- "patchedDependencies": {- "[email protected]": "patches/[email protected]"}}diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 427ffbc0dd..ca5467f009 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.59.2.0",+ "version": "0.59.3.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex 7a00007c36..67cd2029e5 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.59.2.0",+ "version": "0.59.3.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex 01608df8f8..38066f76ac 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.2.0 -->+<!-- gbrain-plugin-tree-stamp: 0.59.3.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 9bad349503..8f4d06b227 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.59.2.0",+ "version": "0.59.3.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex ce2eac4cbe..6658245c21 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.59.2.0",+ "version": "0.59.3.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex ed07e6f415..d7dfb62019 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.2.0 -->+<!-- gbrain-plugin-tree-stamp: 0.59.3.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin/README.md b/plugin/README.mdindex 6038b4a13d..210877076d 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.2.0 -->+<!-- gbrain-plugin-tree-stamp: 0.59.3.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/scripts/check-pglite-embedded.sh b/scripts/check-pglite-embedded.shindex d542ce6bf9..e8d8ab68cd 100755--- a/scripts/check-pglite-embedded.sh+++ b/scripts/check-pglite-embedded.sh@@ -36,6 +36,7 @@ GBRAIN_HOME_DIR="$BUILD_DIR/home"trap 'rm -rf "$BUILD_DIR"' EXITmkdir -p "$BUILD_DIR/scripts" "$GBRAIN_HOME_DIR"cp -R "$REPO_ROOT/src" "$BUILD_DIR/src"+cp -R "$REPO_ROOT/vendor" "$BUILD_DIR/vendor"cp -R "$REPO_ROOT/native" "$BUILD_DIR/native"# Shared operation/queue boundaries can reach embedded bootstrap assets even# from an engine-only import. Keep the compiled graph's file imports available.diff --git a/scripts/check-wasm-embedded.sh b/scripts/check-wasm-embedded.shindex 7e1b4a4d81..6a1819cdcd 100755--- a/scripts/check-wasm-embedded.sh+++ b/scripts/check-wasm-embedded.sh@@ -28,6 +28,8 @@ OUT_BIN="$BUILD_DIR/chunker-smoketest"trap 'rm -rf "$BUILD_DIR"' EXITmkdir -p "$BUILD_DIR/scripts"cp -R "$REPO_ROOT/src" "$BUILD_DIR/src"+cp -R "$REPO_ROOT/vendor" "$BUILD_DIR/vendor"+cp "$REPO_ROOT/package.json" "$BUILD_DIR/package.json"cp "$REPO_ROOT/scripts/chunker-smoketest.ts" "$BUILD_DIR/scripts/chunker-smoketest.ts"ln -s "$REPO_ROOT/node_modules" "$BUILD_DIR/node_modules"diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex 61c2887e58..758b7f0249 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -159,6 +159,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {],// Any minions queue/worker/handler change exercises all minion E2E."src/core/minions/**": [+ "test/e2e/worker-readiness-cli.test.ts",+ "test/e2e/worker-configuration-release.test.ts","test/e2e/delegated-grants-withdrawal.test.ts","test/e2e/delegated-http-worker.test.ts","test/e2e/minions-concurrency.test.ts",@@ -221,6 +223,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/pool-budget.ts": ["test/e2e/persistence-runtime-matrix.test.ts"],"src/core/connection-manager.ts": ["test/e2e/persistence-runtime-matrix.test.ts", "test/e2e/pgbouncer-teardown.test.ts"],"src/core/postgres-engine.ts": [+ "test/e2e/postgres-driver-install.test.ts","test/e2e/unsupported-embedding-identity-postgres.test.ts","test/e2e/fixture-reset-postgres.test.ts","test/e2e/persistence-chaos.test.ts",@@ -359,7 +362,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {],// Autopilot linux install/uninstall lifecycle (PATH-shimmed crontab +// systemctl; the ubuntu CI runner's only behavioral pin on those arms).- "src/commands/autopilot.ts": ["test/e2e/autopilot-linux-lifecycle.serial.test.ts"],+ "src/commands/autopilot.ts": ["test/e2e/autopilot-linux-lifecycle.serial.test.ts", "test/e2e/worker-readiness-cli.test.ts"],"src/commands/doctor.ts": ["test/e2e/doctor-progress.test.ts"],// Doctor check modules peeled from doctor.ts feed the same e2e surface."src/commands/doctor/**": ["test/e2e/doctor-progress.test.ts"],diff --git a/scripts/generate-flag-registry.ts b/scripts/generate-flag-registry.tsindex 6cec660718..48f7bc7995 100644--- a/scripts/generate-flag-registry.ts+++ b/scripts/generate-flag-registry.ts@@ -56,9 +56,13 @@ const EXTRA_FLAGS: Record<string, string[]> = {* its flag literals belong to the commands it routes (takes/search/jobs/cache/* quarantine), and each of those declares its own flags in its own case block;* scanning the router bleeds takes/quarantine flags into jobs (whose case- * block imports it for the `jobs stats` thin-client route).+ * block imports it for the `jobs stats` thin-client route). job-isolation.ts+ * builds the INTERNAL `jobs run-child` argv (`--job-id`, `--allow-shell-jobs`):+ * those literals are what a worker passes to its child, not flags an importer+ * parses — autopilot imports it only to resolve the child CLI, and `jobs`+ * declares both flags in its own source.*/-const EXCLUDED_MODULES = ['thin-client-routing.ts', 'persistence-delegate.ts'];+const EXCLUDED_MODULES = ['thin-client-routing.ts', 'persistence-delegate.ts', 'job-isolation.ts'];function isExcludedModule(p: string): boolean {// Basename comparison is path-separator agnostic: on Windows p ends indiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 1ed4f67102..1492bf3f96 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -3,13 +3,13 @@# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy note-src/cli.ts 4096 ratchet +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; #5252 wave: partial-retrieval notices and resident code reindex delegation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared skills: parse typed object/array operation flags before resident-owner delegation; merged reliability/shared-skills source integration Explicit-policy thin recall routing before local engine connection; actual CLI subprocess regression coverage. Reject explicit thin recall brain selection before dispatch.; +10 A2 preview-bound attendance repair dispatch and help; integrated upstream provider retirement with thin recall and gated repair dispatch-src/commands/autopilot.ts 2671 ratchet grown v0.46.26.0 megawave (#4300 #4285 #3696) + master v0.46.27.0 env-file lane + boot warning + reload-safe install (#2608 #4443) + 1 nosemgrep dataflow annotation (path-traversal audit); +chat-connectors wiring; +20 #4728 wrapper exec guard (baked CLI path gone -> PATH fallback / --install hint); +5 #4952 (refs #4399): syncEnabled=false skip in the freshness dispatch loop+src/cli.ts 4119 ratchet +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; #5252 wave: partial-retrieval notices and resident code reindex delegation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared skills: parse typed object/array operation flags before resident-owner delegation; merged reliability/shared-skills source integration Explicit-policy thin recall routing before local engine connection; actual CLI subprocess regression coverage. Reject explicit thin recall brain selection before dispatch.; +10 A2 preview-bound attendance repair dispatch and help; integrated upstream provider retirement with thin recall and gated repair dispatch; typed readiness, configuration-blocked lifecycle and bounded release+src/commands/autopilot.ts 2725 ratchet grown v0.46.26.0 megawave (#4300 #4285 #3696) + master v0.46.27.0 env-file lane + boot warning + reload-safe install (#2608 #4443) + 1 nosemgrep dataflow annotation (path-traversal audit); +chat-connectors wiring; +20 #4728 wrapper exec guard (baked CLI path gone -> PATH fallback / --install hint); +5 #4952 (refs #4399): syncEnabled=false skip in the freshness dispatch loop; typed readiness, configuration-blocked lifecycle and bounded release; +3 guard transaction callbacks and roll back on configuration blocksrc/commands/doctor.ts 4593 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): one in-branch live-column diff on detectMissingColumns + engine-aware superseded upgrade-error suppression (explicit ok); grown db-availability loop: classified connection check + synthesized total-outage entry + hoisted pgbouncer helper + engine-fit check wiring + report engine/db_url_source fields; +chat-connectors wiring (master merge); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +7 backup_coverage check registration (monthly backup check); +master-merge true-up; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +9 v0.47 gmail-loops: google_oauth vault-health check dispatch; +17 (#4712: git-root-pinned source skip note wiring + all-skipped warn-not-ok status for multi_source_drift); +8 memorable_relay_health wiring (check itself is a peel: doctor/checks/integrations-memorable.ts); +9 ambient-writeback WP6: memory_writeback check registration (logic lives in doctor/checks/memory-writeback.ts); +14 default_source_local_path registration (#4739 — check body peeled to doctor/checks/default-source-path.ts); +9 atom_provenance_drift registration (#4566 — check body lives in doctor/checks/extraction-sync.ts); master: | merged v0.48.1.0 true-up; #5252 wave: scoped projection readiness registration; shared content: register the separately scoped canonical publication/recovery check; merged reliability/shared-skills source integrationsrc/commands/embed.ts 2144 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiringsrc/commands/extract-conversation-facts.ts 2125 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364)src/commands/extract.ts 2571 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain-src/commands/jobs.ts 3173 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); #5105: two-line delegate validates revision and durable authority before fact backstop execution; upstream integration: preserve independently reviewed master additions with branch facade extraction; +13 v0.50.5.0 security merge (upstream delta; coordinated facade retained); merged reliability/shared-skills source integration; +1 #5584: skillopt job reflect_max_tokens (validated + clamped via skillopt/output-cap.ts); lowered #5585: skillopt handler body peeled to skillopt/job.ts (execution-time model re-resolution + strict re-check)+src/commands/jobs.ts 3260 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); #5105: two-line delegate validates revision and durable authority before fact backstop execution; upstream integration: preserve independently reviewed master additions with branch facade extraction; +13 v0.50.5.0 security merge (upstream delta; coordinated facade retained); merged reliability/shared-skills source integration; +1 #5584: skillopt job reflect_max_tokens (validated + clamped via skillopt/output-cap.ts); lowered #5585: skillopt handler body peeled to skillopt/job.ts (execution-time model re-resolution + strict re-check); typed readiness, configuration-blocked lifecycle and bounded release (issue #5560 merge)src/commands/serve-http.ts 3098 ratchet registration and grant routes extracted; owner authentication and configured discovery remain in the HTTP facade; one shared bootstrap-token-shape import from serve-service; merged scoped shared-skill resources and named capability checkssrc/core/ai/gateway.ts 4439 ratchet +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removedsrc/commands/sync.ts 5995 ratchet +1 #4786/#3068 pre-landing: pullFailed early return reports the sweep count (comment line); +1 #4786 x #2139 pre-landing: both embed-backfill submit gates require syncProducedEmbeddableContent (import line); re-summed after merging master v0.50.0.0 with the wave (include_hidden, sweep count, cost-gate envelope); +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; master integration: +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; #5252 wave: post-batch planner statistics refresh; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; merged reliability/shared-skills source integration; +1 cancellation guard before company dispatch@@ -24,12 +24,12 @@ src/core/pglite-engine.ts 6120 ratchet +6 #4881: ontology provenance-page visibisrc/core/postgres-engine.ts 5577 ratchet +6 #4881: ontology provenance-page visibility gate (parity twin); lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069); +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +61: #4592 source-scoped getStats/getHealth (scope predicate, both-endpoint link rule); +11 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); rule); +12: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata, parity twin); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +3: #4681 listPages projects updated_at_iso (microsecond keyset cursor, parity twin); #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop barrier and direct transaction route; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained)src/core/search/hybrid.ts 3213 ratchet grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380); +59 2026-09 adversarial batch 2: both-mode text-only demotion gate (textVectorArmNonEmpty) + relaxed_dropped meta + keyword_relaxed_carried degraded stamp + intent-skew caveat docs; +35 #3617 follow-up: relaxed-row fusion demotion (vectorArmNonEmpty gate + keywordFusionList/titleFusionList) with the LongMemEval 51.3%-vs-93.8% receipt comment; +24 2026-08 eval fix wave (E5b/D8): adaptive-return knobs-hash v27 fold (resolved gate + intent class threaded to the cache key), adaptive-on skipCache removal, dedupOpts cache-skip honesty, explicit-maxPerPage min() precedence under walk widening; (#4380); +20 wave #4256: compiledTruthBoost helper — synthetic chunkless title rows (chunk_id 0 + empty chunk_text) never gain the 2x compiled-truth boost (#3695); composition true-up (fix-wave multi-train) | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: read-policy propagation and semantic result-cache containment; ranker wave v0.48.4.0: role-tagged fusion arms, relational rerank pin, metadata boost gate, per-call knob seams, onRerankPool hook (+150) merged over master's read-policy plumbing (+31); +11 #4359 (#4972): thread the loaded search-mode config snapshot from hybridSearchCached into the inner hybridSearch call (INTERNAL _searchModeInput opt) so both resolve from the same one DB-plane config read instead of two independent ones — closes the cache-key/result desync window and removes the second config-table round trip on every hybridSearchCached call; #5252 wave: inclusive date bounds and public vector incompleteness; shared date-bounds peel retains exports; merged company ingestion/schema routing changes; retired provider integration removedsrc/core/types.ts 2072 ratchet +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed-src/core/minions/queue.ts 2484 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced+src/core/minions/queue.ts 2513 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded releasesrc/commands/init.ts 1932 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-initsrc/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatchsrc/commands/bootstrap.ts 2115 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics-src/core/minions/worker.ts 1546 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch+src/core/minions/worker.ts 1764 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retrysrc/commands/sources.ts 1993 ratchet grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.tssrc/core/link-extraction.ts 2082 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance rangessrc/core/embedding-migration.ts 1435 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removeddiff --git a/scripts/persistence/matrix.ts b/scripts/persistence/matrix.tsindex 4497176382..a767ff044c 100644--- a/scripts/persistence/matrix.ts+++ b/scripts/persistence/matrix.ts@@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto';import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join, resolve } from 'node:path';-import postgres from 'postgres';+import postgres from '#postgres'import { assertSafeE2eDatabaseUrl } from '../../test/helpers/db-guard.ts';import { spawnWorker } from './validate.ts';import type { RuntimeCase } from './matrix-cases.ts';diff --git a/scripts/persistence/performance.ts b/scripts/persistence/performance.tsindex e490569c92..4b09554ebb 100644--- a/scripts/persistence/performance.ts+++ b/scripts/persistence/performance.ts@@ -3,7 +3,7 @@ import { createHash, randomUUID } from 'node:crypto';import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { availableParallelism, cpus, loadavg, tmpdir, totalmem } from 'node:os';import { dirname, join, resolve } from 'node:path';-import postgres from 'postgres';+import postgres from '#postgres'import { assertSafeE2eDatabaseUrl } from '../../test/helpers/db-guard.ts';import { childEnvironment } from './validate.ts';import { summarizeReadRuns } from './read-metrics.ts';diff --git a/scripts/persistence/validate.ts b/scripts/persistence/validate.tsindex 2dd0f4c15a..bd422726d1 100644--- a/scripts/persistence/validate.ts+++ b/scripts/persistence/validate.ts@@ -3,7 +3,7 @@ import { createHash, randomUUID } from 'node:crypto';import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { availableParallelism, loadavg, tmpdir, totalmem } from 'node:os';import { basename, dirname, join, resolve } from 'node:path';-import postgres from 'postgres';+import postgres from '#postgres'import { assertSafeE2eDatabaseUrl } from '../../test/helpers/db-guard.ts';import { distribution, type HarnessConfig } from './harness.ts';import { keylessBrainEnv } from '../../test/helpers/provider-env.ts';diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex fbc28a4536..9afcb1e0ec 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -233,6 +233,7 @@ test/pglite-engine.test.ts PGLiteEngine: v0.13.1 error-wrap on connect() (#223)test/pglite-repair-command.serial.test.ts gbrain pglite-repair — interactive confirm wiring (#4318 residual) 1 readFileSynctest/pglite-wal-repair.serial.test.ts WAL auto-repair — real-brain regression (#223/#1670/#2575) 6 readFileSynctest/phantom-redirect-per-source-lock.test.ts phantom-redirect lock contract 3 readFileSync+test/postgres-driver-vendor.test.ts vendored Postgres driver packaging 3 readFileSynctest/postgres-engine-singleton-ownership.test.ts postgres-engine / module-singleton ownership (#1471) 7 readFileSynctest/postgres-engine.test.ts postgres-engine / search date filtering 1 readFileSynctest/postgres-engine.test.ts postgres-engine / search path timeout isolation 7 readFileSync@@ -345,3 +346,5 @@ test/v0_37_gap_fill.serial.test.ts Lane E.4 — loadRecommendationContext is protest/v0_37_gap_fill.serial.test.ts reinit-pglite — backup + reinit 7 readFileSynctest/voyage-response-cap.test.ts v0.31.8 — voyage Content-Length pre-check + per-item cap 6 bun-filetest/worker-supervised-db-probe.test.ts issue #1801 fix #2 — supervised DB self-defense 5 readFileSync+# unknown (detectors present, no attributable suite):+# unknown test/e2e/postgres-driver-install.test.tsdiff --git a/src/cli.ts b/src/cli.tsindex d47b81bada..a73fd5a5de 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -2938,6 +2938,17 @@ async function handleCliOnly(command: string, args: string[]) {}refuseThinClient('jobs', cfgJobs!.remote_mcp!.mcp_url);}+ if (args[0] === 'supervisor' && args[1] === 'status') {+ const { DEFAULT_PID_FILE } = await import('./core/minions/supervisor.ts');+ const { readSupervisorPid } = await import('./core/minions/supervisor-pid.ts');+ const pidFileIndex = args.indexOf('--pid-file');+ const pidFile = pidFileIndex >= 0 ? args[pidFileIndex + 1] ?? DEFAULT_PID_FILE : DEFAULT_PID_FILE;+ if (readSupervisorPid(pidFile).running) {+ const { runJobs } = await import('./commands/jobs.ts');+ await runJobs(null, args);+ return;+ }+ }}// Autopilot status + uninstall are filesystem-only verdicts and MUST stay@@ -2991,8 +3002,20 @@ async function handleCliOnly(command: string, args: string[]) {// TODOS 1050, out of scope). Kill switch: GBRAIN_SERVE_DEGRADED=0.let engine: BrainEngine;try {- engine = await connectEngine();+ engine = await connectEngine({ probeOnly: command === 'jobs' && args[0] === 'supervisor' && args[1] === 'status' });} catch (serveConnectError) {+ if (command === 'jobs' && args[0] === 'child-readiness') {+ const { writeChildReadinessFailure } = await import('./core/minions/child-readiness.ts');+ process.exit(writeChildReadinessFailure(serveConnectError));+ }+ if (command === 'jobs' && args[0] === 'run-child') {+ const { CHILD_ENV } = await import('./core/minions/job-isolation.ts');+ const resultPath = process.env[CHILD_ENV.resultPath];+ if (resultPath) {+ const { writeChildBootstrapError } = await import('./core/minions/run-child.ts');+ process.exit(writeChildBootstrapError(resultPath, serveConnectError));+ }+ }// Gate on the engine of the RESOLVED brain, not the host config —// connectEngine routes mounts FIRST, so a PGLite mount's failure on a// postgres host must NOT get a lazy reconnect proxy (the single-writerdiff --git a/src/commands/autopilot.ts b/src/commands/autopilot.tsindex 70ff616840..c10730f5d0 100644--- a/src/commands/autopilot.ts+++ b/src/commands/autopilot.ts@@ -31,6 +31,8 @@ import {isPidAlive,} from '../core/autopilot-lock.ts';import { ChildWorkerSupervisor } from '../core/minions/child-worker-supervisor.ts';+import { resolveChildCliInvocation } from '../core/minions/job-isolation.ts';+import { OwnerProcessingState, readAutopilotProcessingStatus } from '../core/minions/processing-state.ts';import { VERSION } from '../version.ts';import {canSelfUpdate,@@ -366,6 +368,30 @@ async function computeAutopilotIdle(engine: BrainEngine, engineType: string): Pr}}+export function guardAutopilotEngine(engine: BrainEngine, state: OwnerProcessingState): BrainEngine {+ const refuse = (): never => {+ throw new Error('Autopilot processing is configuration-blocked; repair and restart the owner.');+ };+ return new Proxy(engine, {+ get(target, property) {+ const value = Reflect.get(target, property);+ if (typeof value !== 'function') return value;+ return (...args: unknown[]) => {+ if (property !== 'disconnect' && state.blocked) refuse();+ if (property === 'transaction' || property === 'transactionDirect') {+ const fn = args[0] as (tx: BrainEngine) => Promise<unknown>;+ return Reflect.apply(value, target, [async (tx: BrainEngine) => {+ const result = await fn(guardAutopilotEngine(tx, state));+ if (state.blocked) refuse();+ return result;+ }]);+ }+ return Reflect.apply(value, target, args);+ };+ },+ });+}+/*** The autopilot silent self-upgrade channel. Opt-in (`self_upgrade.mode=auto`).* Fires only when behind + idle + in quiet hours + the install can self-update@@ -378,6 +404,7 @@ async function attemptAutopilotSelfUpgrade(engine: BrainEngine,engineType: string,lockPath: string,+ mayContinue: () => boolean = () => true,): Promise<void> {try {const cfg = loadConfig();@@ -430,6 +457,7 @@ async function attemptAutopilotSelfUpgrade(return;}+ if (!mayContinue()) return;// Apply. Breadcrumb first so a crash-on-launch is attributable.cfg.self_upgrade = { ...(cfg.self_upgrade ?? {}), attempting_version: latestVersion };saveConfig(cfg);@@ -463,6 +491,7 @@ async function attemptAutopilotSelfUpgrade(return;}+ if (!mayContinue()) return;// Swap done + smoke-verified by `upgrade --swap-only`. Exit cleanly so the// supervisor relaunches the NEW binary, which reconciles the breadcrumb.logSelfUpgrade({@@ -679,6 +708,9 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {let stopping = false;let childSupervisor: ChildWorkerSupervisor | null = null;+ const processingState = spawnManagedWorker ? new OwnerProcessingState('autopilot', 'default') : null;+ const configurationBlocked = () => processingState?.blocked ?? false;+ if (processingState) engine = guardAutopilotEngine(engine, processingState);// #1872: graceful engine shutdown. On PGLite the cycle steps run INLINE in// this process, so a hard `process.exit` mid-write (systemctl stop →@@ -713,7 +745,8 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {const deregisterEngineClose = registerCleanup('autopilot-engine-close', closeEngine);if (spawnManagedWorker) {- const cliPath = resolveGbrainCliPath();+ const invocation = resolveChildCliInvocation({}, process.execPath, process.argv[1], resolveGbrainCliPath);+ if (!invocation) throw new Error('Could not resolve the worker CLI. Repair the current GBrain installation.');// Cgroup-aware auto-sized RSS watchdog cap (issue #1678). The old flat// 2048MB killed legit embed work (~10GB) on every cycle → silent// ~400×/24h respawn loop. resolveDefaultMaxRssMb clamps 0.5×min(cgroup,@@ -722,17 +755,12 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {const { resolveDefaultMaxRssMb } = await import('../core/minions/rss-default.ts');const autopilotMaxRssMb = resolveDefaultMaxRssMb();childSupervisor = new ChildWorkerSupervisor({- cliPath,- // Orphaned-private-queue recovery runs INSIDE each spawned worker's- // startup (jobs.ts 'work', gated on GBRAIN_SUPERVISED !== '1', which- // autopilot children never set) — so every spawn AND crash-respawn- // recovers without a parent-side beforeSpawn double-running the scan.- args: ['jobs', 'work', '--max-rss', String(autopilotMaxRssMb)],- // process.env clone; autopilot doesn't gate shell jobs the way the- // standalone supervisor does (autopilot is the operator-trust path).- // GBRAIN_SUPERVISED is stripped explicitly: worker-startup recovery is- // autopilot's ONLY private-queue recovery lane, and an inherited =1- // (operator export, nested supervision) would silently disable it.+ processingState: processingState ?? undefined,+ onConfigurationBlocked: (status) => {+ console.error(`[autopilot] processing configuration-blocked (${status?.reason_code ?? 'unknown'}); repair the worker/child installation and explicitly restart autopilot.`);+ },+ cliPath: invocation.cmd,+ args: [...invocation.argsPrefix, 'jobs', 'work', '--max-rss', String(autopilotMaxRssMb)],env: { ...process.env, GBRAIN_SUPERVISED: undefined } as Record<string, string | undefined>,maxCrashes: 5,isStopping: () => stopping,@@ -744,7 +772,9 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {// Route ChildWorkerSupervisor events to autopilot's stderr log.// Matches the prior console output shape so operators reading// existing logs see the same lines.- if (event.kind === 'worker_spawned') {+ if (event.kind === 'worker_startup_timeout') {+ console.error(`[autopilot] worker readiness was not confirmed within ${event.timeoutMs}ms; stopping this worker and retrying with bounded backoff.`);+ } else if (event.kind === 'worker_spawned') {console.log(`[autopilot] Minions worker spawned (pid: ${event.pid}, watchdog: ${autopilotMaxRssMb}MB${event.tini ? ', tini: active' : ''})`,);@@ -796,6 +826,7 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {// No `process.on('exit')` handler — its callback runs synchronously and// cannot await the worker's drain.const shutdown = async (sig: string) => {+ if (configurationBlocked() && sig !== 'SIGTERM' && sig !== 'SIGINT') return;if (stopping) return;stopping = true;console.log(`Autopilot stopping (${sig}).`);@@ -806,10 +837,15 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {childSupervisor.killChild('SIGKILL');}}+ if (configurationBlocked() && sig !== 'SIGTERM' && sig !== 'SIGINT') {+ stopping = false;+ return;+ }// #1872: abort the in-flight inline cycle and close the engine BEFORE// process.exit — a hard exit mid-write corrupts PGLite's WASM Postgres.await closeEngine();deregisterEngineClose();+ processingState?.close();try { unlinkSync(lockPath); } catch { /* already gone */ }process.exit(sig === 'max_crashes' || sig === 'cycle-failure-cap' ? 1 : 0);};@@ -861,6 +897,11 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {// declare the instance stale after 10 minutes (Codex C).try { utimesSync(lockPath, new Date(), new Date()); } catch { /* best-effort */ }+ if (processingState && !processingState.snapshot.processing_ready) {+ await new Promise(r => setTimeout(r, 250));+ continue;+ }+// #2608: loud once-per-process signal when no chat provider is servable.// Without this a keyless daemon looks healthy forever while every LLM// phase quietly skips.@@ -953,6 +994,7 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {await engine.getConfig('version');autopilotReconnectFails = 0; // reset on success} catch (probeErr) {+ if (configurationBlocked()) continue;try {// #2034: use reconnect() — it restores the config captured at connect()// and avoids the null-connection window. The previous@@ -963,6 +1005,7 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {await engine.reconnect({ error: probeErr });autopilotReconnectFails = 0;} catch (e) {+ if (configurationBlocked()) continue;logError('reconnect', e);autopilotReconnectFails++;const klass = classifyReconnectError(e);@@ -1000,7 +1043,9 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {// v0.42 self-upgrade silent channel (opt-in self_upgrade.mode=auto). Runs// each tick; cache TTL throttles the actual GitHub fetch. On apply it swaps// + exits for supervisor relaunch (never returns). No-op unless mode=auto.- await attemptAutopilotSelfUpgrade(engine, engineType, lockPath);+ if (configurationBlocked()) continue;+ await attemptAutopilotSelfUpgrade(engine, engineType, lockPath, () => !configurationBlocked());+ if (configurationBlocked()) continue;// --no-worker peer-liveness probe (v0.19.1). Runs every cycle, cheap// (single SELECT). See NO_WORKER_WARN_TICKS comment above for caveats.@@ -1516,6 +1561,7 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {} catch (e) { logError('cycle-inline', e); cycleOk = false; }}+ if (configurationBlocked()) continue;// 4. Health check + adaptive interval (same for both paths)let interval = baseInterval;try {@@ -1534,13 +1580,15 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {}} catch (e) { logError('health', e); }+ if (configurationBlocked()) continue;if (cycleOk) {consecutiveErrors = 0;} else {consecutiveErrors++;if (consecutiveErrors >= 5) {console.error('5 consecutive cycle failures. Stopping autopilot.');- void shutdown('cycle-failure-cap');+ await shutdown('cycle-failure-cap');+ if (!stopping) continue;break;}}@@ -2625,9 +2673,10 @@ function showStatus(json: boolean, intervalSeconds: number) {intervalSeconds,lastLog: lastLine,});+ const processing = readAutopilotProcessingStatus();if (json) {- console.log(JSON.stringify(report));+ console.log(JSON.stringify({ ...report, ...processing }));} else {switch (report.state) {case 'not_installed':@@ -2660,6 +2709,11 @@ function showStatus(json: boolean, intervalSeconds: number) {);break;}+ if (processing) {+ console.log(`Processing: ${processing.processing_state}${processing.reason_code ? ` (${processing.reason_code})` : ''}`);+ console.log(`Stage: ${processing.processing_stage}${processing.retry_at ? `; next retry ${processing.retry_at}` : ''}`);+ if (processing.processing_state === 'configuration_blocked') console.log('Repair the worker and selected child installation, then explicitly restart autopilot.');+ }if (lastLine) console.log(`Last log: ${lastLine}`);}diff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex b55865da1b..7f11fc4fc7 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -25,6 +25,8 @@ import { VERSION as GBRAIN_BINARY_VERSION } from '../version.ts';import { schemaVersionHealth } from '../core/schema-version-health.ts';import { zeroTotalContradictionsCheck } from '../core/eval-contradictions/run-health.ts';import { checkProjectionReadiness } from './doctor/checks/projection-readiness.ts';+import { checkPostgresCancellationDriver } from './doctor/checks/postgres-cancellation.ts';+export { checkPostgresCancellationDriver } from './doctor/checks/postgres-cancellation.ts';export { checkProjectionReadiness } from './doctor/checks/projection-readiness.ts';// Peeled doctor modules (containment sprint): each is a verbatim move out of// this file. doctor.ts re-exports every moved public symbol under its@@ -1875,6 +1877,8 @@ export async function buildChecks(// 4. pgvector extensionprogress.heartbeat('pgvector');checks.push(await pgvectorCheck(engine));+ const postgresCancellation = await checkPostgresCancellationDriver(engine);+ if (postgresCancellation) checks.push(postgresCancellation);// 4a-bis. #550: pages(source_id, slug) upsert arbiter — when missing, every// page write fails brain-wide and the version counter can't see the drift.diff --git a/src/commands/doctor/checks/postgres-cancellation.ts b/src/commands/doctor/checks/postgres-cancellation.tsnew file mode 100644index 0000000000..cd498519bb--- /dev/null+++ b/src/commands/doctor/checks/postgres-cancellation.ts@@ -0,0 +1,40 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { PostgresEngine } from '../../../core/postgres-engine.ts';+import { hasPostgresCancellationCapability, postgresCancellationUnavailable, reserveWithCancellation } from '../../../core/postgres-engine/cancellation.ts';+import type { Check } from '../../doctor.ts';++export async function checkPostgresCancellationDriver(+ engine: BrainEngine,+ opts: { timeoutMs?: number } = {},+): Promise<Check | null> {+ if (engine.kind !== 'postgres') return null;+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? 5_000);+ let owner: { release(): void } | undefined;+ try {+ owner = await reserveWithCancellation(options => (engine as PostgresEngine).sql.reserve(options), controller.signal);+ if (!hasPostgresCancellationCapability(owner)) {+ const error = postgresCancellationUnavailable();+ return {+ name: 'postgres_cancellation_driver',+ status: 'fail',+ message: error.message,+ details: { reason_code: error.reasonCode },+ };+ }+ return {+ name: 'postgres_cancellation_driver',+ status: 'ok',+ message: 'Postgres driver supports safe query cancellation.',+ };+ } catch {+ return {+ name: 'postgres_cancellation_driver',+ status: 'warn',+ message: 'Could not inspect a reserved Postgres connection within the readiness budget. Check database connectivity and retry; a timeout does not prove a driver fault.',+ };+ } finally {+ clearTimeout(timer);+ owner?.release();+ }+}diff --git a/src/commands/jobs-readiness.ts b/src/commands/jobs-readiness.tsnew file mode 100644index 0000000000..92f2104c38--- /dev/null+++ b/src/commands/jobs-readiness.ts@@ -0,0 +1,75 @@+import type { BrainEngine } from '../core/engine.ts';+import { VERSION } from '../version.ts';+import { assertWorkerDbReadiness } from '../core/minions/db-probe.ts';+import { checkChildReadiness, CHILD_READINESS_PROTOCOL_VERSION } from '../core/minions/child-readiness.ts';+import { childConfigurationError, resolveChildCliInvocation, type ChildCliInvocation } from '../core/minions/job-isolation.ts';+import type { LocalConfigurationError } from '../core/minions/configuration-error.ts';+import { writeWorkerProcessingStatus, type ProcessingRuntimeIdentity, type WorkerProcessingUpdate, type WorkerStartupStage } from '../core/minions/processing-state.ts';++let selectedChildIdentity: ProcessingRuntimeIdentity | undefined;+const currentInvocation = resolveChildCliInvocation({}, process.execPath, process.argv[1], () => null);+const workerIdentity = {+ executable: currentInvocation?.argsPrefix[0] ?? currentInvocation?.cmd ?? process.execPath,+ version: VERSION,+};++export async function checkWorkerStartup(+ engine: BrainEngine,+ invocation: ChildCliInvocation | null,+ tiniPath: string,+): Promise<ProcessingRuntimeIdentity | undefined> {+ selectedChildIdentity = invocation+ ? { executable: invocation.argsPrefix[0] ?? invocation.cmd, version: 'unknown' }+ : undefined;+ reportWorkerStarting('database_readiness');+ await assertWorkerDbReadiness(engine);+ if (!invocation) return undefined;+ reportWorkerStarting('child_readiness');+ const child = await checkChildReadiness({ invocation, tiniPath });+ if (child.versionSkew) {+ console.error(`[gbrain jobs] selected child version ${child.version} differs from worker ${VERSION}; required protocol and capabilities are compatible.`);+ }+ selectedChildIdentity = {+ executable: invocation.argsPrefix[0] ?? invocation.cmd,+ version: child.version,+ protocol_version: CHILD_READINESS_PROTOCOL_VERSION,+ };+ return selectedChildIdentity;+}++function publishRequiredWorkerStatus(update: WorkerProcessingUpdate): void {+ const published = writeWorkerProcessingStatus(update);+ if (!published && (process.env.GBRAIN_WORKER_STATUS_PATH || process.env.GBRAIN_WORKER_STATUS_TOKEN)) {+ const error = new Error('Worker readiness status could not be published; no jobs were admitted. Inspect the owner runtime directory and restart its owner.');+ console.error(`[health] ${error.message}`);+ throw error;+ }+}++export function reportWorkerStarting(stage: WorkerStartupStage): void {+ publishRequiredWorkerStatus({ state: 'starting', stage, worker_identity: workerIdentity, child_identity: selectedChildIdentity });+}++export function reportWorkerReady(childIdentity?: ProcessingRuntimeIdentity): void {+ publishRequiredWorkerStatus({+ state: 'ready',+ worker_identity: workerIdentity,+ child_identity: childIdentity,+ });+}++export function reportWorkerConfiguration(error: LocalConfigurationError): void {+ writeWorkerProcessingStatus({+ state: 'configuration_blocked',+ reason_code: error.reasonCode,+ worker_identity: workerIdentity,+ child_identity: selectedChildIdentity,+ });+ console.error(`[health] configuration blocked (${error.reasonCode}): ${childConfigurationError(error.reasonCode).message}`);+ console.error('[health] No new jobs will run. Repair this installation and explicitly restart its owner. See docs/guides/minions-fix.md.');+}++export function reportInlineWorkerConfiguration(error: LocalConfigurationError): void {+ console.error(`[health] configuration blocked (${error.reasonCode}): ${childConfigurationError(error.reasonCode).message}`);+ console.error('[health] The inline worker admitted no jobs. Repair this installation and rerun. See docs/guides/minions-fix.md.');+}diff --git a/src/commands/jobs.ts b/src/commands/jobs.tsindex f6770bab04..eca5b0d732 100644--- a/src/commands/jobs.ts+++ b/src/commands/jobs.ts@@ -16,11 +16,14 @@ import { MinionQueue, deriveWedgeSignal } from '../core/minions/queue.ts';import { MinionWorker } from '../core/minions/worker.ts';import {WORKER_EXIT_RSS_WATCHDOG,+ WORKER_EXIT_CONFIGURATION,JOB_CHILD_EXIT_USAGE,} from '../core/minions/worker-exit-codes.ts';import { CHILD_ENV, resolveChildCliInvocation } from '../core/minions/job-isolation.ts';+import { isLocalConfigurationError, LocalConfigurationError } from '../core/minions/configuration-error.ts';+import { checkWorkerStartup, reportInlineWorkerConfiguration, reportWorkerConfiguration, reportWorkerReady, reportWorkerStarting } from './jobs-readiness.ts';import { withFactsAbsorbHaltCooldown } from '../core/minions/llm-halt-cooldown.ts';-import { runChildJobEntry } from '../core/minions/run-child.ts';+import { runChildJobEntry, writeChildBootstrapError } from '../core/minions/run-child.ts';import type { MinionHandler, MinionJob, MinionJobStatus } from '../core/minions/types.ts';import type { PaceKeyOverrides } from '../core/pace-mode.ts';import { loadConfig, loadConfigWithEngine, isThinClient } from '../core/config.ts';@@ -597,19 +600,22 @@ OPTIONS`,};-// Bare (unsupervised) workers run the same orphaned-private-queue recovery-// the supervisor runs in beforeSpawn — a deployment that starts-// `gbrain jobs work` directly must not lose the crash-recovery lane.-// Supervised children skip it: their supervisor already ran it.export async function maybeRunWorkerStartupRecovery(queue: MinionQueue,env: NodeJS.ProcessEnv = process.env,+ readinessVerified = false,): Promise<void> {- if (env.GBRAIN_SUPERVISED === '1') return;+ if (env.GBRAIN_SUPERVISED === '1' && !readinessVerified) return;+ let deadline: ReturnType<typeof setTimeout> | undefined;try {- const recovered = await queue.reconcileOrphanedPrivateQueues({- reason: 'worker startup recovery: orphaned dream-inline private queue',- });+ const recovered = await Promise.race([+ queue.reconcileOrphanedPrivateQueues({+ reason: 'worker startup recovery: orphaned dream-inline private queue',+ }),+ new Promise<never>((_, reject) => {+ deadline = setTimeout(() => reject(new Error('private-queue startup recovery did not settle within 30 seconds; recovery is unconfirmed')), 30_000);+ }),+ ]);if (recovered.cancelled_jobs > 0) {console.error(`[gbrain jobs] private-queue startup recovery: cancelled ${recovered.cancelled_jobs} ` +@@ -617,7 +623,10 @@ export async function maybeRunWorkerStartupRecovery();}} catch (e) {+ if (isLocalConfigurationError(e)) throw e;console.error(`[gbrain jobs] private-queue startup recovery failed: ${e instanceof Error ? e.message : String(e)}`);+ } finally {+ if (deadline) clearTimeout(deadline);}}@@ -646,7 +655,8 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):// ever built. Any other subcommand arriving with a null engine is a// routing bug upstream of this function — refuse instead of crashing// inside MinionQueue.- if (!engineOrNull && sub !== 'list' && sub !== 'get') {+ const localSupervisorStatus = sub === 'supervisor' && args[1] === 'status';+ if (!engineOrNull && sub !== 'list' && sub !== 'get' && !localSupervisorStatus) {console.error(`\`gbrain jobs ${sub ?? ''}\` needs a local engine and cannot run on a thin client.`);process.exit(1);}@@ -873,6 +883,7 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):if (final.result) console.log(`Result: ${JSON.stringify(final.result)}`);} else {console.error(`Job #${job.id} ${final?.status}: ${final?.error_text}`);+ if (worker.configurationError) reportInlineWorkerConfiguration(worker.configurationError);process.exit(1);}} else {@@ -1362,6 +1373,7 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):if (final?.status !== 'completed') {console.error(`SMOKE FAIL — job #${job.id} status: ${final?.status ?? 'timeout'} (${elapsedSec}s elapsed)`);if (final?.error_text) console.error(` Error: ${final.error_text}`);+ if (worker.configurationError) reportInlineWorkerConfiguration(worker.configurationError);process.exit(1);}@@ -1480,6 +1492,14 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):process.exit(0);}+ case 'child-readiness': {+ const { runChildReadinessEntry } = await import('../core/minions/child-readiness.ts');+ const { assertWorkerDbReadiness } = await import('../core/minions/db-probe.ts');+ const code = await runChildReadinessEntry(engine, assertWorkerDbReadiness);+ try { await engine.disconnect(); } catch {}+ process.exit(code);+ }+case 'run-child': {// INTERNAL (issue #5 process isolation): spawned by `jobs work` with// process isolation enabled. One job, one process: validate the claim,@@ -1513,10 +1533,10 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):// Same handler surface as the worker: registerBuiltinHandlers also// performs plugin discovery, so plugin subagent jobs isolate too.const throwaway = new MinionWorker(engine, { queue: 'default', concurrency: 1 });- await registerBuiltinHandlers(throwaway, engine, { quiet: true });let code: number;try {+ await registerBuiltinHandlers(throwaway, engine, { quiet: true });code = await runChildJobEntry(engine,{@@ -1528,8 +1548,8 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):{ resolveHandler: (name) => throwaway.getHandler(name) },);} catch (e) {- console.error(`[run-child] fatal: ${e instanceof Error ? e.message : String(e)}`);- code = 1;+ code = writeChildBootstrapError(resultPath, e);+ console.error('[run-child] bootstrap failed; the parent will inspect the structured outcome.');}await engine.disconnect();process.exit(code);@@ -1618,11 +1638,8 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):() => resolveGbrainCliPath(),);if (!inv) {- console.error(- 'Error: process isolation needs a resolvable gbrain CLI for job children ' +- '(compiled binary on PATH, or GBRAIN_JOB_CHILD_CLI override).',- );- process.exit(1);+ reportWorkerConfiguration(new LocalConfigurationError('child_executable_invalid', 'No child CLI could be resolved.'));+ process.exit(WORKER_EXIT_CONFIGURATION);}// Canonicalize BEFORE validating: existsSync on a relative name checks// cwd while spawn() resolves via PATH — the validated file and the@@ -1632,11 +1649,8 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):const { resolve: resolveCliPath } = await import('node:path');inv.cmd = resolveCliPath(inv.cmd);if (!childCliExists(inv.cmd)) {- console.error(- `Error: resolved child CLI does not exist: ${inv.cmd} ` +- '(set GBRAIN_JOB_CHILD_CLI to a valid gbrain binary).',- );- process.exit(1);+ reportWorkerConfiguration(new LocalConfigurationError('child_executable_invalid', 'The selected child CLI does not exist.'));+ process.exit(WORKER_EXIT_CONFIGURATION);}childCliInvocation = inv;const { detectTini } = await import('../core/minions/spawn-helpers.ts');@@ -1650,10 +1664,29 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):}}- try { await queue.ensureSchema(); }- catch (e) { console.error(e instanceof Error ? e.message : String(e)); process.exit(1); }+ let childIdentity: Awaited<ReturnType<typeof checkWorkerStartup>>;+ try {+ childIdentity = await checkWorkerStartup(engine, childCliInvocation, childTiniPath);+ } catch (error) {+ if (isLocalConfigurationError(error)) {+ reportWorkerConfiguration(error);+ process.exit(WORKER_EXIT_CONFIGURATION);+ }+ console.error('[health] Worker readiness is temporarily unavailable; no jobs were admitted. The supervisor will retry.');+ process.exit(1);+ }- await maybeRunWorkerStartupRecovery(queue);+ try {+ await queue.ensureSchema();+ await maybeRunWorkerStartupRecovery(queue, process.env, true);+ } catch (error) {+ if (isLocalConfigurationError(error)) {+ reportWorkerConfiguration(error);+ process.exit(WORKER_EXIT_CONFIGURATION);+ }+ console.error('[gbrain jobs] Worker schema readiness failed; no jobs were admitted. Inspect doctor before retrying.');+ process.exit(1);+ }// issue #6: the direct-pool kill switch collapses lock renewal, health// probes, and handler workload onto ONE shared pool — silently. Make@@ -1677,13 +1710,27 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):queue: queueName, concurrency, maxRssMb, healthCheckInterval,jobIsolation, childCliInvocation, childTiniPath,});- await registerBuiltinHandlers(worker, engine);+ try {+ await registerBuiltinHandlers(worker, engine);+ } catch (error) {+ if (!isLocalConfigurationError(error)) throw error;+ reportWorkerConfiguration(error);+ process.exit(WORKER_EXIT_CONFIGURATION);+ }// Subscribe to self-health failures emitted by the worker. Library code// (worker.ts) never calls process.exit directly so it stays embeddable;// this CLI layer is the right place to terminate the process and let// the external PM (systemd, Docker, cron watchdog) restart cleanly.worker.on('unhealthy', (info) => {+ if (info.reason === 'client_misconfigured') {+ reportWorkerConfiguration(info.error);+ setTimeout(() => {+ console.error('[health] release-unconfirmed: shutdown exceeded its deadline; lease expiry may consume stall budget.');+ process.exit(WORKER_EXIT_CONFIGURATION);+ }, 31_000);+ return;+ }if (info.reason === 'db_dead') {// issue #6: name the failing LAYER, not just "DB unreachable" —// that message sent operators chasing database capacity while the@@ -1765,9 +1812,19 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):process.on('exit', () => unregisterWorker());try {+ reportWorkerStarting('worker_startup');+ worker.once('ready', () => reportWorkerReady(childIdentity));await worker.start();} finally {unregisterWorker();+ if (worker.configurationError) {+ const releases = worker.configurationReleaseResults;+ const unconfirmed = releases.filter(result => result.outcome === 'unconfirmed').length;+ console.error(`[health] Configuration shutdown settled ${releases.length} claim(s); ${unconfirmed} release(s) unconfirmed.`);+ if (unconfirmed > 0) {+ console.error('[health] release-unconfirmed: execution or database release could not be confirmed. Lease expiry may consume stall budget or allow duplicate side effects; inspect affected jobs before retrying.');+ }+ }// Release the DB connection pool immediately on shutdown so// PgBouncer slots are freed rather than waiting for TCP keepalive// (~minutes). Disconnect failure is best-effort but logged loudly:@@ -1780,6 +1837,10 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):try { await engine.disconnect(); }catch (e) { console.error('[gbrain jobs work] engine disconnect failed during shutdown:', e); }+ if (worker.configurationError) {+ process.exit(WORKER_EXIT_CONFIGURATION);+ }+// If the RSS watchdog (not a normal SIGTERM) drained the worker, exit// with the distinct WORKER_EXIT_RSS_WATCHDOG code so the supervisor// classifies the drain as `rss_watchdog` (cause-keyed backoff + loud@@ -1834,7 +1895,7 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):const supQueue = parseFlag(args, '--queue') ?? 'default';let detectedViaDbLock = false;let dbLockHolder: { holder_pid: number; holder_host: string } | null = null;- if (!pidfileRunning) {+ if (!pidfileRunning && engineOrNull) {try {const { inspectLock, isLockHolderLive } = await import('../core/db-lock.ts');const { supervisorLockId, SUPERVISOR_LOCK_TTL_MIN } = await import('../core/minions/supervisor.ts');@@ -1869,9 +1930,22 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):const supervisorNice = pidfileRunning && supervisorPid !== null? getEffectiveNiceness(supervisorPid): null;+ const { readOwnerProcessingStatus } = await import('../core/minions/processing-state.ts');+ const { resolve: resolvePidPath } = await import('node:path');+ const processing = pidfileRunning && supervisorPid !== null+ ? readOwnerProcessingStatus('supervisor', resolvePidPath(pidFile), supervisorPid)+ : null;const status = {running,+ processing_ready: processing?.processing_ready ?? false,+ processing_state: processing?.processing_state ?? (running ? 'unknown' : 'stopped'),+ processing_stage: processing?.processing_stage ?? (running ? 'unknown' : 'stopped'),+ retry_at: processing?.retry_at ?? null,+ reason_code: processing?.reason_code ?? null,+ blocked_since: processing?.blocked_since ?? null,+ worker_identity: processing?.worker_identity ?? null,+ child_identity: processing?.child_identity ?? null,detected_via: detectedViaDbLock ? 'db_lock' : (pidfileRunning ? 'pidfile' : null),supervisor_pid: supervisorPid ?? dbLockHolder?.holder_pid ?? null,db_lock_holder: dbLockHolder,@@ -1893,6 +1967,11 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):} else {const via = detectedViaDbLock ? ' (detected via DB lock; pidfile not found at the configured path)' : '';console.log(`Supervisor: ${running ? 'running' : 'not running'}${via}`);+ console.log(` Processing: ${status.processing_state}`);+ console.log(` Stage: ${status.processing_stage}${status.retry_at ? `; next retry ${status.retry_at}` : ''}`);+ if (status.processing_state === 'configuration_blocked') {+ console.log(` Repair: ${status.reason_code ?? 'local configuration failure'}; repair the installation and restart the supervisor. See docs/guides/minions-fix.md.`);+ }if (status.supervisor_pid) console.log(` PID: ${status.supervisor_pid}${detectedViaDbLock ? ` @ ${dbLockHolder?.holder_host}` : ''}`);console.log(` PID file: ${pidFile}`);if (detectedViaDbLock && status.concurrency !== null) console.log(` Concurrency: ${status.concurrency}${status.max_rss_mb !== null ? ` (max-rss ${status.max_rss_mb}MB)` : ''}`);@@ -2016,7 +2095,14 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):// and exits, not the long-lived re-exec'd child (Codex #1).const supNice = parseNiceFlag(args);- const cliPath = parseFlag(args, '--cli-path') ?? resolveGbrainCliPath();+ const explicitCliPath = parseFlag(args, '--cli-path');+ const workerInvocation = explicitCliPath+ ? { cmd: explicitCliPath, argsPrefix: [] }+ : resolveChildCliInvocation({}, process.execPath, process.argv[1], resolveGbrainCliPath);+ if (!workerInvocation) {+ console.error('Could not resolve this worker installation. Repair the CLI or pass --cli-path.');+ process.exit(WORKER_EXIT_CONFIGURATION);+ }// --detach: fork a background supervisor, print PID payload, exit 0.// #4418: the child gets a DURABLE stderr sink (audit-dir log, null-device@@ -2062,7 +2148,8 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):pidFile,maxCrashes,healthInterval,- cliPath,+ cliPath: workerInvocation.cmd,+ cliArgsPrefix: workerInvocation.argsPrefix,allowShellJobs,json: jsonMode,maxRssMb,diff --git a/src/core/connection-manager.ts b/src/core/connection-manager.tsindex d9bda48b83..28665230ae 100644--- a/src/core/connection-manager.ts+++ b/src/core/connection-manager.ts@@ -36,7 +36,7 @@* GBRAIN_DIRECT_DATABASE_URL override, ddl()/bulk() share the read pool.*/-import postgres from 'postgres';+import postgres from '#postgres'import { resolvePrepare, resolveSessionTimeouts, resolvePoolSize, resolveMaxLifetimeSeconds, endPoolBounded } from './db.ts';import { redactPgUrl } from './url-redact.ts';import { logConnectionEvent } from './connection-audit.ts';diff --git a/src/core/db.ts b/src/core/db.tsindex 34c87357ad..ff09c3d272 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -1,4 +1,4 @@-import postgres from 'postgres';+import postgres from '#postgres'import { GBrainError, type EngineConfig } from './types.ts';import { SCHEMA_SQL } from './schema-embedded.generated.ts';import { applyPostgresForwardReferenceBootstrap } from './postgres-engine/forward-reference-bootstrap.ts';diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex ac7872f2ad..6338851492 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -195,6 +195,7 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['db_repair_recurrence','pglite_leftovers','pgvector',+ 'postgres_cancellation_driver','plugin_lane_collision','pool_budget','progressive_batch_audit_health',diff --git a/src/core/env-trust.ts b/src/core/env-trust.tsindex 3e955d55bc..967e71000b 100644--- a/src/core/env-trust.ts+++ b/src/core/env-trust.ts@@ -178,6 +178,8 @@ export const CWD_DOTENV_PROTECTED_KEYS: readonly string[] = [// --- root / registry redirect ------------------------------------------'GBRAIN_HOME', // relocates ~/.gbrain (config, .env, keys, registry)'GBRAIN_MOUNTS_PATH', // brain mounts registry file+ 'GBRAIN_WORKER_STATUS_PATH',+ 'GBRAIN_WORKER_STATUS_TOKEN','GBRAIN_DATABASE_URL', // THE brain connection string: a cwd .env would retarget every hook, query and write at a planted database; the #427 value guard covers only the bare DATABASE_URL, and this key is "stated intent" everywhere it is read'GBRAIN_DIRECT_DATABASE_URL', // direct-pool override (connection-manager.ts): retargets brain writes at a planted host; has no #427 value guard'GBRAIN_REMOTE_MCP_URL', // `init --remote` default: where the thin client sends its MCP traffic and bearer tokendiff --git a/src/core/minions/child-job-runner.ts b/src/core/minions/child-job-runner.tsindex 1f6f8946a2..64a6364cbe 100644--- a/src/core/minions/child-job-runner.ts+++ b/src/core/minions/child-job-runner.ts@@ -6,14 +6,18 @@* renewal and ALL result recording; this module owns spawn → signal → reap →* decode:*- * spawn — detached (own process group; group signals reach handler- * grandchildren even under tini), tini-wrapped when available,+ * spawn — detached, tracking tini's separate child group on Linux;+ * escaped descendants remain outside the cleanup guarantee,* stdio ['ignore','inherit','inherit'] so handler logs stream* to the operator; results travel by outcome file, never stdout.* signal — per-job abort (timeout / cancel / lock-lost /* lock-renewal-failed) → group SIGTERM now, group SIGKILL at* +CHILD_KILL_GRACE_MS (25s — inside the worker's 30s* force-evict window, which stays as an untouched backstop).+ * After the direct child exits, termination settles as soon+ * as supported Linux proof confirms the owned groups gone;+ * without that proof the group is SIGKILLed at once and the+ * stop stays unconfirmed. Survivors keep the grace SIGKILL.* Worker shutdown → same SIGTERM (the child's own handler fires* ctx.shutdownSignal, giving handlers the drain window to* finish AND write their outcome) with the SIGKILL backstop.@@ -33,6 +37,7 @@ import { mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { buildSpawnInvocation } from './spawn-helpers.ts';+import { LocalConfigurationError, isLocalConfigurationError } from './configuration-error.ts';import {UnrecoverableError,ABORT_REASON_TIMEOUT,@@ -47,11 +52,16 @@ import {CHILD_ENV,CHILD_KILL_GRACE_MS,CHILD_READ_POOL_MAX,+ childConfigurationError,buildChildArgs,decodeChildOutcomeFileAsync,killProcessGroup,+ observeTiniChildProcessGroups,+ captureChildCleanup,+ confirmChildCleanup,+ validateChildExecutable,+ type ChildCleanupSnapshot,reconstructHandlerError,- unrefTimer,type ChildCliInvocation,} from './job-isolation.ts';@@ -64,10 +74,9 @@ export class ChildSpawnInfraError extends Error {}}-/** Child terminated by worker shutdown before it could report. Released with- * no attempt burned — routine deploys must not burn attempts (codex-2 #7). */+/** Shutdown before a report; execution stop requires independent evidence. */export class ChildWorkerShutdownError extends Error {- constructor(message: string) {+ constructor(message: string, readonly executionStopped = false) {super(message);this.name = 'ChildWorkerShutdownError';}@@ -114,6 +123,9 @@ export interface RunJobInChildOpts {killGraceMs?: number;/** Injectable base env for tests. Default process.env. */env?: Record<string, string | undefined>;+ signalProcessGroup?: typeof killProcessGroup;+ onConfigurationError?: (error: LocalConfigurationError) => void;+ onExecutionStopped?: () => void;}interface ChildExit {@@ -129,10 +141,43 @@ interface ChildExit {* them verbatim).*/export async function runJobInChild(opts: RunJobInChildOpts): Promise<unknown> {+ let executionStopped = false;+ let configurationError: LocalConfigurationError | undefined;+ try {+ return await runJobChildProcess({+ ...opts,+ onConfigurationError: error => {+ configurationError = error;+ opts.onConfigurationError?.(error);+ },+ onExecutionStopped: () => {+ executionStopped = true;+ opts.onExecutionStopped?.();+ },+ });+ } catch (error) {+ if (configurationError) throw configurationError;+ if (isLocalConfigurationError(error)) throw error;+ const abortReason = opts.abortSignal.reason instanceof Error ? opts.abortSignal.reason.message : String(opts.abortSignal.reason ?? '');+ if (opts.shutdownSignal.aborted && (isLocalConfigurationError(opts.shutdownSignal.reason) || !PER_JOB_ABORT_REASONS.has(abortReason))) {+ throw new ChildWorkerShutdownError('Job child stopped reporting during worker shutdown; cleanup evidence determines whether its claim can be released.', executionStopped);+ }+ throw error;+ }+}++async function runJobChildProcess(opts: RunJobInChildOpts): Promise<unknown> {+ const base = opts.env ?? process.env;+ let executable: string;+ try { executable = validateChildExecutable(opts.invocation.cmd, base); }+ catch (error) {+ if (isLocalConfigurationError(error)) opts.onExecutionStopped?.();+ throw error;+ }const dir = mkdtempSync(join(tmpdir(), `gbrain-job-${opts.jobId}-`));const resultPath = join(dir, 'outcome.json');const graceMs = opts.killGraceMs ?? CHILD_KILL_GRACE_MS;- const base = opts.env ?? process.env;+ const signalGroup = opts.signalProcessGroup ?? killProcessGroup;// Bound the child's pools: sockets die with the process (the isolation// win), but per-child footprint must stay small — read pool <= 3, direct@@ -160,7 +205,7 @@ export async function runJobInChild(opts: RunJobInChildOpts): Promise<unknown> {GBRAIN_DIRECT_POOL_SIZE: '1',};- const inv = buildSpawnInvocation(opts.tiniPath, opts.invocation.cmd, [+ const inv = buildSpawnInvocation(opts.tiniPath, executable, [...opts.invocation.argsPrefix,...buildChildArgs(opts.jobId, base),]);@@ -174,35 +219,113 @@ export async function runJobInChild(opts: RunJobInChildOpts): Promise<unknown> {});} catch (e) {rmSync(dir, { recursive: true, force: true });- const msg = e instanceof Error ? e.message : String(e);- throw new ChildSpawnInfraError(`job child spawn failed (${inv.cmd}): ${msg}`);+ if (['ENOENT', 'EACCES'].includes((e as NodeJS.ErrnoException).code ?? '')) {+ opts.onExecutionStopped?.();+ throw childConfigurationError('child_executable_invalid');+ }+ throw new ChildSpawnInfraError('Job child could not be spawned.');}let killTimer: ReturnType<typeof setTimeout> | null = null;+ let directExited = false;+ let stopPublished = false;+ let naturalCleanupConfirmed = false;+ const publishExecutionStopped = (): void => {+ if (stopPublished) return;+ stopPublished = true;+ opts.onExecutionStopped?.();+ };+ const directExit = new Promise<ChildExit>((resolve) => {+ child.once('error', error => {+ if (child.pid == null && ['ENOENT', 'EACCES'].includes((error as NodeJS.ErrnoException).code ?? '')) publishExecutionStopped();+ resolve({ code: null, signal: null, spawnErr: error });+ });+ child.once('exit', (code, signal) => { directExited = true; resolve({ code, signal }); });+ });+ const processGroups = new Set<number>(child.pid ? [child.pid] : []);+ const observeTiniChildGroup = (): void => {+ if (opts.tiniPath && child.pid) observeTiniChildProcessGroups(child.pid, processGroups);+ };+ const groupObserver = opts.tiniPath ? setInterval(() => {+ observeTiniChildGroup();+ if (processGroups.size > 1 && groupObserver != null) clearInterval(groupObserver);+ }, 25) : null;+ groupObserver?.unref();+ let finishTermination!: () => void;+ const terminationDone = new Promise<void>((resolve) => { finishTermination = resolve; });+ let cleanupSnapshot: ChildCleanupSnapshot | undefined;+ let signallingFailed = false;let termed = false;+ let terminationSettled = false;+ let graceExpired = false;+ let cleanupPoll: ReturnType<typeof setTimeout> | null = null;+ const settleTermination = (executionStopped: boolean): void => {+ if (terminationSettled) return;+ terminationSettled = true;+ if (killTimer != null) clearTimeout(killTimer);+ if (cleanupPoll != null) clearTimeout(cleanupPoll);+ if (executionStopped) publishExecutionStopped();+ else {+ console.error(`[isolation] job ${opts.jobId} (${opts.jobName}): execution stop is unconfirmed ` ++ `(pid=${child.pid ?? 'unknown'}, platform=${process.platform}); lease expiry and duplicate-side-effect risk remain.`);+ }+ finishTermination();+ };+ const killGroups = (): void => {+ try { for (const group of processGroups) signalGroup(group, 'SIGKILL'); }+ catch { signallingFailed = true; }+ };+ const pollCleanup = (delayMs: number): void => {+ cleanupPoll = setTimeout(() => {+ cleanupPoll = null;+ if (terminationSettled || graceExpired) return;+ if (cleanupSnapshot && confirmChildCleanup(cleanupSnapshot)) settleTermination(true);+ else pollCleanup(Math.min(delayMs * 2, 500));+ }, delayMs);+ };const terminate = (): void => {if (termed) return;termed = true;+ observeTiniChildGroup();+ if (groupObserver != null) clearInterval(groupObserver);if (child.pid != null) {- killProcessGroup(child.pid, 'SIGTERM');- killTimer = setTimeout(() => {- // Loud on failure (red-team finding): the /bin/kill fallback is the- // NORMAL delivery path in Bun-compiled binaries, and a container- // without /bin/kill (distroless) would otherwise silently void the- // SIGKILL guarantee while the child runs to completion and the job- // gets requeued elsewhere (duplicate side effects).- if (child.pid != null && child.exitCode == null && child.signalCode == null) {- const delivered = killProcessGroup(child.pid, 'SIGKILL');- if (!delivered) {- console.error(- `[isolation] job ${opts.jobId} (${opts.jobName}): group SIGKILL was NOT delivered ` +- `to pid ${child.pid} (platform=${process.platform}; is /bin/kill present?). ` +- `The child may still be running — the SIGKILL guarantee is degraded on this host.`,- );+ cleanupSnapshot = captureChildCleanup(child.pid, processGroups);+ if (opts.tiniPath && processGroups.size < 2) cleanupSnapshot.supported = false;+ for (const group of processGroups) {+ const delivered = signalGroup(group, 'SIGTERM');+ if (!delivered && cleanupSnapshot.observed.some(entry => entry.group === group && entry.state !== 'Z' && entry.state !== 'X')) signallingFailed = true;+ }+ void directExit.then(() => {+ if (!directExited || terminationSettled || graceExpired) return;+ if (!signallingFailed && cleanupSnapshot?.supported) {+ pollCleanup(25);+ return;+ }+ killGroups();+ settleTermination(false);+ });+ killTimer = setTimeout(async () => {+ graceExpired = true;+ if (cleanupPoll != null) clearTimeout(cleanupPoll);+ let executionStopped = false;+ try {+ killGroups();+ await new Promise<void>(resolve => {+ const timer = setTimeout(resolve, 250);+ void directExit.then(() => { clearTimeout(timer); resolve(); });+ });+ if (directExited && !signallingFailed && cleanupSnapshot?.supported) {+ await new Promise(resolve => setTimeout(resolve, 10));+ executionStopped = confirmChildCleanup(cleanupSnapshot);}+ } catch {+ signallingFailed = true;+ } finally {+ settleTermination(executionStopped);}}, graceMs);- unrefTimer(killTimer);+ } else {+ finishTermination();}};const onAbort = (): void => terminate();@@ -217,20 +340,27 @@ export async function runJobInChild(opts: RunJobInChildOpts): Promise<unknown> {);try {- const exit = await new Promise<ChildExit>((resolve) => {- child.once('error', (e) => resolve({ code: null, signal: null, spawnErr: e }));- child.once('exit', (code, signal) => resolve({ code, signal }));- });+ const exit = await Promise.race([directExit, terminationDone.then(() => ({ code: child.exitCode, signal: child.signalCode }))]);- if (exit.spawnErr && child.pid == null) {+ if (termed) await terminationDone;+ if (!termed && directExited && child.pid != null) {+ observeTiniChildGroup();+ const snapshot = captureChildCleanup(child.pid, processGroups);+ naturalCleanupConfirmed = (!opts.tiniPath || processGroups.size > 1) && confirmChildCleanup(snapshot);+ }++ if ('spawnErr' in exit && exit.spawnErr && child.pid == null) {+ if (['ENOENT', 'EACCES'].includes((exit.spawnErr as NodeJS.ErrnoException).code ?? '')) {+ throw childConfigurationError('child_executable_invalid');+ }throw new ChildSpawnInfraError(- `job child spawn failed (${inv.cmd}): ${exit.spawnErr.message}`,+ 'Job child could not be spawned.',);}console.log(`[isolation] job ${opts.jobId} (${opts.jobName}) child pid ${child.pid ?? '?'} ` +- `exited code=${exit.code ?? 'null'} signal=${exit.signal ?? 'null'}`,+ `settled code=${exit.code ?? 'null'} signal=${exit.signal ?? 'null'}`,);const abortReason = opts.abortSignal.aborted@@ -252,6 +382,17 @@ export async function runJobInChild(opts: RunJobInChildOpts): Promise<unknown> {// event loop that runs lock-renewal ticks (performance review).outcome = await decodeChildOutcomeFileAsync(resultPath);} catch (decodeErr) {+ if (exit.code === 126 || exit.code === 127) {+ try { validateChildExecutable(executable, base); }+ catch (error) {+ if (isLocalConfigurationError(error)) {+ opts.onConfigurationError?.(error);+ terminate();+ await terminationDone;+ }+ throw error;+ }+ }// No usable outcome. Classify by WHY the child died.if (decodeErr instanceof UnrecoverableError) throw decodeErr; // oversize cap — dead on attempt 1if (isShutdownClass) {@@ -288,6 +429,13 @@ export async function runJobInChild(opts: RunJobInChildOpts): Promise<unknown> {}if (outcome.outcome === 'success') return outcome.result;+ const handlerError = reconstructHandlerError(outcome);+ if (isLocalConfigurationError(handlerError)) {+ opts.onConfigurationError?.(handlerError);+ terminate();+ await terminationDone;+ throw handlerError;+ }// A handler-error outcome DURING worker shutdown is presumed// shutdown-induced (cooperative handlers that honor shutdownSignal bail// and report an error): release with no attempt burned rather than@@ -296,12 +444,15 @@ export async function runJobInChild(opts: RunJobInChildOpts): Promise<unknown> {// coincided with a deploy gets one free retry — bounded and benign.if (isShutdownClass) {throw new ChildWorkerShutdownError(- `job child reported an error during worker shutdown (${outcome.message}) — released, not burned`,+ 'Job child reported an error during worker shutdown; execution stop is unconfirmed, so lease expiry remains the fallback.',);}- throw reconstructHandlerError(outcome);+ throw handlerError;} finally {+ if (termed) await terminationDone;+ if (naturalCleanupConfirmed) publishExecutionStopped();if (killTimer != null) clearTimeout(killTimer);+ if (groupObserver != null) clearInterval(groupObserver);opts.abortSignal.removeEventListener('abort', onAbort);opts.shutdownSignal.removeEventListener('abort', onShutdown);rmSync(dir, { recursive: true, force: true });diff --git a/src/core/minions/child-readiness.ts b/src/core/minions/child-readiness.tsnew file mode 100644index 0000000000..079842eeb7--- /dev/null+++ b/src/core/minions/child-readiness.ts@@ -0,0 +1,169 @@+import { spawn } from 'node:child_process';+import type { BrainEngine } from '../engine.ts';+import { VERSION } from '../../version.ts';+import { isLocalConfigurationError } from './configuration-error.ts';+import {+ childConfigurationError, isChildConfigurationReason, killProcessGroup,+ observeTiniChildProcessGroups,+ validateChildExecutable,+ type ChildCliInvocation,+} from './job-isolation.ts';+import { buildSpawnInvocation } from './spawn-helpers.ts';+import { WORKER_EXIT_CONFIGURATION } from './worker-exit-codes.ts';++export const CHILD_READINESS_PROTOCOL_VERSION = 1;+export const CHILD_READINESS_TIMEOUT_MS = 20_000;+export const CHILD_READINESS_MAX_BYTES = 64 * 1024;+export const CHILD_READINESS_FEATURES = ['local-configuration-outcome-v1', 'postgres-cancellation-v1'] as const;++export interface ChildReadinessOptions {+ invocation: ChildCliInvocation;+ tiniPath: string;+ env?: Record<string, string | undefined>;+ timeoutMs?: number;+ signal?: AbortSignal;+}++export function parseChildReadiness(raw: string): { version: string; versionSkew: boolean } {+ let response: unknown;+ try { response = JSON.parse(raw); } catch {+ throw childConfigurationError('child_protocol_incompatible');+ }+ if (!response || typeof response !== 'object') throw childConfigurationError('child_protocol_incompatible');+ const r = response as Record<string, unknown>;+ if (r.protocolVersion !== CHILD_READINESS_PROTOCOL_VERSION ||+ typeof r.version !== 'string' || !/^\d+(?:\.\d+){2,3}$/.test(r.version) || r.version.length > 80 ||+ !Array.isArray(r.features) || !r.features.every((feature) => typeof feature === 'string') ||+ !CHILD_READINESS_FEATURES.every((feature) => (r.features as unknown[]).includes(feature))) {+ throw childConfigurationError('child_protocol_incompatible');+ }+ if (r.status === 'configuration_error' && isChildConfigurationReason(r.reasonCode)) {+ throw childConfigurationError(r.reasonCode);+ }+ if (r.status === 'transient_error') throw new Error('Selected job child readiness failed transiently; no jobs were admitted.');+ if (r.status !== 'ready') throw childConfigurationError('child_protocol_incompatible');+ return { version: r.version, versionSkew: r.version !== VERSION };+}++export async function checkChildReadiness(options: ChildReadinessOptions): Promise<{ version: string; versionSkew: boolean }> {+ const timeoutMs = options.timeoutMs ?? CHILD_READINESS_TIMEOUT_MS;+ if (!Number.isFinite(timeoutMs) || timeoutMs < 1 || timeoutMs > 120_000) throw new Error('Invalid child readiness deadline.');+ if (options.signal?.aborted) throw new Error('Selected job child readiness was interrupted.');+ const executable = validateChildExecutable(options.invocation.cmd, options.env ?? process.env);+ const invocation = buildSpawnInvocation(options.tiniPath, executable, [+ ...options.invocation.argsPrefix, 'jobs', 'child-readiness', '--json',+ ]);+ return new Promise((resolve, reject) => {+ let settled = false;+ let bytes = 0;+ const chunks: Buffer[] = [];+ let timer: ReturnType<typeof setTimeout> | undefined;+ let stopTimer: ReturnType<typeof setTimeout> | undefined;+ let pendingFailure: Error | undefined;+ let groupObserver: ReturnType<typeof setInterval> | undefined;+ const processGroups = new Set<number>();+ let child: ReturnType<typeof spawn>;+ const finish = (error?: unknown, result?: { version: string; versionSkew: boolean }): void => {+ if (settled) return;+ settled = true;+ if (timer) clearTimeout(timer);+ if (stopTimer) clearTimeout(stopTimer);+ if (groupObserver) clearInterval(groupObserver);+ options.signal?.removeEventListener('abort', interrupt);+ if (error) reject(error);+ else resolve(result!);+ };+ const stop = (forceWrapper = false): void => {+ if (child?.pid) {+ if (options.tiniPath) observeTiniChildProcessGroups(child.pid, processGroups);+ for (const group of processGroups) killProcessGroup(group, 'SIGKILL');+ if (options.tiniPath && processGroups.size > 0 && !forceWrapper) return;+ killProcessGroup(child.pid, 'SIGKILL');+ }+ try { child?.kill('SIGKILL'); } catch {}+ };+ const interrupt = (): void => {+ pendingFailure = new Error('Selected job child readiness was interrupted; no jobs were admitted.');+ stop();+ };+ const spawnError = (error: unknown): void => {+ const code = (error as NodeJS.ErrnoException)?.code;+ finish(code === 'ENOENT' || code === 'EACCES'+ ? childConfigurationError('child_executable_invalid')+ : new Error('Selected job child readiness transport failed; no jobs were admitted.'));+ };+ try {+ child = spawn(invocation.cmd, invocation.args, {+ env: options.env ?? process.env, detached: true, stdio: ['ignore', 'pipe', 'pipe'],+ });+ } catch (error) { spawnError(error); return; }+ if (options.tiniPath) groupObserver = setInterval(() => {+ if (child.pid) observeTiniChildProcessGroups(child.pid, processGroups);+ if (processGroups.size > 0 && groupObserver) clearInterval(groupObserver);+ }, 25);+ const capture = (chunk: Buffer, stdout: boolean): void => {+ if (settled || pendingFailure) return;+ bytes += chunk.length;+ if (bytes > CHILD_READINESS_MAX_BYTES) {+ pendingFailure = new Error('Selected job child readiness exceeded its combined output limit; the unfinished handshake is transient.');+ stop();+ return;+ }+ if (stdout) chunks.push(chunk);+ };+ child.stdout!.on('data', (chunk: Buffer) => capture(chunk, true));+ child.stderr!.on('data', (chunk: Buffer) => capture(chunk, false));+ child.once('error', spawnError);+ child.once('close', (code, signal) => {+ if (settled) return;+ if (pendingFailure) { finish(pendingFailure); return; }+ if (signal || code === null || (code >= 128 && code <= 192)) {+ finish(new Error('Selected job child readiness ended before completion.'));+ return;+ }+ try {+ if (code === 126 || code === 127) validateChildExecutable(executable, options.env ?? process.env);+ const result = parseChildReadiness(Buffer.concat(chunks).toString('utf8'));+ if (code !== 0) { finish(new Error('Selected job child readiness did not complete successfully.')); return; }+ finish(undefined, result);+ } catch (error) { finish(error); }+ });+ options.signal?.addEventListener('abort', interrupt, { once: true });+ stopTimer = setTimeout(() => {+ pendingFailure ??= new Error('Selected job child readiness timed out; no jobs were admitted.');+ stop();+ }, Math.max(1, timeoutMs - Math.min(250, timeoutMs / 10)));+ timer = setTimeout(() => {+ stop(true);+ child.stdout?.destroy();+ child.stderr?.destroy();+ finish(new Error('Selected job child readiness timed out with subprocess cleanup unconfirmed; no jobs were admitted.'));+ }, timeoutMs);+ if (options.signal?.aborted) interrupt();+ });+}++export function writeChildReadinessFailure(error: unknown): number {+ const permanent = isLocalConfigurationError(error);+ process.stdout.write(JSON.stringify({+ protocolVersion: CHILD_READINESS_PROTOCOL_VERSION, version: VERSION,+ features: CHILD_READINESS_FEATURES,+ status: permanent ? 'configuration_error' : 'transient_error',+ ...(permanent ? { reasonCode: error.reasonCode } : {}),+ }) + '\n');+ return permanent ? WORKER_EXIT_CONFIGURATION : 1;+}++export async function runChildReadinessEntry(+ engine: BrainEngine,+ check: (engine: BrainEngine) => Promise<void>,+): Promise<number> {+ try {+ await check(engine);+ process.stdout.write(JSON.stringify({+ protocolVersion: CHILD_READINESS_PROTOCOL_VERSION, version: VERSION,+ features: CHILD_READINESS_FEATURES, status: 'ready',+ }) + '\n');+ return 0;+ } catch (error) { return writeChildReadinessFailure(error); }+}diff --git a/src/core/minions/child-worker-supervisor.ts b/src/core/minions/child-worker-supervisor.tsindex ed4c5d0991..9452817516 100644--- a/src/core/minions/child-worker-supervisor.ts+++ b/src/core/minions/child-worker-supervisor.ts@@ -37,13 +37,20 @@*/import { spawn, type ChildProcess } from 'child_process';+import { existsSync, mkdtempSync, realpathSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { basename, isAbsolute, join, resolve as resolvePath } from 'node:path';import { buildSpawnInvocation, detectTini } from './spawn-helpers.ts';import { classifyWorkerExit } from './exit-classification.ts';import { calculateBackoffMs } from './supervisor.ts';-import { WORKER_EXIT_RSS_WATCHDOG } from './worker-exit-codes.ts';+import { WORKER_EXIT_CONFIGURATION, WORKER_EXIT_RSS_WATCHDOG } from './worker-exit-codes.ts';+import type { OwnerProcessingState, OwnerProcessingStatus } from './processing-state.ts';+import { killProcessGroup, observeTiniChildProcessGroups } from './job-isolation.ts';+import { CWD_ENV_QUARANTINED_MARKER } from '../cli-preflight.ts';export type ChildSupervisorEvent =| { kind: 'worker_spawned'; pid: number; tini: boolean }+ | { kind: 'worker_startup_timeout'; timeoutMs: number }| { kind: 'worker_spawn_failed'; error: string; phase: 'sync' | 'async'; errnoCode?: string }| {kind: 'worker_exited';@@ -70,6 +77,10 @@ export type ChildSupervisorEvent =};export interface ChildWorkerSupervisorOpts {+ processingState?: OwnerProcessingState;+ onConfigurationBlocked?: (status: OwnerProcessingStatus | null) => void;+ _startupReadyTimeoutMs?: number;+ _startupKillGraceMs?: number;/** Path to the gbrain CLI binary. */cliPath: string;/** Worker argv after cliPath (e.g. ['jobs', 'work', '--max-rss', '2048']). */@@ -165,6 +176,7 @@ export interface ChildWorkerSupervisorOpts {* consecutive crashes (each within the stable-run window) before we conclude* it's a genuine code bug and stop. A transient outage recovers long before. */export const HARD_STOP_CRASH_MULTIPLIER = 10;+export const WORKER_STARTUP_READY_TIMEOUT_MS = 120_000;const DEFAULTS = {stableRunResetMs: 5 * 60 * 1000,@@ -194,6 +206,8 @@ export class ChildWorkerSupervisor {/** issue #1801: carried from the exit handler to applyBackoff so a wedge* self-heal respawns immediately (ms:0) instead of paying crash backoff. */private _lastWasIntentionalRestart = false;+ private _configurationBlocked = false;+ private wakeBackoff: (() => void) | null = null;constructor(opts: ChildWorkerSupervisorOpts) {this.opts = opts;@@ -210,6 +224,18 @@ export class ChildWorkerSupervisor {get crashCount(): number {return this._crashCount;}+ get configurationBlocked(): boolean {+ if (this.opts.processingState?.blocked) this.markConfigurationBlocked();+ return this._configurationBlocked;+ }++ private markConfigurationBlocked(): void {+ if (this._configurationBlocked) return;+ this._configurationBlocked = true;+ this.wakeBackoff?.();+ this.opts.processingState?.block();+ this.opts.onConfigurationBlocked?.(this.opts.processingState?.snapshot ?? null);+ }/** Whether tini was detected at construction. Used by tests + worker_spawned event payload. */get isTiniDetected(): boolean {return this.tiniPath !== '';@@ -297,6 +323,7 @@ export class ChildWorkerSupervisor {* loop budget. `run()` respawns a fresh worker (and a fresh DB pool) on exit.*/async restartCurrentChild(graceMs: number): Promise<void> {+ if (this.configurationBlocked) return;const child = this._child;if (!child) return;this._intentionalRestart = true;@@ -335,68 +362,108 @@ export class ChildWorkerSupervisor {* for a genuinely unrecoverable hot crash-loop.*/async run(): Promise<void> {- const hardStop = this.opts.hardStopMaxCrashes ??- this.opts.maxCrashes * HARD_STOP_CRASH_MULTIPLIER;- let degradedAnnounced = false;- while (!this.opts.isStopping()) {- await this.opts.beforeSpawn?.();- if (this.opts.isStopping()) return;- await this.spawnOnce();-- if (this.opts.isStopping()) return;-- // Hard ceiling: permanent give-up (the runaway backstop). hardStop <= 0- // disables it entirely (retry-forever-with-backoff for deployments that- // would rather never auto-stop a recoverable supervisor).- if (hardStop > 0 && this._crashCount >= hardStop) {- this.opts.onMaxCrashesExceeded(this._crashCount, hardStop);- return;- }+ const statusTimer = this.opts.processingState+ ? setInterval(() => { void this.configurationBlocked; }, 100)+ : null;+ try {+ const hardStop = this.opts.hardStopMaxCrashes ??+ this.opts.maxCrashes * HARD_STOP_CRASH_MULTIPLIER;+ let degradedAnnounced = false;+ while (!this.opts.isStopping() && !this.configurationBlocked) {+ try {+ await this.opts.beforeSpawn?.();+ } catch (error) {+ if (this.configurationBlocked) return;+ throw error;+ }+ if (this.opts.isStopping() || this.configurationBlocked) return;+ await this.spawnOnce();- // Soft budget crossed → degraded mode. Announce once per degradation- // episode; re-arm after a stable-run reset drops us back under budget.- if (this._crashCount >= this.opts.maxCrashes) {- if (!degradedAnnounced) {- degradedAnnounced = true;- this.opts.onEvent({- kind: 'health_warn',- reason: 'crash_budget_degraded',- count: this._crashCount,- max: this.opts.maxCrashes,- });+ if (this.configurationBlocked || this.opts.isStopping()) return;++ // Hard ceiling: permanent give-up (the runaway backstop). hardStop <= 0+ // disables it entirely (retry-forever-with-backoff for deployments that+ // would rather never auto-stop a recoverable supervisor).+ if (hardStop > 0 && this._crashCount >= hardStop) {+ this.opts.processingState?.waiting('stopped');+ this.opts.onMaxCrashesExceeded(this._crashCount, hardStop);+ return;+ }++ // Soft budget crossed → degraded mode. Announce once per degradation+ // episode; re-arm after a stable-run reset drops us back under budget.+ if (this._crashCount >= this.opts.maxCrashes) {+ if (!degradedAnnounced) {+ degradedAnnounced = true;+ this.opts.onEvent({+ kind: 'health_warn',+ reason: 'crash_budget_degraded',+ count: this._crashCount,+ max: this.opts.maxCrashes,+ });+ }+ } else {+ degradedAnnounced = false;}- } else {- degradedAnnounced = false;- }- await this.applyBackoff();+ await this.applyBackoff();+ }+ } finally {+ if (statusTimer) clearInterval(statusTimer);}}/** Single spawn lifecycle: spawn -> await exit -> classify. */private spawnOnce(): Promise<void> {return new Promise<void>((resolve) => {- if (this.opts.isStopping()) {+ if (this.opts.isStopping() || this.configurationBlocked) {resolve();return;}- const env = this.opts.env ?? { ...process.env };+ const env: NodeJS.ProcessEnv = { ...(this.opts.env ?? process.env) };this._lastStartTime = this.now();+ const originalCwd = process.cwd();+ const args = [...this.opts.args];+ if (this.opts.processingState && ['bun', 'bun.exe', 'node', 'node.exe'].includes(basename(this.opts.cliPath)) &&+ args[0] && !args[0].startsWith('-') && !isAbsolute(args[0]) && existsSync(resolvePath(originalCwd, args[0]))) {+ args[0] = resolvePath(originalCwd, args[0]);+ }const { cmd: spawnCmd, args: spawnArgs } = buildSpawnInvocation(this.tiniPath,- this.opts.cliPath,- this.opts.args,+ this.opts.processingState && !isAbsolute(this.opts.cliPath) && /[/\\]/.test(this.opts.cliPath)+ ? resolvePath(this.opts.cliPath) : this.opts.cliPath,+ args,);let child: ChildProcess;+ let neutralCwd: string | undefined;+ let startupTimer: ReturnType<typeof setInterval> | undefined;+ let killTimer: ReturnType<typeof setTimeout> | undefined;+ let startupTimedOut = false;+ const processGroups = new Set<number>();+ const cleanup = () => {+ if (startupTimer) clearInterval(startupTimer);+ if (killTimer) clearTimeout(killTimer);+ if (neutralCwd) {+ try { rmSync(neutralCwd, { recursive: true, force: true }); } catch {}+ }+ };try {+ if (this.opts.processingState) {+ Object.assign(env, this.opts.processingState.prepareChild());+ neutralCwd = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-worker-')));+ env[CWD_ENV_QUARANTINED_MARKER] = JSON.stringify({ cwd: originalCwd, neutral: neutralCwd });+ }child = spawn(spawnCmd, spawnArgs, {stdio: 'inherit',env,+ ...(neutralCwd ? { cwd: neutralCwd } : {}),});} catch (err: unknown) {+ cleanup();+ this.opts.processingState?.workerExited();// Synchronous spawn error (e.g. invalid cliPath shape). Count as a crash.this.opts.onEvent({kind: 'worker_spawn_failed',@@ -411,6 +478,31 @@ export class ChildWorkerSupervisor {this._child = child;+ if (this.opts.processingState) {+ const deadlineMs = this.opts._startupReadyTimeoutMs ?? WORKER_STARTUP_READY_TIMEOUT_MS;+ const deadline = this.now() + deadlineMs;+ const signalStartupChild = (signal: 'SIGTERM' | 'SIGKILL') => {+ if (child.pid && this.tiniPath) observeTiniChildProcessGroups(child.pid, processGroups);+ for (const group of processGroups) killProcessGroup(group, signal);+ if (!this.tiniPath || processGroups.size === 0 || signal === 'SIGTERM') {+ try { child.kill(signal); } catch {}+ }+ };+ startupTimer = setInterval(() => {+ if (this.configurationBlocked || this.opts.isStopping() || this.opts.processingState!.snapshot.processing_ready) {+ clearInterval(startupTimer);+ return;+ }+ if (this.now() < deadline) return;+ clearInterval(startupTimer);+ if (!this.opts.processingState!.waiting('startup_timeout')) return;+ startupTimedOut = true;+ this.opts.onEvent({ kind: 'worker_startup_timeout', timeoutMs: deadlineMs });+ signalStartupChild('SIGTERM');+ killTimer = setTimeout(() => signalStartupChild('SIGKILL'), this.opts._startupKillGraceMs ?? 35_000);+ }, Math.min(100, Math.max(1, deadlineMs)));+ }+this.opts.onEvent({kind: 'worker_spawned',pid: child.pid ?? -1,@@ -441,6 +533,7 @@ export class ChildWorkerSupervisor {const settleSpawnFailure = () => {if (settled) return;settled = true;+ cleanup();this._child = null;this._intentionalRestart = false;@@ -490,8 +583,24 @@ export class ChildWorkerSupervisor {child.on('exit', (code, signal) => {if (settled) return;settled = true;+ cleanup();this._child = null;+ if (code === WORKER_EXIT_CONFIGURATION) {+ this.opts.processingState?.workerExited();+ this._lastExitCode = code;+ this.markConfigurationBlocked();+ this.opts.onEvent({ kind: 'worker_exited', code, signal: signal ?? null,+ runDurationMs: this.now() - this._lastStartTime, likelyCause: 'configuration_blocked', crashCount: this._crashCount });+ resolve();+ return;+ }+ this.opts.processingState?.workerExited();+ if (this.configurationBlocked) {+ resolve();+ return;+ }+if (this.opts.isStopping()) {resolve();return;@@ -505,8 +614,11 @@ export class ChildWorkerSupervisor {// tracking and prune entries outside the sliding window. Routes// through the shared `classifyWorkerExit` helper so doctor.ts and// jobs.ts (audit-log consumers) read the same rule.- this._lastExitCode = code;- if (this._intentionalRestart) {+ this._lastExitCode = startupTimedOut ? 1 : code;+ if (startupTimedOut) {+ this._intentionalRestart = false;+ this._crashCount++;+ } else if (this._intentionalRestart) {// issue #1801: deliberate wedge self-heal (restartCurrentChild). Leave// crashCount UNTOUCHED — like the RSS watchdog — so a recurring wedge// never trips max_crashes and kills the daemon. A SIGTERM exit has@@ -548,7 +660,9 @@ export class ChildWorkerSupervisor {// Likely-cause heuristic, kept verbatim from MinionSupervisor.let likelyCause: string;- if (this._lastWasIntentionalRestart) {+ if (startupTimedOut) {+ likelyCause = 'startup_readiness_timeout';+ } else if (this._lastWasIntentionalRestart) {// issue #1801: a deliberate wedge restart. Label it as such even// though the kill signal was SIGTERM/SIGKILL, so the audit summary// (supervisor-audit.ts CLEAN_EXIT_CAUSES) counts it as a self-heal,@@ -700,7 +814,17 @@ export class ChildWorkerSupervisor {}private sleep(ms: number): Promise<void> {- return new Promise<void>((resolve) => setTimeout(resolve, ms));+ if (this.configurationBlocked) return Promise.resolve();+ this.opts.processingState?.waiting('retry_backoff', this.now() + ms);+ return new Promise<void>((resolve) => {+ const finish = () => {+ clearTimeout(timer);+ this.wakeBackoff = null;+ resolve();+ };+ const timer = setTimeout(finish, ms);+ this.wakeBackoff = finish;+ });}private now(): number {diff --git a/src/core/minions/configuration-error.ts b/src/core/minions/configuration-error.tsnew file mode 100644index 0000000000..efe30ce402--- /dev/null+++ b/src/core/minions/configuration-error.ts@@ -0,0 +1,18 @@+export type LocalConfigurationReasonCode =+ | 'postgres_cancellation_unavailable'+ | 'child_executable_invalid'+ | 'child_protocol_incompatible';++export class LocalConfigurationError extends Error {+ readonly reasonCode: LocalConfigurationReasonCode;++ constructor(reasonCode: LocalConfigurationReasonCode, message: string) {+ super(message);+ this.name = 'LocalConfigurationError';+ this.reasonCode = reasonCode;+ }+}++export function isLocalConfigurationError(error: unknown): error is LocalConfigurationError {+ return error instanceof LocalConfigurationError;+}diff --git a/src/core/minions/db-probe.ts b/src/core/minions/db-probe.tsindex ac9faf585f..1f3e08a25a 100644--- a/src/core/minions/db-probe.ts+++ b/src/core/minions/db-probe.ts@@ -28,8 +28,11 @@*/import type { PoolGaugeSnapshot } from '../pool-gauge.ts';+import type { BrainEngine } from '../engine.ts';+import { redactConnectionInfo } from '../audit/redact-connection-info.ts';+import { isLocalConfigurationError, type LocalConfigurationError } from './configuration-error.ts';-export type ProbeVerdict = 'pool_starved' | 'server_unreachable' | 'unknown';+export type ProbeVerdict = 'pool_starved' | 'server_unreachable' | 'unknown' | 'client_misconfigured';/** Default budget for the direct-lane disambiguation probe. */export const DIRECT_PROBE_TIMEOUT_MS = 3_000;@@ -61,7 +64,8 @@ export interface DbProbeDeps {export type DbProbeResult =| { ok: true }- | { ok: false; verdict: ProbeVerdict; detail: string };+ | { ok: false; verdict: Exclude<ProbeVerdict, 'client_misconfigured'>; detail: string }+ | { ok: false; verdict: 'client_misconfigured'; detail: string; configurationError: LocalConfigurationError };/*** Narrow, shared view of the engine's ConnectionManager for routing-aware@@ -126,13 +130,43 @@ function renderDiagnostics(getDiagnostics?: () => PoolDiagnostics | null): strin}export async function runDbProbe(deps: DbProbeDeps): Promise<DbProbeResult> {- let readErrMsg: string;+ return probeLanes(deps, false);+}++export async function runDbReadinessProbe(deps: DbProbeDeps): Promise<DbProbeResult> {+ return probeLanes(deps, true);+}++export async function assertWorkerDbReadiness(engine: BrainEngine): Promise<void> {+ if (engine.kind !== 'postgres') return;+ const result = await runDbReadinessProbe({+ probeRead: async signal => { await engine.executeRaw('SELECT 1', [], { signal }); },+ probeDirect: getConnectionRouting(engine)?.isDualPoolActive?.()+ ? async signal => { await engine.executeRawDirect('SELECT 1', [], { signal }); }+ : undefined,+ timeoutMs: 10_000,+ directTimeoutMs: DIRECT_PROBE_TIMEOUT_MS,+ });+ if (result.ok) return;+ if (result.verdict === 'client_misconfigured') throw result.configurationError;+ throw new Error(`Database readiness ${result.verdict}: ${result.detail}`);+}++async function probeLanes(deps: DbProbeDeps, requireDirect: boolean): Promise<DbProbeResult> {+ let readFailed = false;+ let readError: unknown;try {await withDeadline(deps.probeRead, deps.timeoutMs, 'probe');- return { ok: true };+ if (!requireDirect || !deps.probeDirect) return { ok: true };} catch (e) {- readErrMsg = e instanceof Error ? e.message : String(e);+ readFailed = true;+ readError = e;+ }++ if (isLocalConfigurationError(readError)) {+ return { ok: false, verdict: 'client_misconfigured', detail: readError.message, configurationError: readError };}+ const readErrMsg = redactConnectionInfo(readError instanceof Error ? readError.message : String(readError));if (!deps.probeDirect) {return {@@ -145,6 +179,7 @@ export async function runDbProbe(deps: DbProbeDeps): Promise<DbProbeResult> {const t0 = Date.now();try {await withDeadline(deps.probeDirect, deps.directTimeoutMs, 'direct probe');+ if (!readFailed) return { ok: true };return {ok: false,verdict: 'pool_starved',@@ -155,7 +190,17 @@ export async function runDbProbe(deps: DbProbeDeps): Promise<DbProbeResult> {renderDiagnostics(deps.getDiagnostics),};} catch (e) {- const directErrMsg = e instanceof Error ? e.message : String(e);+ if (isLocalConfigurationError(e)) {+ return { ok: false, verdict: 'client_misconfigured', detail: e.message, configurationError: e };+ }+ const directErrMsg = redactConnectionInfo(e instanceof Error ? e.message : String(e));+ if (!readFailed) {+ return {+ ok: false,+ verdict: 'unknown',+ detail: `read probe succeeded; required direct probe failed: ${directErrMsg} — direct lane is not ready`,+ };+ }return {ok: false,verdict: 'server_unreachable',diff --git a/src/core/minions/handlers/supervisor-audit.ts b/src/core/minions/handlers/supervisor-audit.tsindex c117406885..fa089b11a7 100644--- a/src/core/minions/handlers/supervisor-audit.ts+++ b/src/core/minions/handlers/supervisor-audit.ts@@ -158,7 +158,7 @@ export function readRecentSupervisorEvents(* silently underreporting — denylist semantics close the bug class this* helper was added to fix.*/-const CLEAN_EXIT_CAUSES = new Set(['clean_exit', 'graceful_shutdown', 'wedge_restart']);+const CLEAN_EXIT_CAUSES = new Set(['clean_exit', 'graceful_shutdown', 'wedge_restart', 'configuration_blocked']);/*** Per-cause crash bucket shape returned by `summarizeCrashes()`. Bucket namesdiff --git a/src/core/minions/job-isolation.ts b/src/core/minions/job-isolation.tsindex 7e4194d8df..2f1219192b 100644--- a/src/core/minions/job-isolation.ts+++ b/src/core/minions/job-isolation.ts@@ -24,19 +24,22 @@* binary, so the group signal falls back to POSIX* /bin/kill when needed.*- * Handler-error semantics survive the boundary: the child encodes the two+ * Handler-error semantics survive the boundary: the child encodes the* error classes executeJob branches on (UnrecoverableError → 'dead',* RateLeaseUnavailableError → lease release, no attempt burned) and* `reconstructHandlerError` rebuilds real instances parent-side so the* existing `instanceof` branches work verbatim. Everything else degrades to* a generic Error → the normal delayed/dead backoff path, same as inline.+ * Versioned local-configuration outcomes preserve the typed permanent fault.*/-import { readFileSync, writeFileSync, renameSync, statSync } from 'node:fs';+import { accessSync, constants, readdirSync, readFileSync, writeFileSync, renameSync, statSync } from 'node:fs';import { readFile, stat } from 'node:fs/promises';import { spawnSync } from 'node:child_process';import { UnrecoverableError } from './types.ts';import { RateLeaseUnavailableError } from './handlers/subagent.ts';+import { LocalConfigurationError, isLocalConfigurationError } from './configuration-error.ts';+import { basename, delimiter, resolve } from 'node:path';/** Grace between group-SIGTERM and group-SIGKILL on abort. Deliberately* inside the worker's 30s force-evict window so the evict path stays a@@ -69,7 +72,25 @@ export const CHILD_ENV = {childPoolSize: 'GBRAIN_JOB_CHILD_POOL_SIZE',} as const;-export type ChildErrorKind = 'unrecoverable' | 'rate_lease' | 'generic';+export const CHILD_OUTCOME_PROTOCOL_VERSION = 1;+export const CHILD_CONFIGURATION_REASONS = [+ 'postgres_cancellation_unavailable', 'child_executable_invalid', 'child_protocol_incompatible',+] as const;++export function isChildConfigurationReason(value: unknown): value is typeof CHILD_CONFIGURATION_REASONS[number] {+ return CHILD_CONFIGURATION_REASONS.some((reason) => reason === value);+}++export function childConfigurationError(reason: typeof CHILD_CONFIGURATION_REASONS[number]): LocalConfigurationError {+ const messages = {+ postgres_cancellation_unavailable: 'The PostgreSQL driver lacks required cancellation support. Reinstall a known-good GBrain release or run bun install in the checkout to repair the shipped driver.',+ child_executable_invalid: 'The selected job child executable is missing or not executable. Fix GBRAIN_JOB_CHILD_CLI or repair the current GBrain executable path.',+ child_protocol_incompatible: 'The selected job child uses an incompatible readiness or outcome protocol. Reinstall the selected child with a compatible GBrain release.',+ };+ return new LocalConfigurationError(reason, `${messages[reason]} Verify worker and child readiness, then restart. See docs/guides/minions-fix.md#configuration-blocked.`);+}++export type ChildErrorKind = 'unrecoverable' | 'rate_lease' | 'generic' | 'local_configuration';export type ChildOutcome =| { outcome: 'success'; result: unknown }@@ -79,10 +100,20 @@ export type ChildOutcome =message: string;stack?: string;lease?: { key: string; active: number; max: number };+ protocolVersion?: number;+ reasonCode?: typeof CHILD_CONFIGURATION_REASONS[number];};/** Child-side: classify a handler throw into the wire shape. */export function encodeHandlerError(err: unknown): ChildOutcome {+ if (isLocalConfigurationError(err)) {+ return {+ outcome: 'error', errorKind: 'local_configuration',+ protocolVersion: CHILD_OUTCOME_PROTOCOL_VERSION,+ reasonCode: err.reasonCode,+ message: childConfigurationError(err.reasonCode).message,+ };+ }if (err instanceof RateLeaseUnavailableError) {return {outcome: 'error',@@ -111,6 +142,9 @@ export function encodeHandlerError(err: unknown): ChildOutcome {* file is same-user-written but a malformed kind must not crash the worker).*/export function reconstructHandlerError(o: Extract<ChildOutcome, { outcome: 'error' }>): Error {+ if (o.errorKind === 'local_configuration' && o.protocolVersion === CHILD_OUTCOME_PROTOCOL_VERSION && isChildConfigurationReason(o.reasonCode)) {+ return childConfigurationError(o.reasonCode);+ }if (o.errorKind === 'rate_lease' && o.lease) {return new RateLeaseUnavailableError(o.lease.key, o.lease.active, o.lease.max);}@@ -158,6 +192,9 @@ export function parseChildOutcome(raw: string, size: number, maxBytes = CHILD_OUif (o && o.outcome === 'success') return { outcome: 'success', result: (o as { result?: unknown }).result };if (o && o.outcome === 'error' && typeof (o as { message?: unknown }).message === 'string') {const kind = (o as { errorKind?: unknown }).errorKind;+ if (kind === 'local_configuration' && o.protocolVersion === CHILD_OUTCOME_PROTOCOL_VERSION && isChildConfigurationReason(o.reasonCode)) {+ return encodeHandlerError(childConfigurationError(o.reasonCode));+ }const rawLease = (o as { lease?: unknown }).lease as| { key?: unknown; active?: unknown; max?: unknown }| undefined;@@ -240,15 +277,99 @@ export interface ChildCliInvocation {argsPrefix: string[];}+export function validateChildExecutable(cmd: string, env: Record<string, string | undefined>): string {+ const candidates = cmd.includes('/') || (process.platform === 'win32' && cmd.includes('\\'))+ ? [resolve(cmd)]+ : (env.PATH ?? '/usr/bin:/bin').split(delimiter).map(directory => resolve(directory || '.', cmd));+ for (const candidate of candidates) {+ try {+ accessSync(candidate, constants.X_OK);+ if (statSync(candidate).isFile()) return candidate;+ } catch (error) {+ if (!['ENOENT', 'EACCES', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) {+ throw new Error('Selected job child executable accessibility could not be checked.');+ }+ }+ }+ throw childConfigurationError('child_executable_invalid');+}++interface ProcessSnapshotEntry {+ pid: number;+ parent: number;+ group: number;+ start: string;+ state: string;+}++export interface ChildCleanupSnapshot {+ groups: Set<number>;+ observed: ProcessSnapshotEntry[];+ supported: boolean;+}++function readProcessSnapshot(): ProcessSnapshotEntry[] | null {+ if (process.platform !== 'linux') return null;+ const deadline = performance.now() + 200;+ try {+ const names = readdirSync('/proc').filter(name => /^\d+$/.test(name));+ if (names.length > 8192) return null;+ const entries: ProcessSnapshotEntry[] = [];+ for (const name of names) {+ if (performance.now() > deadline) return null;+ try {+ const raw = readFileSync(`/proc/${name}/stat`, 'utf8');+ const fields = raw.slice(raw.lastIndexOf(')') + 2).split(' ');+ if (fields.length < 20) return null;+ entries.push({ pid: Number(name), parent: Number(fields[1]), group: Number(fields[2]), start: fields[19], state: fields[0] });+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT' && (error as NodeJS.ErrnoException).code !== 'ESRCH') return null;+ }+ }+ return entries.some(entry => entry.pid === process.pid) ? entries : null;+ } catch { return null; }+}++export function captureChildCleanup(pid: number, groups: Set<number>): ChildCleanupSnapshot {+ const entries = readProcessSnapshot();+ if (!entries) return { groups: new Set(groups), observed: [], supported: false };+ const children = new Map<number, number[]>();+ for (const entry of entries) {+ const siblings = children.get(entry.parent) ?? [];+ siblings.push(entry.pid);+ children.set(entry.parent, siblings);+ }+ const owned = new Set([pid, ...entries.filter(entry => groups.has(entry.group)).map(entry => entry.pid)]);+ const pending = [...owned];+ for (let index = 0; index < pending.length; index++) {+ for (const child of children.get(pending[index]) ?? []) {+ if (!owned.has(child)) { owned.add(child); pending.push(child); }+ }+ }+ const observed = entries.filter(entry => owned.has(entry.pid));+ return {+ groups: new Set(groups), observed,+ supported: groups.size > 0 && observed.every(entry => groups.has(entry.group)),+ };+}++export function confirmChildCleanup(snapshot: ChildCleanupSnapshot): boolean {+ if (!snapshot.supported) return false;+ const entries = readProcessSnapshot();+ if (!entries) return false;+ const observed = new Map(snapshot.observed.map(entry => [entry.pid, entry.start]));+ return !entries.some(entry => entry.state !== 'Z' && entry.state !== 'X' && (+ snapshot.groups.has(entry.group) || observed.get(entry.pid) === entry.start+ ));+}+/*** Resolve how to invoke the gbrain CLI for a child process. Pure — all* inputs injected:** 1. GBRAIN_JOB_CHILD_CLI env override (ops/test escape hatch)- * 2. resolveBinary() — the compiled-binary resolver- * (resolveGbrainCliPath; never returns a .ts path)- * 3. bun-dev fallback: running from `bun src/cli.ts` → invoke- * `<execPath> <argv1>` so dev and tests work without a compiled binary+ * 2. Current compiled executable or source CLI entrypoint+ * 3. resolveBinary() — PATH fallback when the current entrypoint is not a CLI** Returns null when nothing resolves — the caller must fail fast at worker* startup (one bad path must not dead-letter a queue job-by-job).@@ -263,26 +384,25 @@ export function resolveChildCliInvocation(if (override && override.trim() !== '') {return { cmd: override, argsPrefix: [] };}- try {- const bin = resolveBinary();- if (bin) return { cmd: bin, argsPrefix: [] };- } catch {- // fall through to the dev fallback+ if (execPath && !['bun', 'bun.exe', 'node', 'node.exe'].includes(basename(execPath))) {+ return { cmd: execPath, argsPrefix: [] };}if (argv1 && (argv1.endsWith('/cli.ts') || argv1.endsWith('\\cli.ts') || argv1 === 'cli.ts')) {return { cmd: execPath, argsPrefix: [argv1] };}+ try {+ const bin = resolveBinary();+ if (bin) return { cmd: bin, argsPrefix: [] };+ } catch {}return null;}/*** Signal an entire process GROUP.*- * Children are spawned `detached: true` (own group) so this reaches the- * handler grandchildren even under a tini wrapper — SIGKILL on the tini pid- * alone kills tini and ORPHANS the still-running handler (tini cannot- * forward SIGKILL; that failure mode would silently void issue #5's- * headline guarantee exactly in container deployments).+ * Children are spawned `detached: true`. Tini creates another group for its+ * child, so callers must also signal that observed group. Neither group+ * signalling nor subreaping contains descendants that create a new session.** Bun's process.kill() rejects negative pids (oven-sh/bun#15791), so on any* throw other than ESRCH we fall back to POSIX /bin/kill, which@@ -312,3 +432,17 @@ export function killProcessGroup(pid: number, signal: 'SIGTERM' | 'SIGKILL'): bo}}}++export function observeTiniChildProcessGroups(pid: number, groups: Set<number>): void {+ if (process.platform !== 'linux' || !Number.isInteger(pid) || pid <= 1) return;+ try {+ const children = readFileSync(`/proc/${pid}/task/${pid}/children`, 'utf8').trim().split(/\s+/);+ for (const value of children) {+ const childPid = Number(value);+ if (!Number.isInteger(childPid) || childPid <= 1) continue;+ const stat = readFileSync(`/proc/${childPid}/stat`, 'utf8');+ const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');+ if (Number(fields[1]) === pid && Number(fields[2]) === childPid) groups.add(childPid);+ }+ } catch {}+}diff --git a/src/core/minions/processing-state.ts b/src/core/minions/processing-state.tsnew file mode 100644index 0000000000..e50aa691fa--- /dev/null+++ b/src/core/minions/processing-state.ts@@ -0,0 +1,278 @@+import { createHash, randomUUID } from 'node:crypto';+import { mkdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { gbrainPath } from '../config.ts';+import { classifyAutopilotLockHolder, type AutopilotLockProbeDeps } from '../autopilot-lock.ts';+import { autopilotLockPath } from '../autopilot-paths.ts';+import { redactUrlsInText } from '../url-redact.ts';+import type { LocalConfigurationReasonCode } from './configuration-error.ts';++export type ProcessingOwnerKind = 'supervisor' | 'autopilot';+export type ProcessingState = 'starting' | 'ready' | 'configuration_blocked';+export type WorkerStartupStage = 'database_readiness' | 'child_readiness' | 'worker_startup';+export type ProcessingStage = WorkerStartupStage | 'startup_readiness' | 'ready' | 'startup_timeout' | 'retry_backoff' | 'configuration_blocked' | 'stopped';+export interface ProcessingRuntimeIdentity {+ executable: string;+ version: string;+ protocol_version?: number;+}+export interface WorkerProcessingUpdate {+ state: ProcessingState;+ stage?: WorkerStartupStage;+ reason_code?: LocalConfigurationReasonCode | null;+ worker_identity?: ProcessingRuntimeIdentity;+ child_identity?: ProcessingRuntimeIdentity;+}+export interface OwnerProcessingStatus {+ processing_ready: boolean;+ processing_state: ProcessingState;+ processing_stage: ProcessingStage;+ retry_at: string | null;+ reason_code: LocalConfigurationReasonCode | null;+ blocked_since: string | null;+ owner_pid: number;+ runtime_id: string;+ worker_pid: number | null;+ worker_identity: ProcessingRuntimeIdentity | null;+ child_identity: ProcessingRuntimeIdentity | null;+}++function startupStage(value: unknown): WorkerStartupStage | null {+ return value === 'database_readiness' || value === 'child_readiness' || value === 'worker_startup' ? value : null;+}++function processingStage(value: unknown): ProcessingStage {+ return startupStage(value) ?? (value === 'ready' || value === 'startup_timeout' || value === 'retry_backoff' || value === 'configuration_blocked' || value === 'stopped' ? value : 'startup_readiness');+}++function reasonCode(value: unknown): LocalConfigurationReasonCode | null {+ return value === 'postgres_cancellation_unavailable' || value === 'child_executable_invalid' || value === 'child_protocol_incompatible' ? value : null;+}++function identity(value: unknown): ProcessingRuntimeIdentity | null {+ if (!value || typeof value !== 'object') return null;+ const v = value as Record<string, unknown>;+ if (typeof v.executable !== 'string' || v.executable.length > 4096 || typeof v.version !== 'string' || !/^[\w.+-]{1,100}$/.test(v.version)) return null;+ return {+ executable: redactUrlsInText(v.executable).replace(/[\r\n\x00-\x1f]/g, ''),+ version: v.version,+ ...(Number.isSafeInteger(v.protocol_version) ? { protocol_version: v.protocol_version as number } : {}),+ };+}++function readJson(path: string): Record<string, unknown> | null {+ try {+ if (statSync(path).size > 16_384) return null;+ const value = JSON.parse(readFileSync(path, 'utf8'));+ return value && typeof value === 'object' && !Array.isArray(value) ? value : null;+ } catch { return null; }+}++function writeJson(path: string, value: unknown, createParent = true): void {+ const temp = `${path}.${randomUUID()}.tmp`;+ try {+ if (createParent) mkdirSync(dirname(path), { recursive: true, mode: 0o700 });+ writeFileSync(temp, JSON.stringify(value), { mode: 0o600 });+ renameSync(temp, path);+ } finally {+ try { unlinkSync(temp); } catch {}+ }+}++function ownerPath(kind: ProcessingOwnerKind, key: string): string {+ const hash = createHash('sha256').update(key).digest('hex').slice(0, 24);+ return join(gbrainPath(), 'runtime', `${kind}-${hash}.json`);+}++export function writeWorkerProcessingStatus(update: WorkerProcessingUpdate, env: NodeJS.ProcessEnv = process.env): boolean {+ const path = env.GBRAIN_WORKER_STATUS_PATH;+ const token = env.GBRAIN_WORKER_STATUS_TOKEN;+ if (!path || !token) return false;+ try {+ const envelopePath = join(dirname(path), 'owner.json');+ const envelope = readJson(envelopePath);+ const activeGeneration = () => {+ const current = readJson(envelopePath);+ if (!envelope || envelope.kind !== 'gbrain-worker-channel-v1' || envelope.token !== token ||+ !Number.isSafeInteger(envelope.owner_pid) || Number(envelope.owner_pid) <= 0 ||+ typeof envelope.runtime_id !== 'string' || typeof envelope.owner_status_path !== 'string' ||+ current?.kind !== envelope.kind || current.token !== token || current.owner_pid !== envelope.owner_pid ||+ current.runtime_id !== envelope.runtime_id || current.owner_status_path !== envelope.owner_status_path) return false;+ const owner = readJson(envelope.owner_status_path);+ if (!owner || owner.owner_pid !== envelope.owner_pid || owner.runtime_id !== envelope.runtime_id ||+ owner.worker_channel_token !== token ||+ (owner.processing_stage !== 'startup_readiness' && owner.processing_stage !== 'ready' && !startupStage(owner.processing_stage))) return false;+ try { process.kill(envelope.owner_pid as number, 0); } catch { return false; }+ return true;+ };+ if (!activeGeneration()) return false;+ const previous = readJson(path);+ if (!previous || previous.token !== token || previous.owner_pid !== envelope!.owner_pid || previous.runtime_id !== envelope!.runtime_id ||+ (previous.worker_pid !== null && previous.worker_pid !== process.pid)) return false;+ const sameWorker = previous.worker_pid === process.pid;+ writeJson(path, {+ owner_pid: envelope!.owner_pid, runtime_id: envelope!.runtime_id,+ token, worker_pid: process.pid, state: update.state, stage: startupStage(update.stage),+ reason_code: reasonCode(update.reason_code),+ worker_identity: identity(update.worker_identity) ?? (sameWorker ? identity(previous?.worker_identity) : null),+ child_identity: identity(update.child_identity) ?? (sameWorker ? identity(previous?.child_identity) : null),+ }, false);+ const published = readJson(path);+ return activeGeneration() && published?.token === token && published.worker_pid === process.pid &&+ published.owner_pid === envelope!.owner_pid && published.runtime_id === envelope!.runtime_id;+ } catch { return false; }+}++export function readOwnerProcessingStatus(kind: ProcessingOwnerKind, key: string, pid?: number): OwnerProcessingStatus | null {+ const v = readJson(ownerPath(kind, key));+ if (!v || !Number.isSafeInteger(v.owner_pid) || Number(v.owner_pid) <= 0 || (pid !== undefined && v.owner_pid !== pid) || typeof v.runtime_id !== 'string') return null;+ try { process.kill(v.owner_pid as number, 0); } catch { return null; }+ if (v.processing_state !== 'starting' && v.processing_state !== 'ready' && v.processing_state !== 'configuration_blocked') return null;+ return {+ processing_ready: v.processing_state === 'ready',+ processing_state: v.processing_state,+ processing_stage: processingStage(v.processing_stage),+ retry_at: typeof v.retry_at === 'string' && Number.isFinite(Date.parse(v.retry_at)) ? v.retry_at : null,+ reason_code: reasonCode(v.reason_code),+ blocked_since: typeof v.blocked_since === 'string' ? v.blocked_since : null,+ owner_pid: v.owner_pid as number,+ runtime_id: v.runtime_id,+ worker_pid: Number.isSafeInteger(v.worker_pid) ? v.worker_pid as number : null,+ worker_identity: identity(v.worker_identity),+ child_identity: identity(v.child_identity),+ };+}++export function readAutopilotProcessingStatus(deps: AutopilotLockProbeDeps = {}): OwnerProcessingStatus | null {+ let lockPid: number;+ try { lockPid = Number.parseInt(readFileSync(autopilotLockPath(), 'utf-8').trim(), 10); } catch { return null; }+ const holder = classifyAutopilotLockHolder(lockPid, process.pid, deps).state;+ return holder === 'alive-foreign' || holder === 'dead' ? null : readOwnerProcessingStatus('autopilot', 'default', lockPid);+}++export class OwnerProcessingState {+ private readonly path: string;+ private childPath: string | null = null;+ private childToken: string | null = null;+ private status: OwnerProcessingStatus = {+ processing_ready: false, processing_state: 'starting', processing_stage: 'startup_readiness', retry_at: null, reason_code: null,+ blocked_since: null, owner_pid: process.pid, runtime_id: randomUUID(),+ worker_pid: null, worker_identity: null, child_identity: null,+ };++ constructor(kind: ProcessingOwnerKind, key: string) {+ this.path = ownerPath(kind, key);+ this.publish();+ }++ get snapshot(): OwnerProcessingStatus {+ this.observeWorker();+ return { ...this.status };+ }++ get blocked(): boolean { return this.snapshot.processing_state === 'configuration_blocked'; }++ prepareChild(): NodeJS.ProcessEnv {+ if (this.blocked) throw new Error('Processing is configuration-blocked; restart the owner after repair.');+ this.removeChildFile();+ this.childToken = randomUUID();+ this.childPath = join(`${this.path}.${this.status.runtime_id}.${this.childToken}.worker`, 'status.json');+ this.status.processing_ready = false;+ this.status.processing_state = 'starting';+ this.status.processing_stage = 'startup_readiness';+ this.status.retry_at = null;+ this.status.worker_pid = null;+ this.status.worker_identity = null;+ this.status.child_identity = null;+ this.publish();+ mkdirSync(dirname(this.childPath), { mode: 0o700 });+ writeJson(join(dirname(this.childPath), 'owner.json'), {+ kind: 'gbrain-worker-channel-v1', token: this.childToken,+ owner_pid: this.status.owner_pid, runtime_id: this.status.runtime_id, owner_status_path: this.path,+ }, false);+ writeJson(this.childPath, {+ token: this.childToken, owner_pid: this.status.owner_pid, runtime_id: this.status.runtime_id,+ worker_pid: null, state: 'starting', stage: null,+ }, false);+ return { GBRAIN_WORKER_STATUS_PATH: this.childPath, GBRAIN_WORKER_STATUS_TOKEN: this.childToken };+ }++ block(reason: LocalConfigurationReasonCode | null = null): void {+ if (this.status.processing_state === 'configuration_blocked') return;+ this.status.processing_state = 'configuration_blocked';+ this.status.processing_stage = 'configuration_blocked';+ this.status.retry_at = null;+ this.status.processing_ready = false;+ this.status.reason_code = reason;+ this.status.blocked_since = new Date().toISOString();+ this.publish();+ }++ workerExited(): void {+ this.observeWorker();+ if (!this.blocked) {+ this.status.processing_ready = false;+ this.status.processing_state = 'starting';+ this.status.processing_stage = 'startup_readiness';+ this.status.retry_at = null;+ }+ this.removeChildFile();+ this.publish();+ }++ waiting(stage: 'startup_timeout' | 'retry_backoff' | 'stopped', retryAt: number | null = null): boolean {+ if (this.blocked || (stage === 'startup_timeout' && this.status.processing_ready)) return false;+ if (stage === 'startup_timeout') this.removeChildFile();+ this.status.processing_ready = false;+ this.status.processing_state = 'starting';+ this.status.processing_stage = stage;+ this.status.retry_at = retryAt === null ? null : new Date(retryAt).toISOString();+ this.publish();+ return true;+ }++ close(): void {+ this.removeChildFile();+ if (readJson(this.path)?.runtime_id === this.status.runtime_id) {+ try { unlinkSync(this.path); } catch {}+ }+ }++ private observeWorker(): void {+ if (!this.childPath || this.status.processing_state === 'configuration_blocked') return;+ const v = readJson(this.childPath);+ if (!v || v.token !== this.childToken || v.owner_pid !== this.status.owner_pid || v.runtime_id !== this.status.runtime_id ||+ !Number.isSafeInteger(v.worker_pid) || Number(v.worker_pid) <= 0) return;+ if (v.state !== 'ready' && v.state !== 'configuration_blocked' && v.state !== 'starting') return;+ this.status.worker_pid = v.worker_pid as number;+ this.status.worker_identity = identity(v.worker_identity) ?? this.status.worker_identity;+ this.status.child_identity = identity(v.child_identity) ?? this.status.child_identity;+ if (v.state === 'configuration_blocked') {+ this.block(reasonCode(v.reason_code));+ } else if (v.state === 'ready' && !this.status.processing_ready && this.status.processing_stage !== 'startup_timeout') {+ this.status.processing_state = 'ready';+ this.status.processing_stage = 'ready';+ this.status.retry_at = null;+ this.status.processing_ready = true;+ this.publish();+ } else if (v.state === 'starting' && !this.status.processing_ready && this.status.processing_stage !== 'startup_timeout') {+ const stage = startupStage(v.stage) ?? 'startup_readiness';+ if (this.status.processing_stage !== stage) {+ this.status.processing_stage = stage;+ this.publish();+ }+ }+ }++ private removeChildFile(): void {+ if (this.childPath) {+ try { rmSync(dirname(this.childPath), { recursive: true, force: true }); } catch {}+ }+ this.childPath = null;+ this.childToken = null;+ }++ private publish(): void {+ try { writeJson(this.path, { ...this.status, worker_channel_token: this.childToken }); } catch {}+ }+}diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.tsindex 38bb7ccbda..425abbe55a 100644--- a/src/core/minions/queue.ts+++ b/src/core/minions/queue.ts@@ -1989,6 +1989,38 @@ export class MinionQueue {return rowToMinionJob(rows[0]);}+ async releaseConfigurationJob(+ id: number,+ lockToken: string,+ signal: AbortSignal,+ ): Promise<'released' | 'no_op' | 'unconfirmed'> {+ if (signal.aborted) return 'unconfirmed';+ let onAbort: () => void = () => {};+ try {+ const cancelled = new Promise<'unconfirmed'>(resolve => {+ onAbort = () => resolve('unconfirmed');+ signal.addEventListener('abort', onAbort, { once: true });+ });+ const release = this.engine.executeRaw<{ id: number }>(+ `UPDATE minion_jobs SET+ status = 'delayed',+ error_text = 'worker_configuration_blocked',+ delay_until = now() + interval '30 seconds',+ started_at = NULL, timeout_at = NULL,+ lock_token = NULL, lock_until = NULL, updated_at = now()+ WHERE id = $1 AND status = 'active' AND lock_token = $2+ RETURNING id`,+ [id, lockToken],+ { signal },+ ).then(rows => signal.aborted ? 'unconfirmed' as const : rows.length > 0 ? 'released' as const : 'no_op' as const);+ return await Promise.race([release, cancelled]);+ } catch {+ return 'unconfirmed';+ } finally {+ signal.removeEventListener('abort', onAbort);+ }+ }+/** Update job progress (token-fenced). */async updateProgress(id: number, lockToken: string, progress: unknown): Promise<boolean> {const rows = await this.engine.executeRaw<Record<string, unknown>>(diff --git a/src/core/minions/run-child.ts b/src/core/minions/run-child.tsindex e2e2b60fa4..d51bb7daff 100644--- a/src/core/minions/run-child.ts+++ b/src/core/minions/run-child.ts@@ -38,8 +38,17 @@ import { withChatPhase } from '../ai/chat-usage.ts';import {JOB_CHILD_EXIT_NOT_CLAIMED,JOB_CHILD_EXIT_RESULT_WRITE_FAILED,+ WORKER_EXIT_CONFIGURATION,} from './worker-exit-codes.ts';import { encodeHandlerError, unrefTimer, writeChildOutcomeFile } from './job-isolation.ts';+import { isLocalConfigurationError } from './configuration-error.ts';++export function writeChildBootstrapError(resultPath: string, error: unknown): number {+ if (!isLocalConfigurationError(error)) return 1;+ try { writeChildOutcomeFile(resultPath, encodeHandlerError(error)); }+ catch { return JOB_CHILD_EXIT_RESULT_WRITE_FAILED; }+ return WORKER_EXIT_CONFIGURATION;+}export interface RunChildOpts {jobId: number;diff --git a/src/core/minions/spawn-helpers.ts b/src/core/minions/spawn-helpers.tsindex 8d88c41942..89cf41a64d 100644--- a/src/core/minions/spawn-helpers.ts+++ b/src/core/minions/spawn-helpers.ts@@ -40,8 +40,8 @@ export function detectTini(): string {/*** Build the (cmd, args) tuple for spawning the gbrain worker, optionally* wrapped in tini. When `tiniPath` is non-empty, returns- * { cmd: tiniPath, args: ['--', cliPath, ...args] }- * which makes tini PID 1 of the spawned subtree. When empty, returns+ * { cmd: tiniPath, args: ['-s', '--', cliPath, ...args] }+ * enabling subreaping without assuming PID 1. When empty, returns* { cmd: cliPath, args }* for a direct spawn. Pure function, no side effects.*/@@ -51,6 +51,6 @@ export function buildSpawnInvocation(args: string[],): { cmd: string; args: string[] } {return tiniPath- ? { cmd: tiniPath, args: ['--', cliPath, ...args] }+ ? { cmd: tiniPath, args: ['-s', '--', cliPath, ...args] }: { cmd: cliPath, args };}diff --git a/src/core/minions/supervisor.ts b/src/core/minions/supervisor.tsindex 644247a6ea..c29f245389 100644--- a/src/core/minions/supervisor.ts+++ b/src/core/minions/supervisor.ts@@ -27,6 +27,7 @@*/import { detectTini } from './spawn-helpers.ts';+import { OwnerProcessingState, type OwnerProcessingStatus } from './processing-state.ts';import { resolveDefaultMaxRssMb } from './rss-default.ts';import {ChildWorkerSupervisor,@@ -46,7 +47,6 @@ import { dirname, resolve } from 'path';import { hostname } from 'os';import type { BrainEngine } from '../engine.ts';import { tryAcquireDbLock, waitForDbLockTakeover, inspectLock, isLockHolderLive, type DbLockHandle } from '../db-lock.ts';-import { MinionQueue } from './queue.ts';import { currentBrainId, readWorkers } from './worker-registry.ts';import { autopilotPausedMarkerPath } from '../autopilot-paths.ts';import { resolveEnvNumber } from '../env-number.ts';@@ -82,6 +82,7 @@ export interface SupervisorOpts {healthInterval: number;/** Path to the gbrain CLI executable (MUST be a compiled binary; .ts sources cannot be spawned). */cliPath: string;+ cliArgsPrefix?: string[];/** Allow shell jobs on child worker. Default: false. When true, sets GBRAIN_ALLOW_SHELL_JOBS=1 on the* child env AND passes `--allow-shell-jobs` (buildWorkerArgs) so the worker's cwd-.env quarantine* cannot silently drop the opt-in. */@@ -542,6 +543,13 @@ export function classifySupervisorSingleton(args: {}export class MinionSupervisor {+ private processingState: OwnerProcessingState | null = null;++ get processingStatus(): OwnerProcessingStatus | null { return this.processingState?.snapshot ?? null; }++ private get configurationBlocked(): boolean {+ return this.processingState?.blocked ?? false;+ }private opts: SupervisorOpts;private engine: BrainEngine;/**@@ -703,6 +711,8 @@ export class MinionSupervisor {process.exit(ExitCodes.PID_UNWRITABLE);}+ this.processingState = new OwnerProcessingState('supervisor', resolve(this.opts.pidFile));+// 2. Cleanup on process exit (covers any exit path including process.exit).// Installed BEFORE the DB-lock acquisition below: acquirePidLock just// wrote OUR pid into the pidfile, so any early `process.exit` after this@@ -711,6 +721,7 @@ export class MinionSupervisor {// only unlinks when the file still holds our pid, so it's a no-op on the// 'held'/'unwritable' paths above (those never created our pidfile).this.exitListener = () => {+ this.processingState?.close();try {if (existsSync(this.opts.pidFile)) {const contents = readFileSync(this.opts.pidFile, 'utf8').trim().split('\n')[0];@@ -830,6 +841,7 @@ export class MinionSupervisor {// 7. Run the supervise loop (respawn on crash, bounded by maxCrashes).await this.runSuperviseLoop();+ if (this.configurationBlocked) await new Promise<void>(() => {});}/**@@ -867,42 +879,24 @@ export class MinionSupervisor {}}- private async reconcileOrphanedPrivateQueuesBeforeWorkerSpawn(): Promise<void> {- try {- // 30s bound: a hanging DB call here would otherwise block EVERY worker- // respawn indefinitely (the hook is awaited in the supervise loop with- // isStopping unchecked during the await). Timeout → spawn proceeds; the- // next respawn retries recovery.- const result = await Promise.race([- new MinionQueue(this.engine).reconcileOrphanedPrivateQueues({- reason: 'supervisor startup recovery: orphaned dream-inline private queue',- }),- new Promise<never>((_, reject) => {- const t = setTimeout(() => reject(new Error('private-queue recovery timed out after 30s')), 30_000);- t.unref?.();- }),- ]);- if (result.cancelled_jobs > 0) {- this.emit('health_warn', {- reason: 'private_queue_startup_recovery',- ...result,- });- }- } catch (e) {- this.emit('health_warn', {- reason: 'private_queue_startup_recovery_failed',- error: e instanceof Error ? e.message : String(e),- });- }- }-/** Unified shutdown path. Reason becomes the audit event name; exitCode is process exit. */private async shutdown(reason: string, exitCode: number): Promise<void> {+ if (this.configurationBlocked && reason !== 'SIGTERM' && reason !== 'SIGINT') return;if (this.stopping) return;this.stopping = true;this.emit('shutting_down', { reason, exit_code: exitCode });+ if (this.childSupervisor) {+ this.childSupervisor.killChild('SIGTERM');+ await this.childSupervisor.awaitChildExit(35_000);+ if (this.childSupervisor.childAlive) this.childSupervisor.killChild('SIGKILL');+ }+ if (this.configurationBlocked && reason !== 'SIGTERM' && reason !== 'SIGINT') {+ this.stopping = false;+ return;+ }+if (this.healthTimer) {clearInterval(this.healthTimer);this.healthTimer = null;@@ -921,15 +915,6 @@ export class MinionSupervisor {try { await lock.release(); } catch { /* best-effort; TTL fallback covers it */ }}- if (this.childSupervisor) {- this.childSupervisor.killChild('SIGTERM');- await this.childSupervisor.awaitChildExit(35_000);- // If the child is still up after the 35s drain window, escalate.- if (this.childSupervisor.childAlive) {- this.childSupervisor.killChild('SIGKILL');- }- }-// Remove signal handlers so tests that spin up multiple supervisors on// the same process don't accumulate listeners. `process.on('exit', ...)`// is kept registered — it needs to fire synchronously on the final exit.@@ -972,6 +957,7 @@ export class MinionSupervisor {if (!this.dbLock || this.stopping) return;try {const stillOwned = await this.dbLock.refresh();+ if (this.configurationBlocked) return;if (stillOwned === false) {// W0 fix-wave (D5.10): the fenced refresh matched 0 rows — the lock// was stolen or force-cleared. That is CERTAIN loss, not a blip:@@ -990,6 +976,7 @@ export class MinionSupervisor {this.lockRefreshFailures = 0;} catch (e) {this.lockRefreshFailures++;+ if (this.configurationBlocked) return;this.emit('health_warn', {reason: 'supervisor_lock_refresh_failed',consecutive_failures: this.lockRefreshFailures,@@ -1121,8 +1108,16 @@ export class MinionSupervisor {env.GBRAIN_SUPERVISED = '1';this.childSupervisor = new ChildWorkerSupervisor({+ processingState: this.processingState ?? undefined,+ onConfigurationBlocked: (status) => {+ this.emit('health_error', {+ reason: 'configuration_blocked',+ reason_code: status?.reason_code ?? null,+ queue: this.opts.queue,+ });+ },cliPath: this.opts.cliPath,- args: workerArgs,+ args: [...(this.opts.cliArgsPrefix ?? []), ...workerArgs],env,maxCrashes: this.opts.maxCrashes,// issue #1994: hard permanent-give-up ceiling (the runaway backstop).@@ -1131,11 +1126,6 @@ export class MinionSupervisor {hardStopMaxCrashes: resolveHardStopMaxCrashes(this.opts.maxCrashes),_backoffFloorMs: this.opts._backoffFloorMs,isStopping: () => this.stopping,- // Run under the supervisor's queue-scoped DB singleton lock before every- // child spawn, not merely once when the supervisor starts. The supervisor- // intentionally survives worker crashes/watchdog drains, and those are- // exactly the exits that can strand a parent-owned private queue.- beforeSpawn: () => this.reconcileOrphanedPrivateQueuesBeforeWorkerSpawn(),onMaxCrashesExceeded: (count, max) => {this.emit('max_crashes_exceeded', {crash_count: count,@@ -1158,6 +1148,9 @@ export class MinionSupervisor {*/private relayChildEvent(event: ChildSupervisorEvent): void {switch (event.kind) {+ case 'worker_startup_timeout':+ this.emit('health_error', { reason: 'worker_startup_timeout', timeout_ms: event.timeoutMs, queue: this.opts.queue });+ return;case 'worker_spawned':// issue #1801: anchor the startup grace + reset the wedge counter so a// fresh child is judged on its own forward progress, not the prior@@ -1235,11 +1228,13 @@ export class MinionSupervisor {* connection shouldn't stack duplicate checks).*/private async healthCheck(): Promise<void> {- if (this.healthInFlight) return;+ if (this.healthInFlight || this.configurationBlocked || this.stopping) return;+ if (this.processingState && !this.processingState.snapshot.processing_ready) return;this.healthInFlight = true;try {const sig = await queryWedgeSignals(this.engine, this.opts.queue, this.handlerNames);+ if (this.configurationBlocked || this.stopping) return;// Reset consecutive failure counter on successful health checkthis.consecutiveHealthFailures = 0;@@ -1325,6 +1320,7 @@ export class MinionSupervisor {}} catch (e) {this.consecutiveHealthFailures++;+ if (this.configurationBlocked || this.stopping) return;const errMsg = e instanceof Error ? e.message : String(e);if (this.consecutiveHealthFailures >= 3) {@@ -1382,6 +1378,7 @@ export class MinionSupervisor {waitingClaimable: number,minutesSinceCompletion: number | null,): Promise<void> {+ if (this.configurationBlocked || this.stopping) return;const cs = this.childSupervisor;if (!cs) return;diff --git a/src/core/minions/worker-exit-codes.ts b/src/core/minions/worker-exit-codes.tsindex 354adf38ef..c6dda3d536 100644--- a/src/core/minions/worker-exit-codes.ts+++ b/src/core/minions/worker-exit-codes.ts@@ -23,6 +23,8 @@/** Worker drained itself because RSS crossed the watchdog cap. */export const WORKER_EXIT_RSS_WATCHDOG = 12;+export const WORKER_EXIT_CONFIGURATION = 16;+// --- `gbrain jobs run-child` exit codes (issue #5 process isolation) -------//// The parent (child-job-runner.ts) classifies a child by RESULT-FILE PRESENCEdiff --git a/src/core/minions/worker.ts b/src/core/minions/worker.tsindex 1823d92439..322aa45c8c 100644--- a/src/core/minions/worker.ts+++ b/src/core/minions/worker.ts@@ -42,6 +42,7 @@ import {import { clampLockDurationMs } from './handler-timeouts.ts';import {runDbProbe,+ assertWorkerDbReadiness,getConnectionRouting,DIRECT_PROBE_TIMEOUT_MS,type DbProbeResult,@@ -59,6 +60,7 @@ import { loadavg, cpus } from 'os';import { monitorEventLoopDelay } from 'perf_hooks';import { isRetryableConnError } from '../retry-matcher.ts';import { reconnectAfterConnectionError as reconnectEngineAfterConnError } from './reconnect.ts';+import { LocalConfigurationError, isLocalConfigurationError } from './configuration-error.ts';/*** Abort reasons that signal infrastructure failure (PgBouncer outage,@@ -152,6 +154,7 @@ export function getAccurateRss(* unreachable server so operators stop debugging the wrong layer; absent on* engines without the probe's disambiguation lane. */export type UnhealthyReason =+ | { reason: 'client_misconfigured'; error: LocalConfigurationError }| {reason: 'db_dead';consecutiveFailures: number;@@ -181,8 +184,24 @@ interface InFlightJob {promise: Promise<void>;}+export interface ConfigurationReleaseResult {+ jobId: number | null;+ lockToken: string;+ outcome: 'released' | 'no_op' | 'unconfirmed';+}++interface OwnedExecution {+ job: MinionJob;+ lockToken: string;+ stopped: boolean;+ abort?: AbortController;+ promise?: Promise<void>;+}+/** Type-safe `on('unhealthy', ...)` for callers. */export interface MinionWorker {+ on(event: 'ready', listener: () => void): this;+ emit(event: 'ready'): boolean;on(event: 'unhealthy', listener: (info: UnhealthyReason) => void): this;emit(event: 'unhealthy', info: UnhealthyReason): boolean;}@@ -194,6 +213,13 @@ export class MinionWorker extends EventEmitter {/** Log the pause/resume transition once each, not every poll. */private pausedByMarkerAnnounced = false;private inFlight = new Map<number, InFlightJob>();+ private executions = new Map<string, OwnedExecution>();+ private pendingClaim: { lockToken: string; promise: Promise<MinionJob | null> } | null = null;+ private _configurationError: LocalConfigurationError | null = null;+ private configurationDeadline = 0;+ private configurationDrainFinished = false;+ private configurationBlocked = new AbortController();+ private _configurationReleaseResults: ConfigurationReleaseResult[] = [];private workerId = randomUUID();/** Fires only on worker process SIGTERM/SIGINT. Handlers that need to run@@ -351,6 +377,91 @@ export class MinionWorker extends EventEmitter {return this._rssWatchdogTriggered;}+ get configurationError(): LocalConfigurationError | null {+ return this._configurationError;+ }++ get configurationReleaseResults(): readonly ConfigurationReleaseResult[] {+ return this._configurationReleaseResults;+ }++ private probeDatabase(): Promise<DbProbeResult> {+ const dualPool = getConnectionRouting(this.engine)?.isDualPoolActive?.() === true;+ const getDiag = (this.engine as { getPoolDiagnostics?: () => PoolDiagnostics | null }).getPoolDiagnostics;+ return runDbProbe({+ probeRead: async signal => { await this.engine.executeRaw('SELECT 1', undefined, { signal }); },+ ...(dualPool ? {+ probeDirect: async (signal: AbortSignal) => { await this.engine.executeRawDirect('SELECT 1', undefined, { signal }); },+ } : {}),+ ...(typeof getDiag === 'function' ? { getDiagnostics: () => getDiag.call(this.engine) } : {}),+ timeoutMs: this.opts.dbProbeTimeoutMs,+ directTimeoutMs: DIRECT_PROBE_TIMEOUT_MS,+ });+ }++ blockForConfiguration(error: LocalConfigurationError): void {+ if (this._configurationError) return;+ this._configurationError = error;+ this.configurationDeadline = performance.now() + 30_000;+ this.running = false;+ this.configurationBlocked.abort(error);+ if (!this.shutdownAbort.signal.aborted) this.shutdownAbort.abort(error);+ for (const execution of this.executions.values()) execution.abort?.abort(error);+ this.emit('unhealthy', { reason: 'client_misconfigured', error });+ }++ private async drainConfiguration(): Promise<void> {+ const controller = new AbortController();+ const remaining = Math.max(0, this.configurationDeadline - performance.now());+ if (remaining === 0) controller.abort();+ const timer = setTimeout(() => controller.abort(), remaining);+ const pending = new Map(this.executions);+ const releasing = new Set<string>();+ let claimDone = !this.pendingClaim;+ const claim = this.pendingClaim;+ const collectClaim = claim?.promise.then(job => {+ claimDone = true;+ if (job) {+ const execution = this.executions.get(claim.lockToken);+ if (execution) pending.set(claim.lockToken, execution);+ }+ }, () => {+ claimDone = true;+ if (!this.configurationDrainFinished) {+ this._configurationReleaseResults.push({ jobId: null, lockToken: claim.lockToken, outcome: 'unconfirmed' });+ }+ });+ try {+ while (!controller.signal.aborted && (pending.size > 0 || !claimDone)) {+ for (const [token, execution] of pending) {+ if (!execution.stopped || releasing.has(token)) continue;+ if (releasing.size >= 4) break;+ releasing.add(token);+ void this.queue.releaseConfigurationJob(execution.job.id, token, controller.signal).then(outcome => {+ if (this.configurationDrainFinished) return;+ this._configurationReleaseResults.push({ jobId: execution.job.id, lockToken: token, outcome });+ pending.delete(token);+ releasing.delete(token);+ this.executions.delete(token);+ });+ }+ if (pending.size > 0 || !claimDone) {+ await new Promise(resolve => setTimeout(resolve, Math.min(10, Math.max(0, this.configurationDeadline - performance.now()))));+ }+ }+ for (const [token, execution] of pending) {+ this._configurationReleaseResults.push({ jobId: execution.job.id, lockToken: token, outcome: 'unconfirmed' });+ }+ if (!claimDone && claim) this._configurationReleaseResults.push({ jobId: null, lockToken: claim.lockToken, outcome: 'unconfirmed' });+ void collectClaim;+ } finally {+ this.configurationDrainFinished = true;+ controller.abort();+ clearTimeout(timer);+ for (const entry of this.inFlight.values()) clearInterval(entry.lockTimer);+ }+ }+/** Emit 'unhealthy' with a no-listener fallback. The default contract is* fail-stop: pre-EventEmitter-refactor behavior was process.exit(1) inside* the timer; the refactor moved that responsibility to the CLI subscriber.@@ -360,6 +471,11 @@ export class MinionWorker extends EventEmitter {* ourselves so the worker dies and the PM restarts it. Subscribers* override this default by adding a listener before start(). */private emitUnhealthy(info: UnhealthyReason): void {+ if (info.reason === 'client_misconfigured') {+ this.blockForConfiguration(info.error);+ return;+ }+ if (this.configurationError) return;if (this.listenerCount('unhealthy') === 0) {const detail = info.reason === 'db_dead'? `DB unreachable (${info.consecutiveFailures} probes): ${info.message}`@@ -377,13 +493,42 @@ export class MinionWorker extends EventEmitter {/** Start the worker loop. Blocks until stopped. */async start(): Promise<void> {+ if (this.configurationError) return;if (this.handlers.size === 0) {throw new Error('No handlers registered. Call worker.register(name, handler) before start().');}- await this.queue.ensureSchema();- await assertNoUnreviewedJobs(this.engine);this.running = true;+ if (this.engine.kind === 'postgres') {+ while (this.running) {+ try {+ await assertWorkerDbReadiness(this.engine);+ break;+ } catch (error) {+ if (isLocalConfigurationError(error)) {+ this.blockForConfiguration(error);+ return;+ }+ }+ await new Promise(resolve => setTimeout(resolve, Math.max(100, Math.min(1000, this.opts.pollInterval))));+ }+ }+ if (!this.running) return;+ try {+ await this.queue.ensureSchema();+ await assertNoUnreviewedJobs(this.engine);+ } catch (error) {+ if (!isLocalConfigurationError(error)) throw error;+ this.blockForConfiguration(error);+ return;+ }+ if (!this.running) return;+ try {+ this.emit('ready');+ } catch (error) {+ this.running = false;+ throw error;+ }// R2-9 lifecycle: (re-)enable the event-loop-delay histogram for this// run; stop() disables it so embedding hosts / test suites that cycle// start()/stop() don't leak a ~50Hz native sampling timer per instance.@@ -407,6 +552,7 @@ export class MinionWorker extends EventEmitter {// so a stalled job (lock_until expired) gets requeued before handleTimeouts'// `lock_until > now()` guard would skip it. Stall → retry, timeout → dead.const stalledTimer = setInterval(async () => {+ if (this.configurationError) return;// issue #1720: a dead pool used to spray "Stall detection error: write// CONNECTION_CLOSED ..." every tick forever — this interval was the only// background loop without the #1491-style reconnect. Rebuild the@@ -415,6 +561,10 @@ export class MinionWorker extends EventEmitter {// back-to-back connect attempts would just add pooler pressure).let reconnectedThisTick = false;const recoverConnection = async (site: string, e: unknown): Promise<void> => {+ if (isLocalConfigurationError(e)) {+ this.blockForConfiguration(e);+ return;+ }if (reconnectedThisTick || !isRetryableConnError(e)) return;reconnectedThisTick = true;await this.reconnectAfterConnectionError(site, e);@@ -427,6 +577,7 @@ export class MinionWorker extends EventEmitter {console.error('Stall detection error:', e instanceof Error ? e.message : String(e));await recoverConnection('handleStalled', e);}+ if (this.configurationError) return;try {const timedOut = await this.queue.handleTimeouts();if (timedOut.length > 0) console.log(`Timeout detector: dead-lettered ${timedOut.length} jobs (timeout exceeded)`);@@ -434,6 +585,7 @@ export class MinionWorker extends EventEmitter {console.error('Timeout detection error:', e instanceof Error ? e.message : String(e));await recoverConnection('handleTimeouts', e);}+ if (this.configurationError) return;try {const wallClockTimedOut = await this.queue.handleWallClockTimeouts(this.opts.lockDuration);if (wallClockTimedOut.length > 0) {@@ -443,6 +595,7 @@ export class MinionWorker extends EventEmitter {console.error('Wall-clock timeout detection error:', e instanceof Error ? e.message : String(e));await recoverConnection('handleWallClockTimeouts', e);}+ if (this.configurationError) return;// 4th sweep: waiting-TTL (admission control). Warn-before-act (user// requirement D1A) lives in runWaitingTtlTick (admission.ts): the first// tick counts + stamps the notice timestamp, sweeping starts only after@@ -529,37 +682,17 @@ export class MinionWorker extends EventEmitter {// never abandoned. The direct-lane probe runs ONLY when dual-pool is// genuinely active (a kill-switched executeRawDirect would probe the// same starved read pool twice and fake a verdict).- const runProbe = async (): Promise<DbProbeResult> => {- const cm = getConnectionRouting(this.engine);- const dualPool = cm?.isDualPoolActive?.() === true;- const getDiag = (this.engine as {- getPoolDiagnostics?: () => PoolDiagnostics | null;- }).getPoolDiagnostics;- return runDbProbe({- probeRead: async (signal) => {- await this.engine.executeRaw('SELECT 1', undefined, { signal });- },- ...(dualPool- ? {- probeDirect: async (signal: AbortSignal) => {- await this.engine.executeRawDirect('SELECT 1', undefined, { signal });- },- }- : {}),- ...(typeof getDiag === 'function'- ? { getDiagnostics: () => getDiag.call(this.engine) }- : {}),- timeoutMs: this.opts.dbProbeTimeoutMs,- directTimeoutMs: DIRECT_PROBE_TIMEOUT_MS,- });- };-const runHealthCheck = async (): Promise<void> => {if (healthRunning || !this.running || healthExited) return;healthRunning = true;try {// --- 1. DB liveness probe ---- const probe = await runProbe();+ const probe = await this.probeDatabase();+ if (this.configurationError) return;+ if (!probe.ok && probe.verdict === 'client_misconfigured') {+ this.blockForConfiguration(probe.configurationError);+ return;+ }if (probe.ok) {consecutiveDbFailures = 0;} else {@@ -663,12 +796,16 @@ export class MinionWorker extends EventEmitter {healthTimer = setTimeout(runHealthCheck, this.opts.healthCheckInterval);}- try {+ const runLoop = async () => {while (this.running) {// Promote delayed jobstry {await this.queue.promoteDelayed();} catch (e) {+ if (isLocalConfigurationError(e)) {+ this.blockForConfiguration(e);+ break;+ }const msg = e instanceof Error ? e.message : String(e);console.error('Promotion error:', msg);// issue #1491: a retryable pool/connection loss during promotion used@@ -682,6 +819,8 @@ export class MinionWorker extends EventEmitter {}}+ if (!this.running) break;+// Claim jobs up to concurrency limit — unless the system-wide pause// marker is parked. `gbrain migrate` quiesces writers for the copy// window; the marker stops the autopilot dispatch loop, and gating@@ -701,16 +840,35 @@ export class MinionWorker extends EventEmitter {this.pausedByMarkerAnnounced = false;}if (this.inFlight.size < this.opts.concurrency) {- const lockToken = `${this.workerId}:${Date.now()}`;+ const lockToken = `${this.workerId}:${randomUUID()}`;let job: MinionJob | null;try {- job = await this.queue.claim(+ const claim = this.queue.claim(lockToken,this.opts.lockDuration,this.opts.queue,this.registeredNames,- );+ ).then(claimed => {+ if (claimed) {+ this.executions.set(lockToken, { job: claimed, lockToken, stopped: true });+ if (this.configurationDrainFinished) {+ const previous = this._configurationReleaseResults.find(result => result.lockToken === lockToken);+ if (previous) previous.jobId = claimed.id;+ else this._configurationReleaseResults.push({ jobId: claimed.id, lockToken, outcome: 'unconfirmed' });+ this.executions.delete(lockToken);+ }+ }+ return claimed;+ });+ this.pendingClaim = { lockToken, promise: claim };+ job = await claim;+ this.pendingClaim = null;} catch (e) {+ if (isLocalConfigurationError(e)) {+ this.blockForConfiguration(e);+ break;+ }+ this.pendingClaim = null;// issue #1678 (Codex #1): a reaped pooler socket / nulled instance// pool throws a retryable conn error here. Blind-retrying claim is// UNSAFE — if the UPDATE...RETURNING committed but the connection@@ -727,6 +885,7 @@ export class MinionWorker extends EventEmitter {}if (job) {+ if (this.configurationError) break;// Post-claim fence re-check: the pre-claim marker check above// races migrate's marker write — this claim may have committed// after migrate's drain probe counted zero active jobs. A job@@ -735,6 +894,7 @@ export class MinionWorker extends EventEmitter {if (existsSync(autopilotPausedMarkerPath())) {console.log(`[worker] pause marker appeared after claim — releasing ${job.name} (id=${job.id}) un-run.`);await this.releaseClaimForPause(job, lockToken);+ this.executions.delete(lockToken);continue;}// Quiet-hours gate: evaluated at claim time, not dispatch.@@ -745,6 +905,7 @@ export class MinionWorker extends EventEmitter {const verdict = evaluateQuietHours(quietCfg);if (verdict !== 'allow') {await this.handleQuietHoursDefer(job, lockToken, verdict);+ this.executions.delete(lockToken);} else {this.launchJob(job, lockToken);}@@ -760,6 +921,13 @@ export class MinionWorker extends EventEmitter {await new Promise(resolve => setTimeout(resolve, 100));}}+ };+ const blocked = new Promise<void>(resolve => {+ if (this.configurationBlocked.signal.aborted) resolve();+ else this.configurationBlocked.signal.addEventListener('abort', () => resolve(), { once: true });+ });+ try {+ await Promise.race([runLoop(), blocked]);} finally {clearInterval(stalledTimer);if (rssTimer) clearInterval(rssTimer);@@ -768,13 +936,16 @@ export class MinionWorker extends EventEmitter {process.removeListener('SIGINT', shutdown);// Graceful shutdown: wait for all in-flight jobs with timeout- if (this.inFlight.size > 0) {- console.log(`Waiting for ${this.inFlight.size} in-flight job(s) to finish (30s timeout)...`);- const pending = Array.from(this.inFlight.values()).map(f => f.promise);+ if (this.configurationError) {+ await this.drainConfiguration();+ } else if (this.executions.size > 0) {+ console.log(`Waiting for ${this.executions.size} in-flight job(s) to finish (30s timeout)...`);+ const pending = Array.from(this.executions.values()).map(f => f.promise);await Promise.race([Promise.allSettled(pending),new Promise(resolve => setTimeout(resolve, 30000)),]);+ if (this.configurationError) await this.drainConfiguration();}// The worker does NOT disconnect the engine: it doesn't own the@@ -1028,7 +1199,10 @@ export class MinionWorker extends EventEmitter {}private launchJob(job: MinionJob, lockToken: string): void {+ if (this.configurationError) return;const abort = new AbortController();+ const execution: OwnedExecution = { job, lockToken, stopped: false, abort };+ this.executions.set(lockToken, execution);// --- D1: cancellation flag for the in-flight renewal IIFE ---let cancelled = false;@@ -1081,7 +1255,17 @@ export class MinionWorker extends EventEmitter {// and the tick keeps its legacy no-reconnect behavior.const engineReconnect = (this.engine as { reconnect?: (ctx?: { error?: unknown }) => Promise<void> }).reconnect;const renewalDeps: LockRenewalDeps = {- renewLock: (id, tok, dur, opts) => this.queue.renewLock(id, tok, dur, opts),+ renewLock: async (id, tok, dur, opts) => {+ try {+ return await this.queue.renewLock(id, tok, dur, opts);+ } catch (error) {+ if (isLocalConfigurationError(error)) {+ cancelled = true;+ this.blockForConfiguration(error);+ }+ throw error;+ }+ },audit: lockRenewalAudit,// R2-4: monotonic — see monotonicNow above.now: monotonicNow,@@ -1177,7 +1361,9 @@ export class MinionWorker extends EventEmitter {console.warn(`Job ${job.id} (${job.name}) did not exit within 30s of abort (reason: ${reason}).${meta} ` +`Force-evicting from inFlight to unblock worker. ` +- `The handler is still running but the worker will claim new jobs.` ++ (this.configurationError+ ? 'The handler is still running; configuration blocking prevents new claims.'+ : 'The handler is still running but the worker will claim new jobs.') +this.formatEvictionTelemetry());clearInterval(lockTimer);@@ -1199,7 +1385,7 @@ export class MinionWorker extends EventEmitter {// also skip — the group SIGKILL already fired and executeJob's// own recording follows; a competing evict failJob('dead') could// dead-letter a job with attempts remaining (adversarial-review P3).- if (!INFRASTRUCTURE_ABORT_REASONS.has(reason) && this.opts.jobIsolation !== 'process') {+ if (!this.configurationError && !INFRASTRUCTURE_ABORT_REASONS.has(reason) && this.opts.jobIsolation !== 'process') {this.queue.failJob(job.id,lockToken,@@ -1232,6 +1418,10 @@ export class MinionWorker extends EventEmitter {}const promise = this.executeJob(job, lockToken, abort, lockTimer)+ .catch(error => {+ if (isLocalConfigurationError(error)) this.blockForConfiguration(error);+ throw error;+ }).finally(() => {// D1: signal in-flight IIFE to bail at its next checkpoint so// a renewLock resolution that lands after the job ended@@ -1247,6 +1437,7 @@ export class MinionWorker extends EventEmitter {if (this.inFlight.get(job.id)?.lockToken === lockToken) {this.inFlight.delete(job.id);}+ if (!this.configurationError || this.configurationDrainFinished) this.executions.delete(lockToken);this.jobsCompleted += 1;this.checkMemoryLimit('post-job');})@@ -1264,6 +1455,7 @@ export class MinionWorker extends EventEmitter {});this.inFlight.set(job.id, { job, lockToken, lockTimer, abort, promise });+ execution.promise = promise;}private async executeJob(@@ -1305,8 +1497,14 @@ export class MinionWorker extends EventEmitter {this.shutdownAbort.signal,);+ let childExecutionStopped = false;try {const authority = await authorizeJobExecution(this.engine, job);+ if (this.configurationError) {+ const execution = this.executions.get(lockToken);+ if (execution) execution.stopped = true;+ return;+ }const result = isolated? await runJobInChild({jobId: job.id,@@ -1316,6 +1514,14 @@ export class MinionWorker extends EventEmitter {shutdownSignal: this.shutdownAbort.signal,invocation: this.opts.childCliInvocation as { cmd: string; argsPrefix: string[] },tiniPath: this.opts.childTiniPath,+ onExecutionStopped: () => {+ childExecutionStopped = true;+ const execution = this.executions.get(lockToken);+ if (execution) execution.stopped = true;+ },+ onConfigurationError: error => {+ this.blockForConfiguration(error);+ },})// #4218: attribute every gateway.chat() the handler makes to this// job so chat_usage_log rows carry `phase = 'job:<name>'`.@@ -1332,6 +1538,8 @@ export class MinionWorker extends EventEmitter {lockToken,result != null ? (typeof result === 'object' ? result as Record<string, unknown> : { value: result }) : undefined,);+ const execution = this.executions.get(lockToken);+ if (execution) execution.stopped = true;if (!completed) {console.warn(`Job ${job.id} completion dropped (lock token mismatch, job was reclaimed)`);@@ -1342,6 +1550,12 @@ export class MinionWorker extends EventEmitter {// strand the parent in waiting-children.} catch (err) {clearInterval(lockTimer);+ const execution = this.executions.get(lockToken);+ if (execution) execution.stopped = err instanceof ChildWorkerShutdownError+ ? err.executionStopped === true+ : !isolated || childExecutionStopped;+ if (isLocalConfigurationError(err)) this.blockForConfiguration(err);+ if (this.configurationError) return;// If the per-job abort fired, derive the reason from signal.reason (set// by whichever site aborted: 'timeout' / 'cancel' / 'lock-lost'). We call@@ -1519,6 +1733,10 @@ export class MinionWorker extends EventEmitter {try {failed = await this.queue.failJob(job.id, lockToken, errorText, newStatus, backoffMs);} catch (retryErr) {+ if (isLocalConfigurationError(retryErr)) {+ this.blockForConfiguration(retryErr);+ return;+ }console.error(`Job ${job.id} (${job.name}) failure-recording retry also failed ` +`(${retryErr instanceof Error ? retryErr.message : String(retryErr)}); ` +diff --git a/src/core/page-state/transactions.ts b/src/core/page-state/transactions.tsindex f961f831a0..8fd17ec6e2 100644--- a/src/core/page-state/transactions.ts+++ b/src/core/page-state/transactions.ts@@ -1,5 +1,5 @@import type { PGlite, Transaction } from '@electric-sql/pglite';-import type postgres from 'postgres';+import type postgres from '#postgres'/** Sibling savepoints must finish in order; children receive a separate queue. */function serial<T>() {diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 6390f9219a..c06158dd1f 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -10,7 +10,9 @@ import { composablePostgresTransaction } from './page-state/transactions.ts';import type { PageReadScope } from './types.ts';import type { PageReadPolicy } from './types.ts';import { readRelationalFanout, readAliases, readBacklinkCounts, readAdjacencyBoosts, readContentFlags, readExtractionStates, readEffectiveDates, readSalienceScores } from './search/read-enrichment.ts';-import postgres from 'postgres';+import postgres from '#postgres'+import { hasPostgresCancellationCapability, postgresCancellationUnavailable, reserveWithCancellation } from './postgres-engine/cancellation.ts';+export { hasPostgresCancellationCapability } from './postgres-engine/cancellation.ts';import type {BrainEngine,BatchOpts,@@ -5305,11 +5307,11 @@ export class PostgresEngine implements BrainEngine {let owner: postgres.TransactionSql | postgres.ReservedSql = conn as unknown as postgres.TransactionSql;signal?.addEventListener('abort', onAbort, { once: true });try {- reserved = signal && typeof conn.reserve === 'function' ? await conn.reserve({ signal }) : undefined;+ reserved = signal && typeof conn.reserve === 'function' ? await reserveWithCancellation(opts => conn.reserve(opts), signal) : undefined;if (reserved) conn = reserved;owner = reserved ?? conn as unknown as postgres.TransactionSql;if (signal?.aborted) throw new DOMException('aborted', 'AbortError');- if (signal && typeof owner.discard !== 'function') throw new Error('Postgres cancellation requires the pinned driver patch');+ if (signal && !hasPostgresCancellationCapability(owner)) throw postgresCancellationUnavailable();pending = conn.unsafe(sql, params as Parameters<typeof conn.unsafe>[1], { cancelFence: !!signal });return await pending as unknown as T[];} finally {diff --git a/src/core/postgres-engine/cancellation.ts b/src/core/postgres-engine/cancellation.tsnew file mode 100644index 0000000000..99f941d0f8--- /dev/null+++ b/src/core/postgres-engine/cancellation.ts@@ -0,0 +1,43 @@+import { LocalConfigurationError } from '../minions/configuration-error.ts';++export function hasPostgresCancellationCapability(owner: unknown): boolean {+ return typeof (owner as { discard?: unknown } | null)?.discard === 'function';+}++export function postgresCancellationUnavailable(): LocalConfigurationError {+ return new LocalConfigurationError(+ 'postgres_cancellation_unavailable',+ 'The installed Postgres driver lacks safe cancellation support (discard). ' ++ 'Repair this installation, then restart the worker: reinstall the current GBrain package ' ++ '(global: bun install -g github:garrytan/gbrain; checkout: bun install; compiled: replace with the current release). ' ++ 'See docs/guides/minions-fix.md#postgres-cancellation-unavailable.',+ );+}++export async function reserveWithCancellation<T extends { release(): void }>(+ reserve: (opts: { signal: AbortSignal }) => Promise<T>,+ signal: AbortSignal,+): Promise<T> {+ if (signal.aborted) throw new DOMException('aborted', 'AbortError');+ let abandoned = false;+ let abort: () => void = () => {};+ const aborted = new Promise<never>((_, reject) => {+ abort = () => {+ abandoned = true;+ reject(new DOMException('aborted', 'AbortError'));+ };+ signal.addEventListener('abort', abort, { once: true });+ });+ try {+ const reserving = reserve({ signal }).then(owner => {+ if (abandoned) {+ owner.release();+ throw new DOMException('aborted', 'AbortError');+ }+ return owner;+ });+ return await Promise.race([reserving, aborted]);+ } finally {+ signal.removeEventListener('abort', abort);+ }+}diff --git a/src/core/postgres-engine/code-edges.ts b/src/core/postgres-engine/code-edges.tsindex 4798fd41bd..915473153b 100644--- a/src/core/postgres-engine/code-edges.ts+++ b/src/core/postgres-engine/code-edges.ts@@ -3,7 +3,7 @@* (containment sprint C15). Free functions over a NARROW deps surface —* never the whole engine class.*/-import type postgres from 'postgres';+import type postgres from '#postgres'import { currentCodeEdgeFilter } from '../code-intel/read-scope.ts';type PgSql = ReturnType<typeof postgres>;diff --git a/src/core/postgres-engine/facts.ts b/src/core/postgres-engine/facts.tsindex 19eca30638..b440f46a09 100644--- a/src/core/postgres-engine/facts.ts+++ b/src/core/postgres-engine/facts.ts@@ -4,7 +4,7 @@* live postgres.js pool + the engine's cached facts.embedding cast probe.* Never the whole engine class.*/-import type postgres from 'postgres';+import type postgres from '#postgres'type PgSql = ReturnType<typeof postgres>;diff --git a/src/core/postgres-engine/forward-reference-bootstrap.ts b/src/core/postgres-engine/forward-reference-bootstrap.tsindex 7f8697f19f..0478be8617 100644--- a/src/core/postgres-engine/forward-reference-bootstrap.ts+++ b/src/core/postgres-engine/forward-reference-bootstrap.ts@@ -19,7 +19,7 @@// file's source) and `test/e2e/postgres-bootstrap.test.ts` (live Postgres// convergence cases).-import type postgres from 'postgres';+import type postgres from '#postgres'import { GRANT_COLUMNS_SQL } from '../grants/schema.ts';/**diff --git a/src/core/postgres-engine/salience.ts b/src/core/postgres-engine/salience.tsindex bff97abfc7..53314637b4 100644--- a/src/core/postgres-engine/salience.ts+++ b/src/core/postgres-engine/salience.ts@@ -4,7 +4,7 @@ import { pageReadFilter } from '../search/read-policy-sql.ts';* (containment sprint C15). Free functions over a NARROW deps surface —* never the whole engine class.*/-import type postgres from 'postgres';+import type postgres from '#postgres'type PgSql = ReturnType<typeof postgres>;diff --git a/src/core/postgres-engine/takes.ts b/src/core/postgres-engine/takes.tsindex 9b3b39238e..4c85327875 100644--- a/src/core/postgres-engine/takes.ts+++ b/src/core/postgres-engine/takes.ts@@ -3,7 +3,7 @@* peeled out of PostgresEngine (containment sprint C15). Free functions over* a NARROW deps surface — never the whole engine class.*/-import type postgres from 'postgres';+import type postgres from '#postgres'type PgSql = ReturnType<typeof postgres>;diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 0c5be0619f..eb98daca31 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.59.2.0 -->+<!-- gbrain-template-stamp: 0.59.3.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/autopilot-self-upgrade.test.ts b/test/autopilot-self-upgrade.test.tsindex 98a341a176..a7589b2cca 100644--- a/test/autopilot-self-upgrade.test.ts+++ b/test/autopilot-self-upgrade.test.ts@@ -34,7 +34,8 @@ describe('autopilot self-upgrade static-shape regressions', () => {});test('boot reconciles the breadcrumb and the tick attempts the channel', () => {expect(AUTOPILOT_SRC).toContain('reconcileSelfUpgradeAtBoot()');- expect(AUTOPILOT_SRC).toContain('attemptAutopilotSelfUpgrade(engine, engineType, lockPath)');+ expect(AUTOPILOT_SRC).toContain('attemptAutopilotSelfUpgrade(engine, engineType, lockPath, () => !configurationBlocked())');+ expect(AUTOPILOT_SRC).toMatch(/if \(!mayContinue\(\)\) return;[\s\S]*?execSync\('gbrain upgrade --swap-only'/);});test('apply path unlinks the lock before exit so the relaunched binary does not self-exit on a stale lock', () => {// The exit-for-relaunch block unlinks lockPath then process.exit(0).diff --git a/test/autopilot-supervisor-wiring.test.ts b/test/autopilot-supervisor-wiring.test.tsindex a9d27316b3..c148cf6856 100644--- a/test/autopilot-supervisor-wiring.test.ts+++ b/test/autopilot-supervisor-wiring.test.ts@@ -61,13 +61,13 @@ describe('autopilot.ts ↔ ChildWorkerSupervisor wiring', () => {expect(AUTOPILOT_SRC).not.toContain("'--max-rss', '2048'");});- it('strips GBRAIN_SUPERVISED from the spawned worker env (worker-startup recovery lane)', () => {- // Worker-startup recovery (jobs.ts 'work') is autopilot's ONLY- // private-queue recovery lane and is gated on GBRAIN_SUPERVISED !== '1'.- // An inherited =1 (operator export, nested supervision) would silently- // disable it, so the spawn env must strip it explicitly. Behavioral- // proof lives in child-worker-supervisor.test.ts ("GBRAIN_SUPERVISED- // env strip"); this pins that autopilot's construction uses the strip.+ it('uses managed processing state and strips GBRAIN_SUPERVISED so the worker keeps stall detection', () => {+ // Mandatory readiness publication keys on the status channel env that+ // processingState hands off, not on GBRAIN_SUPERVISED. An inherited =1+ // would disable the worker's stall detection, and autopilot has no+ // progress watchdog to replace it. Behavioral proof lives in+ // supervisor-configuration-blocked.test.ts.+ expect(AUTOPILOT_SRC).toContain('processingState: processingState ?? undefined');expect(AUTOPILOT_SRC).toMatch(/env:\s*\{\s*\.\.\.process\.env,\s*GBRAIN_SUPERVISED:\s*undefined\s*\}/,);diff --git a/test/autopilot-transaction-fence.test.ts b/test/autopilot-transaction-fence.test.tsnew file mode 100644index 0000000000..e5f0452a66--- /dev/null+++ b/test/autopilot-transaction-fence.test.ts@@ -0,0 +1,130 @@+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import { OwnerProcessingState } from '../src/core/minions/processing-state.ts';+import { guardAutopilotEngine } from '../src/commands/autopilot.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++afterEach(async () => {+ delete (engine as unknown as Record<string, unknown>).executeRaw;+ await engine.executeRaw('DELETE FROM minion_jobs');+});++async function withOwner(fn: (state: OwnerProcessingState) => Promise<void>): Promise<void> {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-autopilot-txn-fence-'));+ try {+ await withEnv({ GBRAIN_HOME: root, HOME: root }, async () => {+ const state = new OwnerProcessingState('autopilot', 'default');+ try { await fn(state); } finally { state.close(); }+ });+ } finally { rmSync(root, { recursive: true, force: true }); }+}++function pauseAfter(fragment: string): { reached: Promise<void>; release: () => void } {+ let entered!: () => void;+ let release!: () => void;+ const reached = new Promise<void>(resolve => { entered = resolve; });+ const released = new Promise<void>(resolve => { release = resolve; });+ const raw = PGLiteEngine.prototype.executeRaw;+ Object.defineProperty(engine, 'executeRaw', {+ configurable: true,+ value: async function (this: PGLiteEngine, sql: string, ...rest: unknown[]) {+ const rows = await Reflect.apply(raw, this, [sql, ...rest]);+ if (sql.includes(fragment)) { entered(); await released; }+ return rows;+ },+ });+ return { reached, release };+}++async function jobCount(): Promise<number> {+ const rows = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM minion_jobs');+ return Number(rows[0]?.n ?? 0);+}++describe('guardAutopilotEngine transaction fence', () => {+ test('block latched after the in-transaction idempotency lookup rolls back the dispatch', async () => withOwner(async (state) => {+ const pause = pauseAfter('WHERE idempotency_key = $1');+ const pending = new MinionQueue(guardAutopilotEngine(engine, state)).add('sync', { sourceId: 'default' }, {+ queue: 'default', idempotency_key: 'fence-after-lookup', maxWaiting: 1,+ });+ await pause.reached;+ state.block('postgres_cancellation_unavailable');+ pause.release();+ await expect(pending).rejects.toThrow('configuration-blocked');+ expect(await jobCount()).toBe(0);+ }));++ test('block latched after the in-transaction insert still rolls back the dispatch', async () => withOwner(async (state) => {+ const pause = pauseAfter('INSERT INTO minion_jobs');+ const pending = new MinionQueue(guardAutopilotEngine(engine, state)).add('sync', { sourceId: 'default' }, {+ queue: 'default', idempotency_key: 'fence-after-insert', maxWaiting: 1,+ });+ await pause.reached;+ state.block('postgres_cancellation_unavailable');+ pause.release();+ await expect(pending).rejects.toThrow('configuration-blocked');+ expect(await jobCount()).toBe(0);+ }));++ test('transactionDirect callback that finishes after blocking rolls back', async () => withOwner(async (state) => {+ const guarded = guardAutopilotEngine(engine, state);+ const pending = guarded.transactionDirect(async (tx) => {+ await tx.executeRaw(`INSERT INTO minion_jobs (name, submission_authority) VALUES ('fence-direct', '{}'::jsonb)`);+ state.block('postgres_cancellation_unavailable');+ return 'done';+ });+ await expect(pending).rejects.toThrow('configuration-blocked');+ expect(await jobCount()).toBe(0);+ }));++ test('nested transactions inherit the guard', async () => withOwner(async (state) => {+ const guarded = guardAutopilotEngine(engine, state);+ let innerRan = false;+ const pending = guarded.transaction(async (tx) => {+ state.block('postgres_cancellation_unavailable');+ return tx.transaction(async () => { innerRan = true; });+ });+ await expect(pending).rejects.toThrow('configuration-blocked');+ expect(innerRan).toBe(false);+ }));++ test('work committed before blocking persists and later dispatch is refused', async () => withOwner(async (state) => {+ const queue = new MinionQueue(guardAutopilotEngine(engine, state));+ const job = await queue.add('sync', { sourceId: 'default' }, { queue: 'default', idempotency_key: 'fence-committed', maxWaiting: 1 });+ state.block('postgres_cancellation_unavailable');+ const rows = await engine.executeRaw<{ id: number; status: string }>('SELECT id, status FROM minion_jobs');+ expect(rows).toEqual([{ id: job.id, status: 'waiting' }]);+ await expect(queue.add('sync', { sourceId: 'other' }, { queue: 'default', idempotency_key: 'fence-refused', maxWaiting: 1 }))+ .rejects.toThrow('configuration-blocked');+ expect(await jobCount()).toBe(1);+ }));++ test('healthy owner dispatches and runs nested direct transactions', async () => withOwner(async (state) => {+ const guarded = guardAutopilotEngine(engine, state);+ const job = await new MinionQueue(guarded).add('sync', { sourceId: 'default' }, { queue: 'default', idempotency_key: 'fence-healthy', maxWaiting: 1 });+ expect(job.status).toBe('waiting');+ const inner = await guarded.transactionDirect(async (tx) => {+ await tx.executeRaw(`INSERT INTO minion_jobs (name, submission_authority) VALUES ('fence-nested', '{}'::jsonb)`);+ return tx.transaction(async (nested) => (await nested.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM minion_jobs'))[0].n);+ });+ expect(Number(inner)).toBe(2);+ expect(await jobCount()).toBe(2);+ expect(state.blocked).toBe(false);+ }));+});diff --git a/test/child-handler-configuration.test.ts b/test/child-handler-configuration.test.tsnew file mode 100644index 0000000000..0342685f2e--- /dev/null+++ b/test/child-handler-configuration.test.ts@@ -0,0 +1,24 @@+import { expect, test } from 'bun:test';+import { checkChildReadiness } from '../src/core/minions/child-readiness.ts';+import { runJobInChild } from '../src/core/minions/child-job-runner.ts';+import { LocalConfigurationError } from '../src/core/minions/configuration-error.ts';+import { detectTini } from '../src/core/minions/spawn-helpers.ts';++test('actual isolated handler fault after healthy readiness preserves typed outcome and confirms supported cleanup', async () => {+ const invocation = { cmd: process.execPath, argsPrefix: [new URL('./fixtures/child-configuration-handler.ts', import.meta.url).pathname] };+ const tiniPath = detectTini();+ await checkChildReadiness({ invocation, tiniPath });+ const events: string[] = [];+ const error = await runJobInChild({+ invocation, tiniPath, jobId: 1, jobName: 'sync', lockToken: 'fixture-token',+ abortSignal: new AbortController().signal, shutdownSignal: new AbortController().signal,+ killGraceMs: 50,+ onConfigurationError: error => { events.push(error.reasonCode); },+ onExecutionStopped: () => { events.push('stopped'); },+ }).then(() => null, (error: unknown) => error);+ expect(error).toBeInstanceOf(LocalConfigurationError);+ expect((error as LocalConfigurationError).reasonCode).toBe('postgres_cancellation_unavailable');+ expect(events[0]).toBe('postgres_cancellation_unavailable');+ if (process.platform === 'linux') expect(events).toEqual(['postgres_cancellation_unavailable', 'stopped']);+ else expect(events).toEqual(['postgres_cancellation_unavailable']);+}, 30_000);diff --git a/test/child-job-descendants.test.ts b/test/child-job-descendants.test.tsnew file mode 100644index 0000000000..6e5866a7d5--- /dev/null+++ b/test/child-job-descendants.test.ts@@ -0,0 +1,386 @@+import { expect, test } from 'bun:test';+import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { ChildWorkerShutdownError, runJobInChild } from '../src/core/minions/child-job-runner.ts';+import { detectTini } from '../src/core/minions/spawn-helpers.ts';+import { killProcessGroup } from '../src/core/minions/job-isolation.ts';+import { LocalConfigurationError } from '../src/core/minions/configuration-error.ts';+import { UnrecoverableError } from '../src/core/minions/types.ts';++async function until(condition: () => boolean): Promise<void> {+ const deadline = Date.now() + 5000;+ while (!condition()) {+ if (Date.now() >= deadline) throw new Error('Process fixture did not reach the expected state');+ await Bun.sleep(10);+ }+}++function running(pid: number): boolean {+ try {+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');+ return stat.slice(stat.lastIndexOf(')') + 2).split(' ')[0] !== 'Z';+ } catch { return false; }+}++const tini = detectTini();++for (const tiniPath of ['', tini].filter((value, index, all) => all.indexOf(value) === index)) {+ for (const escaped of [false, true]) {+ test.skipIf(process.platform !== 'linux')(`shutdown preserves group backstop after direct exit (${tiniPath ? 'tini -s' : 'no tini'}, escaped=${escaped})`, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'job-descendants-'));+ const pidFile = join(dir, 'grandchild.pid');+ const ready = join(dir, 'ready');+ const parent = join(dir, 'parent.mjs');+ const grandchild = join(dir, 'grandchild.mjs');+ let pid = 0;+ let stopped = false;+ try {+ writeFileSync(grandchild, `import {writeFileSync} from 'node:fs';+ process.on('SIGTERM',()=>{}); writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); setInterval(()=>{},1000);`);+ writeFileSync(parent, `import {spawn} from 'node:child_process'; import {existsSync,writeFileSync} from 'node:fs';+ process.on('SIGTERM',()=>process.exit(0));+ const child=spawn(process.execPath,[${JSON.stringify(grandchild)}],{detached:${escaped},stdio:'ignore'}); child.unref();+ while(!existsSync(${JSON.stringify(pidFile)})) await new Promise(r=>setTimeout(r,5));+ writeFileSync(${JSON.stringify(ready)},'1'); setInterval(()=>{},1000);`);+ const shutdown = new AbortController();+ const result = runJobInChild({+ jobId: 1, jobName: 'fixture', lockToken: 'fixture',+ invocation: { cmd: process.execPath, argsPrefix: [parent] }, tiniPath,+ abortSignal: new AbortController().signal, shutdownSignal: shutdown.signal, killGraceMs: 100,+ onExecutionStopped: () => { stopped = true; },+ }).catch((error: unknown) => error);+ await until(() => existsSync(ready));+ pid = Number(readFileSync(pidFile, 'utf8'));+ expect(running(pid)).toBe(true);+ shutdown.abort();+ const error = await result;+ expect(error).toBeInstanceOf(ChildWorkerShutdownError);+ expect((error as ChildWorkerShutdownError).executionStopped).toBe(!escaped);+ expect(stopped).toBe(!escaped);+ if (escaped) expect(running(pid)).toBe(true);+ else await until(() => !running(pid));+ } finally {+ if (!pid && existsSync(pidFile)) pid = Number(readFileSync(pidFile, 'utf8'));+ if (pid) {+ if (escaped) killProcessGroup(pid, 'SIGKILL');+ try { process.kill(pid, 'SIGKILL'); } catch {}+ await until(() => !running(pid));+ }+ rmSync(dir, { recursive: true, force: true });+ }+ });+ }+}++test.skipIf(process.platform !== 'linux')('failed group signalling returns bounded unconfirmed cleanup while execution remains live', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'job-signal-failure-'));+ const pidFile = join(dir, 'pid');+ const script = join(dir, 'child.mjs');+ let pid = 0;+ let stopped = false;+ try {+ writeFileSync(script, `import {writeFileSync} from 'node:fs'; writeFileSync(${JSON.stringify(pidFile)},String(process.pid)); setInterval(()=>{},1000);`);+ const shutdown = new AbortController();+ const result = runJobInChild({+ jobId: 2, jobName: 'fixture', lockToken: 'fixture',+ invocation: { cmd: process.execPath, argsPrefix: [script] }, tiniPath: '',+ abortSignal: new AbortController().signal, shutdownSignal: shutdown.signal, killGraceMs: 100,+ signalProcessGroup: () => false,+ onExecutionStopped: () => { stopped = true; },+ }).catch((error: unknown) => error);+ await until(() => existsSync(pidFile));+ pid = Number(readFileSync(pidFile, 'utf8'));+ shutdown.abort();+ const error = await result;+ expect(error).toBeInstanceOf(ChildWorkerShutdownError);+ expect((error as ChildWorkerShutdownError).executionStopped).toBe(false);+ expect(stopped).toBe(false);+ expect(running(pid)).toBe(true);+ } finally {+ if (pid) { killProcessGroup(pid, 'SIGKILL'); await until(() => !running(pid)); }+ rmSync(dir, { recursive: true, force: true });+ }+});++test.skipIf(process.platform !== 'linux')('oversized output cannot erase unconfirmed configuration shutdown while the child remains live', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'job-oversize-shutdown-'));+ const pidFile = join(dir, 'pid');+ const script = join(dir, 'child.mjs');+ let pid = 0;+ let stopped = false;+ try {+ writeFileSync(script, `import {writeFileSync,truncateSync} from 'node:fs';+ writeFileSync(process.env.GBRAIN_JOB_RESULT_PATH,'');+ truncateSync(process.env.GBRAIN_JOB_RESULT_PATH,33*1024*1024);+ writeFileSync(${JSON.stringify(pidFile)},String(process.pid)); setInterval(()=>{},1000);`);+ const shutdown = new AbortController();+ const result = runJobInChild({+ jobId: 3, jobName: 'fixture', lockToken: 'fixture',+ invocation: { cmd: process.execPath, argsPrefix: [script] }, tiniPath: '',+ abortSignal: new AbortController().signal, shutdownSignal: shutdown.signal, killGraceMs: 20,+ signalProcessGroup: () => false, onExecutionStopped: () => { stopped = true; },+ }).catch((error: unknown) => error);+ await until(() => existsSync(pidFile));+ pid = Number(readFileSync(pidFile, 'utf8'));+ shutdown.abort(new LocalConfigurationError('postgres_cancellation_unavailable', 'fixture'));+ const error = await result;+ expect(error).toBeInstanceOf(ChildWorkerShutdownError);+ expect((error as ChildWorkerShutdownError).executionStopped).toBe(false);+ expect(stopped).toBe(false);+ expect(running(pid)).toBe(true);+ } finally {+ if (pid) { killProcessGroup(pid, 'SIGKILL'); await until(() => !running(pid)); }+ rmSync(dir, { recursive: true, force: true });+ }+});++test('normally exited oversized output retains its unrecoverable classification', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'job-oversize-completed-'));+ const script = join(dir, 'child.mjs');+ try {+ writeFileSync(script, `import {writeFileSync,truncateSync} from 'node:fs';+ writeFileSync(process.env.GBRAIN_JOB_RESULT_PATH,''); truncateSync(process.env.GBRAIN_JOB_RESULT_PATH,33*1024*1024);`);+ await expect(runJobInChild({+ jobId: 4, jobName: 'fixture', lockToken: 'fixture',+ invocation: { cmd: process.execPath, argsPrefix: [script] }, tiniPath: '',+ abortSignal: new AbortController().signal, shutdownSignal: new AbortController().signal,+ })).rejects.toBeInstanceOf(UnrecoverableError);+ } finally { rmSync(dir, { recursive: true, force: true }); }+});++for (const typedOutcome of [false, true]) {+ test.skipIf(process.platform !== 'linux' || process.getuid?.() === 0)(`final filesystem cleanup failure preserves shutdown provenance (typed outcome=${typedOutcome})`, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'job-final-cleanup-'));+ const ready = join(dir, 'ready');+ const script = join(dir, 'child.mjs');+ let pid = 0;+ let resultDir = '';+ let stopped = false;+ try {+ const outcome = typedOutcome+ ? { outcome: 'error', errorKind: 'local_configuration', protocolVersion: 1, reasonCode: 'postgres_cancellation_unavailable', message: 'fixture' }+ : { outcome: 'error', errorKind: 'generic', message: 'fixture' };+ writeFileSync(script, `import {writeFileSync,chmodSync} from 'node:fs'; import {dirname} from 'node:path';+ const dir=dirname(process.env.GBRAIN_JOB_RESULT_PATH);+ writeFileSync(process.env.GBRAIN_JOB_RESULT_PATH,${JSON.stringify(JSON.stringify(outcome))});+ chmodSync(dir,0o500); writeFileSync(${JSON.stringify(ready)},JSON.stringify({pid:process.pid,dir})); setInterval(()=>{},1000);`);+ const shutdown = new AbortController();+ const result = runJobInChild({+ jobId: 5, jobName: 'fixture', lockToken: 'fixture',+ invocation: { cmd: process.execPath, argsPrefix: [script] }, tiniPath: '',+ abortSignal: new AbortController().signal, shutdownSignal: shutdown.signal, killGraceMs: 20,+ signalProcessGroup: () => false, onExecutionStopped: () => { stopped = true; },+ }).catch((error: unknown) => error);+ await until(() => existsSync(ready));+ const record = JSON.parse(readFileSync(ready, 'utf8'));+ pid = record.pid;+ resultDir = record.dir;+ shutdown.abort(new LocalConfigurationError('postgres_cancellation_unavailable', 'fixture'));+ const error = await result;+ expect(error).toBeInstanceOf(typedOutcome ? LocalConfigurationError : ChildWorkerShutdownError);+ if (!typedOutcome) expect((error as ChildWorkerShutdownError).executionStopped).toBe(false);+ expect(stopped).toBe(false);+ expect(running(pid)).toBe(true);+ expect(existsSync(resultDir)).toBe(true);+ } finally {+ if (pid) { killProcessGroup(pid, 'SIGKILL'); await until(() => !running(pid)); }+ if (resultDir) { chmodSync(resultDir, 0o700); rmSync(resultDir, { recursive: true, force: true }); }+ rmSync(dir, { recursive: true, force: true });+ }+ });+}++test.skipIf(process.platform !== 'linux')('an unobserved wrapper child group never produces positive stop evidence', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'job-unknown-wrapper-group-'));+ const wrapper = join(dir, 'wrapper.mjs');+ let stopped = false;+ try {+ writeFileSync(wrapper, `#!${process.execPath}\nimport {writeFileSync} from 'node:fs';+ writeFileSync(process.env.GBRAIN_JOB_RESULT_PATH,JSON.stringify({outcome:'error',errorKind:'local_configuration',protocolVersion:1,reasonCode:'postgres_cancellation_unavailable',message:'fixture'}));`);+ chmodSync(wrapper, 0o700);+ const error = await runJobInChild({+ jobId: 6, jobName: 'fixture', lockToken: 'fixture',+ invocation: { cmd: process.execPath, argsPrefix: [] }, tiniPath: wrapper,+ abortSignal: new AbortController().signal, shutdownSignal: new AbortController().signal, killGraceMs: 20,+ onExecutionStopped: () => { stopped = true; },+ }).catch((error: unknown) => error);+ expect(error).toBeInstanceOf(LocalConfigurationError);+ expect(stopped).toBe(false);+ } finally { rmSync(dir, { recursive: true, force: true }); }+});++for (const liveGrandchild of [false, true]) {+ test.skipIf(process.platform !== 'linux')(`normal successful child exit publishes only supported cleanup evidence (live grandchild=${liveGrandchild})`, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'job-normal-stop-proof-'));+ const pidFile = join(dir, 'grandchild.pid');+ const script = join(dir, 'child.mjs');+ let pid = 0;+ let stopped = 0;+ try {+ writeFileSync(script, `import {writeFileSync} from 'node:fs'; import {spawn} from 'node:child_process';+ if (${liveGrandchild}) {+ const child=spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'ignore'});+ child.unref(); writeFileSync(${JSON.stringify(pidFile)},String(child.pid));+ }+ writeFileSync(process.env.GBRAIN_JOB_RESULT_PATH,JSON.stringify({outcome:'success',result:{ok:true}})); process.exit(0);`);+ const result = await runJobInChild({+ jobId: 7, jobName: 'fixture', lockToken: 'fixture',+ invocation: { cmd: process.execPath, argsPrefix: [script] }, tiniPath: '',+ abortSignal: new AbortController().signal, shutdownSignal: new AbortController().signal,+ onExecutionStopped: () => { stopped++; },+ });+ expect(result).toEqual({ ok: true });+ expect(stopped).toBe(liveGrandchild ? 0 : 1);+ if (liveGrandchild) {+ pid = Number(readFileSync(pidFile, 'utf8'));+ expect(running(pid)).toBe(true);+ }+ } finally {+ if (!pid && existsSync(pidFile)) pid = Number(readFileSync(pidFile, 'utf8'));+ if (pid) { try { process.kill(pid, 'SIGKILL'); } catch {} await until(() => !running(pid)); }+ rmSync(dir, { recursive: true, force: true });+ }+ });+}++for (const tiniPath of ['', tini].filter((value, index, all) => all.indexOf(value) === index)) {+ for (const kind of ['timeout', 'shutdown', 'configuration'] as const) {+ test.skipIf(process.platform !== 'linux')(`prompt SIGTERM exit settles without the full kill grace and publishes stop evidence (${tiniPath ? 'tini -s' : 'no tini'}, ${kind})`, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'job-prompt-settle-'));+ const ready = join(dir, 'ready');+ const script = join(dir, 'child.mjs');+ let stopped = 0;+ try {+ writeFileSync(script, `import {writeFileSync} from 'node:fs';+ process.on('SIGTERM',()=>process.exit(0)); writeFileSync(${JSON.stringify(ready)},'1'); setInterval(()=>{},1000);`);+ const abort = new AbortController();+ const shutdown = new AbortController();+ const result = runJobInChild({+ jobId: 8, jobName: 'fixture', lockToken: 'fixture',+ invocation: { cmd: process.execPath, argsPrefix: [script] }, tiniPath,+ abortSignal: abort.signal, shutdownSignal: shutdown.signal, killGraceMs: 5000,+ onExecutionStopped: () => { stopped++; },+ }).catch((error: unknown) => error);+ await until(() => existsSync(ready));+ const started = performance.now();+ if (kind === 'timeout') abort.abort(new Error('timeout'));+ else if (kind === 'shutdown') shutdown.abort(new Error('worker-shutdown'));+ else shutdown.abort(new LocalConfigurationError('postgres_cancellation_unavailable', 'fixture'));+ const error = await result;+ const settleMs = performance.now() - started;+ console.log(`[prompt-settle] tini=${tiniPath ? 'yes' : 'no'} kind=${kind} settleMs=${Math.round(settleMs)}`);+ expect(settleMs).toBeLessThan(1000);+ expect(stopped).toBe(1);+ if (kind === 'timeout') {+ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toMatch(/terminated after abort/);+ } else {+ expect(error).toBeInstanceOf(ChildWorkerShutdownError);+ expect((error as ChildWorkerShutdownError).executionStopped).toBe(true);+ }+ } finally { rmSync(dir, { recursive: true, force: true }); }+ }, 15_000);+ }+}++test.skipIf(process.platform !== 'linux')('SIGTERM-ignoring grandchild keeps the group SIGKILL at the grace deadline after a prompt direct exit', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'job-deadline-kill-'));+ const pidFile = join(dir, 'grandchild.pid');+ const ready = join(dir, 'ready');+ const parent = join(dir, 'parent.mjs');+ const grandchild = join(dir, 'grandchild.mjs');+ const graceMs = 1500;+ let pid = 0;+ let stopped = 0;+ const signals: Array<{ signal: string; at: number }> = [];+ try {+ writeFileSync(grandchild, `import {writeFileSync} from 'node:fs';+ process.on('SIGTERM',()=>{}); writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); setInterval(()=>{},1000);`);+ writeFileSync(parent, `import {spawn} from 'node:child_process'; import {existsSync,writeFileSync} from 'node:fs';+ process.on('SIGTERM',()=>process.exit(0));+ const child=spawn(process.execPath,[${JSON.stringify(grandchild)}],{stdio:'ignore'}); child.unref();+ while(!existsSync(${JSON.stringify(pidFile)})) await new Promise(r=>setTimeout(r,5));+ writeFileSync(${JSON.stringify(ready)},'1'); setInterval(()=>{},1000);`);+ const shutdown = new AbortController();+ const result = runJobInChild({+ jobId: 9, jobName: 'fixture', lockToken: 'fixture',+ invocation: { cmd: process.execPath, argsPrefix: [parent] }, tiniPath: '',+ abortSignal: new AbortController().signal, shutdownSignal: shutdown.signal, killGraceMs: graceMs,+ signalProcessGroup: (group, signal) => { signals.push({ signal, at: performance.now() }); return killProcessGroup(group, signal); },+ onExecutionStopped: () => { stopped++; },+ }).catch((error: unknown) => error);+ await until(() => existsSync(ready));+ pid = Number(readFileSync(pidFile, 'utf8'));+ const started = performance.now();+ shutdown.abort();+ await Bun.sleep(graceMs - 500);+ expect(running(pid)).toBe(true);+ expect(signals.map(entry => entry.signal)).toEqual(['SIGTERM']);+ const error = await result;+ const kill = signals.find(entry => entry.signal === 'SIGKILL');+ expect(kill).toBeDefined();+ expect(kill!.at - started).toBeGreaterThanOrEqual(graceMs - 50);+ expect(error).toBeInstanceOf(ChildWorkerShutdownError);+ expect((error as ChildWorkerShutdownError).executionStopped).toBe(true);+ expect(stopped).toBe(1);+ await until(() => !running(pid));+ } finally {+ if (!pid && existsSync(pidFile)) pid = Number(readFileSync(pidFile, 'utf8'));+ if (pid) { try { process.kill(pid, 'SIGKILL'); } catch {} await until(() => !running(pid)); }+ rmSync(dir, { recursive: true, force: true });+ }+}, 15_000);++test.skipIf(process.platform !== 'linux')('unsupported cleanup proof sends the group SIGKILL once the direct child exits and settles unconfirmed', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'job-unsupported-settle-'));+ const pidFile = join(dir, 'grandchild.pid');+ const ready = join(dir, 'ready');+ const wrapper = join(dir, 'exec-wrapper.sh');+ const parent = join(dir, 'parent.mjs');+ const grandchild = join(dir, 'grandchild.mjs');+ let pid = 0;+ let stopped = 0;+ const signals: string[] = [];+ const errors: string[] = [];+ const originalError = console.error;+ try {+ writeFileSync(wrapper, '#!/bin/sh\nshift 2\nexec "$@"\n');+ chmodSync(wrapper, 0o700);+ writeFileSync(grandchild, `import {writeFileSync} from 'node:fs';+ process.on('SIGTERM',()=>{}); writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); setInterval(()=>{},1000);`);+ writeFileSync(parent, `import {spawn} from 'node:child_process'; import {existsSync,writeFileSync} from 'node:fs';+ process.on('SIGTERM',()=>process.exit(0));+ const child=spawn(process.execPath,[${JSON.stringify(grandchild)}],{stdio:'ignore'}); child.unref();+ while(!existsSync(${JSON.stringify(pidFile)})) await new Promise(r=>setTimeout(r,5));+ writeFileSync(${JSON.stringify(ready)},'1'); setInterval(()=>{},1000);`);+ const shutdown = new AbortController();+ console.error = (...args: unknown[]) => { errors.push(args.map(String).join(' ')); };+ const result = runJobInChild({+ jobId: 10, jobName: 'fixture', lockToken: 'fixture',+ invocation: { cmd: process.execPath, argsPrefix: [parent] }, tiniPath: wrapper,+ abortSignal: new AbortController().signal, shutdownSignal: shutdown.signal, killGraceMs: 5000,+ signalProcessGroup: (group, signal) => { signals.push(signal); return killProcessGroup(group, signal); },+ onExecutionStopped: () => { stopped++; },+ }).catch((error: unknown) => error);+ await until(() => existsSync(ready));+ pid = Number(readFileSync(pidFile, 'utf8'));+ const started = performance.now();+ shutdown.abort(new LocalConfigurationError('postgres_cancellation_unavailable', 'fixture'));+ const error = await result;+ const settleMs = performance.now() - started;+ console.log(`[unsupported-settle] settleMs=${Math.round(settleMs)}`);+ expect(settleMs).toBeLessThan(1000);+ expect(signals).toEqual(['SIGTERM', 'SIGKILL']);+ expect(error).toBeInstanceOf(ChildWorkerShutdownError);+ expect((error as ChildWorkerShutdownError).executionStopped).toBe(false);+ expect(stopped).toBe(0);+ expect(errors.some(line => line.includes('execution stop is unconfirmed'))).toBe(true);+ await until(() => !running(pid));+ } finally {+ console.error = originalError;+ if (!pid && existsSync(pidFile)) pid = Number(readFileSync(pidFile, 'utf8'));+ if (pid) { try { process.kill(pid, 'SIGKILL'); } catch {} await until(() => !running(pid)); }+ rmSync(dir, { recursive: true, force: true });+ }+}, 15_000);diff --git a/test/child-job-runner.test.ts b/test/child-job-runner.test.tsindex 81a43e3786..9279882d5a 100644--- a/test/child-job-runner.test.ts+++ b/test/child-job-runner.test.ts@@ -27,6 +27,7 @@ import {} from '../src/core/minions/child-job-runner.ts';import { UnrecoverableError } from '../src/core/minions/types.ts';import { RateLeaseUnavailableError } from '../src/core/minions/handlers/subagent.ts';+import { LocalConfigurationError } from '../src/core/minions/configuration-error.ts';const TEST_TIMEOUT_MS = 30_000;@@ -184,12 +185,12 @@ describe('runJobInChild (real children)', () => {await expect(runJobInChild(opts)).rejects.toThrow(/terminated after abort/);}, TEST_TIMEOUT_MS);- test('spawn ENOENT → ChildSpawnInfraError (infra release, not a job defect)', async () => {+ test('spawn ENOENT → typed executable configuration failure', async () => {const opts = {...baseOpts('/nonexistent'),invocation: { cmd: '/nonexistent/gbrain-binary', argsPrefix: [] },};- await expect(runJobInChild(opts)).rejects.toBeInstanceOf(ChildSpawnInfraError);+ await expect(runJobInChild(opts)).rejects.toBeInstanceOf(LocalConfigurationError);}, TEST_TIMEOUT_MS);test('worker shutdown: child finishes + reports during the drain window → normal success', async () => {diff --git a/test/child-readiness.test.ts b/test/child-readiness.test.tsnew file mode 100644index 0000000000..b9e27f29d3--- /dev/null+++ b/test/child-readiness.test.ts@@ -0,0 +1,294 @@+import { describe, expect, test } from 'bun:test';+import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ checkChildReadiness, parseChildReadiness, CHILD_READINESS_FEATURES,+ CHILD_READINESS_MAX_BYTES, CHILD_READINESS_TIMEOUT_MS,+} from '../src/core/minions/child-readiness.ts';+import { isLocalConfigurationError, LocalConfigurationError } from '../src/core/minions/configuration-error.ts';+import { VERSION } from '../src/version.ts';+import { ChildSpawnInfraError, runJobInChild } from '../src/core/minions/child-job-runner.ts';+import { detectTini } from '../src/core/minions/spawn-helpers.ts';++const reply = {+ protocolVersion: 1, version: VERSION, features: [...CHILD_READINESS_FEATURES], status: 'ready',+};++async function fixture(body: string, run: (invocation: { cmd: string; argsPrefix: string[] }) => Promise<void>): Promise<void> {+ const dir = mkdtempSync(join(tmpdir(), 'child readiness '));+ const path = join(dir, 'selected child.mjs');+ try {+ writeFileSync(path, body);+ await run({ cmd: process.execPath, argsPrefix: [path] });+ } finally { rmSync(dir, { recursive: true, force: true }); }+}++describe('selected child readiness protocol', () => {+ test('defaults are bounded and compatible version skew is diagnostic', () => {+ expect(CHILD_READINESS_TIMEOUT_MS).toBe(20_000);+ expect(CHILD_READINESS_MAX_BYTES).toBe(64 * 1024);+ expect(parseChildReadiness(JSON.stringify(reply))).toEqual({ version: VERSION, versionSkew: false });+ expect(parseChildReadiness(JSON.stringify({ ...reply, version: '0.0.1' })))+ .toEqual({ version: '0.0.1', versionSkew: true });+ });++ test('completed malformed, missing-feature and wrong-major replies are permanent and redacted', () => {+ for (const raw of ['', 'null', 'postgres://private:[email protected]/db', '{}',+ JSON.stringify({ ...reply, protocolVersion: 999 }),+ JSON.stringify({ ...reply, features: ['unknown-feature'] }),+ JSON.stringify({ ...reply, status: 'configuration_error', reasonCode: 'unknown', message: 'password' }),+ JSON.stringify({ ...reply, version: 'postgres://private:[email protected]/db' }),+ JSON.stringify({ ...reply, version: '1.2.3-private-password' }),+ ]) {+ try { parseChildReadiness(raw); throw new Error('unexpected success'); }+ catch (error) {+ expect(error).toBeInstanceOf(LocalConfigurationError);+ expect((error as Error).message).not.toContain('password');+ expect((error as Error).message).not.toContain('GSTACK_EXAMPLE_NONCE');+ }+ }+ });++ test('only allowlisted typed replies assert capability faults; valid unreachable DB is transient', () => {+ try {+ parseChildReadiness(JSON.stringify({ ...reply, status: 'configuration_error', reasonCode: 'postgres_cancellation_unavailable' }));+ throw new Error('unexpected success');+ }+ catch (error) { expect((error as LocalConfigurationError).reasonCode).toBe('postgres_cancellation_unavailable'); }+ expect(() => parseChildReadiness(JSON.stringify({ ...reply, status: 'transient_error', message: 'password' })))+ .toThrow('transiently');+ try { parseChildReadiness(JSON.stringify({ ...reply, status: 'transient_error' })); }+ catch (error) { expect(isLocalConfigurationError(error)).toBe(false); }+ });++ test('invokes the actual selected path with spaces and hidden command', async () => {+ await fixture(`if (JSON.stringify(process.argv.slice(2)) !== JSON.stringify(['jobs','child-readiness','--json'])) process.exit(3);+ console.log(${JSON.stringify(JSON.stringify(reply))});`, async (invocation) => {+ expect(await checkChildReadiness({ invocation, tiniPath: '' })).toEqual({ version: VERSION, versionSkew: false });+ });+ });++ test('successful readiness followed by real typed bootstrap failure retains provenance and latches before cleanup', async () => {+ const moduleUrl = new URL('../src/core/minions/run-child.ts', import.meta.url).href;+ const errorUrl = new URL('../src/core/minions/configuration-error.ts', import.meta.url).href;+ await fixture(`+ if (process.argv.includes('child-readiness')) { console.log(${JSON.stringify(JSON.stringify(reply))}); process.exit(0); }+ const {writeChildBootstrapError} = await import(${JSON.stringify(moduleUrl)});+ const {LocalConfigurationError} = await import(${JSON.stringify(errorUrl)});+ const code = writeChildBootstrapError(process.env.GBRAIN_JOB_RESULT_PATH, new LocalConfigurationError('postgres_cancellation_unavailable','private-password'));+ process.exit(code);+ `, async (invocation) => {+ await checkChildReadiness({ invocation, tiniPath: '' });+ let latched = false;+ const started = Date.now();+ const result = runJobInChild({+ invocation, tiniPath: '', jobId: 1, jobName: 'fixture', lockToken: 'fixture',+ abortSignal: new AbortController().signal, shutdownSignal: new AbortController().signal,+ killGraceMs: 100,+ onConfigurationError: (error) => {+ expect(error.reasonCode).toBe('postgres_cancellation_unavailable');+ latched = true;+ },+ });+ await expect(result).rejects.toBeInstanceOf(LocalConfigurationError);+ expect(latched).toBe(true);+ expect(Date.now() - started).toBeGreaterThanOrEqual(100);+ });+ });++ test('ordinary bootstrap failure preserves the original exit-one crash classification without an outcome', async () => {+ const moduleUrl = new URL('../src/core/minions/run-child.ts', import.meta.url).href;+ await fixture(`+ const {writeChildBootstrapError} = await import(${JSON.stringify(moduleUrl)});+ const {existsSync} = await import('node:fs');+ const code = writeChildBootstrapError(process.env.GBRAIN_JOB_RESULT_PATH, new Error('temporary connection failure'));+ if (existsSync(process.env.GBRAIN_JOB_RESULT_PATH)) process.exit(99);+ process.exit(code);+ `, async (invocation) => {+ const error = await runJobInChild({+ invocation, tiniPath: '', jobId: 1, jobName: 'fixture', lockToken: 'fixture',+ abortSignal: new AbortController().signal, shutdownSignal: new AbortController().signal,+ }).then(() => null, (error: unknown) => error);+ expect(error).toBeInstanceOf(Error);+ expect(error).not.toBeInstanceOf(ChildSpawnInfraError);+ expect(isLocalConfigurationError(error)).toBe(false);+ expect((error as Error).message).toContain('exit code=1');+ });+ });++ test('completed malformed child blocks without leaking either stream', async () => {+ await fixture(`console.error('postgres://private:[email protected]/db'); console.log('invalid password');`, async (invocation) => {+ try { await checkChildReadiness({ invocation, tiniPath: '' }); throw new Error('unexpected success'); }+ catch (error) {+ expect(error).toBeInstanceOf(LocalConfigurationError);+ expect((error as Error).message).not.toContain('password');+ expect((error as Error).message).not.toContain('GSTACK_EXAMPLE_NONCE');+ }+ });+ });++ test('combined output flood terminates unfinished child transiently without echoing credentials', async () => {+ await fixture(`process.stdout.write('x'.repeat(40000)); process.stderr.write('password'.repeat(5000)); setInterval(()=>{},1000);`, async (invocation) => {+ const start = Date.now();+ try { await checkChildReadiness({ invocation, tiniPath: '', timeoutMs: 2000 }); throw new Error('unexpected success'); }+ catch (error) {+ expect(isLocalConfigurationError(error)).toBe(false);+ expect((error as Error).message).toContain('combined output limit');+ expect((error as Error).message).not.toContain('password');+ expect((error as Error).message).not.toContain('GSTACK_EXAMPLE_NONCE');+ }+ expect(Date.now() - start).toBeLessThan(2000);+ });+ });++ test('timeout, killed and interrupted children remain transient', async () => {+ for (const body of [`setInterval(()=>{},1000)`, `process.kill(process.pid, 'SIGKILL')`, `process.exit(137)`]) {+ await fixture(body, async (invocation) => {+ for (const tiniPath of [...new Set(['', detectTini()])]) {+ const error = await checkChildReadiness({ invocation, tiniPath, timeoutMs: 100 }).then(() => null, (error: unknown) => error);+ expect(error).toBeInstanceOf(Error);+ expect(isLocalConfigurationError(error)).toBe(false);+ }+ });+ }+ await fixture(`setInterval(()=>{},1000)`, async (invocation) => {+ const abort = new AbortController();+ abort.abort();+ await expect(checkChildReadiness({ invocation, tiniPath: '', signal: abort.signal })).rejects.toThrow('interrupted');+ });+ });++ test('timeout stops the selected process and reaps its invocation before settling, including beneath tini', async () => {+ for (const tiniPath of [...new Set(['', detectTini()])]) {+ await fixture(`import {writeFileSync} from 'node:fs';+ writeFileSync(process.argv[1]+'.pid',String(process.pid));+ setInterval(()=>{},1000);`, async (invocation) => {+ await expect(checkChildReadiness({ invocation, tiniPath, timeoutMs: 500 })).rejects.toThrow('timed out');+ const pid = Number(readFileSync(invocation.argsPrefix[0] + '.pid', 'utf8'));+ try {+ process.kill(pid, 0);+ if (process.platform !== 'linux') throw new Error('Selected child is still alive');+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');+ expect(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[0]).toBe('Z');+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ESRCH' && (error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ });+ }+ });++ test('ENOENT and EACCES are executable faults without exposing arbitrary paths', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'readiness-executable-'));+ try {+ const denied = join(dir, 'private-password');+ writeFileSync(denied, '#!/bin/sh\nexit 0');+ chmodSync(denied, 0o600);+ for (const cmd of [join(dir, 'missing-password'), denied]) {+ for (const tiniPath of [...new Set(['', detectTini()])]) {+ try { await checkChildReadiness({ invocation: { cmd, argsPrefix: [] }, tiniPath }); throw new Error('unexpected success'); }+ catch (error) {+ expect((error as LocalConfigurationError).reasonCode).toBe('child_executable_invalid');+ expect((error as Error).message).not.toContain('password');+ expect((error as Error).message).not.toContain('GSTACK_EXAMPLE_NONCE');+ }+ let stopped = 0;+ const error = await runJobInChild({+ invocation: { cmd, argsPrefix: [] }, tiniPath, jobId: 1, jobName: 'fixture', lockToken: 'fixture',+ abortSignal: new AbortController().signal, shutdownSignal: new AbortController().signal,+ onExecutionStopped: () => { stopped++; },+ }).then(() => null, (error: unknown) => error);+ expect((error as LocalConfigurationError).reasonCode).toBe('child_executable_invalid');+ expect((error as Error).message).not.toContain('password');+ expect((error as Error).message).not.toContain('GSTACK_EXAMPLE_NONCE');+ expect(stopped).toBe(1);+ }+ }+ } finally { rmSync(dir, { recursive: true, force: true }); }+ });++ test('PATH executable lookup preserves compatible child selection beneath tini', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'readiness path '));+ const executable = join(dir, 'selected-example');+ try {+ writeFileSync(executable, `#!/bin/sh\nprintf '%s\\n' '${JSON.stringify(reply)}'\n`);+ chmodSync(executable, 0o700);+ expect(await checkChildReadiness({+ invocation: { cmd: 'selected-example', argsPrefix: [] }, tiniPath: detectTini(), env: { PATH: dir },+ })).toEqual({ version: VERSION, versionSkew: false });+ } finally { rmSync(dir, { recursive: true, force: true }); }+ });++ test('job executable permissions are rechecked after successful selected-child readiness', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'readiness-permission-change-'));+ const executable = join(dir, 'selected-example');+ try {+ writeFileSync(executable, `#!/bin/sh\nprintf '%s\\n' '${JSON.stringify(reply)}'\n`);+ chmodSync(executable, 0o700);+ await checkChildReadiness({ invocation: { cmd: executable, argsPrefix: [] }, tiniPath: detectTini() });+ chmodSync(executable, 0o600);+ const error = await runJobInChild({+ invocation: { cmd: executable, argsPrefix: [] }, tiniPath: detectTini(), jobId: 1, jobName: 'fixture', lockToken: 'fixture',+ abortSignal: new AbortController().signal, shutdownSignal: new AbortController().signal,+ }).then(() => null, (error: unknown) => error);+ expect((error as LocalConfigurationError).reasonCode).toBe('child_executable_invalid');+ } finally { rmSync(dir, { recursive: true, force: true }); }+ });++ test('exit 126 and 127 alone do not assert native executable failure', async () => {+ for (const code of [126, 127]) {+ await fixture(`process.exit(${code});`, async (invocation) => {+ const error = await runJobInChild({+ invocation, tiniPath: detectTini(), jobId: 1, jobName: 'fixture', lockToken: 'fixture',+ abortSignal: new AbortController().signal, shutdownSignal: new AbortController().signal,+ }).then(() => null, (error: unknown) => error);+ expect(error).toBeInstanceOf(Error);+ expect(isLocalConfigurationError(error)).toBe(false);+ expect((error as Error).message).toContain(`exit code=${code}`);+ });+ }+ });++ test('native executable failures racing prevalidation remain typed behind a wrapper', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'child-exec-race-'));+ const executable = join(dir, 'selected-example');+ const wrapper = join(dir, 'wrapper');+ try {+ for (const action of ['/bin/chmod 600', '/bin/rm -f']) {+ writeFileSync(wrapper, `#!/bin/sh\n${action} "$3"\nshift 2\nexec "$@"\n`);+ chmodSync(wrapper, 0o700);+ for (const mode of ['readiness', 'job']) {+ writeFileSync(executable, '#!/bin/sh\nexit 0\n');+ chmodSync(executable, 0o700);+ const invocation = { cmd: executable, argsPrefix: [] };+ const pending = mode === 'readiness'+ ? checkChildReadiness({ invocation, tiniPath: wrapper })+ : runJobInChild({+ invocation, tiniPath: wrapper, jobId: 1, jobName: 'fixture', lockToken: 'fixture',+ abortSignal: new AbortController().signal, shutdownSignal: new AbortController().signal,+ killGraceMs: 20,+ });+ const error = await pending.then(() => null, (error: unknown) => error);+ expect((error as LocalConfigurationError).reasonCode).toBe('child_executable_invalid');+ }+ }+ } finally { rmSync(dir, { recursive: true, force: true }); }+ });++ test('native exec failure with no child PID publishes no-execution evidence once', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'child-native-exec-failure-'));+ const executable = join(dir, 'selected-example');+ let stopped = 0;+ try {+ writeFileSync(executable, `#!${join(dir, 'missing-interpreter')}\n`);+ chmodSync(executable, 0o700);+ const error = await runJobInChild({+ invocation: { cmd: executable, argsPrefix: [] }, tiniPath: '', jobId: 1, jobName: 'fixture', lockToken: 'fixture',+ abortSignal: new AbortController().signal, shutdownSignal: new AbortController().signal,+ onExecutionStopped: () => { stopped++; },+ }).then(() => null, (error: unknown) => error);+ expect((error as LocalConfigurationError).reasonCode).toBe('child_executable_invalid');+ expect(stopped).toBe(1);+ } finally { rmSync(dir, { recursive: true, force: true }); }+ });+});diff --git a/test/child-worker-supervisor.test.ts b/test/child-worker-supervisor.test.tsindex e071df8693..c5c2a9a91f 100644--- a/test/child-worker-supervisor.test.ts+++ b/test/child-worker-supervisor.test.ts@@ -32,6 +32,7 @@ import {type ChildSupervisorEvent,} from '../src/core/minions/child-worker-supervisor.ts';import { withEnv } from './helpers/with-env.ts';+import { detectTini } from '../src/core/minions/spawn-helpers.ts';/*** Per-test bun timeout for the spawn-driving tests. Generous because each test@@ -835,7 +836,7 @@ describe('ChildWorkerSupervisor', () => {};}- it('settles the run loop instead of hanging, and counts each failure as a crash', async () => {+ it('settles the run loop instead of hanging, and counts each failure as a crash', async () => withEnv({ PATH: '' }, async () => {const h = makeUnlaunchableHarness('enoent');const { events, maxCrashesFired } = await runUntilTerminal(h, {maxCrashes: 2,@@ -874,6 +875,17 @@ describe('ChildWorkerSupervisor', () => {);expect(backoffs.length).toBeGreaterThanOrEqual(1);expect(backoffs.every((b) => b.reason === 'crash')).toBe(true);+ }), TEST_TIMEOUT_MS);++ it.skipIf(!detectTini())('bounds a missing executable behind tini at the same hard ceiling', async () => {+ const { events, maxCrashesFired } = await runUntilTerminal(makeUnlaunchableHarness('tini-enoent'), {+ maxCrashes: 2, hardStopMaxCrashes: 3, _backoffFloorMs: 1,+ });+ expect(maxCrashesFired).toEqual({ count: 3, max: 3 });+ const exits = events.filter((e): e is Extract<ChildSupervisorEvent, { kind: 'worker_exited' }> => e.kind === 'worker_exited');+ expect(exits).toHaveLength(3);+ expect(exits.map(e => e.crashCount)).toEqual([1, 2, 3]);+ expect(exits.every(e => e.code === 127)).toBe(true);}, TEST_TIMEOUT_MS);it('honours isStopping so a shutdown mid-failure does not keep respawning', async () => {diff --git a/test/cli-flag-validation.test.ts b/test/cli-flag-validation.test.tsindex 3bba6b6a99..9b1f19f013 100644--- a/test/cli-flag-validation.test.ts+++ b/test/cli-flag-validation.test.ts@@ -226,6 +226,16 @@ describe('#2185 red-team regressions', () => {// the gate must not strip real consumers.expect(CLI_FLAG_REGISTRY['backfill']).toContain('--dry-run');});++ test('the internal run-child argv builder does not legalise its flags for importers', () => {+ // autopilot imports job-isolation.ts only to resolve the child CLI; the+ // module's `jobs run-child --job-id N [--allow-shell-jobs]` literals are+ // the worker-to-child argv, not autopilot flags.+ expect(validateCommandFlags('autopilot', ['--status', '--allow-shell-jobs'])).toBe('--allow-shell-jobs');+ expect(validateCommandFlags('autopilot', ['--status', '--job-id', '1'])).toBe('--job-id');+ expect(validateCommandFlags('jobs', ['work', '--allow-shell-jobs'])).toBeNull();+ expect(validateCommandFlags('jobs', ['run-child', '--job-id', '1', '--allow-shell-jobs'])).toBeNull();+ });});describe('#2185 drift + freshness guards', () => {diff --git a/test/db-probe-configuration.test.ts b/test/db-probe-configuration.test.tsnew file mode 100644index 0000000000..d1abe48a7f--- /dev/null+++ b/test/db-probe-configuration.test.ts@@ -0,0 +1,102 @@+import { describe, expect, test } from 'bun:test';+import { runDbProbe, runDbReadinessProbe, assertWorkerDbReadiness } from '../src/core/minions/db-probe.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { LocalConfigurationError, isLocalConfigurationError } from '../src/core/minions/configuration-error.ts';++const budgets = { timeoutMs: 20, directTimeoutMs: 20 };+const fault = new LocalConfigurationError('postgres_cancellation_unavailable', 'Repair the driver, then restart.');+const success = async () => {};+const fail = (error: unknown) => async () => { throw error; };++describe('typed database configuration faults', () => {+ for (const probe of [runDbProbe, runDbReadinessProbe]) {+ for (const other of [new Error('ECONNREFUSED'), new DOMException('aborted', 'AbortError')]) {+ test(`${probe.name}: typed read fault precedes ${other.name} on direct`, async () => {+ const result = await probe({ ...budgets, probeRead: fail(fault), probeDirect: fail(other) });+ expect(result).toEqual({ ok: false, verdict: 'client_misconfigured', detail: fault.message, configurationError: fault });+ });+ test(`${probe.name}: typed direct fault precedes ${other.name} on read`, async () => {+ const result = await probe({ ...budgets, probeRead: fail(other), probeDirect: fail(fault) });+ expect(result).toEqual({ ok: false, verdict: 'client_misconfigured', detail: fault.message, configurationError: fault });+ });+ }+ test(`${probe.name}: typed fault needs no direct lane`, async () => {+ const result = await probe({ ...budgets, probeRead: fail(fault) });+ expect(result.ok === false && result.verdict).toBe('client_misconfigured');+ });+ test(`${probe.name}: matching text and structural impostors remain transient`, async () => {+ for (const error of [new Error(fault.message), { name: fault.name, reasonCode: fault.reasonCode, message: fault.message }]) {+ expect(isLocalConfigurationError(error)).toBe(false);+ const result = await probe({ ...budgets, probeRead: fail(error), probeDirect: fail(error) });+ expect(result.ok === false && result.verdict).toBe('server_unreachable');+ }+ });+ test(`${probe.name}: exhausted budgets abort both lanes without a permanent verdict`, async () => {+ const signals: AbortSignal[] = [];+ const hang = (signal: AbortSignal) => { signals.push(signal); return new Promise<void>(() => {}); };+ const result = await probe({ ...budgets, probeRead: hang, probeDirect: hang });+ expect(result.ok === false && result.verdict).toBe('server_unreachable');+ expect(signals.length).toBe(2);+ expect(signals.every(signal => signal.aborted)).toBe(true);+ });+ test(`${probe.name}: a typed direct fault takes precedence over a read timeout`, async () => {+ const result = await probe({+ ...budgets,+ probeRead: () => new Promise<void>(() => {}),+ probeDirect: fail(fault),+ });+ expect(result.ok === false && result.verdict).toBe('client_misconfigured');+ });+ }++ test('startup validates direct lane even with a healthy read pool', async () => {+ expect(await runDbProbe({ ...budgets, probeRead: success, probeDirect: fail(fault) })).toEqual({ ok: true });+ const result = await runDbReadinessProbe({ ...budgets, probeRead: success, probeDirect: fail(fault) });+ expect(result.ok === false && result.verdict).toBe('client_misconfigured');+ expect(await runDbReadinessProbe({ ...budgets, probeRead: success, probeDirect: success })).toEqual({ ok: true });+ });++ test('startup direct-only network fault is unknown, not a server outage', async () => {+ const result = await runDbReadinessProbe({ ...budgets, probeRead: success, probeDirect: fail(new Error('ECONNREFUSED')) });+ expect(result.ok === false && result.verdict).toBe('unknown');+ });++ test('single-lane healthy readiness requires no invented direct capability', async () => {+ expect(await runDbReadinessProbe({ ...budgets, probeRead: success })).toEqual({ ok: true });+ });++ test('engine adapter skips PGLite and probes both actual Postgres lanes', async () => {+ await assertWorkerDbReadiness({ kind: 'pglite' } as BrainEngine);+ const lanes: string[] = [];+ const engine = {+ kind: 'postgres',+ connectionManager: { isDualPoolActive: () => true },+ executeRaw: async (_sql: string, _params: unknown[], opts: { signal: AbortSignal }) => { expect(opts.signal).toBeInstanceOf(AbortSignal); lanes.push('read'); },+ executeRawDirect: async () => { lanes.push('direct'); throw fault; },+ } as unknown as BrainEngine;+ await expect(assertWorkerDbReadiness(engine)).rejects.toBe(fault);+ expect(lanes).toEqual(['read', 'direct']);+ });++ test('engine adapter does not duplicate a collapsed direct lane', async () => {+ let direct = false;+ await assertWorkerDbReadiness({+ kind: 'postgres',+ connectionManager: { isDualPoolActive: () => false },+ executeRaw: success,+ executeRawDirect: async () => { direct = true; },+ } as unknown as BrainEngine);+ expect(direct).toBe(false);+ });++ test('transient diagnostics redact connection credentials on both lanes', async () => {+ const result = await runDbReadinessProbe({+ ...budgets,+ probeRead: fail(new Error('postgresql://fixture:GSTACK_EXAMPLE_NONCE@localhost/test')),+ probeDirect: fail(new Error('password=other-private-value')),+ });+ expect(JSON.stringify(result)).not.toContain('private-value');+ expect(JSON.stringify(result)).not.toContain('GSTACK_EXAMPLE_NONCE');+ expect(result.ok === false && result.verdict).toBe('server_unreachable');+ });+});diff --git a/test/doctor-postgres-cancellation-driver.test.ts b/test/doctor-postgres-cancellation-driver.test.tsnew file mode 100644index 0000000000..c439b788ff--- /dev/null+++ b/test/doctor-postgres-cancellation-driver.test.ts@@ -0,0 +1,45 @@+import { describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { checkPostgresCancellationDriver } from '../src/commands/doctor/checks/postgres-cancellation.ts';++type Owner = { discard?: () => void; release(): void };+const engine = (reserve: () => Promise<Owner>) => ({ kind: 'postgres', sql: { reserve } }) as unknown as BrainEngine;++describe('doctor Postgres cancellation driver check', () => {+ test('stock driver fails with stable reason and actionable repair', async () => {+ let releases = 0;+ const result = await checkPostgresCancellationDriver(engine(async () => ({ release: () => { releases++; } })));+ expect(result?.status).toBe('fail');+ expect(result?.details?.reason_code).toBe('postgres_cancellation_unavailable');+ expect(result?.message).toContain('restart');+ expect(releases).toBe(1);+ });++ test('supported driver passes and releases the inspected owner', async () => {+ let releases = 0;+ const result = await checkPostgresCancellationDriver(engine(async () => ({ discard() {}, release: () => { releases++; } })));+ expect(result?.status).toBe('ok');+ expect(releases).toBe(1);+ });++ test('connection errors warn without disclosing the driver error', async () => {+ const result = await checkPostgresCancellationDriver(engine(async () => { throw new Error('postgres://fixture:GSTACK_EXAMPLE_NONCE@localhost/db'); }));+ expect(result?.status).toBe('warn');+ expect(JSON.stringify(result)).not.toContain('GSTACK_EXAMPLE_NONCE');+ });++ test('reservation timeout is transient and a late connection is released', async () => {+ let resolve!: (owner: Owner) => void;+ let releases = 0;+ const result = await checkPostgresCancellationDriver(engine(() => new Promise(done => { resolve = done; })), { timeoutMs: 10 });+ expect(result?.status).toBe('warn');+ resolve({ release: () => { releases++; } });+ await Promise.resolve();+ await Promise.resolve();+ expect(releases).toBe(1);+ });++ test('PGLite requires no driver inspection', async () => {+ expect(await checkPostgresCancellationDriver({ kind: 'pglite' } as BrainEngine)).toBeNull();+ });+});diff --git a/test/e2e/fixtures/worker-configuration-child.ts b/test/e2e/fixtures/worker-configuration-child.tsnew file mode 100644index 0000000000..1fa12a2426--- /dev/null+++ b/test/e2e/fixtures/worker-configuration-child.ts@@ -0,0 +1,61 @@+import { appendFileSync } from 'node:fs';+import { spawn } from 'node:child_process';+import { loadConfig } from '../../../src/core/config.ts';+import { PostgresEngine } from '../../../src/core/postgres-engine.ts';+import { LocalConfigurationError } from '../../../src/core/minions/configuration-error.ts';+import { runChildReadinessEntry } from '../../../src/core/minions/child-readiness.ts';+import { assertWorkerDbReadiness } from '../../../src/core/minions/db-probe.ts';+import { CHILD_ENV } from '../../../src/core/minions/job-isolation.ts';+import { runChildJobEntry } from '../../../src/core/minions/run-child.ts';+import { assertSafeE2eDatabaseUrl } from '../../helpers/db-guard.ts';++const databaseUrl = loadConfig()?.database_url;+if (!databaseUrl) throw new Error('The isolated configuration fixture requires a test database');+assertSafeE2eDatabaseUrl(databaseUrl);+const trace = process.env.GBRAIN_TEST_CHILD_TRACE;+const queueName = process.env.GBRAIN_TEST_CHILD_QUEUE;+if (!trace || !queueName) throw new Error('The isolated configuration fixture requires its trace and queue');+const engine = new PostgresEngine();+await engine.connect({ database_url: databaseUrl, poolSize: 1 });+let code: number;+try {+ if (process.argv.includes('child-readiness')) {+ code = await runChildReadinessEntry(engine, assertWorkerDbReadiness);+ const jobs = await engine.executeRaw<{ id: number; status: string; attempts_started: number }>(+ 'SELECT id, status, attempts_started FROM minion_jobs WHERE queue = $1 ORDER BY id', [queueName],+ );+ appendFileSync(trace, JSON.stringify({ kind: 'readiness', code, pid: process.pid, jobs }) + '\n');+ } else {+ const jobId = Number(process.argv[process.argv.indexOf('--job-id') + 1]);+ code = await runChildJobEntry(engine, {+ jobId,+ lockToken: process.env[CHILD_ENV.lockToken]!,+ resultPath: process.env[CHILD_ENV.resultPath]!,+ parentPid: Number(process.env[CHILD_ENV.parentPid]),+ }, {+ resolveHandler: name => name === 'orphans' ? async context => {+ let descendantPid: number | undefined;+ if (process.env.GBRAIN_TEST_CHILD_MODE === 'success-with-live-descendant') {+ const descendant = spawn(process.execPath, ['--no-env-file', '-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' });+ await new Promise<void>((resolve, reject) => {+ descendant.once('spawn', resolve);+ descendant.once('error', reject);+ });+ descendantPid = descendant.pid;+ descendant.unref();+ }+ appendFileSync(trace, JSON.stringify({+ kind: 'handler', id: context.id, pid: process.pid,+ parentPid: Number(process.env[CHILD_ENV.parentPid]),+ lockToken: process.env[CHILD_ENV.lockToken],+ ...(descendantPid ? { descendantPid } : {}),+ }) + '\n');+ if (descendantPid) return { fixtureSuccess: true };+ throw new LocalConfigurationError('postgres_cancellation_unavailable', 'Isolated handler fixture cancellation fault');+ } : undefined,+ });+ }+} finally {+ await engine.disconnect();+}+process.exit(code);diff --git a/test/e2e/migrate-chain.test.ts b/test/e2e/migrate-chain.test.tsindex c3b9a3cfb2..974a690f98 100644--- a/test/e2e/migrate-chain.test.ts+++ b/test/e2e/migrate-chain.test.ts@@ -17,7 +17,7 @@*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';-import postgres from 'postgres';+import postgres from '#postgres'import {hasDatabase,setupDB,diff --git a/test/e2e/persistence-chaos.test.ts b/test/e2e/persistence-chaos.test.tsindex d2302d5072..7924672f12 100644--- a/test/e2e/persistence-chaos.test.ts+++ b/test/e2e/persistence-chaos.test.ts@@ -5,7 +5,7 @@ import { createRequire } from 'node:module';import { randomUUID } from 'node:crypto';import { createServer as createTlsServer } from 'node:tls';import { readFileSync } from 'node:fs';-import postgres from 'postgres';+import postgres from '#postgres'import { PostgresEngine } from '../../src/core/postgres-engine.ts';import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';import { waitFor } from '../helpers/wait-for.ts';@@ -344,7 +344,7 @@ describe.skipIf(!url)('Postgres cancellation ownership', () => {expect(await ctx.engine.executeRaw('SELECT 42 AS answer')).toEqual([{ answer: 42 }]);}), 30000);- const drivers = { esm: postgres, commonjs: createRequire(import.meta.url)('../../node_modules/postgres/cjs/src/index.js') as typeof postgres };+ const drivers = { esm: postgres, commonjs: createRequire(import.meta.url)('#postgres') as typeof postgres };for (const [name, driver] of Object.entries(drivers)) {test(`${name} releasing a lease during pool shutdown cannot grant its waiter`, async () => {assertSafeE2eDatabaseUrl(url!);diff --git a/test/e2e/persistence-phase-liveness.test.ts b/test/e2e/persistence-phase-liveness.test.tsindex f808f1f145..deafd4972e 100644--- a/test/e2e/persistence-phase-liveness.test.ts+++ b/test/e2e/persistence-phase-liveness.test.ts@@ -13,7 +13,7 @@ import { PersistenceConsumer } from '../../src/core/persistence/consumer.ts';import { disposePersistenceConsumer, startPersistenceConsumer, waitForWrite } from '../../src/core/persistence/service.ts';import { sha256 } from '../../src/core/persistence/digest.ts';import { PostgresEngine } from '../../src/core/postgres-engine.ts';-import postgres from 'postgres';+import postgres from '#postgres'const url = process.env.DATABASE_URL;describe.skipIf(!url)('PostgreSQL persistence phase cancellation', () => {@@ -37,10 +37,20 @@ describe.skipIf(!url)('PostgreSQL persistence phase cancellation', () => {let cancellation: unknown;let stopping: Promise<void> | undefined;let consumer: PersistenceConsumer;+ const reserve = engine.sql.reserve.bind(engine.sql);+ engine.sql.reserve = async (options) => {+ const owner = await reserve(options);+ const unsafe = owner.unsafe.bind(owner);+ owner.unsafe = ((...args: Parameters<typeof owner.unsafe>) => {+ const pending = unsafe(...args);+ queueMicrotask(() => { stopping = consumer.stop(); });+ return pending;+ }) as typeof owner.unsafe;+ return owner;+ };const proxy = new Proxy(engine, { get(target, key) {if (key === 'executeRaw') return (...args: Parameters<typeof engine.executeRaw>) => {const work = target.executeRaw(...args);- if (args[2]?.signal) queueMicrotask(() => { stopping = consumer.stop(); });return work.catch(error => { cancellation = error; throw error; });};const value = Reflect.get(target, key);@@ -57,6 +67,34 @@ describe.skipIf(!url)('PostgreSQL persistence phase cancellation', () => {} finally { await consumer.stop(); }}), 30000);+ test('stopping during reservation recognizes an earlier abort without reporting a storage failure', () => fixture(async ({ engine }, config) => {+ await engine.executeRaw('SELECT 1');+ const errors: unknown[] = [];+ let cancellation: unknown;+ let stopping: Promise<void> | undefined;+ let consumer: PersistenceConsumer;+ const reserve = engine.sql.reserve.bind(engine.sql);+ engine.sql.reserve = async (options) => {+ queueMicrotask(() => { stopping = consumer.stop(); });+ return reserve(options);+ };+ const proxy = new Proxy(engine, { get(target, key) {+ if (key === 'executeRaw') return (...args: Parameters<typeof engine.executeRaw>) =>+ target.executeRaw(...args).catch(error => { cancellation = error; throw error; });+ const value = Reflect.get(target, key);+ return typeof value === 'function' ? value.bind(target) : value;+ } });+ consumer = new PersistenceConsumer(proxy, { engine: 'postgres' }, async () => { throw new Error('unexpected preparation'); },+ { hostId: config.hostId, onError: error => errors.push(error) });+ try {+ await consumer.tick(); await stopping;+ expect(cancellation).toMatchObject({ name: 'AbortError' });+ expect(errors).toEqual([]);+ expect(consumer.status().last_error).toBeUndefined();+ expect(await engine.executeRaw('SELECT 42 AS answer')).toEqual([{ answer: 42 }]);+ } finally { await consumer.stop(); }+ }), 30000);+test('a slow PostgreSQL receipt read cannot hide an independently committed request', () => fixture(async ({ engine }, config) => {const sources = await fixtures(engine, config);const first = await admitWrite(engine, admission(config, sources[0], 'slow-receipt', 'first body'));diff --git a/test/e2e/pgbouncer-teardown.test.ts b/test/e2e/pgbouncer-teardown.test.tsindex efbadae90c..2b8bf14333 100644--- a/test/e2e/pgbouncer-teardown.test.ts+++ b/test/e2e/pgbouncer-teardown.test.ts@@ -28,7 +28,7 @@ import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';import { join, resolve } from 'path';import { tmpdir } from 'os';-import postgres from 'postgres';+import postgres from '#postgres'import { PostgresEngine } from '../../src/core/postgres-engine.ts';import { keylessBrainEnv } from '../helpers/provider-env.ts';import { fixtureDiagnostic } from '../helpers/fixture-diagnostics.ts';diff --git a/test/e2e/postgres-driver-install.test.ts b/test/e2e/postgres-driver-install.test.tsnew file mode 100644index 0000000000..dca47f146e--- /dev/null+++ b/test/e2e/postgres-driver-install.test.ts@@ -0,0 +1,84 @@+import { test, expect } from 'bun:test';+import { mkdtemp, mkdir, rm, readFile } from 'node:fs/promises';+import { join, resolve } from 'node:path';+import { tmpdir } from 'node:os';+import { keylessBrainEnv } from '../helpers/provider-env.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';++const enabled = process.env.GBRAIN_TEST_PACKAGE_SMOKE === '1' && !!process.env.DATABASE_URL;++test.skipIf(!enabled)('packed, global, upgraded and compiled distributions use vendored cancellation bytes and complete a harmless job', async () => {+ const root = resolve(import.meta.dir, '../..');+ const scratch = await mkdtemp(join(tmpdir(), 'gbrain-driver-package-'));+ const url = process.env.DATABASE_URL!;+ assertSafeE2eDatabaseUrl(url);+ const started = performance.now();+ const env = keylessBrainEnv(process.env, join(scratch, 'home'), {+ DATABASE_URL: url,+ GBRAIN_DATABASE_URL: undefined,+ GBRAIN_DIRECT_DATABASE_URL: undefined,+ GBRAIN_SKIP_STARTUP_HOOKS: '1',+ BUN_INSTALL: join(scratch, 'bun'),+ BUN_INSTALL_CACHE_DIR: join(scratch, 'cache'),+ });+ const run = async (args: string[], cwd: string) => {+ const child = Bun.spawn(args, { cwd, env, stdout: 'pipe', stderr: 'pipe' });+ const timer = setTimeout(() => child.kill('SIGKILL'), 180_000);+ try {+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);+ expect(code, `${args[1]} failed: ${stderr.slice(-3000)}`).toBe(0);+ return stdout;+ } finally { clearTimeout(timer); }+ };+ try {+ await mkdir(env.HOME, { recursive: true });+ const packed = join(scratch, 'gbrain.tgz');+ await run([process.execPath, 'pm', 'pack', '--ignore-scripts', '--quiet', '--filename', packed], root);+ const install = join(scratch, 'install');+ await mkdir(install);+ await run([process.execPath, 'add', '--ignore-scripts', packed], install);+ const installed = join(install, 'node_modules/gbrain');+ expect(await readFile(join(installed, 'vendor/postgres/src/index.js'), 'utf8')).toBe(await readFile(join(root, 'vendor/postgres/src/index.js'), 'utf8'));+ expect(JSON.parse(await readFile(join(installed, 'package.json'), 'utf8')).dependencies.postgres).toBeUndefined();+ for (const [mode, cwd] of [['checkout', root], ['packed', installed]]) {+ const output = await run([process.execPath, '--no-env-file', 'test/fixtures/postgres-package-smoke.ts'], cwd);+ expect(output).toContain('"job_status":"completed"');+ console.log(`${mode}: ${output.trim()}`);+ }+ const globalPackage = process.env.GBRAIN_TEST_GITHUB_PACKAGE ?? packed;+ await run([process.execPath, 'add', '--ignore-scripts', '--global', globalPackage], install);+ const globalRoot = join(env.BUN_INSTALL, 'install/global/node_modules/gbrain');+ const globalOutput = await run([process.execPath, '--no-env-file', 'test/fixtures/postgres-package-smoke.ts'], globalRoot);+ expect(globalOutput).toContain('"job_status":"completed"');+ console.log(`${process.env.GBRAIN_TEST_GITHUB_PACKAGE ? 'github-global' : 'tarball-global'}: ${globalOutput.trim()}`);+ await run([process.execPath, 'add', '--ignore-scripts', '[email protected]'], install);+ expect(await run([process.execPath, '--no-env-file', '-e', `+ import assert from 'node:assert/strict';+ import stock from '../postgres/src/index.js';+ import { PostgresEngine } from './src/core/postgres-engine.ts';+ import { assertWorkerDbReadiness } from './src/core/minions/db-probe.ts';+ import { isLocalConfigurationError } from './src/core/minions/configuration-error.ts';+ const sql = stock(process.env.DATABASE_URL, { max: 1 });+ const engine = new PostgresEngine();+ Object.defineProperty(engine, '_sql', { value: sql });+ try {+ assert.equal((await engine.executeRaw('SELECT 1::int AS n'))[0].n, 1);+ await assert.rejects(assertWorkerDbReadiness(engine), isLocalConfigurationError);+ console.log('STOCK_DRIVER_REJECTED');+ } finally { await sql.end({ timeout: 1 }); }+ `], installed)).toContain('STOCK_DRIVER_REJECTED');+ const staleOutput = await run([process.execPath, '--no-env-file', 'test/fixtures/postgres-package-smoke.ts'], installed);+ expect(staleOutput).toContain('"job_status":"completed"');+ console.log(`stale-module: ${staleOutput.trim()}`);+ const binary = join(scratch, 'smoke-linux');+ await run([process.execPath, 'build', '--compile', '--no-compile-autoload-bunfig', '--outfile', binary, 'test/fixtures/postgres-package-smoke.ts'], root);+ const compiledOutput = await run([binary], scratch);+ expect(compiledOutput).toContain('"job_status":"completed"');+ console.log(`linux-compiled: ${compiledOutput.trim()}`);+ const macBinary = join(scratch, 'smoke-darwin-arm64');+ await run([process.execPath, 'build', '--compile', '--no-compile-autoload-bunfig', '--target=bun-darwin-arm64', '--outfile', macBinary, 'test/fixtures/postgres-package-smoke.ts'], root);+ expect((await readFile(macBinary)).readUInt32LE(0)).toBe(0xfeedfacf);+ console.log('darwin-arm64: cross-compiled; native execution not available on this Linux host');+ console.log(`Distribution smoke including setup: ${Math.round(performance.now() - started)}ms`);+ } finally { await rm(scratch, { recursive: true, force: true }); }+}, 600_000);diff --git a/test/e2e/projection-statistics-postgres.test.ts b/test/e2e/projection-statistics-postgres.test.tsindex 89d7b53a4e..b056124321 100644--- a/test/e2e/projection-statistics-postgres.test.ts+++ b/test/e2e/projection-statistics-postgres.test.ts@@ -1,6 +1,6 @@import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';-import postgres from 'postgres';+import postgres from '#postgres'import type { BrainEngine } from '../../src/core/engine.ts';import { currentTextProjectionFilter } from '../../src/core/search/safe-chunks.ts';import { PROJECTION_STATISTICS_SQL, verifyProjectionStatistics } from '../../src/core/search/projection-statistics.ts';diff --git a/test/e2e/reconcile-pgbouncer.test.ts b/test/e2e/reconcile-pgbouncer.test.tsindex 0aecaa7b9f..3d78155db7 100644--- a/test/e2e/reconcile-pgbouncer.test.ts+++ b/test/e2e/reconcile-pgbouncer.test.ts@@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto';import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import postgres from 'postgres';+import postgres from '#postgres'import { PostgresEngine } from '../../src/core/postgres-engine.ts';import { importFromContent } from '../../src/core/import-file.ts';import { parseMarkdown, serializePageToMarkdown } from '../../src/core/markdown.ts';diff --git a/test/e2e/serve-http-oauth.test.ts b/test/e2e/serve-http-oauth.test.tsindex a82ec2cfd4..04c76bd9f3 100644--- a/test/e2e/serve-http-oauth.test.ts+++ b/test/e2e/serve-http-oauth.test.ts@@ -228,7 +228,7 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {}async function withSql<T>(fn: (sql: any) => Promise<T>): Promise<T> {- const postgres = (await import('postgres')).default;+ const postgres = (await import('#postgres')).default;const sql = postgres(process.env.GBRAIN_DATABASE_URL || process.env.DATABASE_URL || '', { prepare: false });try {return await fn(sql);@@ -268,7 +268,7 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {] as const) {test(`MCP enforces the ${label} persisted resource audience`, async () => {const { access_token } = await mintToken('read');- const { default: postgres } = await import('postgres');+ const { default: postgres } = await import('#postgres');const sql = postgres(process.env.GBRAIN_DATABASE_URL || process.env.DATABASE_URL!, { max: 1 });try {await sql`UPDATE oauth_tokens SET resource = ${resource}@@ -873,7 +873,7 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {const publicToken = `gbrain_at_public_${Date.now()}`;const tokenHash = createHash('sha256').update(publicToken).digest('hex');- const postgres = (await import('postgres')).default;+ const postgres = (await import('#postgres')).default;const sql = postgres(process.env.GBRAIN_DATABASE_URL || process.env.DATABASE_URL || '', { prepare: false });try {// Plain-array bind, NOT `sql.array([...])`: sql.array resolves its@@ -914,7 +914,7 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {const suffix = Date.now().toString();const functionName = `e2e_fail_revoke_${suffix}`;const triggerName = `e2e_fail_revoke_trigger_${suffix}`;- const postgres = (await import('postgres')).default;+ const postgres = (await import('#postgres')).default;const sql = postgres(process.env.GBRAIN_DATABASE_URL || process.env.DATABASE_URL || '', { prepare: false });try {await sql.unsafe(`@@ -1129,7 +1129,7 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {// and the row never appears.test('v0.26.3: /mcp request persists agent_name + params + error_message', async () => {- const postgres = (await import('postgres')).default;+ const postgres = (await import('#postgres')).default;const sql = postgres(process.env.GBRAIN_DATABASE_URL || process.env.DATABASE_URL || '', { prepare: false });try {// Wipe any prior log rows for our test client so we can assert exact counts.@@ -1240,7 +1240,7 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {// mints a token, and asserts the response's expires_in matches.test('v0.26.3: per-client token_ttl is honored on token mint', async () => {- const postgres = (await import('postgres')).default;+ const postgres = (await import('#postgres')).default;const sql = postgres(process.env.GBRAIN_DATABASE_URL || process.env.DATABASE_URL || '', { prepare: false });try {// Register a client + set a custom token_ttl (24 hours = 86400 seconds).@@ -1351,7 +1351,7 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {// auth lanes (oauth client + legacy api key).test('v0.26.3: agent_name resolves correctly for OAuth + legacy paths', async () => {- const postgres = (await import('postgres')).default;+ const postgres = (await import('#postgres')).default;const sql = postgres(process.env.GBRAIN_DATABASE_URL || process.env.DATABASE_URL || '', { prepare: false });try {// Make an OAuth-authenticated request — agent_name should be the OAuth client_name.diff --git a/test/e2e/source-boundary-mutation-postgres.test.ts b/test/e2e/source-boundary-mutation-postgres.test.tsindex 0742f6cbf0..ae3fc4dc97 100644--- a/test/e2e/source-boundary-mutation-postgres.test.ts+++ b/test/e2e/source-boundary-mutation-postgres.test.ts@@ -16,7 +16,7 @@*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';-import postgres, { type Sql } from 'postgres';+import postgres, { type Sql } from '#postgres'import { hasDatabase, setupDB, teardownDB, getEngine } from './helpers.ts';const describePg = hasDatabase() ? describe : describe.skip;diff --git a/test/e2e/sync-lock-overlap-postgres.test.ts b/test/e2e/sync-lock-overlap-postgres.test.tsindex 74bf7ef8da..927e5e3fa7 100644--- a/test/e2e/sync-lock-overlap-postgres.test.ts+++ b/test/e2e/sync-lock-overlap-postgres.test.ts@@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test';import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';import { hostname, tmpdir } from 'node:os';import { join, resolve } from 'node:path';-import postgres from 'postgres';+import postgres from '#postgres'import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';import { makeGitFixture } from '../helpers/git-fixture.ts';diff --git a/test/e2e/sync-sigkill-resume-postgres.test.ts b/test/e2e/sync-sigkill-resume-postgres.test.tsindex 6ae2335c99..95f1722af0 100644--- a/test/e2e/sync-sigkill-resume-postgres.test.ts+++ b/test/e2e/sync-sigkill-resume-postgres.test.ts@@ -47,7 +47,7 @@ import { createHash, randomUUID } from 'node:crypto';import { join } from 'path';import { execSync } from 'child_process';import { tmpdir, hostname } from 'os';-import postgres from 'postgres';+import postgres from '#postgres'import { PostgresEngine } from '../../src/core/postgres-engine.ts';import { loadOpCheckpoint, syncFingerprint } from '../../src/core/op-checkpoint.ts';import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';diff --git a/test/e2e/worker-configuration-release.test.ts b/test/e2e/worker-configuration-release.test.tsnew file mode 100644index 0000000000..38bc60c525--- /dev/null+++ b/test/e2e/worker-configuration-release.test.ts@@ -0,0 +1,201 @@+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { hasDatabase, setupDB, teardownDB, getEngine } from './helpers.ts';+import { MinionQueue } from '../../src/core/minions/queue.ts';+import { MinionWorker } from '../../src/core/minions/worker.ts';+import { LocalConfigurationError } from '../../src/core/minions/configuration-error.ts';+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { runCli } from '../helpers/cli-spawn.ts';+import { withEnv } from '../helpers/with-env.ts';+import { checkChildReadiness } from '../../src/core/minions/child-readiness.ts';+import { killProcessGroup } from '../../src/core/minions/job-isolation.ts';++const describeDb = hasDatabase() ? describe : describe.skip;+let queue: MinionQueue;++beforeAll(async () => {+ if (!hasDatabase()) return;+ await setupDB();+ queue = new MinionQueue(getEngine());+});++afterAll(async () => {+ if (hasDatabase()) await teardownDB();+});++describeDb('Postgres worker configuration release', () => {+ test('owned release preserves both counters and stale or terminal releases no-op', async () => {+ for (const terminal of [null, 'cancelled', 'completed'] as const) {+ const job = await queue.add('fixture-release', {});+ const token = `fixture-token-${job.id}`;+ await queue.claim(token, 30_000, 'default', ['fixture-release']);+ await getEngine().executeRaw('UPDATE minion_jobs SET stalled_counter = 2 WHERE id = $1', [job.id]);+ if (terminal) await getEngine().executeRaw('UPDATE minion_jobs SET status = $1 WHERE id = $2', [terminal, job.id]);+ const before = await queue.getJob(job.id);+ expect(await queue.releaseConfigurationJob(job.id, 'stale-token', new AbortController().signal)).toBe('no_op');+ expect(await queue.releaseConfigurationJob(job.id, token, new AbortController().signal)).toBe(terminal ? 'no_op' : 'released');+ const after = await queue.getJob(job.id);+ expect(after?.attempts_made).toBe(before?.attempts_made);+ expect(after?.stalled_counter).toBe(2);+ expect(after?.status).toBe(terminal ?? 'delayed');+ if (!terminal) {+ expect(after?.lock_token).toBeNull();+ expect(after?.lock_until).toBeNull();+ expect(after?.delay_until!.getTime()).toBeGreaterThan(Date.now());+ }+ expect(await queue.releaseConfigurationJob(job.id, token, new AbortController().signal)).toBe('no_op');+ }+ });++ test('runtime typed fault stops admission and preserves the real claimed row', async () => {+ const first = await queue.add('fixture-fault', {}, { max_attempts: 1 });+ const second = await queue.add('fixture-fault', {});+ const worker = new MinionWorker(getEngine(), { pollInterval: 5, healthCheckInterval: 0 });+ worker.register('fixture-fault', async () => {+ throw new LocalConfigurationError('postgres_cancellation_unavailable', 'Fixture driver fault');+ });+ await worker.start();+ expect(worker.configurationError?.reasonCode).toBe('postgres_cancellation_unavailable');+ expect((await queue.getJob(first.id))?.status).toBe('delayed');+ expect((await queue.getJob(first.id))?.attempts_made).toBe(0);+ expect((await queue.getJob(first.id))?.stalled_counter).toBe(0);+ expect((await queue.getJob(second.id))?.status).toBe('waiting');+ expect(worker.configurationReleaseResults.map(result => result.outcome)).toEqual(['released']);+ });++ test.skipIf(process.platform !== 'linux')('real child readiness and typed handler fault compose through CLI exit and confirmed release', async () => {+ const home = mkdtempSync(join(tmpdir(), 'worker-configuration-journey-'));+ const queueName = `configuration-journey-${process.pid}`;+ const tracePath = join(home, 'child-events.jsonl');+ const launcher = join(home, 'selected-child');+ const fixture = resolve(import.meta.dir, 'fixtures/worker-configuration-child.ts');+ const first = await queue.add('orphans', {}, { queue: queueName, max_attempts: 1 });+ const second = await queue.add('orphans', {}, { queue: queueName });+ try {+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain/config.json'), JSON.stringify({ engine: 'postgres', database_url: process.env.DATABASE_URL }));+ const quoted = [process.execPath, '--no-env-file', fixture].map(value => `'${value.replaceAll("'", "'\\''")}'`).join(' ');+ writeFileSync(launcher, `#!/bin/sh\nexec ${quoted} "$@"\n`);+ chmodSync(launcher, 0o700);+ const result = await runCli(['jobs', 'work', '--queue', queueName, '--concurrency', '1', '--job-isolation', 'process', '--health-interval', '0', '--max-rss', '0'], {+ home,+ timeoutMs: 45_000,+ env: {+ GBRAIN_JOB_CHILD_CLI: launcher,+ GBRAIN_TEST_CHILD_TRACE: tracePath,+ GBRAIN_TEST_CHILD_QUEUE: queueName,+ GBRAIN_TEST_CHILD_MODE: undefined,+ ANTHROPIC_API_KEY: undefined,+ OPENAI_API_KEY: undefined,+ },+ });+ const diagnostic = `${result.stdout}\n${result.stderr}`;+ expect(result.exitCode, diagnostic).toBe(16);+ expect(result.stderr).toContain('configuration blocked (postgres_cancellation_unavailable)');+ expect(result.stderr).toContain('Configuration shutdown settled 1 claim(s); 0 release(s) unconfirmed.');+ const events = readFileSync(tracePath, 'utf8').trim().split('\n').map(line => JSON.parse(line));+ expect(events.map(event => event.kind)).toEqual(['readiness', 'handler']);+ expect(events[0].code).toBe(0);+ expect(events[0].jobs).toEqual([+ { id: first.id, status: 'waiting', attempts_started: 0 },+ { id: second.id, status: 'waiting', attempts_started: 0 },+ ]);+ expect(events[1].id).toBe(first.id);+ expect(events[1].pid).not.toBe(events[1].parentPid);+ expect(events[1].parentPid).toBeGreaterThan(1);+ expect(() => process.kill(events[1].pid, 0)).toThrow();+ const released = await queue.getJob(first.id);+ expect(released?.status).toBe('delayed');+ expect(released?.attempts_made).toBe(0);+ expect(released?.stalled_counter).toBe(0);+ expect(released?.lock_token).toBeNull();+ expect(released?.lock_until).toBeNull();+ expect(released?.delay_until!.getTime()).toBeGreaterThan(Date.now());+ expect((await queue.getJob(second.id))?.status).toBe('waiting');+ expect((await queue.getJob(second.id))?.attempts_started).toBe(0);+ expect(await queue.releaseConfigurationJob(first.id, events[1].lockToken, new AbortController().signal)).toBe('no_op');+ } finally {+ await queue.removeJob(first.id);+ await queue.removeJob(second.id);+ rmSync(home, { recursive: true, force: true });+ }+ }, 50_000);++ test.skipIf(process.platform !== 'linux')('completion-recording failure never releases an isolated handler with a live descendant', async () => {+ const home = mkdtempSync(join(tmpdir(), 'worker-configuration-recording-'));+ const queueName = `configuration-recording-${process.pid}`;+ const tracePath = join(home, 'child-events.jsonl');+ const fixture = resolve(import.meta.dir, 'fixtures/worker-configuration-child.ts');+ const invocation = { cmd: process.execPath, argsPrefix: ['--no-env-file', fixture] };+ const job = await queue.add('orphans', {}, { queue: queueName, max_attempts: 1 });+ const worker = new MinionWorker(getEngine(), {+ queue: queueName, concurrency: 1, pollInterval: 5, healthCheckInterval: 0,+ jobIsolation: 'process', childCliInvocation: invocation, childTiniPath: '',+ });+ let childGroup: number | undefined;+ let descendant: number | undefined;+ let completionCalls = 0;+ let liveAtRecordingFailure = false;+ worker.register('orphans', async () => { throw new Error('The parent must not run the isolated fixture handler'); });+ (worker as unknown as { queue: MinionQueue }).queue.completeJob = async () => {+ completionCalls++;+ const event = readFileSync(tracePath, 'utf8').trim().split('\n').map(line => JSON.parse(line)).find(event => event.kind === 'handler');+ childGroup = event.pid;+ descendant = event.descendantPid;+ process.kill(descendant!, 0);+ liveAtRecordingFailure = true;+ throw new LocalConfigurationError('postgres_cancellation_unavailable', 'Fixture completion recording fault');+ };+ try {+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain/config.json'), JSON.stringify({ engine: 'postgres', database_url: process.env.DATABASE_URL }));+ await withEnv({+ HOME: home, GBRAIN_HOME: home,+ GBRAIN_TEST_CHILD_TRACE: tracePath,+ GBRAIN_TEST_CHILD_QUEUE: queueName,+ GBRAIN_TEST_CHILD_MODE: 'success-with-live-descendant',+ ANTHROPIC_API_KEY: undefined, OPENAI_API_KEY: undefined,+ }, async () => {+ await checkChildReadiness({ invocation, tiniPath: '' });+ await worker.start();+ });+ expect(completionCalls).toBe(1);+ expect(liveAtRecordingFailure).toBe(true);+ expect(() => process.kill(descendant!, 0)).not.toThrow();+ expect(worker.configurationError?.reasonCode).toBe('postgres_cancellation_unavailable');+ expect(worker.configurationReleaseResults.map(result => result.outcome)).toEqual(['unconfirmed']);+ const unchanged = await queue.getJob(job.id);+ expect(unchanged?.status).toBe('active');+ expect(unchanged?.attempts_made).toBe(0);+ expect(unchanged?.stalled_counter).toBe(0);+ expect(unchanged?.lock_token).not.toBeNull();+ } finally {+ worker.stop();+ if (!childGroup) {+ try {+ const event = readFileSync(tracePath, 'utf8').trim().split('\n').map(line => JSON.parse(line)).find(event => event.kind === 'handler');+ childGroup = event?.pid;+ descendant = event?.descendantPid;+ } catch {}+ }+ if (childGroup) killProcessGroup(childGroup, 'SIGKILL');+ if (descendant) {+ let running = true;+ for (let attempt = 0; attempt < 40 && running; attempt++) {+ try {+ const stat = readFileSync(`/proc/${descendant}/stat`, 'utf8');+ running = !['Z', 'X'].includes(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[0]);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ running = false;+ }+ if (running) await new Promise(resolve => setTimeout(resolve, 25));+ }+ expect(running).toBe(false);+ }+ await queue.removeJob(job.id);+ rmSync(home, { recursive: true, force: true });+ }+ }, 45_000);+});diff --git a/test/e2e/worker-readiness-cli.test.ts b/test/e2e/worker-readiness-cli.test.tsnew file mode 100644index 0000000000..0c1fa51e7e--- /dev/null+++ b/test/e2e/worker-readiness-cli.test.ts@@ -0,0 +1,132 @@+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { chmodSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { MinionQueue } from '../../src/core/minions/queue.ts';+import { runCli } from '../helpers/cli-spawn.ts';+import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';++const describeDatabase = hasDatabase() ? describe : describe.skip;++describeDatabase('worker CLI admission against Postgres', () => {+ beforeAll(async () => { await setupDB(); });+ afterAll(async () => { await teardownDB(); });++ test('an incompatible selected child blocks before any waiting job is claimed', async () => {+ const home = mkdtempSync(join(tmpdir(), 'worker-readiness-cli-'));+ const queue = new MinionQueue(getEngine());+ const queueName = `readiness-${process.pid}`;+ const job = await queue.add('shell', { cmd: 'printf readiness-fixture', cwd: home }, { queue: queueName }, { allowProtectedSubmit: true });+ try {+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({+ engine: 'postgres',+ database_url: process.env.DATABASE_URL,+ }));+ const child = join(home, 'incompatible-child');+ writeFileSync(child, '#!/bin/sh\nprintf \'%s\\n\' \'{"protocolVersion":999,"version":"0.1.0.0","features":[],"status":"ready"}\'\n');+ chmodSync(child, 0o700);+ const result = await runCli(['jobs', 'work', '--queue', queueName, '--job-isolation', 'process', '--allow-shell-jobs', '--health-interval', '0', '--max-rss', '0'], {+ home,+ timeoutMs: 25_000,+ env: { GBRAIN_JOB_CHILD_CLI: child },+ });+ expect(result.exitCode).toBe(16);+ expect(result.stderr).toContain('child_protocol_incompatible');+ expect(result.stderr).toContain('Repair');+ const unchanged = await queue.getJob(job.id);+ expect(unchanged?.status).toBe('waiting');+ expect(unchanged?.attempts_made).toBe(0);+ expect(unchanged?.stalled_counter).toBe(0);+ expect(unchanged?.started_at).toBeNull();+ } finally {+ await queue.removeJob(job.id);+ rmSync(home, { recursive: true, force: true });+ }+ });++ test('the selected current CLI passes readiness and completes a harmless isolated job', async () => {+ const home = mkdtempSync(join(tmpdir(), 'worker-ready-cli-'));+ const queue = new MinionQueue(getEngine());+ const queueName = `ready-${process.pid}`;+ const job = await queue.add('shell', { cmd: 'printf ready-fixture', cwd: home }, { queue: queueName }, { allowProtectedSubmit: true });+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({+ engine: 'postgres', database_url: process.env.DATABASE_URL,+ }));+ const env: Record<string, string | undefined> = { ...process.env, HOME: home, GBRAIN_HOME: home, GBRAIN_SKIP_STARTUP_HOOKS: '1' };+ for (const key of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_JOB_CHILD_CLI', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY']) delete env[key];+ const child = Bun.spawn({+ cmd: [process.execPath, '--no-env-file', resolve(import.meta.dir, '../../src/cli.ts'), 'jobs', 'work', '--queue', queueName, '--job-isolation', 'process', '--allow-shell-jobs', '--max-rss', '0', '--health-interval', '0'],+ env,+ stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',+ });+ const stdout = new Response(child.stdout).text();+ const stderr = new Response(child.stderr).text();+ const deadline = setTimeout(() => child.kill('SIGKILL'), 25_000);+ try {+ const until = Date.now() + 15_000;+ let current = await queue.getJob(job.id);+ while (Date.now() < until && current?.status !== 'completed' && child.exitCode === null) {+ await Bun.sleep(50);+ current = await queue.getJob(job.id);+ }+ child.kill('SIGTERM');+ await child.exited;+ const diagnostic = `${await stdout}\n${await stderr}`;+ expect(current?.status, diagnostic).toBe('completed');+ expect(current?.attempts_made).toBe(0);+ expect(current?.stalled_counter).toBe(0);+ expect(current?.result?.stdout_tail).toBe('ready-fixture');+ expect(child.exitCode, diagnostic).toBe(143);+ } finally {+ if (child.exitCode === null) child.kill('SIGKILL');+ await child.exited;+ clearTimeout(deadline);+ await queue.removeJob(job.id);+ rmSync(home, { recursive: true, force: true });+ }+ }, 30_000);++ test('a legacy supervised worker without a status channel is admitted and completes a job', async () => {+ const home = mkdtempSync(join(tmpdir(), 'worker-legacy-owner-'));+ const queue = new MinionQueue(getEngine());+ const queueName = `legacy-owner-${process.pid}`;+ const job = await queue.add('shell', { cmd: 'printf legacy-owner-fixture', cwd: home }, { queue: queueName }, { allowProtectedSubmit: true });+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({+ engine: 'postgres', database_url: process.env.DATABASE_URL,+ }));+ const env: Record<string, string | undefined> = { ...process.env, HOME: home, GBRAIN_HOME: home, GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SUPERVISED: '1' };+ for (const key of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_JOB_CHILD_CLI', 'GBRAIN_WORKER_STATUS_PATH', 'GBRAIN_WORKER_STATUS_TOKEN', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY']) delete env[key];+ const child = Bun.spawn({+ cmd: [process.execPath, '--no-env-file', resolve(import.meta.dir, '../../src/cli.ts'), 'jobs', 'work', '--queue', queueName, '--allow-shell-jobs', '--max-rss', '0', '--health-interval', '0'],+ env,+ stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',+ });+ const stdout = new Response(child.stdout).text();+ const stderr = new Response(child.stderr).text();+ const deadline = setTimeout(() => child.kill('SIGKILL'), 25_000);+ try {+ const until = Date.now() + 15_000;+ let current = await queue.getJob(job.id);+ while (Date.now() < until && current?.status !== 'completed' && child.exitCode === null) {+ await Bun.sleep(50);+ current = await queue.getJob(job.id);+ }+ child.kill('SIGTERM');+ await child.exited;+ const diagnostic = `${await stdout}\n${await stderr}`;+ expect(diagnostic).not.toContain('could not be published');+ expect(current?.status, diagnostic).toBe('completed');+ expect(current?.result?.stdout_tail).toBe('legacy-owner-fixture');+ expect(child.exitCode, diagnostic).toBe(143);+ } finally {+ if (child.exitCode === null) child.kill('SIGKILL');+ await child.exited;+ clearTimeout(deadline);+ await queue.removeJob(job.id);+ rmSync(home, { recursive: true, force: true });+ }+ }, 30_000);+});diff --git a/test/env-trust.test.ts b/test/env-trust.test.tsindex e426cfd65a..809dccb347 100644--- a/test/env-trust.test.ts+++ b/test/env-trust.test.ts@@ -86,6 +86,7 @@ describe('CWD_DOTENV_PROTECTED_KEYS', () => {'GBRAIN_GUARDRAILS_MODULE', 'GBRAIN_PLUGIN_PATH','GBRAIN_CLAUDE_CLI_BIN', 'GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG', 'GBRAIN_JOB_CHILD_CLI', 'GBRAIN_BIN_OVERRIDE','GBRAIN_HOME', 'GBRAIN_MOUNTS_PATH',+ 'GBRAIN_WORKER_STATUS_PATH', 'GBRAIN_WORKER_STATUS_TOKEN','GBRAIN_ALLOW_SHELL_JOBS', 'GBRAIN_ALLOW_PRIVATE_REMOTES', 'GBRAIN_ALLOW_UNVERIFIED_REMOTE','GBRAIN_GIT_ALLOW_FILE_TRANSPORT', 'GBRAIN_ALLOW_MASS_RECONCILE', 'GBRAIN_ALLOW_DEFAULT_WRITE','GBRAIN_NO_SANITY', 'GBRAIN_REMOTE_PRIVATE_PAGES',diff --git a/test/fixtures/child-configuration-handler.ts b/test/fixtures/child-configuration-handler.tsnew file mode 100644index 0000000000..e3dd247cf8--- /dev/null+++ b/test/fixtures/child-configuration-handler.ts@@ -0,0 +1,27 @@+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { MinionQueue } from '../../src/core/minions/queue.ts';+import { runChildReadinessEntry } from '../../src/core/minions/child-readiness.ts';+import { assertWorkerDbReadiness } from '../../src/core/minions/db-probe.ts';+import { runChildJobEntry } from '../../src/core/minions/run-child.ts';+import { LocalConfigurationError } from '../../src/core/minions/configuration-error.ts';++const engine = new PGLiteEngine();+await engine.connect({ database_url: '' });+let code = 1;+try {+ if (process.argv.includes('child-readiness')) {+ code = await runChildReadinessEntry(engine, assertWorkerDbReadiness);+ } else {+ await engine.initSchema();+ const queue = new MinionQueue(engine);+ const token = process.env.GBRAIN_JOB_LOCK_TOKEN!;+ const job = await queue.add('sync', {});+ await queue.claim(token, 30_000, 'default', ['sync']);+ code = await runChildJobEntry(engine, {+ jobId: job.id, lockToken: token, resultPath: process.env.GBRAIN_JOB_RESULT_PATH!, parentPid: 0,+ }, {+ resolveHandler: () => async () => { throw new LocalConfigurationError('postgres_cancellation_unavailable', 'fixture capability failure'); },+ });+ }+} finally { await engine.disconnect(); }+process.exit(code);diff --git a/test/fixtures/postgres-package-smoke.ts b/test/fixtures/postgres-package-smoke.tsnew file mode 100644index 0000000000..9a4c392c0a--- /dev/null+++ b/test/fixtures/postgres-package-smoke.ts@@ -0,0 +1,59 @@+import assert from 'node:assert/strict';+import { randomUUID } from 'node:crypto';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { MinionQueue } from '../../src/core/minions/queue.ts';+import { MinionWorker } from '../../src/core/minions/worker.ts';+import { assertWorkerDbReadiness } from '../../src/core/minions/db-probe.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import postgres from '#postgres';+import pkg from '../../package.json';+import driverPackage from '../../vendor/postgres/package.json';++const url = process.env.DATABASE_URL;+assert(url, 'An explicit disposable DATABASE_URL is required');+assertSafeE2eDatabaseUrl(url);+const started = performance.now();+const engine = new PostgresEngine();+await engine.connect({ database_url: url, poolSize: 2 });+let worker: MinionWorker | undefined;+let running: Promise<void> | undefined;+try {+ await assertWorkerDbReadiness(engine);+ const readinessMs = performance.now() - started;+ const controller = new AbortController();+ const cancelling = engine.executeRaw('SELECT pg_sleep(10)', [], { signal: controller.signal });+ const timer = setTimeout(() => controller.abort(), 50);+ try {+ await assert.rejects(cancelling);+ } finally { clearTimeout(timer); }+ assert.equal((await engine.executeRaw<{ n: number }>('SELECT 42::int AS n', [], { signal: new AbortController().signal }))[0]?.n, 42);+ await engine.initSchema();+ const queueName = `driver-smoke-${randomUUID()}`;+ const queue = new MinionQueue(engine);+ await queue.ensureSchema();+ const job = await queue.add('driver-smoke', {}, { queue: queueName });+ worker = new MinionWorker(engine, { queue: queueName, concurrency: 1, pollInterval: 10, maxRssMb: 0, jobIsolation: 'inline' });+ let handled = 0;+ worker.register('driver-smoke', async () => { handled++; return { smoke: true }; });+ running = worker.start();+ const deadline = performance.now() + 20_000;+ let completed = await queue.getJob(job.id);+ while (completed?.status !== 'completed' && performance.now() < deadline) {+ await Bun.sleep(20);+ completed = await queue.getJob(job.id);+ }+ assert.equal(completed?.status, 'completed');+ assert.equal(handled, 1);+ assert.equal(completed?.stalled_counter, 0);+ const driver = postgres(url, { max: 1 });+ try {+ const owner = await driver.reserve();+ assert.equal(typeof owner.discard, 'function');+ owner.release();+ } finally { await driver.end({ timeout: 1 }); }+ console.log(JSON.stringify({ ok: true, gbrain_version: pkg.version, driver_version: driverPackage.version, runtime: Bun.version, platform: `${process.platform}-${process.arch}`, readiness_ms: readinessMs, total_ms: performance.now() - started, job_status: completed.status, handled, attempts_made: completed.attempts_made, stall_count: completed.stalled_counter }));+} finally {+ worker?.stop();+ await running;+ await engine.disconnect();+}diff --git a/test/fixtures/reconcile-crash-worker.ts b/test/fixtures/reconcile-crash-worker.tsindex 15e6d51c98..2e1236d5f0 100644--- a/test/fixtures/reconcile-crash-worker.ts+++ b/test/fixtures/reconcile-crash-worker.ts@@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto';import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, writeSync } from 'node:fs';import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';-import postgres from 'postgres';+import postgres from '#postgres'import { CRASH_BOUNDARIES, childEnvironment } from '../../scripts/persistence/validate.ts';import { assertConservation } from '../../scripts/persistence/harness.ts';import { configDir, type GBrainConfig } from '../../src/core/config.ts';diff --git a/test/helpers/persistence-postgres.ts b/test/helpers/persistence-postgres.tsindex 9b366aa121..8cdb14686b 100644--- a/test/helpers/persistence-postgres.ts+++ b/test/helpers/persistence-postgres.ts@@ -1,4 +1,4 @@-import postgres from 'postgres';+import postgres from '#postgres'import { randomUUID } from 'node:crypto';import { PostgresEngine } from '../../src/core/postgres-engine.ts';import { assertSafeE2eDatabaseUrl } from './db-guard.ts';diff --git a/test/job-isolation-protocol.test.ts b/test/job-isolation-protocol.test.tsindex d53999c315..e54bd91f31 100644--- a/test/job-isolation-protocol.test.ts+++ b/test/job-isolation-protocol.test.ts@@ -28,7 +28,9 @@ import {resolveChildCliInvocation,writeChildOutcomeFile,type ChildOutcome,+ parseChildOutcome,} from '../src/core/minions/job-isolation.ts';+import { LocalConfigurationError, isLocalConfigurationError } from '../src/core/minions/configuration-error.ts';import { UnrecoverableError } from '../src/core/minions/types.ts';import { RateLeaseUnavailableError } from '../src/core/minions/handlers/subagent.ts';@@ -107,6 +109,31 @@ describe('outcome file round-trip', () => {});describe('handler-error encode → reconstruct (instanceof parity with inline mode)', () => {+ test('versioned typed configuration outcome roundtrips without disclosing error text', () => {+ const encoded = encodeHandlerError(new LocalConfigurationError('postgres_cancellation_unavailable', 'postgres://private:[email protected]/db'));+ const raw = JSON.stringify(encoded);+ expect(raw).not.toContain('GSTACK_EXAMPLE_NONCE');+ const decoded = parseChildOutcome(raw, raw.length);+ expect(decoded.outcome).toBe('error');+ if (decoded.outcome !== 'error') throw new Error('expected error');+ const error = reconstructHandlerError(decoded);+ expect(isLocalConfigurationError(error)).toBe(true);+ expect((error as LocalConfigurationError).reasonCode).toBe('postgres_cancellation_unavailable');+ });++ test('unknown tags, missing versions and matching generic messages cannot assert permanent provenance', () => {+ for (const payload of [+ { errorKind: 'local_configuration', reasonCode: 'postgres_cancellation_unavailable' },+ { errorKind: 'local_configuration', protocolVersion: 1, reasonCode: 'unknown' },+ { errorKind: 'local_configuration', protocolVersion: 999, reasonCode: 'postgres_cancellation_unavailable' },+ { errorKind: 'generic', protocolVersion: 1, reasonCode: 'postgres_cancellation_unavailable' },+ ]) {+ const raw = JSON.stringify({ outcome: 'error', message: 'postgres_cancellation_unavailable', ...payload });+ const outcome = parseChildOutcome(raw, raw.length);+ if (outcome.outcome !== 'error') throw new Error('expected error');+ expect(isLocalConfigurationError(reconstructHandlerError(outcome))).toBe(false);+ }+ });test('UnrecoverableError survives the boundary', () => {const enc = encodeHandlerError(new UnrecoverableError('bad config, never retry'));expect(enc.outcome).toBe('error');@@ -161,9 +188,19 @@ describe('child CLI invocation resolution', () => {expect(inv).toEqual({ cmd: '/opt/custom/gbrain', argsPrefix: [] });});- test('compiled binary next', () => {+ test('current source entrypoint precedes PATH', () => {const inv = resolveChildCliInvocation({}, '/usr/bin/bun', '/repo/src/cli.ts', () => '/usr/local/bin/gbrain');- expect(inv).toEqual({ cmd: '/usr/local/bin/gbrain', argsPrefix: [] });+ expect(inv).toEqual({ cmd: '/usr/bin/bun', argsPrefix: ['/repo/src/cli.ts'] });+ });++ test('current compiled executable precedes PATH', () => {+ expect(resolveChildCliInvocation({}, '/opt/current/gbrain', '/$bunfs/root/cli.ts', () => '/opt/old/gbrain'))+ .toEqual({ cmd: '/opt/current/gbrain', argsPrefix: [] });+ });++ test('PATH is the fallback when the current runtime is not a CLI', () => {+ expect(resolveChildCliInvocation({}, '/usr/bin/bun', '/repo/test.ts', () => '/opt/gbrain'))+ .toEqual({ cmd: '/opt/gbrain', argsPrefix: [] });});test('bun-dev fallback when no binary resolves', () => {diff --git a/test/jobs-child-readiness.serial.test.ts b/test/jobs-child-readiness.serial.test.tsnew file mode 100644index 0000000000..e1ee6b7774--- /dev/null+++ b/test/jobs-child-readiness.serial.test.ts@@ -0,0 +1,87 @@+import { describe, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runCli } from './helpers/cli-spawn.ts';+import { withEnv } from './helpers/with-env.ts';+import { reportInlineWorkerConfiguration, reportWorkerReady, reportWorkerStarting } from '../src/commands/jobs-readiness.ts';+import { LocalConfigurationError } from '../src/core/minions/configuration-error.ts';++describe('selected child readiness CLI', () => {+ test('a supervised worker without any status channel proceeds (legacy owner)', async () => {+ await withEnv({ GBRAIN_SUPERVISED: '1', GBRAIN_WORKER_STATUS_PATH: undefined, GBRAIN_WORKER_STATUS_TOKEN: undefined }, () => {+ expect(() => reportWorkerReady()).not.toThrow();+ });+ await withEnv({ GBRAIN_SUPERVISED: undefined, GBRAIN_WORKER_STATUS_PATH: undefined, GBRAIN_WORKER_STATUS_TOKEN: undefined }, () => {+ expect(() => reportWorkerReady()).not.toThrow();+ });+ });++ test('a legacy-shaped supervised worker passes every readiness publication stage', async () => {+ await withEnv({ GBRAIN_SUPERVISED: '1', GBRAIN_WORKER_STATUS_PATH: undefined, GBRAIN_WORKER_STATUS_TOKEN: undefined }, () => {+ expect(() => reportWorkerStarting('database_readiness')).not.toThrow();+ expect(() => reportWorkerStarting('child_readiness')).not.toThrow();+ expect(() => reportWorkerReady()).not.toThrow();+ });+ });++ test('a partial status channel fails closed', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'worker-status-partial-'));+ try {+ await withEnv({ GBRAIN_SUPERVISED: undefined, GBRAIN_WORKER_STATUS_PATH: join(dir, 'worker.json'), GBRAIN_WORKER_STATUS_TOKEN: undefined }, () => {+ expect(() => reportWorkerReady()).toThrow('no jobs were admitted');+ });+ await withEnv({ GBRAIN_SUPERVISED: undefined, GBRAIN_WORKER_STATUS_PATH: undefined, GBRAIN_WORKER_STATUS_TOKEN: 'token' }, () => {+ expect(() => reportWorkerReady()).toThrow('no jobs were admitted');+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('a full status channel whose publication fails refuses to start', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'worker-status-full-'));+ try {+ await withEnv({ GBRAIN_SUPERVISED: '1', GBRAIN_WORKER_STATUS_PATH: join(dir, 'worker.json'), GBRAIN_WORKER_STATUS_TOKEN: 'token' }, () => {+ expect(() => reportWorkerStarting('database_readiness')).toThrow('no jobs were admitted');+ expect(() => reportWorkerReady()).toThrow('no jobs were admitted');+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('inline worker configuration faults name the reason and the runbook', () => {+ const lines: string[] = [];+ const error = spyOn(console, 'error').mockImplementation((...args: unknown[]) => { lines.push(args.join(' ')); });+ try {+ reportInlineWorkerConfiguration(new LocalConfigurationError('postgres_cancellation_unavailable', 'fixture'));+ } finally {+ error.mockRestore();+ }+ expect(lines.join('\n')).toContain('postgres_cancellation_unavailable');+ expect(lines.join('\n')).toContain('docs/guides/minions-fix.md');+ expect(lines.join('\n')).not.toContain('restart its owner');+ });++ test('database connection failure produces a transient protocol reply', async () => {+ const home = mkdtempSync(join(tmpdir(), 'child-readiness-offline-'));+ try {+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({+ engine: 'postgres',+ database_url: 'postgresql://127.0.0.1:1/gbrain_test',+ }));+ const result = await runCli(['jobs', 'child-readiness', '--json'], { home, timeoutMs: 10_000 });+ expect(result.exitCode).toBe(1);+ const reply = JSON.parse(result.stdout);+ expect(reply.protocolVersion).toBe(1);+ expect(reply.status).toBe('transient_error');+ expect(reply.reasonCode).toBeUndefined();+ expect(reply.features).toContain('local-configuration-outcome-v1');+ expect(result.stdout).not.toContain('postgresql://');+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });+});diff --git a/test/jobs-supervisor-offline-status.serial.test.ts b/test/jobs-supervisor-offline-status.serial.test.tsnew file mode 100644index 0000000000..2cdfb137ce--- /dev/null+++ b/test/jobs-supervisor-offline-status.serial.test.ts@@ -0,0 +1,54 @@+import { describe, expect, test } from 'bun:test';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runCli } from './helpers/cli-spawn.ts';+import { PGlite } from '@electric-sql/pglite';+import { vector } from '@electric-sql/pglite/vector';+import { pg_trgm } from '@electric-sql/pglite/contrib/pg_trgm';++describe('supervisor status without a database connection', () => {+ test('the no-pidfile database fallback does not run migrations', async () => {+ const home = mkdtempSync(join(tmpdir(), 'supervisor-status-no-migrate-'));+ const dataDir = join(home, '.gbrain', 'brain.pglite');+ try {+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: dataDir }));+ const result = await runCli(['jobs', 'supervisor', 'status', '--pid-file', join(home, 'absent.pid'), '--json'], { home, timeoutMs: 30_000 });+ expect(result.exitCode).toBe(1);+ expect(JSON.parse(result.stdout).running).toBe(false);+ const db = await PGlite.create({ dataDir, extensions: { vector, pg_trgm } });+ try {+ const tables = await db.query<{ pages: string | null }>("SELECT to_regclass('public.pages')::text AS pages");+ expect(tables.rows[0]?.pages).toBeNull();+ } finally { await db.close(); }+ } finally { rmSync(home, { recursive: true, force: true }); }+ }, 40_000);++ test('a locally live owner remains inspectable while its database is unavailable', async () => {+ const home = mkdtempSync(join(tmpdir(), 'supervisor-offline-status-'));+ try {+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({+ engine: 'postgres',+ database_url: 'postgresql://127.0.0.1:1/gbrain_test',+ }));+ const pidFile = join(home, 'supervisor.pid');+ writeFileSync(pidFile, `${process.pid}\n`);+ const result = await runCli(['jobs', 'supervisor', 'status', '--pid-file', pidFile, '--json'], {+ home,+ timeoutMs: 10_000,+ env: { GBRAIN_AUDIT_DIR: join(home, 'audit') },+ });+ expect(result.exitCode).toBe(0);+ const status = JSON.parse(result.stdout);+ expect(status.running).toBe(true);+ expect(status.supervisor_pid).toBe(process.pid);+ expect(status.detected_via).toBe('pidfile');+ expect(status.crashes_by_cause).toBeDefined();+ expect(result.stderr).not.toContain('GBRAIN_DB_ACCESS');+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });+});diff --git a/test/jobs-worker-startup-recovery.test.ts b/test/jobs-worker-startup-recovery.test.tsindex ac0b0dbf5f..430eb45cf2 100644--- a/test/jobs-worker-startup-recovery.test.ts+++ b/test/jobs-worker-startup-recovery.test.ts@@ -108,6 +108,14 @@ describe('maybeRunWorkerStartupRecovery', () => {).resolves.toBeUndefined();});+ test('verified readiness lets supervised workers recover orphaned queues on every start', async () => {+ const { childId } = await seedOrphanQueue();+ await maybeRunWorkerStartupRecovery(queue, { GBRAIN_SUPERVISED: '1' }, true);+ const row = await childRow(childId);+ expect(row.status).toBe('cancelled');+ expect(row.error_text).toContain('worker startup recovery');+ });+});// Structural (separate suite so the behavioral tests above stay classified@@ -119,7 +127,7 @@ describe('work-handler recovery placement (structural)', () => {join(import.meta.dir, '..', 'src', 'commands', 'jobs.ts'),'utf8',);- const callSite = 'await maybeRunWorkerStartupRecovery(queue);';+ const callSite = 'await maybeRunWorkerStartupRecovery(queue, process.env, true);';const callIdx = jobsSource.indexOf(callSite);expect(callIdx).toBeGreaterThan(-1);// Exactly one call site — the work handler.@@ -128,6 +136,9 @@ describe('work-handler recovery placement (structural)', () => {const ensureIdx = jobsSource.lastIndexOf('await queue.ensureSchema();', callIdx);expect(ensureIdx).toBeGreaterThan(-1);expect(callIdx - ensureIdx).toBeLessThan(400);+ const readinessIdx = jobsSource.lastIndexOf('await checkWorkerStartup(', callIdx);+ expect(readinessIdx).toBeGreaterThan(-1);+ expect(readinessIdx).toBeLessThan(ensureIdx);// …and BEFORE the work loop's worker is even constructed.const workerIdx = jobsSource.indexOf('new MinionWorker(engine', callIdx);expect(workerIdx).toBeGreaterThan(callIdx);diff --git a/test/openclaw-context-engine-native.serial.test.ts b/test/openclaw-context-engine-native.serial.test.tsindex 430ffc3a3f..2156d5c4ba 100644--- a/test/openclaw-context-engine-native.serial.test.ts+++ b/test/openclaw-context-engine-native.serial.test.ts@@ -3,7 +3,7 @@ import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'nodimport { createServer } from 'node:http';import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';-import postgres from 'postgres';+import postgres from '#postgres'import { PostgresEngine } from '../src/core/postgres-engine.ts';import { assertSafeE2eDatabaseUrl } from './helpers/db-guard.ts';diff --git a/test/persistence-skill-crash.slow.test.ts b/test/persistence-skill-crash.slow.test.tsindex e90dbed7ed..0f395980e8 100644--- a/test/persistence-skill-crash.slow.test.ts+++ b/test/persistence-skill-crash.slow.test.ts@@ -3,7 +3,7 @@ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { randomUUID } from 'node:crypto';-import postgres from 'postgres';+import postgres from '#postgres'import { assertSafeE2eDatabaseUrl } from './helpers/db-guard.ts';import { testBackends } from './helpers/test-backends.ts';diff --git a/test/postgres-cancellation-capability.test.ts b/test/postgres-cancellation-capability.test.tsnew file mode 100644index 0000000000..497023e65d--- /dev/null+++ b/test/postgres-cancellation-capability.test.ts@@ -0,0 +1,46 @@+import { describe, expect, test } from 'bun:test';+import { PostgresEngine, hasPostgresCancellationCapability } from '../src/core/postgres-engine.ts';+import { isLocalConfigurationError } from '../src/core/minions/configuration-error.ts';+import { reserveWithCancellation } from '../src/core/postgres-engine/cancellation.ts';++describe('Postgres cancellation runtime owner capability', () => {+ test('validates the reserved owner, while unsignalled diagnostics remain usable', async () => {+ let releases = 0;+ let executions = 0;+ const owner = { release: () => { releases++; }, unsafe: async () => { executions++; return [{ ok: 1 }]; } };+ const engine = new PostgresEngine();+ Object.defineProperty(engine, '_sql', { value: { discard() {}, reserve: async () => owner, unsafe: owner.unsafe } });+ expect(hasPostgresCancellationCapability(owner)).toBe(false);+ expect(await engine.executeRaw('SELECT 1')).toEqual([{ ok: 1 }]);+ try {+ await engine.executeRaw('SELECT 1', [], { signal: new AbortController().signal });+ throw new Error('Expected a configuration error');+ } catch (error) {+ expect(isLocalConfigurationError(error)).toBe(true);+ if (isLocalConfigurationError(error)) expect(error.reasonCode).toBe('postgres_cancellation_unavailable');+ }+ expect(executions).toBe(1);+ expect(releases).toBe(1);+ });++ test('pre-aborted reserve never acquires a slot', async () => {+ const controller = new AbortController();+ controller.abort();+ let acquired = false;+ await expect(reserveWithCancellation(async () => { acquired = true; return { release() {} }; }, controller.signal)).rejects.toMatchObject({ name: 'AbortError' });+ expect(acquired).toBe(false);+ });++ test('unsupported driver reserve is bounded and late ownership is released once', async () => {+ const controller = new AbortController();+ let resolve!: (owner: { release(): void }) => void;+ let releases = 0;+ const reservation = reserveWithCancellation(() => new Promise<{ release(): void }>(done => { resolve = done; }), controller.signal);+ controller.abort();+ await expect(reservation).rejects.toMatchObject({ name: 'AbortError' });+ resolve({ release: () => { releases++; } });+ await Promise.resolve();+ await Promise.resolve();+ expect(releases).toBe(1);+ });+});diff --git a/test/postgres-driver-vendor.test.ts b/test/postgres-driver-vendor.test.tsnew file mode 100644index 0000000000..8e6255922c--- /dev/null+++ b/test/postgres-driver-vendor.test.ts@@ -0,0 +1,38 @@+import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { createRequire } from 'node:module';+import postgres from '#postgres';+import pkg from '../package.json';++describe('vendored Postgres driver packaging', () => {+ test('all supported imports use checked-in source, not node_modules patch installation', () => {+ expect(pkg.imports['#postgres']).toEqual({+ types: './vendor/postgres/types/index.d.ts',+ require: './vendor/postgres/cjs/src/index.js',+ default: './vendor/postgres/src/index.js',+ });+ expect('postgres' in pkg.dependencies).toBe(false);+ expect('patchedDependencies' in pkg).toBe(false);+ expect(import.meta.resolve('#postgres')).toContain('/vendor/postgres/src/index.js');+ expect(createRequire(import.meta.url).resolve('#postgres')).toContain('/vendor/postgres/cjs/src/index.js');+ expect(typeof postgres).toBe('function');+ expect(typeof createRequire(import.meta.url)('#postgres')).toBe('function');+ });++ test('preserves pinned upstream metadata and actual license', () => {+ const upstream = JSON.parse(readFileSync(new URL('../vendor/postgres/package.json', import.meta.url), 'utf8'));+ expect(upstream.name).toBe('postgres');+ expect(upstream.version).toBe('3.4.9');+ expect(upstream.license).toBe('Unlicense');+ expect(readFileSync(new URL('../vendor/postgres/UNLICENSE', import.meta.url), 'utf8')).toContain('free and unencumbered software');+ });++ test('all shipped runtime exports carry the cancellation ownership patch', () => {+ for (const path of ['src', 'cjs/src', 'cf/src']) {+ const index = readFileSync(new URL(`../vendor/postgres/${path}/index.js`, import.meta.url), 'utf8');+ expect(index).toContain('async function reserve({ signal } = {})');+ expect(index).toContain('sql.discard = reservation.discard');+ expect(index).toContain('completed.cancelPromise');+ }+ });+});diff --git a/test/run-child-entry.test.ts b/test/run-child-entry.test.tsindex dfa3fb506d..c044d246ba 100644--- a/test/run-child-entry.test.ts+++ b/test/run-child-entry.test.ts@@ -26,6 +26,8 @@ import {JOB_CHILD_EXIT_NOT_CLAIMED,} from '../src/core/minions/worker-exit-codes.ts';import { UnrecoverableError, type MinionHandler } from '../src/core/minions/types.ts';+import { LocalConfigurationError } from '../src/core/minions/configuration-error.ts';+import { reconstructHandlerError } from '../src/core/minions/job-isolation.ts';let engine: PGLiteEngine;let queue: MinionQueue;@@ -77,6 +79,18 @@ function handlers(map: Record<string, MinionHandler>) {}describe('runChildJobEntry', () => {+ test('handler configuration error preserves typed provenance in the actual outcome file', async () => {+ const job = await addAndClaim('sync');+ const resultPath = join(dir, `configuration-${job.id}.json`);+ const code = await runChildJobEntry(engine,+ { jobId: job.id, lockToken: 'parent-tok-1', resultPath, parentPid: 0 },+ handlers({ sync: async () => { throw new LocalConfigurationError('postgres_cancellation_unavailable', 'private-password'); } }));+ expect(code).toBe(0);+ const outcome = decodeChildOutcomeFile(resultPath);+ if (outcome.outcome !== 'error') throw new Error('expected error');+ expect(reconstructHandlerError(outcome)).toBeInstanceOf(LocalConfigurationError);+ expect(outcome.message).not.toContain('private-password');+ });test('success: outcome file carries the handler result; exit 0; ctx wired to the job row', async () => {const job = await addAndClaim('sync', { full: true });const resultPath = join(dir, `ok-${job.id}.json`);diff --git a/test/spawn-helpers.test.ts b/test/spawn-helpers.test.tsindex f2467a8430..c7512e4877 100644--- a/test/spawn-helpers.test.ts+++ b/test/spawn-helpers.test.ts@@ -21,7 +21,7 @@ describe('buildSpawnInvocation', () => {const result = buildSpawnInvocation('/usr/bin/tini', '/bin/gbrain', ['jobs', 'work']);expect(result).toEqual({cmd: '/usr/bin/tini',- args: ['--', '/bin/gbrain', 'jobs', 'work'],+ args: ['-s', '--', '/bin/gbrain', 'jobs', 'work'],});});@@ -32,7 +32,7 @@ describe('buildSpawnInvocation', () => {});expect(buildSpawnInvocation('/usr/bin/tini', '/bin/gbrain', [])).toEqual({cmd: '/usr/bin/tini',- args: ['--', '/bin/gbrain'],+ args: ['-s', '--', '/bin/gbrain'],});});});diff --git a/test/supervisor-audit.test.ts b/test/supervisor-audit.test.tsindex 1c79b3863c..af4b87c319 100644--- a/test/supervisor-audit.test.ts+++ b/test/supervisor-audit.test.ts@@ -92,6 +92,16 @@ describe('isCrashExit — branch matrix', () => {});describe('summarizeCrashes — aggregation', () => {+ test('configuration-blocked exits remain visible without inflating crash totals', () => {+ const blocked = evt('worker_exited', { likely_cause: 'configuration_blocked', code: 16 });+ expect(isCrashExit(blocked)).toBe(false);+ const summary = summarizeCrashes([blocked, evt('worker_exited', { likely_cause: 'runtime_error', code: 1 })]);+ expect(summary.total).toBe(1);+ expect(summary.by_cause.runtime_error).toBe(1);+ expect(summary.by_cause.legacy).toBe(0);+ expect(summary.clean_exits).toBe(1);+ });+// Feed a representative mixed stream and assert every bucket. The mix// exercises every classifier branch so the message-format consumers// (doctor.ts and jobs.ts) get a stable shape.diff --git a/test/supervisor-configuration-blocked.test.ts b/test/supervisor-configuration-blocked.test.tsnew file mode 100644index 0000000000..797850a630--- /dev/null+++ b/test/supervisor-configuration-blocked.test.ts@@ -0,0 +1,628 @@+import { describe, expect, test, spyOn } from 'bun:test';+import { existsSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import * as fs from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { pathToFileURL } from 'node:url';+import { spawn, type ChildProcess } from 'node:child_process';+import { ChildWorkerSupervisor } from '../src/core/minions/child-worker-supervisor.ts';+import { OwnerProcessingState, readAutopilotProcessingStatus, readOwnerProcessingStatus, writeWorkerProcessingStatus } from '../src/core/minions/processing-state.ts';+import { MinionSupervisor } from '../src/core/minions/supervisor.ts';+import { guardAutopilotEngine } from '../src/commands/autopilot.ts';+import { autopilotLockPath } from '../src/core/autopilot-paths.ts';+import { killProcessGroup } from '../src/core/minions/job-isolation.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { withEnv } from './helpers/with-env.ts';++async function isolated(fn: (root: string) => Promise<void>): Promise<void> {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-blocked-owner-'));+ try { await withEnv({ GBRAIN_HOME: root, HOME: root }, () => fn(root)); }+ finally { rmSync(root, { recursive: true, force: true }); }+}++describe('configuration-blocked worker ownership', () => {+ test('real spawn keeps the owner handoff through hostile-cwd quarantine without restoring untrusted values', async () => isolated(async (root) => {+ const quarantineModule = pathToFileURL(join(import.meta.dir, '../src/core/env-trust.ts')).href;+ const preflightModule = pathToFileURL(join(import.meta.dir, '../src/core/cli-preflight.ts')).href;+ const statusModule = pathToFileURL(join(import.meta.dir, '../src/core/minions/processing-state.ts')).href;+ const supervisorModule = pathToFileURL(join(import.meta.dir, '../src/core/minions/child-worker-supervisor.ts')).href;+ const poisonedPath = join(root, 'untrusted-status');+ writeFileSync(join(root, '.env'), `GBRAIN_WORKER_STATUS_PATH=${poisonedPath}\nGBRAIN_WORKER_STATUS_TOKEN=untrusted\n`);+ const worker = join(root, 'worker.ts');+ writeFileSync(worker, `+import {writeFileSync} from 'node:fs';+import {runCliPreflight,CWD_ENV_QUARANTINED_MARKER} from ${JSON.stringify(preflightModule)};+import {writeWorkerProcessingStatus} from ${JSON.stringify(statusModule)};+const neutral=JSON.parse(process.env[CWD_ENV_QUARANTINED_MARKER]!).neutral;+await runCliPreflight();+const published=writeWorkerProcessingStatus({state:'ready'});+writeFileSync('worker-observation.json',JSON.stringify({cwd:process.cwd(),neutral,marker:process.env[CWD_ENV_QUARANTINED_MARKER]??null,published,supervised:process.env.GBRAIN_SUPERVISED,path:process.env.GBRAIN_WORKER_STATUS_PATH}));+process.exit(1);+`);+ const parent = join(root, 'parent.ts');+ writeFileSync(parent, `+import {quarantineCwdDotenv} from ${JSON.stringify(quarantineModule)};+import {OwnerProcessingState} from ${JSON.stringify(statusModule)};+import {ChildWorkerSupervisor} from ${JSON.stringify(supervisorModule)};+quarantineCwdDotenv();+const state=new OwnerProcessingState('supervisor','fixture');+await new ChildWorkerSupervisor({cliPath:process.execPath,args:['./worker.ts'],env:{...process.env,GBRAIN_SUPERVISED:undefined},processingState:state,maxCrashes:1,hardStopMaxCrashes:1,isStopping:()=>false,onMaxCrashesExceeded:()=>{},onEvent:()=>{}}).run();+state.close();+`);+ const child = Bun.spawn([process.execPath, '--no-env-file', parent], {+ cwd: root, env: { ...process.env, GBRAIN_WORKER_STATUS_PATH: poisonedPath, GBRAIN_WORKER_STATUS_TOKEN: 'untrusted' }, stdout: 'pipe', stderr: 'pipe',+ });+ const stdout = new Response(child.stdout).text();+ const stderr = new Response(child.stderr).text();+ const timer = setTimeout(() => child.kill('SIGKILL'), 10_000);+ try {+ expect(await child.exited, `${await stdout}\n${await stderr}`).toBe(0);+ const observation = JSON.parse(readFileSync(join(root, 'worker-observation.json'), 'utf8'));+ expect(observation.published).toBe(true);+ expect(observation.supervised).toBeUndefined();+ expect(observation.marker).toBeNull();+ expect(observation.cwd).toBe(root);+ expect(observation.path).not.toBe(poisonedPath);+ expect(existsSync(poisonedPath)).toBe(false);+ expect(existsSync(observation.neutral)).toBe(false);+ } finally { clearTimeout(timer); }+ }));++ test('unpublished readiness is bounded independently of health, retries softly, and stops at hard equality', async () => isolated(async (root) => {+ const state = new OwnerProcessingState('supervisor', 'fixture');+ const worker = join(root, 'unready.ts');+ writeFileSync(worker, `import {appendFileSync} from 'node:fs';+appendFileSync(${JSON.stringify(join(root, 'worker-pids'))},process.pid+'\\n');+process.on('SIGTERM',()=>{}); setInterval(()=>{},1000);`);+ let timeouts = 0;+ let hard = 0;+ let degraded = 0;+ const retrySnapshots: any[] = [];+ const sup = new ChildWorkerSupervisor({+ cliPath: process.execPath, args: [worker], processingState: state,+ maxCrashes: 1, hardStopMaxCrashes: 2, _startupReadyTimeoutMs: 500, _startupKillGraceMs: 20, _backoffFloorMs: 50,+ isStopping: () => false, onMaxCrashesExceeded: (count, ceiling) => { expect(count).toBe(ceiling); hard++; },+ onEvent: e => {+ if (e.kind === 'worker_startup_timeout') { timeouts++; expect(state.snapshot.processing_stage).toBe('startup_timeout'); }+ if (e.kind === 'health_warn' && e.reason === 'crash_budget_degraded') degraded++;+ if (e.kind === 'backoff') queueMicrotask(() => retrySnapshots.push(state.snapshot));+ },+ });+ await sup.run();+ expect({ timeouts, hard, degraded }).toEqual({ timeouts: 2, hard: 1, degraded: 1 });+ expect(sup.crashCount).toBe(2);+ expect(retrySnapshots).toHaveLength(1);+ expect(retrySnapshots[0].processing_stage).toBe('retry_backoff');+ expect(Number.isFinite(Date.parse(retrySnapshots[0].retry_at))).toBe(true);+ expect(state.snapshot.processing_stage).toBe('stopped');+ expect(state.snapshot.retry_at).toBeNull();+ const pids = readFileSync(join(root, 'worker-pids'), 'utf8').trim().split('\n').map(Number);+ expect(pids).toHaveLength(2);+ for (const pid of pids) expect(() => process.kill(pid, 0)).toThrow();+ state.close();+ }), 10_000);++ test('a confirmed ready worker survives the startup deadline and blocked state has no retry timestamp', async () => isolated(async (root) => {+ const state = new OwnerProcessingState('autopilot', 'default');+ const worker = join(root, 'ready.ts');+ const statusModule = pathToFileURL(join(import.meta.dir, '../src/core/minions/processing-state.ts')).href;+ writeFileSync(worker, `import {writeWorkerProcessingStatus} from ${JSON.stringify(statusModule)};+writeWorkerProcessingStatus({state:'ready'});+setTimeout(()=>{writeWorkerProcessingStatus({state:'configuration_blocked',reason_code:'child_protocol_incompatible'});process.exit(16);},800);`);+ let timeouts = 0;+ const sup = new ChildWorkerSupervisor({+ cliPath: process.execPath, args: [worker], processingState: state,+ maxCrashes: 1, _startupReadyTimeoutMs: 500, _startupKillGraceMs: 20,+ isStopping: () => false, onMaxCrashesExceeded: () => {},+ onEvent: e => { if (e.kind === 'worker_startup_timeout') timeouts++; },+ });+ await sup.run();+ expect(timeouts).toBe(0);+ expect(state.snapshot.processing_stage).toBe('configuration_blocked');+ expect(state.snapshot.retry_at).toBeNull();+ expect(sup.crashCount).toBe(0);+ state.close();+ }));++ test('autopilot status binds processing state to the live lock holder PID', async () => isolated(async () => {+ const state = new OwnerProcessingState('autopilot', 'default');+ const other = spawn('sleep', ['30'], { stdio: 'ignore' });+ try {+ const otherPid = other.pid!;+ const autopilot = { readProcessCommand: () => 'gbrain autopilot' };+ expect(readAutopilotProcessingStatus()).toBeNull();+ writeFileSync(autopilotLockPath(), String(process.pid));+ expect(readAutopilotProcessingStatus()?.owner_pid).toBe(process.pid);+ writeFileSync(autopilotLockPath(), String(otherPid));+ expect(readAutopilotProcessingStatus(autopilot)).toBeNull();+ const runtime = join(autopilotLockPath(), '..', 'runtime');+ const ownerFile = join(runtime, readdirSync(runtime).find(f => f.startsWith('autopilot-') && f.endsWith('.json'))!);+ writeFileSync(ownerFile, JSON.stringify({ ...JSON.parse(readFileSync(ownerFile, 'utf8')), owner_pid: otherPid, processing_state: 'ready', processing_stage: 'ready' }));+ expect(readAutopilotProcessingStatus({ readProcessCommand: () => 'sleep 30' })).toBeNull();+ expect(readAutopilotProcessingStatus({ isPidAlive: () => false })).toBeNull();+ expect(readAutopilotProcessingStatus(autopilot)?.processing_ready).toBe(true);+ } finally {+ other.kill('SIGKILL');+ state.close();+ }+ }));++ test('startup timeout also reaps an unready direct worker without tini', async () => withEnv({ PATH: '' }, () => isolated(async () => {+ const state = new OwnerProcessingState('supervisor', 'fixture');+ let pid = 0;+ let timeouts = 0;+ const sup = new ChildWorkerSupervisor({+ cliPath: process.execPath, args: ['-e', "process.on('SIGTERM',()=>{});setInterval(()=>{},1000)"], processingState: state,+ maxCrashes: 1, hardStopMaxCrashes: 1, _startupReadyTimeoutMs: 300, _startupKillGraceMs: 20,+ isStopping: () => false, onMaxCrashesExceeded: () => {},+ onEvent: e => {+ if (e.kind === 'worker_spawned') pid = e.pid;+ if (e.kind === 'worker_startup_timeout') timeouts++;+ },+ });+ expect(sup.isTiniDetected).toBe(false);+ await sup.run();+ expect(timeouts).toBe(1);+ expect(sup.crashCount).toBe(1);+ expect(pid).toBeGreaterThan(0);+ expect(() => process.kill(pid, 0)).toThrow();+ state.close();+ })));++ test('managed spawns leave GBRAIN_SUPERVISED to the owner and always hand off the status channel', async () => withEnv({ GBRAIN_SUPERVISED: '1' }, () => isolated(async (root) => {+ const statusModule = pathToFileURL(join(import.meta.dir, '../src/core/minions/processing-state.ts')).href;+ const observations = join(root, 'observations');+ const worker = join(root, 'env-observer.ts');+ writeFileSync(worker, `import {appendFileSync} from 'node:fs';+import {writeWorkerProcessingStatus} from ${JSON.stringify(statusModule)};+appendFileSync(${JSON.stringify(observations)},JSON.stringify({supervised:process.env.GBRAIN_SUPERVISED??null,path:Boolean(process.env.GBRAIN_WORKER_STATUS_PATH),token:Boolean(process.env.GBRAIN_WORKER_STATUS_TOKEN),published:writeWorkerProcessingStatus({state:'ready'})})+'\\n');+process.exit(1);`);+ const observe = async (kind: 'autopilot' | 'supervisor', env: NodeJS.ProcessEnv) => {+ const state = new OwnerProcessingState(kind, 'fixture');+ await new ChildWorkerSupervisor({+ cliPath: process.execPath, args: [worker], env, processingState: state, maxCrashes: 1, hardStopMaxCrashes: 1,+ isStopping: () => false, onMaxCrashesExceeded: () => {}, onEvent: () => {},+ }).run();+ state.close();+ };+ await observe('autopilot', { ...process.env, GBRAIN_SUPERVISED: undefined });+ await observe('supervisor', { ...process.env, GBRAIN_SUPERVISED: '1' });+ const [autopilot, supervisor] = readFileSync(observations, 'utf8').trim().split('\n').map(line => JSON.parse(line));+ expect(autopilot).toEqual({ supervised: null, path: true, token: true, published: true });+ expect(supervisor).toEqual({ supervised: '1', path: true, token: true, published: true });+ })));++ test.skipIf(process.platform === 'win32')('without tini, killing the owner process group also kills its managed worker', async () => isolated(async (root) => {+ const statusModule = pathToFileURL(join(import.meta.dir, '../src/core/minions/processing-state.ts')).href;+ const supervisorModule = pathToFileURL(join(import.meta.dir, '../src/core/minions/child-worker-supervisor.ts')).href;+ const workerPidFile = join(root, 'worker.pid');+ const worker = join(root, 'worker.ts');+ writeFileSync(worker, `import {writeFileSync} from 'node:fs';+writeFileSync(${JSON.stringify(workerPidFile)},String(process.pid));+setInterval(()=>{},1000);`);+ const ownerScript = join(root, 'owner.ts');+ writeFileSync(ownerScript, `import {OwnerProcessingState} from ${JSON.stringify(statusModule)};+import {ChildWorkerSupervisor} from ${JSON.stringify(supervisorModule)};+const state=new OwnerProcessingState('autopilot','default');+const sup=new ChildWorkerSupervisor({cliPath:process.execPath,args:[${JSON.stringify(worker)}],env:{...process.env,GBRAIN_SUPERVISED:undefined},processingState:state,maxCrashes:5,isStopping:()=>false,onMaxCrashesExceeded:()=>{},onEvent:()=>{}});+if (sup.isTiniDetected) process.exit(3);+void sup.run();+setInterval(()=>{},1000);`);+ const alive = (pid: number) => {+ try { process.kill(pid, 0); } catch { return false; }+ if (process.platform !== 'linux') return true;+ try {+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');+ return stat.slice(stat.lastIndexOf(')') + 2, stat.lastIndexOf(')') + 3) !== 'Z';+ } catch { return false; }+ };+ const owner = spawn(process.execPath, [ownerScript], {+ cwd: root, detached: true, stdio: 'ignore', env: { ...process.env, PATH: '', TMPDIR: root },+ });+ let workerPid = 0;+ try {+ const started = Date.now() + 10_000;+ while (!existsSync(workerPidFile) && owner.exitCode === null && Date.now() < started) await Bun.sleep(20);+ expect(owner.exitCode).toBeNull();+ workerPid = Number(readFileSync(workerPidFile, 'utf8'));+ expect(workerPid).toBeGreaterThan(0);+ expect(killProcessGroup(owner.pid!, 'SIGKILL')).toBe(true);+ const reaped = Date.now() + 5_000;+ while (alive(workerPid) && Date.now() < reaped) await Bun.sleep(20);+ expect(alive(workerPid)).toBe(false);+ } finally {+ killProcessGroup(owner.pid!, 'SIGKILL');+ if (workerPid) {+ killProcessGroup(workerPid, 'SIGKILL');+ try { process.kill(workerPid, 'SIGKILL'); } catch {}+ }+ }+ }), 20_000);++ test('unwritable managed status fails publication before admission and follows ordinary bounded retry', async () => isolated(async (root) => {+ const state = new OwnerProcessingState('autopilot', 'default');+ const reporter = pathToFileURL(join(import.meta.dir, '../src/commands/jobs-readiness.ts')).href;+ const worker = join(root, 'unwritable.ts');+ writeFileSync(worker, `import {mkdirSync,appendFileSync,writeFileSync,unlinkSync} from 'node:fs';+import {reportWorkerReady} from ${JSON.stringify(reporter)};+unlinkSync(process.env.GBRAIN_WORKER_STATUS_PATH!);+mkdirSync(process.env.GBRAIN_WORKER_STATUS_PATH!);+try {reportWorkerReady();writeFileSync(${JSON.stringify(join(root, 'admitted'))},'unexpected');}+catch(error){appendFileSync(${JSON.stringify(join(root, 'publication-failures'))},String(error)+'\\n');process.exit(1);}`);+ let spawns = 0;+ let hardStops = 0;+ let timeouts = 0;+ const sup = new ChildWorkerSupervisor({+ cliPath: process.execPath, args: [worker], processingState: state,+ env: { ...process.env, GBRAIN_SUPERVISED: undefined }, maxCrashes: 1, hardStopMaxCrashes: 2,+ _startupReadyTimeoutMs: 10_000, _backoffFloorMs: 1, isStopping: () => false,+ onMaxCrashesExceeded: () => { hardStops++; },+ onEvent: e => {+ if (e.kind === 'worker_spawned') spawns++;+ if (e.kind === 'worker_startup_timeout') timeouts++;+ },+ });+ await sup.run();+ expect({ spawns, hardStops, timeouts }).toEqual({ spawns: 2, hardStops: 1, timeouts: 0 });+ expect(existsSync(join(root, 'admitted'))).toBe(false);+ const failures = readFileSync(join(root, 'publication-failures'), 'utf8').trim().split('\n');+ expect(failures).toHaveLength(2);+ expect(failures.every(line => line.includes('no jobs were admitted'))).toBe(true);+ expect(state.snapshot.processing_ready).toBe(false);+ expect(state.snapshot.processing_stage).toBe('stopped');+ state.close();+ }));++ test('authenticated startup phases and bounded retry timestamps survive offline status reads', async () => isolated(async () => {+ const state = new OwnerProcessingState('autopilot', 'default');+ const env = state.prepareChild();+ for (const stage of ['database_readiness', 'child_readiness', 'worker_startup'] as const) {+ writeWorkerProcessingStatus({ state: 'starting', stage }, env);+ expect(state.snapshot.processing_stage).toBe(stage);+ expect(readOwnerProcessingStatus('autopilot', 'default')?.processing_stage).toBe(stage);+ }+ state.workerExited();+ state.waiting('retry_backoff', Date.now() + 1000);+ const offline = readOwnerProcessingStatus('autopilot', 'default');+ expect(offline?.processing_stage).toBe('retry_backoff');+ expect(Date.parse(offline!.retry_at!)).toBeGreaterThan(Date.now());+ state.close();+ }));++ test('publication rejects absent channels, retired generations, and another bound worker PID', async () => isolated(async (root) => {+ const missing = { GBRAIN_WORKER_STATUS_PATH: join(root, 'missing', 'status.json'), GBRAIN_WORKER_STATUS_TOKEN: 'fixture-token' };+ expect(writeWorkerProcessingStatus({ state: 'ready' }, missing)).toBe(false);+ expect(existsSync(join(root, 'missing'))).toBe(false);+ const state = new OwnerProcessingState('supervisor', 'fixture');+ const first = state.prepareChild();+ expect(writeWorkerProcessingStatus({ state: 'ready' }, { ...first, GBRAIN_WORKER_STATUS_TOKEN: 'wrong-token' })).toBe(false);+ const status = JSON.parse(readFileSync(first.GBRAIN_WORKER_STATUS_PATH!, 'utf8'));+ writeFileSync(first.GBRAIN_WORKER_STATUS_PATH!, JSON.stringify({ ...status, worker_pid: process.pid + 1 }));+ expect(writeWorkerProcessingStatus({ state: 'ready' }, first)).toBe(false);+ const current = state.prepareChild();+ expect(writeWorkerProcessingStatus({ state: 'ready' }, first)).toBe(false);+ expect(existsSync(first.GBRAIN_WORKER_STATUS_PATH!)).toBe(false);+ expect(writeWorkerProcessingStatus({ state: 'starting', stage: 'worker_startup' }, current)).toBe(true);+ state.waiting('startup_timeout');+ expect(writeWorkerProcessingStatus({ state: 'ready' }, current)).toBe(false);+ expect(existsSync(current.GBRAIN_WORKER_STATUS_PATH!)).toBe(false);+ state.close();+ }));++ test('retirement after atomic publication but before its return fails the generation recheck', async () => isolated(async () => {+ const state = new OwnerProcessingState('supervisor', 'fixture');+ const previous = state.prepareChild();+ const originalRename = fs.renameSync;+ let intercepted = false;+ const rename = spyOn(fs, 'renameSync').mockImplementation((from, to) => {+ originalRename(from, to);+ if (to === previous.GBRAIN_WORKER_STATUS_PATH && !intercepted) {+ intercepted = true;+ state.prepareChild();+ }+ });+ try {+ expect(writeWorkerProcessingStatus({ state: 'ready' }, previous)).toBe(false);+ expect(intercepted).toBe(true);+ expect(state.snapshot.processing_ready).toBe(false);+ expect(existsSync(previous.GBRAIN_WORKER_STATUS_PATH!)).toBe(false);+ } finally {+ rename.mockRestore();+ state.close();+ }+ }));++ test('an old worker resumed by the timeout signal cannot publish ready or admit during the kill grace', async () => isolated(async (root) => {+ const state = new OwnerProcessingState('supervisor', 'fixture');+ const reporter = pathToFileURL(join(import.meta.dir, '../src/commands/jobs-readiness.ts')).href;+ const worker = join(root, 'late-ready.ts');+ writeFileSync(worker, `import {writeFileSync} from 'node:fs';+import {reportWorkerReady} from ${JSON.stringify(reporter)};+process.on('SIGTERM',()=>{+ try {reportWorkerReady();writeFileSync(${JSON.stringify(join(root, 'late-admission'))},'unexpected');}+ catch(error){writeFileSync(${JSON.stringify(join(root, 'late-refusal'))},String(error));}+ process.exit(1);+});+setInterval(()=>{},1000);`);+ let timeouts = 0;+ const sup = new ChildWorkerSupervisor({+ cliPath: process.execPath, args: [worker], processingState: state,+ maxCrashes: 1, hardStopMaxCrashes: 1, _startupReadyTimeoutMs: 1000, _startupKillGraceMs: 1000,+ isStopping: () => false, onMaxCrashesExceeded: () => {},+ onEvent: event => { if (event.kind === 'worker_startup_timeout') timeouts++; },+ });+ await sup.run();+ expect(timeouts).toBe(1);+ expect(existsSync(join(root, 'late-admission'))).toBe(false);+ expect(readFileSync(join(root, 'late-refusal'), 'utf8')).toContain('no jobs were admitted');+ expect(state.snapshot.processing_ready).toBe(false);+ state.close();+ }));++ for (const kind of ['supervisor', 'autopilot'] as const) {+ test.skipIf(process.platform === 'win32')(`${kind} survives Restart=always, retains singleton and recovers only after explicit restart`, async () => isolated(async (root) => {+ mkdirSync(join(root, '.gbrain'), { recursive: true });+ writeFileSync(join(root, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres' }));+ const fixture = join(root, 'owner.ts');+ const worker = join(root, 'cli.ts');+ writeFileSync(join(root, 'gbrain'), `#!${process.execPath}\nprocess.exit(99);\n`, { mode: 0o755 });+ const statusModule = pathToFileURL(join(import.meta.dir, '../src/core/minions/processing-state.ts')).href;+ const ownerModule = pathToFileURL(join(import.meta.dir, kind === 'supervisor' ? '../src/core/minions/supervisor.ts' : '../src/commands/autopilot.ts')).href;+ const pidFile = join(root, 'supervisor.pid');+ const key = kind === 'supervisor' ? pidFile : 'default';+ writeFileSync(worker, `#!${process.execPath}+import {existsSync,appendFileSync} from 'node:fs';+import {writeWorkerProcessingStatus} from ${JSON.stringify(statusModule)};+appendFileSync(${JSON.stringify(join(root, 'spawns'))}, 'spawn\\n');+if (!existsSync(${JSON.stringify(join(root, 'repaired'))})) {+ writeWorkerProcessingStatus({state:'configuration_blocked',reason_code:'postgres_cancellation_unavailable'});+ process.exit(16);+}+writeWorkerProcessingStatus({state:'ready',worker_identity:{executable:'/fixture/gbrain',version:'1.0.0'}});+appendFileSync(${JSON.stringify(join(root, 'handlers'))}, 'completed\\n');+setInterval(()=>{}, 1000);+process.on('SIGTERM',()=>process.exit(0));+`, { mode: 0o755 });+ writeFileSync(fixture, `+import {${kind === 'supervisor' ? 'MinionSupervisor' : 'runAutopilot'}} from ${JSON.stringify(ownerModule)};+const engine = {+ kind:'postgres', sql:async()=>[{id:'fixture',fence:'1'}],+ getConfig:async()=>null, executeRaw:async()=>[], executeRawDirect:async()=>[{id:'fixture'}],+ getHealth:async()=>({brain_score:100}), disconnect:async()=>{}, reconnect:async()=>{}+};+${kind === 'supervisor'+ ? `await new MinionSupervisor(engine as any,{cliPath:process.execPath,cliArgsPrefix:[${JSON.stringify(worker)}],pidFile:${JSON.stringify(pidFile)},healthInterval:10,_backoffFloorMs:1}).start();`+ : `process.argv[1]=${JSON.stringify(worker)}; await runAutopilot(engine as any,['--repo',${JSON.stringify(root)},'--interval','1']);`}+`);+ let owner: ChildProcess;+ let logs = '';+ let outerRestarts = 0;+ const launch = () => {+ owner = spawn(process.execPath, [fixture], {+ env: { ...process.env, HOME: root, GBRAIN_HOME: root, PATH: `${root}:${process.env.PATH}`, OPENAI_API_KEY: '', ANTHROPIC_API_KEY: '', GBRAIN_SKIP_STARTUP_HOOKS: '1' },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ owner.stdout?.on('data', data => { logs += data; });+ owner.stderr?.on('data', data => { logs += data; });+ };+ const until = async (predicate: () => boolean) => {+ const deadline = Date.now() + 15_000;+ while (!predicate() && Date.now() < deadline) await new Promise(r => setTimeout(r, 20));+ if (!predicate()) throw new Error(`Owner fixture timed out: ${logs}`);+ };+ const stop = async () => {+ owner.kill('SIGTERM');+ await until(() => owner.exitCode !== null || owner.signalCode !== null);+ };+ launch();+ try {+ await until(() => readOwnerProcessingStatus(kind, key)?.processing_state === 'configuration_blocked');+ const firstPid = owner!.pid;+ for (let tick = 0; tick < 8; tick++) {+ await new Promise(r => setTimeout(r, 30));+ if (owner!.exitCode !== null || owner!.signalCode !== null) { outerRestarts++; launch(); }+ }+ expect(outerRestarts).toBe(0);+ expect(owner!.pid).toBe(firstPid);+ expect(readFileSync(join(root, 'spawns'), 'utf8').trim().split('\n')).toHaveLength(1);+ expect(readdirSync(root)).not.toContain('handlers');+ const lock = kind === 'supervisor' ? pidFile : join(root, '.gbrain', 'autopilot.lock');+ expect(readFileSync(lock, 'utf8').trim().split('\n')[0]).toBe(String(firstPid));+ writeFileSync(join(root, 'repaired'), 'yes');+ await new Promise(r => setTimeout(r, 150));+ expect(readOwnerProcessingStatus(kind, key)?.processing_state).toBe('configuration_blocked');+ await stop();+ launch();+ await until(() => readOwnerProcessingStatus(kind, key)?.processing_ready === true);+ expect(readFileSync(join(root, 'handlers'), 'utf8').trim()).toBe('completed');+ await stop();+ expect(owner!.exitCode).toBe(0);+ } finally {+ if (owner!.exitCode === null && owner!.signalCode === null) {+ owner!.kill('SIGTERM');+ await until(() => owner!.exitCode !== null || owner!.signalCode !== null).catch(() => { owner!.kill('SIGKILL'); });+ }+ }+ }), 40_000);+ }++ test('exit 16 blocks once before hard threshold, recovery and backoff', async () => isolated(async (root) => {+ const script = join(root, 'worker.mjs');+ writeFileSync(script, 'process.exit(16)');+ const state = new OwnerProcessingState('supervisor', 'fixture');+ let spawns = 0;+ let recoveries = 0;+ let blocked = 0;+ let hardStops = 0;+ let backoffs = 0;+ const supervisor = new ChildWorkerSupervisor({+ cliPath: process.execPath, args: [script], processingState: state,+ maxCrashes: 1, hardStopMaxCrashes: 1, _backoffFloorMs: 0,+ isStopping: () => false, beforeSpawn: async () => { recoveries++; },+ onConfigurationBlocked: () => { blocked++; },+ onMaxCrashesExceeded: () => { hardStops++; },+ onEvent: (e) => { if (e.kind === 'worker_spawned') spawns++; if (e.kind === 'backoff') backoffs++; },+ });+ await supervisor.run();+ await supervisor.run();+ await supervisor.restartCurrentChild(0);+ expect({ spawns, recoveries, blocked, hardStops, backoffs }).toEqual({ spawns: 1, recoveries: 1, blocked: 1, hardStops: 0, backoffs: 0 });+ expect(supervisor.crashCount).toBe(0);+ expect(readOwnerProcessingStatus('supervisor', 'fixture', process.pid)).toMatchObject({ processing_ready: false, processing_state: 'configuration_blocked', reason_code: null });+ state.close();+ }));++ test('runtime handoff latches during drain and wins over a later clean exit', async () => isolated(async (root) => {+ const script = join(root, 'worker.mjs');+ const statusModule = pathToFileURL(join(import.meta.dir, '../src/core/minions/processing-state.ts')).href;+ writeFileSync(script, `import {writeWorkerProcessingStatus} from ${JSON.stringify(statusModule)};+ writeWorkerProcessingStatus({state:'configuration_blocked',reason_code:'postgres_cancellation_unavailable'});+ setTimeout(()=>process.exit(0), 350);`);+ const state = new OwnerProcessingState('autopilot', 'default');+ let observedAlive = false;+ let spawns = 0;+ const supervisor = new ChildWorkerSupervisor({+ cliPath: process.execPath, args: [script], processingState: state, maxCrashes: 1,+ isStopping: () => false, onMaxCrashesExceeded: () => {},+ onConfigurationBlocked: () => { observedAlive = supervisor.childAlive; },+ onEvent: (event) => { if (event.kind === 'worker_spawned') spawns++; },+ });+ await supervisor.run();+ expect(observedAlive).toBe(true);+ expect(spawns).toBe(1);+ expect(state.snapshot.reason_code).toBe('postgres_cancellation_unavailable');+ state.close();+ }));++ test('stale child token cannot make a new runtime ready or blocked; restart resets observation', async () => isolated(async () => {+ const state = new OwnerProcessingState('autopilot', 'default');+ const oldEnv = state.prepareChild();+ const freshEnv = state.prepareChild();+ expect(writeWorkerProcessingStatus({ state: 'configuration_blocked', reason_code: 'child_protocol_incompatible' }, oldEnv)).toBe(false);+ expect(state.snapshot.processing_state).toBe('starting');+ writeWorkerProcessingStatus({ state: 'ready', worker_identity: { executable: '/fixture/gbrain', version: '1.2.3' }, child_identity: { executable: '/fixture/child', version: '1.2.2', protocol_version: 1 } }, freshEnv);+ expect(state.snapshot.processing_ready).toBe(true);+ writeWorkerProcessingStatus({ state: 'configuration_blocked', reason_code: 'child_protocol_incompatible' }, freshEnv);+ expect(state.blocked).toBe(true);+ expect(state.snapshot.child_identity).toEqual({ executable: '/fixture/child', version: '1.2.2', protocol_version: 1 });+ writeWorkerProcessingStatus({ state: 'ready' }, freshEnv);+ expect(state.blocked).toBe(true);+ const restarted = new OwnerProcessingState('autopilot', 'default');+ expect(restarted.snapshot.processing_state).toBe('starting');+ state.close();+ expect(readOwnerProcessingStatus('autopilot', 'default')?.runtime_id).toBe(restarted.snapshot.runtime_id);+ expect(readOwnerProcessingStatus('autopilot', 'default', process.pid + 1)).toBeNull();+ restarted.close();+ }));++ test('block while beforeSpawn is suspended prevents spawn on its continuation', async () => isolated(async () => {+ const state = new OwnerProcessingState('supervisor', 'fixture');+ let resume!: () => void;+ let spawns = 0;+ const supervisor = new ChildWorkerSupervisor({+ cliPath: process.execPath, args: ['-e', 'process.exit(0)'], processingState: state,+ maxCrashes: 1, isStopping: () => false,+ beforeSpawn: () => new Promise<void>(r => { resume = r; }),+ onMaxCrashesExceeded: () => {}, onEvent: (e) => { if (e.kind === 'worker_spawned') spawns++; },+ });+ const running = supervisor.run();+ state.block('child_executable_invalid');+ resume();+ await running;+ expect(spawns).toBe(0);+ state.close();+ }));++ test('configuration block cancels an already pending watchdog backoff', async () => isolated(async () => {+ const state = new OwnerProcessingState('supervisor', 'fixture');+ let spawns = 0;+ let blockTimer: ReturnType<typeof setTimeout> | undefined;+ const supervisor = new ChildWorkerSupervisor({+ cliPath: process.execPath, args: ['-e', 'process.exit(12)'], processingState: state,+ maxCrashes: 1, watchdogBackoffMs: 60_000, isStopping: () => false,+ onMaxCrashesExceeded: () => {},+ onEvent: (e) => {+ if (e.kind === 'worker_spawned') spawns++;+ if (e.kind === 'backoff') blockTimer = setTimeout(() => state.block('child_protocol_incompatible'), 10);+ },+ });+ try {+ await supervisor.run();+ expect(spawns).toBe(1);+ expect(supervisor.inBackoff).toBe(false);+ expect(supervisor.configurationBlocked).toBe(true);+ } finally {+ if (blockTimer) clearTimeout(blockTimer);+ state.close();+ }+ }));++ test('autopilot blocks dispatch continuations and reconnect but still permits engine shutdown', async () => isolated(async () => {+ const state = new OwnerProcessingState('autopilot', 'default');+ let resume!: () => void;+ let writes = 0;+ let disconnects = 0;+ const engine = guardAutopilotEngine({+ getConfig: () => new Promise<void>(r => { resume = r; }),+ executeRaw: async () => { writes++; return []; },+ reconnect: async () => { writes++; },+ disconnect: async () => { disconnects++; },+ } as unknown as BrainEngine, state);+ const dispatch = (async () => { await engine.getConfig('version'); await engine.executeRaw('fixture'); })();+ state.block('postgres_cancellation_unavailable');+ resume();+ await expect(dispatch).rejects.toThrow('configuration-blocked');+ expect(() => engine.reconnect()).toThrow('configuration-blocked');+ await engine.disconnect();+ expect({ writes, disconnects }).toEqual({ writes: 0, disconnects: 1 });+ state.close();+ }));++ test('standalone suppresses an in-flight health failure and failed lock refresh while blocked', async () => isolated(async (root) => {+ const state = new OwnerProcessingState('supervisor', 'fixture');+ let rejectHealth!: (error: Error) => void;+ let reconnects = 0;+ const engine = {+ executeRaw: () => new Promise((_r, reject) => { rejectHealth = reject; }),+ reconnect: async () => { reconnects++; },+ } as unknown as BrainEngine;+ const supervisor = new MinionSupervisor(engine, { cliPath: process.execPath, pidFile: join(root, 'owner.pid') });+ Object.assign(supervisor, { processingState: state, consecutiveHealthFailures: 2 });+ writeWorkerProcessingStatus({ state: 'ready' }, state.prepareChild());+ const health = supervisor._healthCheckOnceForTests();+ state.block('postgres_cancellation_unavailable');+ rejectHealth(new Error('temporary outage'));+ await health;+ supervisor._setDbLockForTests({ refresh: async () => false } as any);+ await supervisor._refreshDbLockForTests();+ supervisor._setDbLockForTests({ refresh: async () => { throw new Error('offline'); } } as any);+ for (let i = 0; i < 4; i++) await supervisor._refreshDbLockForTests();+ expect(reconnects).toBe(0);+ expect(supervisor.processingStatus?.processing_state).toBe('configuration_blocked');+ state.close();+ }));++ test('configuration reported during maintenance shutdown keeps the owner and singleton alive', async () => isolated(async (root) => {+ const state = new OwnerProcessingState('supervisor', 'fixture');+ let released = 0;+ const supervisor = new MinionSupervisor({} as BrainEngine, { cliPath: process.execPath, pidFile: join(root, 'owner.pid') });+ Object.assign(supervisor, {+ processingState: state,+ childSupervisor: {+ killChild: () => {}, childAlive: false,+ awaitChildExit: async () => { state.block('postgres_cancellation_unavailable'); },+ },+ });+ supervisor._setDbLockForTests({ release: async () => { released++; } } as any);+ const exit = spyOn(process, 'exit').mockImplementation(() => { throw new Error('unexpected owner exit'); });+ try {+ await Reflect.get(supervisor, 'shutdown').call(supervisor, 'supervisor_lock_lost', 4);+ expect(exit).not.toHaveBeenCalled();+ expect(released).toBe(0);+ expect(Reflect.get(supervisor, 'stopping')).toBe(false);+ } finally {+ exit.mockRestore();+ state.close();+ }+ }));+});diff --git a/test/supervisor.test.ts b/test/supervisor.test.tsindex a01d2c303b..57b8fa38b4 100644--- a/test/supervisor.test.ts+++ b/test/supervisor.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';+import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, spyOn } from 'bun:test';import { existsSync, readFileSync, writeFileSync, unlinkSync, chmodSync, mkdirSync, rmSync } from 'fs';import { spawn } from 'child_process';import { join } from 'path';@@ -8,6 +8,7 @@ import { calculateBackoffMs, resolveHardStopMaxCrashes, MinionSupervisor, type Simport { PGLiteEngine } from '../src/core/pglite-engine.ts';import { MinionQueue } from '../src/core/minions/queue.ts';import type { BrainEngine } from '../src/core/engine.ts';+import { maybeRunWorkerStartupRecovery } from '../src/commands/jobs.ts';const TEST_PID_FILE = '/tmp/gbrain-supervisor-test.pid';@@ -516,7 +517,7 @@ describe('MinionSupervisor', () => {// Private-queue startup recovery hook (beforeSpawn seam into// ChildWorkerSupervisor). Constructed in-process with a real/throwing engine// — the hook never spawns anything, so no supervisor-runner fixture needed.- describe('reconcileOrphanedPrivateQueuesBeforeWorkerSpawn', () => {+ describe('supervised recovery after worker readiness', () => {let engine: PGLiteEngine;let queue: MinionQueue;let queueSeq = 0;@@ -538,14 +539,6 @@ describe('MinionSupervisor', () => {await engine.executeRaw('DELETE FROM minion_jobs');});- function makeSupervisor(eng: BrainEngine, emissions: SupervisorEmission[]): MinionSupervisor {- return new MinionSupervisor(eng, {- cliPath: '/bin/false', // never spawned — the hook is called directly- json: true,- onEvent: (e) => emissions.push(e),- });- }-/** Orphan fixture: waiting 'subagent' child, terminal owner, aged updated_at. */async function seedOrphanQueue(): Promise<number> {const queueName = `dream-inline-sup-recovery-${++queueSeq}`;@@ -572,52 +565,35 @@ describe('MinionSupervisor', () => {return child.id;}- it("cancels an orphaned queue and emits health_warn reason='private_queue_startup_recovery'", async () => {+ it('cancels an orphaned queue after supervised readiness and reports the recovered counts', async () => {const childId = await seedOrphanQueue();- const emissions: SupervisorEmission[] = [];- const sup = makeSupervisor(engine, emissions);-- await (sup as unknown as {- reconcileOrphanedPrivateQueuesBeforeWorkerSpawn: () => Promise<void>;- }).reconcileOrphanedPrivateQueuesBeforeWorkerSpawn();-- const rows = await engine.executeRaw<{ status: string; error_text: string | null }>(- `SELECT status, error_text FROM minion_jobs WHERE id = $1`,- [childId],- );- expect(rows[0]!.status).toBe('cancelled');- expect(rows[0]!.error_text).toContain('supervisor startup recovery');-- const warn = emissions.find(- (e) => e.event === 'health_warn' &&- (e as Record<string, unknown>).reason === 'private_queue_startup_recovery',- ) as Record<string, unknown> | undefined;- expect(warn).toBeDefined();- expect(warn!.cancelled_jobs).toBe(1);- expect(warn!.cancelled_queues).toBe(1);+ const diagnostic = spyOn(console, 'error').mockImplementation(() => {});+ try {+ await maybeRunWorkerStartupRecovery(queue, { GBRAIN_SUPERVISED: '1' }, true);++ const rows = await engine.executeRaw<{ status: string; error_text: string | null }>(+ `SELECT status, error_text FROM minion_jobs WHERE id = $1`,+ [childId],+ );+ expect(rows[0]!.status).toBe('cancelled');+ expect(rows[0]!.error_text).toContain('worker startup recovery');+ expect(diagnostic).toHaveBeenCalledWith('[gbrain jobs] private-queue startup recovery: cancelled 1 job(s) across 1 orphaned queue(s)');+ } finally { diagnostic.mockRestore(); }});- it("resolves and emits health_warn reason='private_queue_startup_recovery_failed' when the engine throws", async () => {+ it('resolves and reports startup recovery failure when the engine throws', async () => {const throwingEngine = {executeRaw: async () => {throw new Error('injected executeRaw failure');},} as unknown as BrainEngine;- const emissions: SupervisorEmission[] = [];- const sup = makeSupervisor(throwingEngine, emissions);-- await expect(- (sup as unknown as {- reconcileOrphanedPrivateQueuesBeforeWorkerSpawn: () => Promise<void>;- }).reconcileOrphanedPrivateQueuesBeforeWorkerSpawn(),- ).resolves.toBeUndefined();-- const warn = emissions.find(- (e) => e.event === 'health_warn' &&- (e as Record<string, unknown>).reason === 'private_queue_startup_recovery_failed',- ) as Record<string, unknown> | undefined;- expect(warn).toBeDefined();- expect(String(warn!.error)).toContain('injected executeRaw failure');+ const diagnostic = spyOn(console, 'error').mockImplementation(() => {});+ try {+ await expect(+ maybeRunWorkerStartupRecovery(new MinionQueue(throwingEngine), { GBRAIN_SUPERVISED: '1' }, true),+ ).resolves.toBeUndefined();+ expect(diagnostic).toHaveBeenCalledWith('[gbrain jobs] private-queue startup recovery failed: injected executeRaw failure');+ } finally { diagnostic.mockRestore(); }});});@@ -627,15 +603,13 @@ describe('MinionSupervisor', () => {// classifier's reference heuristic can't leak onto sibling suites).describe('recovery hook timeout bound (structural)', () => {it('the hook bounds recovery in a Promise.race with a 30_000ms timeout', () => {- // A hanging DB call here would otherwise block EVERY worker respawn- // (the beforeSpawn await is not isStopping-checked mid-flight).const supervisorSource = readFileSync(- join(import.meta.dir, '..', 'src', 'core', 'minions', 'supervisor.ts'),+ join(import.meta.dir, '..', 'src', 'commands', 'jobs.ts'),'utf8',);- const hookStart = supervisorSource.indexOf('reconcileOrphanedPrivateQueuesBeforeWorkerSpawn');+ const hookStart = supervisorSource.indexOf('export async function maybeRunWorkerStartupRecovery');expect(hookStart).toBeGreaterThan(-1);- const hookEnd = supervisorSource.indexOf('private async shutdown(');+ const hookEnd = supervisorSource.indexOf('export async function runJobs(');expect(hookEnd).toBeGreaterThan(hookStart);const body = supervisorSource.slice(hookStart, hookEnd);expect(body).toContain('Promise.race');diff --git a/test/thin-client-routing-audit.test.ts b/test/thin-client-routing-audit.test.tsindex e9c1cfd384..33ef9ac83d 100644--- a/test/thin-client-routing-audit.test.ts+++ b/test/thin-client-routing-audit.test.ts@@ -170,6 +170,7 @@ describe('thin-client routing audit — scratch-DB additions (jobs partial dispa'utf8',);expect(src).toContain('engineOrNull: BrainEngine | null');- expect(src).toMatch(/if \(!engineOrNull && sub !== 'list' && sub !== 'get'\)/);+ expect(src).toContain("const localSupervisorStatus = sub === 'supervisor' && args[1] === 'status';");+ expect(src).toMatch(/if \(!engineOrNull && sub !== 'list' && sub !== 'get' && !localSupervisorStatus\)/);});});diff --git a/test/worker-configuration-release.test.ts b/test/worker-configuration-release.test.tsnew file mode 100644index 0000000000..a1eafab19c--- /dev/null+++ b/test/worker-configuration-release.test.ts@@ -0,0 +1,478 @@+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import { MinionWorker, type UnhealthyReason } from '../src/core/minions/worker.ts';+import { LocalConfigurationError } from '../src/core/minions/configuration-error.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { ChildWorkerShutdownError } from '../src/core/minions/child-job-runner.ts';+import { assertWorkerDbReadiness } from '../src/core/minions/db-probe.ts';++let engine: PGLiteEngine;+let queue: MinionQueue;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ queue = new MinionQueue(engine);+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await engine.executeRaw('DELETE FROM minion_jobs');+});++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>(r => { resolve = r; });+ return { promise, resolve };+}++function makeWorker() {+ return new MinionWorker(engine, { pollInterval: 5, healthCheckInterval: 0, stalledInterval: 60_000 });+}++function fault() {+ return new LocalConfigurationError('postgres_cancellation_unavailable', 'fixture cancellation unavailable');+}++describe('configuration release ownership and accounting', () => {+ test('confirmed release preserves attempts and stalls and clears ownership', async () => {+ const job = await queue.add('fixture', {});+ await queue.claim('fixture-token', 30_000, 'default', ['fixture']);+ await engine.executeRaw('UPDATE minion_jobs SET stalled_counter = 2 WHERE id = $1', [job.id]);+ const before = await queue.getJob(job.id);+ expect(await queue.releaseConfigurationJob(job.id, 'fixture-token', new AbortController().signal)).toBe('released');+ const after = await queue.getJob(job.id);+ expect(after?.status).toBe('delayed');+ expect(after?.attempts_made).toBe(before?.attempts_made);+ expect(after?.stalled_counter).toBe(2);+ expect(after?.lock_token).toBeNull();+ expect(after?.lock_until).toBeNull();+ expect(after?.delay_until!.getTime()).toBeGreaterThan(Date.now());+ expect(after?.delay_until!.getTime()).toBeLessThanOrEqual(Date.now() + 30_000);+ expect(await queue.releaseConfigurationJob(job.id, 'fixture-token', new AbortController().signal)).toBe('no_op');+ });++ test('stale tokens and terminal statuses are fenced no-ops', async () => {+ for (const status of ['active', 'cancelled', 'completed'] as const) {+ const job = await queue.add('fixture', {});+ const token = `token-${job.id}`;+ await queue.claim(token, 30_000, 'default', ['fixture']);+ if (status !== 'active') await engine.executeRaw('UPDATE minion_jobs SET status = $1 WHERE id = $2', [status, job.id]);+ const before = await queue.getJob(job.id);+ expect(await queue.releaseConfigurationJob(job.id, status === 'active' ? 'stale-token' : token, new AbortController().signal)).toBe('no_op');+ expect(await queue.getJob(job.id)).toEqual(before);+ }+ });++ test('cancelled SQL and late responses remain explicitly unconfirmed', async () => {+ const response = deferred<Array<{ id: number }>>();+ let seenSignal: AbortSignal | undefined;+ const isolated = new MinionQueue({+ executeRaw: (_sql: string, _params: unknown[], opts: { signal: AbortSignal }) => {+ seenSignal = opts.signal;+ return response.promise;+ },+ } as unknown as BrainEngine);+ const controller = new AbortController();+ const release = isolated.releaseConfigurationJob(1, 'token', controller.signal);+ controller.abort();+ expect(await release).toBe('unconfirmed');+ expect(seenSignal?.aborted).toBe(true);+ response.resolve([{ id: 1 }]);+ expect(await release).toBe('unconfirmed');+ });++ test('database loss reports fallback rather than protected release', async () => {+ const isolated = new MinionQueue({ executeRaw: async () => { throw new Error('fixture unavailable'); } } as unknown as BrainEngine);+ expect(await isolated.releaseConfigurationJob(1, 'token', new AbortController().signal)).toBe('unconfirmed');+ });+});++describe('worker configuration admission and actual execution', () => {+ test('ready fires once only after the final probe, schema and authority checks', async () => {+ const probeEntered = deferred<void>();+ const probeReady = deferred<void>();+ const schemaEntered = deferred<void>();+ const schemaReady = deferred<void>();+ const events: string[] = [];+ let probes = 0;+ const engine = {+ kind: 'postgres',+ executeRaw: async (sql: string) => {+ if (sql.trim() === 'SELECT 1') {+ probes++;+ if (probes === 2) throw new Error('fixture transient second probe');+ if (probes === 3) { probeEntered.resolve(); await probeReady.promise; }+ } else { events.push('authority'); }+ return [];+ },+ } as unknown as BrainEngine;+ await assertWorkerDbReadiness(engine);+ const worker = new MinionWorker(engine, { pollInterval: 1, healthCheckInterval: 0 });+ (worker as unknown as { queue: unknown }).queue = {+ ensureSchema: async () => { schemaEntered.resolve(); await schemaReady.promise; events.push('schema'); },+ promoteDelayed: async () => { events.push('promote'); },+ claim: async () => { events.push('claim'); worker.stop(); return null; },+ };+ worker.register('fixture', async () => {});+ worker.on('ready', () => { events.push('ready'); });+ const run = worker.start();+ await probeEntered.promise;+ expect(events).toEqual([]);+ probeReady.resolve();+ await schemaEntered.promise;+ expect(events).toEqual([]);+ schemaReady.resolve();+ await run;+ expect(events).toEqual(['schema', 'authority', 'ready', 'promote', 'claim']);+ expect(probes).toBe(3);+ });++ test('failed ready publication aborts startup before timers and claims', async () => {+ const statements: string[] = [];+ const engine = {+ kind: 'postgres',+ executeRaw: async (sql: string) => { statements.push(sql); return []; },+ } as unknown as BrainEngine;+ const worker = new MinionWorker(engine, { pollInterval: 1, healthCheckInterval: 1, stalledInterval: 1 });+ const events: string[] = [];+ (worker as unknown as { queue: unknown }).queue = {+ ensureSchema: async () => { events.push('schema'); },+ promoteDelayed: async () => { events.push('promote'); },+ claim: async () => { events.push('claim'); return null; },+ };+ worker.register('fixture', async () => {});+ worker.on('ready', () => { throw new Error('fixture status publication failed'); });+ await expect(worker.start()).rejects.toThrow('fixture status publication failed');+ await Bun.sleep(10);+ expect(events).toEqual(['schema']);+ expect(statements).toHaveLength(2);+ expect((worker as unknown as { running: boolean }).running).toBe(false);+ });++ test('Postgres startup faults block before schema recovery, claims, and timers', async () => {+ const error = fault();+ const statements: string[] = [];+ const worker = new MinionWorker({+ kind: 'postgres',+ executeRaw: async (sql: string) => { statements.push(sql); throw error; },+ } as unknown as BrainEngine, { healthCheckInterval: 1, stalledInterval: 1 });+ worker.register('fixture', async () => { throw new Error('handler must not run'); });+ await worker.start();+ await new Promise(resolve => setTimeout(resolve, 10));+ expect(worker.configurationError).toBe(error);+ expect(statements).toEqual(['SELECT 1']);+ });++ test('Postgres readiness waits before any schema recovery or claims', async () => {+ const ready = deferred<void>();+ const entered = deferred<void>();+ const statements: string[] = [];+ const worker = new MinionWorker({+ kind: 'postgres',+ executeRaw: async (sql: string) => {+ statements.push(sql);+ entered.resolve();+ await ready.promise;+ return [];+ },+ } as unknown as BrainEngine, { healthCheckInterval: 1, stalledInterval: 1 });+ worker.register('fixture', async () => {});+ const run = worker.start();+ await entered.promise;+ await new Promise(resolve => setTimeout(resolve, 10));+ expect(statements).toEqual(['SELECT 1']);+ worker.stop();+ ready.resolve();+ await run;+ expect(statements).toEqual(['SELECT 1']);+ });++ test('transient startup failure retries readiness before admitting work', async () => {+ const events: string[] = [];+ let probes = 0;+ const worker = new MinionWorker({+ kind: 'postgres',+ executeRaw: async (sql: string) => {+ if (sql.trim() === 'SELECT 1') {+ events.push('probe');+ if (++probes === 1) throw new Error('fixture connection refused');+ }+ return [];+ },+ } as unknown as BrainEngine, { pollInterval: 1, healthCheckInterval: 0 });+ (worker as unknown as { queue: unknown }).queue = {+ ensureSchema: async () => { events.push('schema'); },+ promoteDelayed: async () => { events.push('promote'); },+ claim: async () => { events.push('claim'); worker.stop(); return null; },+ };+ worker.register('fixture', async () => {});+ await worker.start();+ expect(events).toEqual(['probe', 'probe', 'schema', 'promote', 'claim']);+ expect(worker.configurationError).toBeNull();+ });++ test('periodic typed faults bypass the ordinary database failure counter', async () => {+ const executeRaw = engine.executeRaw;+ const error = fault();+ let probes = 0;+ engine.executeRaw = (async (sql: string, ...args: unknown[]) => {+ if (sql.trim() === 'SELECT 1') { probes++; throw error; }+ return executeRaw.call(engine, sql, ...args as [unknown[]]);+ }) as typeof engine.executeRaw;+ try {+ const worker = new MinionWorker(engine, { pollInterval: 5, healthCheckInterval: 5, dbFailExitAfter: 100 });+ worker.register('fixture', async () => {});+ await worker.start();+ expect(worker.configurationError).toBe(error);+ expect(probes).toBe(1);+ } finally {+ engine.executeRaw = executeRaw;+ }+ });++ test('a late ordinary health failure cannot override a latched configuration block', async () => {+ const original = engine.executeRaw;+ const entered = deferred<void>();+ const resume = deferred<void>();+ engine.executeRaw = (async (sql: string, ...args: unknown[]) => {+ if (sql.trim() === 'SELECT 1') {+ entered.resolve();+ await resume.promise;+ throw new Error('fixture network failure');+ }+ return original.call(engine, sql, ...args as [unknown[]]);+ }) as typeof engine.executeRaw;+ try {+ const worker = new MinionWorker(engine, { pollInterval: 5, healthCheckInterval: 5, dbFailExitAfter: 1 });+ const events: UnhealthyReason[] = [];+ worker.on('unhealthy', event => events.push(event));+ worker.register('fixture', async () => {});+ const run = worker.start();+ await entered.promise;+ worker.blockForConfiguration(fault());+ await run;+ resume.resolve();+ await new Promise(resolve => setTimeout(resolve, 20));+ expect(events.map(event => event.reason)).toEqual(['client_misconfigured']);+ } finally {+ resume.resolve();+ engine.executeRaw = original;+ }+ });++ test('typed handler fault blocks before accounting and preserves the claimed job', async () => {+ const job = await queue.add('fixture', {}, { max_attempts: 1 });+ const second = await queue.add('fixture', {});+ const worker = makeWorker();+ const error = fault();+ const events: UnhealthyReason[] = [];+ let starts = 0;+ worker.register('fixture', async () => { starts++; throw error; });+ worker.on('unhealthy', info => {+ expect(worker.configurationError).toBe(error);+ events.push(info);+ });+ await worker.start();+ worker.blockForConfiguration(fault());+ expect(events).toEqual([{ reason: 'client_misconfigured', error }]);+ expect(starts).toBe(1);+ expect((await queue.getJob(job.id))?.status).toBe('delayed');+ expect((await queue.getJob(job.id))?.attempts_made).toBe(0);+ expect((await queue.getJob(job.id))?.stalled_counter).toBe(0);+ expect((await queue.getJob(second.id))?.status).toBe('waiting');+ expect(worker.configurationReleaseResults.map(result => result.outcome)).toEqual(['released']);+ await worker.start();+ expect(starts).toBe(1);+ });++ test('same error text without the type remains an ordinary job failure', async () => {+ const job = await queue.add('fixture', {}, { max_attempts: 1 });+ const worker = makeWorker();+ worker.register('fixture', async () => { worker.stop(); throw new Error(fault().message); });+ await worker.start();+ expect(worker.configurationError).toBeNull();+ expect((await queue.getJob(job.id))?.status).toBe('dead');+ expect((await queue.getJob(job.id))?.attempts_made).toBe(1);+ });++ test('a typed recording fault blocks before execution tracking is discarded', async () => {+ const job = await queue.add('fixture', {});+ const worker = makeWorker();+ const error = fault();+ (worker as unknown as { queue: MinionQueue }).queue.failJob = async () => { throw error; };+ worker.register('fixture', async () => { throw new Error('fixture ordinary handler error'); });+ await worker.start();+ expect(worker.configurationError).toBe(error);+ expect((await queue.getJob(job.id))?.status).toBe('delayed');+ expect((await queue.getJob(job.id))?.attempts_made).toBe(0);+ expect(worker.configurationReleaseResults.map(result => result.outcome)).toEqual(['released']);+ });++ test('a paused late claim is registered and released without executing', async () => {+ const job = await queue.add('fixture', {});+ const worker = makeWorker();+ const claimed = deferred<void>();+ const resume = deferred<void>();+ const internals = worker as unknown as { queue: MinionQueue };+ const claim = internals.queue.claim.bind(internals.queue);+ internals.queue.claim = async (...args) => {+ const result = await claim(...args);+ claimed.resolve();+ await resume.promise;+ return result;+ };+ let starts = 0;+ worker.register('fixture', async () => { starts++; });+ const run = worker.start();+ await claimed.promise;+ worker.blockForConfiguration(fault());+ resume.resolve();+ await run;+ expect(starts).toBe(0);+ expect((await queue.getJob(job.id))?.status).toBe('delayed');+ expect((await queue.getJob(job.id))?.attempts_made).toBe(0);+ expect(worker.configurationReleaseResults.map(result => result.outcome)).toEqual(['released']);+ });++ test('scheduling eviction cannot authorize release of a live inline handler', async () => {+ const job = await queue.add('fixture', {});+ const worker = makeWorker();+ const started = deferred<void>();+ const settle = deferred<void>();+ const internals = worker as unknown as { inFlight: Map<number, unknown>; configurationDeadline: number };+ worker.register('fixture', async () => { started.resolve(); await settle.promise; throw fault(); });+ const run = worker.start();+ await started.promise;+ internals.inFlight.clear();+ worker.blockForConfiguration(fault());+ internals.configurationDeadline = performance.now() + 30;+ await run;+ expect((await queue.getJob(job.id))?.status).toBe('active');+ expect((await queue.getJob(job.id))?.attempts_made).toBe(0);+ expect(worker.configurationReleaseResults.map(result => result.outcome)).toEqual(['unconfirmed']);+ settle.resolve();+ await new Promise(resolve => setTimeout(resolve, 20));+ expect((await queue.getJob(job.id))?.status).toBe('active');+ });++ test('cooperative inline shutdown releases only after execution has settled', async () => {+ const job = await queue.add('fixture', {});+ const worker = makeWorker();+ const started = deferred<void>();+ const settle = deferred<void>();+ worker.register('fixture', async () => { started.resolve(); await settle.promise; throw new Error('fixture stopped'); });+ const run = worker.start();+ await started.promise;+ worker.blockForConfiguration(fault());+ await new Promise(resolve => setTimeout(resolve, 20));+ expect((await queue.getJob(job.id))?.status).toBe('active');+ settle.resolve();+ await run;+ expect((await queue.getJob(job.id))?.status).toBe('delayed');+ expect((await queue.getJob(job.id))?.attempts_made).toBe(0);+ expect(worker.configurationReleaseResults.map(result => result.outcome)).toEqual(['released']);+ });++ test('unconfirmed child cleanup cannot authorize delayed release', async () => {+ const job = await queue.add('fixture', {});+ const worker = makeWorker();+ const started = deferred<void>();+ const settle = deferred<void>();+ worker.register('fixture', async () => { started.resolve(); await settle.promise; throw new ChildWorkerShutdownError('fixture cleanup unconfirmed', false); });+ const run = worker.start();+ await started.promise;+ worker.blockForConfiguration(fault());+ (worker as unknown as { configurationDeadline: number }).configurationDeadline = performance.now() + 30;+ settle.resolve();+ await run;+ expect((await queue.getJob(job.id))?.status).toBe('active');+ expect((await queue.getJob(job.id))?.attempts_made).toBe(0);+ expect(worker.configurationReleaseResults.map(result => result.outcome)).toEqual(['unconfirmed']);+ });++ test('the real 30-second eviction cannot dead-letter or release live inline execution', async () => {+ const job = await queue.add('fixture', {}, { max_attempts: 1 });+ const worker = makeWorker();+ const started = deferred<void>();+ const settle = deferred<void>();+ worker.register('fixture', async () => { started.resolve(); await settle.promise; throw new Error('fixture stopped late'); });+ const run = worker.start();+ await started.promise;+ const began = performance.now();+ worker.blockForConfiguration(fault());+ await run;+ expect(performance.now() - began).toBeGreaterThanOrEqual(29_900);+ expect(performance.now() - began).toBeLessThan(32_000);+ expect((await queue.getJob(job.id))?.status).toBe('active');+ expect((await queue.getJob(job.id))?.attempts_made).toBe(0);+ expect(worker.configurationReleaseResults.map(result => result.outcome)).toEqual(['unconfirmed']);+ settle.resolve();+ await new Promise(resolve => setTimeout(resolve, 20));+ expect((await queue.getJob(job.id))?.status).toBe('active');+ }, 40_000);++ test('a claim still unknown at the global deadline reports lease-expiry fallback', async () => {+ const job = await queue.add('fixture', {});+ const worker = makeWorker();+ const entered = deferred<void>();+ const resume = deferred<void>();+ const internals = worker as unknown as { queue: MinionQueue; configurationDeadline: number };+ const claim = internals.queue.claim.bind(internals.queue);+ internals.queue.claim = async (...args) => {+ const result = await claim(...args);+ entered.resolve();+ await resume.promise;+ return result;+ };+ let starts = 0;+ worker.register('fixture', async () => { starts++; });+ const run = worker.start();+ await entered.promise;+ worker.blockForConfiguration(fault());+ internals.configurationDeadline = performance.now() + 30;+ await run;+ expect(worker.configurationReleaseResults).toHaveLength(1);+ expect(worker.configurationReleaseResults[0]).toMatchObject({ jobId: null, outcome: 'unconfirmed' });+ resume.resolve();+ await new Promise(resolve => setTimeout(resolve, 20));+ expect(starts).toBe(0);+ expect(worker.configurationReleaseResults[0]).toMatchObject({ jobId: job.id, outcome: 'unconfirmed' });+ expect((await queue.getJob(job.id))?.status).toBe('active');+ });++ test('40 owned tokens share one deadline and at most four release queries', async () => {+ const worker = makeWorker();+ const internals = worker as unknown as {+ queue: MinionQueue;+ executions: Map<string, { job: { id: number }; lockToken: string; stopped: boolean }>;+ configurationDeadline: number;+ drainConfiguration(): Promise<void>;+ };+ for (let id = 1; id <= 40; id++) internals.executions.set(`token-${id}`, { job: { id }, lockToken: `token-${id}`, stopped: true });+ let active = 0;+ let peak = 0;+ internals.queue.releaseConfigurationJob = async (id, _token, signal) => {+ active++;+ peak = Math.max(peak, active);+ if (id === 1) await new Promise<void>(resolve => signal.addEventListener('abort', () => resolve(), { once: true }));+ else await new Promise(resolve => setTimeout(resolve, 1));+ active--;+ return signal.aborted ? 'unconfirmed' : 'released';+ };+ worker.blockForConfiguration(fault());+ internals.configurationDeadline = performance.now() + 250;+ const began = performance.now();+ await internals.drainConfiguration();+ expect(performance.now() - began).toBeLessThan(1000);+ expect(peak).toBeLessThanOrEqual(4);+ expect(worker.configurationReleaseResults).toHaveLength(40);+ expect(worker.configurationReleaseResults.filter(result => result.outcome === 'released')).toHaveLength(39);+ expect(worker.configurationReleaseResults.filter(result => result.outcome === 'unconfirmed')).toHaveLength(1);+ });+});diff --git a/test/worker-conn-resilience-1720.test.ts b/test/worker-conn-resilience-1720.test.tsindex e30db6de18..9053baba32 100644--- a/test/worker-conn-resilience-1720.test.ts+++ b/test/worker-conn-resilience-1720.test.ts@@ -37,6 +37,7 @@ function makeEngine(counter: { reconnects: number }): BrainEngine {kind: 'postgres',reconnect: async () => { counter.reconnects += 1; },executeRaw: async (sql: string) => {+ if (sql.trim() === 'SELECT 1') return [];// These reconnect fixtures contain no unresolved legacy work. Keep the// real startup authority check, and reject unrelated unexpected queries.if (sql.includes('SELECT id, submission_authority FROM minion_jobs') &&diff --git a/test/worker-job-isolation.test.ts b/test/worker-job-isolation.test.tsindex 0292fee412..58bebf209b 100644--- a/test/worker-job-isolation.test.ts+++ b/test/worker-job-isolation.test.ts@@ -13,6 +13,8 @@*/import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { MinionQueue } from '../src/core/minions/queue.ts';@@ -103,7 +105,7 @@ describe('worker with jobIsolation=process (PGLite + fake child)', () => {const j1 = await queue.add('isotest', {});const j2 = await queue.add('isotest', {});const j3 = await queue.add('isotest', {});- const worker = makeWorker('/nonexistent/gbrain-binary', []);+ const worker = makeWorker(process.execPath, ['-e', 'process.exit(13)']);const unhealthy: unknown[] = [];worker.on('unhealthy', (i) => unhealthy.push(i));const run = worker.start();@@ -200,7 +202,7 @@ describe('worker with jobIsolation=process (PGLite + fake child)', () => {test('spawn failure: RELEASED — still active, attempts NOT burned (infra class)', async () => {const job = await queue.add('isotest', {});- const worker = makeWorker('/nonexistent/gbrain-binary', []);+ const worker = makeWorker(process.execPath, ['-e', 'process.exit(13)']);// The claim happens, the spawn fails, the job is released (stays// 'active' until lock expiry — the stall sweeper's requeue territory).const run = worker.start();@@ -211,4 +213,85 @@ describe('worker with jobIsolation=process (PGLite + fake child)', () => {expect(row.status).toBe('active'); // NOT dead, NOT failedexpect(row.attempts_made).toBe(0); // release = no failJob = no attempt burned}, 20_000);++ test('missing executable blocks once and releases only the owned claim', async () => {+ const first = await queue.add('isotest', {});+ const second = await queue.add('isotest', {});+ const worker = makeWorker('/nonexistent/gbrain-binary', []);+ const events: unknown[] = [];+ worker.on('unhealthy', event => events.push(event));+ await worker.start();+ expect(events).toHaveLength(1);+ expect(events[0]).toMatchObject({ reason: 'client_misconfigured', error: { reasonCode: 'child_executable_invalid' } });+ expect(worker.configurationError?.reasonCode).toBe('child_executable_invalid');+ expect((await jobRow(first.id)).status).toBe('delayed');+ expect((await jobRow(first.id)).attempts_made).toBe(0);+ expect((await jobRow(second.id)).status).toBe('waiting');+ expect((await jobRow(second.id)).attempts_made).toBe(0);+ expect(worker.configurationReleaseResults.map(result => result.outcome)).toEqual(['released']);+ });++ test('typed child outcomes block before cleanup and retain unconfirmed ownership', async () => {+ const first = await queue.add('isotest', {});+ const second = await queue.add('isotest', {});+ const outcome = JSON.stringify({+ outcome: 'error', errorKind: 'local_configuration', protocolVersion: 1,+ reasonCode: 'postgres_cancellation_unavailable', message: 'fixture fault',+ });+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-typed-unconfirmed-'));+ const grandchildPid = join(dir, 'grandchild.pid');+ const grandchild = join(dir, 'grandchild.cjs');+ const parent = join(dir, 'parent.cjs');+ writeFileSync(grandchild, `process.on('SIGTERM', () => {}); require('node:fs').writeFileSync(${JSON.stringify(grandchildPid)}, String(process.pid)); setInterval(() => {}, 1000);`);+ writeFileSync(parent, `const fs = require('node:fs');+ require('node:child_process').spawn(process.execPath, [${JSON.stringify(grandchild)}], { stdio: 'ignore' }).unref();+ while (!fs.existsSync(${JSON.stringify(grandchildPid)})) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5);+ fs.writeFileSync(process.env.GBRAIN_JOB_RESULT_PATH, ${JSON.stringify(outcome)});`);+ try {+ const worker = makeWorker(process.execPath, [parent]);+ const internals = worker as unknown as {+ configurationDeadline: number;+ executions: Map<string, { promise: Promise<void> }>;+ };+ let execution: Promise<void> | undefined;+ worker.on('unhealthy', event => {+ if (event.reason !== 'client_misconfigured') return;+ internals.configurationDeadline = performance.now() + 100;+ execution = [...internals.executions.values()][0]?.promise;+ });+ const began = performance.now();+ await worker.start();+ expect(performance.now() - began).toBeLessThan(5000);+ expect(worker.configurationError?.reasonCode).toBe('postgres_cancellation_unavailable');+ expect((await jobRow(first.id)).status).toBe('active');+ expect((await jobRow(first.id)).attempts_made).toBe(0);+ expect((await jobRow(second.id)).status).toBe('waiting');+ expect(worker.configurationReleaseResults.map(result => result.outcome)).toEqual(['unconfirmed']);+ await execution;+ expect((await jobRow(first.id)).status).toBe('active');+ expect((await jobRow(first.id)).attempts_made).toBe(0);+ } finally {+ if (existsSync(grandchildPid)) { try { process.kill(Number(readFileSync(grandchildPid, 'utf8')), 'SIGKILL'); } catch {} }+ rmSync(dir, { recursive: true, force: true });+ }+ }, 35_000);++ test.skipIf(process.platform !== 'linux')('typed child outcome with confirmed group cleanup releases the claim inside the configuration deadline', async () => {+ const first = await queue.add('isotest', {});+ const second = await queue.add('isotest', {});+ const outcome = JSON.stringify({+ outcome: 'error', errorKind: 'local_configuration', protocolVersion: 1,+ reasonCode: 'postgres_cancellation_unavailable', message: 'fixture fault',+ });+ const program = `require('node:fs').writeFileSync(process.env.GBRAIN_JOB_RESULT_PATH, ${JSON.stringify(outcome)});`;+ const worker = makeWorker(process.execPath, ['-e', program]);+ const began = performance.now();+ await worker.start();+ expect(performance.now() - began).toBeLessThan(5000);+ expect(worker.configurationError?.reasonCode).toBe('postgres_cancellation_unavailable');+ expect(worker.configurationReleaseResults.map(result => result.outcome)).toEqual(['released']);+ expect((await jobRow(first.id)).status).toBe('delayed');+ expect((await jobRow(first.id)).attempts_made).toBe(0);+ expect((await jobRow(second.id)).status).toBe('waiting');+ }, 35_000);});diff --git a/test/worker-promote-reconnect.test.ts b/test/worker-promote-reconnect.test.tsindex 1387378486..aca361c3cf 100644--- a/test/worker-promote-reconnect.test.ts+++ b/test/worker-promote-reconnect.test.ts@@ -6,6 +6,7 @@ function makeEngineWithReconnect(counter: { calls: number }, events: string[]):return {kind: 'postgres',executeRaw: async (sql: string) => {+ if (sql.trim() === 'SELECT 1') return [];// Startup sees no unresolved legacy work; promotion recovery below is// still exercised by the scripted queue error, before the next claim.if (sql.includes('SELECT id, submission_authority FROM minion_jobs') &&diff --git a/test/worker-renewal-configuration.test.ts b/test/worker-renewal-configuration.test.tsnew file mode 100644index 0000000000..6948770e5a--- /dev/null+++ b/test/worker-renewal-configuration.test.ts@@ -0,0 +1,89 @@+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import { MinionWorker, type UnhealthyReason } from '../src/core/minions/worker.ts';+import { LocalConfigurationError } from '../src/core/minions/configuration-error.ts';++let engine: PGLiteEngine;+let queue: MinionQueue;+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ queue = new MinionQueue(engine);+});+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => { await engine.executeRaw('DELETE FROM minion_jobs'); });++test.each([+ { name: 'typed primary renewal', faultAt: 1, typed: true, network: false },+ { name: 'typed deadline verification', faultAt: 2, typed: true, network: false },+ { name: 'same-text ordinary renewal failure', faultAt: 1, typed: false, network: false },+ { name: 'ordinary network renewal failure', faultAt: 1, typed: false, network: true },+])('$name preserves configuration provenance and execution ownership', async ({ faultAt, typed, network }) => {+ const job = await queue.add('fixture', {});+ const next = await queue.add('fixture', {});+ const worker = new MinionWorker(engine, { pollInterval: 5, healthCheckInterval: 0, stalledInterval: 60_000, lockDuration: 200 });+ const internals = worker as unknown as { queue: MinionQueue; running: boolean };+ const error = typed+ ? new LocalConfigurationError('postgres_cancellation_unavailable', 'fixture cancellation unavailable')+ : new Error(network ? 'Connection terminated' : 'fixture cancellation unavailable');+ const originalRenew = internals.queue.renewLock.bind(internals.queue);+ const originalClaim = internals.queue.claim.bind(internals.queue);+ let renewals = 0;+ let claims = 0;+ let ready = false;+ let handlerSignal: AbortSignal | undefined;+ let settle!: () => void;+ const stopped = new Promise<void>(resolve => { settle = resolve; });+ const events: UnhealthyReason[] = [];+ internals.queue.claim = async (...args) => { claims++; return originalClaim(...args); };+ internals.queue.renewLock = async (...args) => {+ renewals++;+ if (renewals === faultAt) throw error;+ if (renewals < faultAt) throw new Error('fixture temporary renewal failure');+ return originalRenew(...args);+ };+ worker.on('ready', () => { ready = true; });+ worker.on('unhealthy', event => { events.push(event); });+ worker.register('fixture', async context => {+ handlerSignal = context.signal;+ await stopped;+ if (context.signal.aborted) throw context.signal.reason;+ return { fixture: true };+ });+ const run = worker.start();+ try {+ const deadline = performance.now() + 1_500;+ while (performance.now() < deadline && (typed ? !worker.configurationError : renewals <= faultAt)) await Bun.sleep(5);+ expect(ready).toBe(true);+ expect((await engine.executeRaw<{ n: number }>('SELECT 1::int AS n'))[0].n).toBe(1);+ expect((await queue.getJob(next.id))?.status).toBe('waiting');+ if (error instanceof LocalConfigurationError) {+ expect(worker.configurationError).toBe(error);+ expect(events).toEqual([{ reason: 'client_misconfigured', error }]);+ expect(internals.running).toBe(false);+ expect(handlerSignal?.reason).toBe(error);+ expect(renewals).toBe(faultAt);+ expect((await queue.getJob(job.id))?.status).toBe('active');+ expect(worker.configurationReleaseResults).toHaveLength(0);+ settle();+ await run;+ expect((await queue.getJob(job.id))?.status).toBe('delayed');+ expect((await queue.getJob(job.id))?.attempts_made).toBe(0);+ expect((await queue.getJob(job.id))?.stalled_counter).toBe(0);+ expect(worker.configurationReleaseResults.map(result => result.outcome)).toEqual(['released']);+ expect(claims).toBe(1);+ } else {+ expect(worker.configurationError).toBeNull();+ expect(events).toEqual([]);+ expect(internals.running).toBe(true);+ expect(handlerSignal?.aborted).toBe(false);+ expect(renewals).toBeGreaterThan(faultAt);+ }+ } finally {+ worker.stop();+ settle();+ await run;+ }+}, 10_000);diff --git a/vendor/README.md b/vendor/README.mdnew file mode 100644index 0000000000..39d9642da6--- /dev/null+++ b/vendor/README.md@@ -0,0 +1,79 @@+# GBrain's Postgres driver++`postgres/` is the exact published `[email protected]` package from+https://github.com/porsager/postgres, with GBrain's checked-in+`patches/[email protected]` applied. The package is **Unlicense**, not MIT;+the original upstream license is preserved in `postgres/UNLICENSE` (the npm+tarball omits this file, so the updater retrieves and verifies it separately).+Original package metadata and attribution are retained.++The registry's latest supported release was inspected on 2026-09-27 and was+still 3.4.9. Its stock reserved and transaction owners do not implement the+`discard()` capability needed by GBrain's cancellation fence. No version+upgrade or opaque third-party fork is being substituted for that capability.++## Why source is shipped++The root package-private `#postgres` import maps directly into this directory.+Every driver import resolves through this one package import. Bun and+Node ESM use `src/`; CommonJS uses `cjs/src/`; compiled Bun artifacts embed+those same resolved source bytes. The workerd export receives the identical+ESM patch, preserving its upstream polyfill imports. GBrain itself does not+support a workerd runtime.++This deliberately avoids Bun's transitive `file:` dependency resolution, which+can report a successful packed installation while leaving the driver absent.+The patched bytes are part of GBrain's checkout and package, not a+`patchedDependencies` instruction that a global install may ignore. No+postinstall mutation of another package's node_modules is needed. The patch+file remains the auditable source of the delta, not an installation hook.++The patch adds abort-aware reservation, reserved/transaction-owner discard,+CancelRequest settlement tracking and ownership/pipeline fences. Cancellation+must settle or retire the connection before another query can own it. This+is necessary for worker admission, query timeout and lease-release safety.+See issues #5466 and #5560 and `test/e2e/persistence-chaos.test.ts`.++## Reproduce and update++Run `bash vendor/update-postgres.sh --check` to download the pinned upstream+tarball, verify SHA-512, apply the checked-in patch to every published runtime+export, verify the upstream license and compare every byte. Run without+`--check` to regenerate `postgres/`. This does not read a brain or alter any+installed service. No driver dependency installation is required after regeneration.++For security updates, the GBrain release maintainer owns this dependency:+review upstream security advisories and supported releases, update the exact+version/URLs/hashes here and in the updater, rebase the patch against pristine+upstream source, regenerate, then review the entire diff. Never edit only an+installed node_modules copy. Do not suppress the runtime capability guard.++Before retiring this vendor, prove the candidate upstream release passes the+same runtime reserved-owner check, interrupted reservation and in-query+cancellation tests, successor-query fence tests, real Postgres and+transaction-mode PgBouncer tests, and fresh/upgrade/packed/GitHub-global and+compiled distribution smokes. An ordinary unsignalled SELECT or matching+version is not evidence of safe cancellation. Publish the distribution and+platform results, including any unavailable target, before changing the+dependency back to the registry.++## Isolated install smoke++With a disposable test-shaped database, run:++```sh+GBRAIN_TEST_ALLOW_DATABASE_URL=1 GBRAIN_TEST_PACKAGE_SMOKE=1 \+ DATABASE_URL="$DISPOSABLE_TEST_DATABASE_URL" \+ bun test test/e2e/postgres-driver-install.test.ts+```++This uses isolated HOME/cache/install directories, no paid providers, and+tests a checkout, actual packed installation, global tarball installation,+an independently installed stock-driver negative fixture, a stale stock+module alongside the new installation, and a Linux compiled job fixture.+Each positive runtime validates readiness and cancellation, then completes a+harmless minion job. The macOS ARM64 fixture is cross-compiled, not run; native+macOS execution is a separate platform acceptance gate. To test a published+GitHub revision's global installation instead of the local global tarball,+also set `GBRAIN_TEST_GITHUB_PACKAGE=github:garrytan/gbrain#<published-sha>`.+Do not claim GitHub transport validation before that revision is available.diff --git a/vendor/postgres/README.md b/vendor/postgres/README.mdnew file mode 100644index 0000000000..3e73281a67--- /dev/null+++ b/vendor/postgres/README.md@@ -0,0 +1,1392 @@+<img align="left" width="440" height="180" alt="Fastest full PostgreSQL nodejs client" src="https://raw.githubusercontent.com/porsager/postgres/master/postgresjs.svg?sanitize=true">++- [🚀 Fastest full-featured node & deno client](https://github.com/porsager/postgres-benchmarks#results)+- 🏷 ES6 Tagged Template Strings at the core+- 🏄♀️ Simple surface API+- 🖊️ Dynamic query support+- 💬 Chat and help on [Gitter](https://gitter.im/porsager/postgres)+- 🐦 Follow on [Twitter](https://twitter.com/rporsager)++<br>++## Getting started++<br>+<img height="220" width="458" alt="Good UX with Postgres.js" src="https://raw.githubusercontent.com/porsager/postgres/master/demo.gif">+<br>++### Installation+```bash+$ npm install postgres+```++### Usage+Create your `sql` database instance+```js+// db.js+import postgres from 'postgres'++const sql = postgres({ /* options */ }) // will use psql environment variables++export default sql+```++Simply import for use elsewhere+```js+// users.js+import sql from './db.js'++async function getUsersOver(age) {+ const users = await sql`+ select+ name,+ age+ from users+ where age > ${ age }+ `+ // users = Result [{ name: "Walter", age: 80 }, { name: 'Murray', age: 68 }, ...]+ return users+}+++async function insertUser({ name, age }) {+ const users = await sql`+ insert into users+ (name, age)+ values+ (${ name }, ${ age })+ returning name, age+ `+ // users = Result [{ name: "Murray", age: 68 }]+ return users+}+```++#### ESM dynamic imports++The library can be used with ESM dynamic imports as well as shown here.++```js+const { default: postgres } = await import('postgres')+```++## Table of Contents++* [Connection](#connection)+* [Queries](#queries)+* [Building queries](#building-queries)+* [Advanced query methods](#advanced-query-methods)+* [Transactions](#transactions)+* [Data Transformation](#data-transformation)+* [Listen & notify](#listen--notify)+* [Realtime subscribe](#realtime-subscribe)+* [Numbers, bigint, numeric](#numbers-bigint-numeric)+* [Result Array](#result-array)+* [Connection details](#connection-details)+* [Custom Types](#custom-types)+* [Teardown / Cleanup](#teardown--cleanup)+* [Error handling](#error-handling)+* [TypeScript support](#typescript-support)+* [Reserving connections](#reserving-connections)+* [Changelog](./CHANGELOG.md)+++## Connection++### `postgres([url], [options])`++You can use either a `postgres://` url connection string or the options to define your database connection properties. Options in the object will override any present in the url. Options will fall back to the same environment variables as psql.++```js+const sql = postgres('postgres://username:password@host:port/database', {+ host : '', // Postgres ip address[s] or domain name[s]+ port : 5432, // Postgres server port[s]+ database : '', // Name of database to connect to+ username : '', // Username of database user+ password : '', // Password of database user+ ...and more+})+```++More options can be found in the [Connection details section](#connection-details).++## Queries++### ```await sql`...` -> Result[]```++Postgres.js utilizes [Tagged template functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates) to process query parameters **before** interpolation. Using tagged template literals benefits developers by:++1. **Enforcing** safe query generation+2. Giving the ` sql`` ` function powerful [utility](#dynamic-inserts) and [query building](#building-queries) features.++Any generic value will be serialized according to an inferred type, and replaced by a PostgreSQL protocol placeholder `$1, $2, ...`. The parameters are then sent separately to the database which handles escaping & casting.++All queries will return a `Result` array, with objects mapping column names to each row.++```js+const xs = await sql`+ insert into users (+ name, age+ ) values (+ 'Murray', 68+ )++ returning *+`++// xs = [{ user_id: 1, name: 'Murray', age: 68 }]+```++> Please note that queries are first executed when `awaited` – or instantly by using [`.execute()`](#execute).++### Query parameters++Parameters are automatically extracted and handled by the database so that SQL injection isn't possible. No special handling is necessary, simply use tagged template literals as usual.++```js+const name = 'Mur'+ , age = 60++const users = await sql`+ select+ name,+ age+ from users+ where+ name like ${ name + '%' }+ and age > ${ age }+`+// users = [{ name: 'Murray', age: 68 }]+```++> Be careful with quotation marks here. Because Postgres infers column types, you do not need to wrap your interpolated parameters in quotes like `'${name}'`. This will cause an error because the tagged template replaces `${name}` with `$1` in the query string, leaving Postgres to do the interpolation. If you wrap that in a string, Postgres will see `'$1'` and interpret it as a string as opposed to a parameter.++### Dynamic column selection++```js+const columns = ['name', 'age']++await sql`+ select+ ${ sql(columns) }+ from users+`++// Which results in:+select "name", "age" from users+```++### Dynamic inserts++```js+const user = {+ name: 'Murray',+ age: 68+}++await sql`+ insert into users ${+ sql(user, 'name', 'age')+ }+`++// Which results in:+insert into users ("name", "age") values ($1, $2)++// The columns can also be given with an array+const columns = ['name', 'age']++await sql`+ insert into users ${+ sql(user, columns)+ }+`+```++**You can omit column names and simply execute `sql(user)` to get all the fields from the object as columns**. Be careful not to allow users to supply columns that you do not want to be inserted.++#### Multiple inserts in one query+If you need to insert multiple rows at the same time it's also much faster to do it with a single `insert`. Simply pass an array of objects to `sql()`.++```js+const users = [{+ name: 'Murray',+ age: 68,+ garbage: 'ignore'+},+{+ name: 'Walter',+ age: 80+}]++await sql`insert into users ${ sql(users, 'name', 'age') }`++// Is translated to:+insert into users ("name", "age") values ($1, $2), ($3, $4)++// Here you can also omit column names which will use object keys as columns+await sql`insert into users ${ sql(users) }`++// Which results in:+insert into users ("name", "age") values ($1, $2), ($3, $4)+```++### Dynamic columns in updates+This is also useful for update queries+```js+const user = {+ id: 1,+ name: 'Murray',+ age: 68+}++await sql`+ update users set ${+ sql(user, 'name', 'age')+ }+ where user_id = ${ user.id }+`++// Which results in:+update users set "name" = $1, "age" = $2 where user_id = $3++// The columns can also be given with an array+const columns = ['name', 'age']++await sql`+ update users set ${+ sql(user, columns)+ }+ where user_id = ${ user.id }+`+```++### Multiple updates in one query+To create multiple updates in a single query, it is necessary to use arrays instead of objects to ensure that the order of the items correspond with the column names.+```js+const users = [+ [1, 'John', 34],+ [2, 'Jane', 27],+]++await sql`+ update users set name = update_data.name, age = (update_data.age)::int+ from (values ${sql(users)}) as update_data (id, name, age)+ where users.id = (update_data.id)::int+ returning users.id, users.name, users.age+`+```++### Dynamic values and `where in`+Value lists can also be created dynamically, making `where in` queries simple too.+```js+const users = await sql`+ select+ *+ from users+ where age in ${ sql([68, 75, 23]) }+`+```++or+```js+const [{ a, b, c }] = await sql`+ select+ *+ from (values ${ sql(['a', 'b', 'c']) }) as x(a, b, c)+`+```++## Building queries++Postgres.js features a simple dynamic query builder by conditionally appending/omitting query fragments.+It works by nesting ` sql`` ` fragments within other ` sql`` ` calls or fragments. This allows you to build dynamic queries safely without risking sql injections through usual string concatenation.++### Partial queries+```js+const olderThan = x => sql`and age > ${ x }`++const filterAge = true++await sql`+ select+ *+ from users+ where name is not null ${+ filterAge+ ? olderThan(50)+ : sql``+ }+`+// Which results in:+select * from users where name is not null+// Or+select * from users where name is not null and age > 50+```++### Dynamic filters+```js+await sql`+ select+ *+ from users ${+ id+ ? sql`where user_id = ${ id }`+ : sql``+ }+`++// Which results in:+select * from users+// Or+select * from users where user_id = $1+```++### Dynamic ordering++```js+const id = 1+const order = {+ username: 'asc'+ created_at: 'desc'+}+await sql`+ select+ *+ from ticket+ where account = ${ id }+ order by ${+ Object.entries(order).flatMap(([column, order], i) =>+ [i ? sql`,` : sql``, sql`${ sql(column) } ${ order === 'desc' ? sql`desc` : sql`asc` }`]+ )+ }+`+```++### SQL functions+Using keywords or calling functions dynamically is also possible by using ``` sql`` ``` fragments.+```js+const date = null++await sql`+ update users set updated_at = ${ date || sql`now()` }+`++// Which results in:+update users set updated_at = now()+```++### Table names+Dynamic identifiers like table names and column names is also supported like so:+```js+const table = 'users'+ , column = 'id'++await sql`+ select ${ sql(column) } from ${ sql(table) }+`++// Which results in:+select "id" from "users"+```++### Quick primer on interpolation++Here's a quick oversight over all the ways to do interpolation in a query template string:++| Interpolation syntax | Usage | Example |+| ------------- | ------------- | ------------- |+| `${ sql`` }` | for keywords or sql fragments | ``await sql`SELECT * FROM users ${sql`order by age desc` }` `` |+| `${ sql(string) }` | for identifiers | ``await sql`SELECT * FROM ${sql('table_name')` `` |+| `${ sql([] or {}, ...) }` | for helpers | ``await sql`INSERT INTO users ${sql({ name: 'Peter'})}` `` |+| `${ 'somevalue' }` | for values | ``await sql`SELECT * FROM users WHERE age = ${42}` `` |++## Advanced query methods++### Cursors++#### ```await sql``.cursor([rows = 1], [fn])```++Use cursors if you need to throttle the amount of rows being returned from a query. You can use a cursor either as an [async iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) or with a callback function. For a callback function new results won't be requested until the promise / async callback function has resolved.++##### callback function+```js+await sql`+ select+ *+ from generate_series(1,4) as x+`.cursor(async([row]) => {+ // row = { x: 1 }+ await http.request('https://example.com/wat', { row })+})+```++##### for await...of+```js+// for await...of+const cursor = sql`select * from generate_series(1,4) as x`.cursor()++for await (const [row] of cursor) {+ // row = { x: 1 }+ await http.request('https://example.com/wat', { row })+}+```++A single row will be returned by default, but you can also request batches by setting the number of rows desired in each batch as the first argument to `.cursor`:+```js+await sql`+ select+ *+ from generate_series(1,1000) as x+`.cursor(10, async rows => {+ // rows = [{ x: 1 }, { x: 2 }, ... ]+ await Promise.all(rows.map(row =>+ http.request('https://example.com/wat', { row })+ ))+})+```++If an error is thrown inside the callback function no more rows will be requested and the outer promise will reject with the thrown error.++You can close the cursor early either by calling `break` in the `for await...of` loop, or by returning the token `sql.CLOSE` from the callback function.++```js+await sql`+ select * from generate_series(1,1000) as x+`.cursor(row => {+ return Math.random() > 0.9 && sql.CLOSE // or sql.END+})+```++### Instant iteration++#### ```await sql``.forEach(fn)```++If you want to handle rows returned by a query one by one, you can use `.forEach` which returns a promise that resolves once there are no more rows.+```js+await sql`+ select created_at, name from events+`.forEach(row => {+ // row = { created_at: '2019-11-22T14:22:00Z', name: 'connected' }+})++// No more rows+```++### Query Descriptions+#### ```await sql``.describe() -> Result[]```++Rather than executing a given query, `.describe` will return information utilized in the query process. This information can include the query identifier, column types, etc.++This is useful for debugging and analyzing your Postgres queries. Furthermore, **`.describe` will give you access to the final generated query string that would be executed.**++### Rows as Array of Values+#### ```sql``.values()```++Using `.values` will return rows as an array of values for each column, instead of objects.++This can be useful to receive identically named columns, or for specific performance/transformation reasons. The column definitions are still included on the result array, plus access to parsers for each column.++### Rows as Raw Array of Buffers+#### ```sql``.raw()```++Using `.raw` will return rows as an array with `Buffer` values for each column, instead of objects.++This can be useful for specific performance/transformation reasons. The column definitions are still included on the result array, plus access to parsers for each column.++### Queries in Files+#### `await sql.file(path, [args], [options]) -> Result[]`++Using a file for a query is also supported with optional parameters to use if the file includes `$1, $2, etc`++```js+const result = await sql.file('query.sql', ['Murray', 68])+```++### Multiple statements in one query+#### ```await sql``.simple()```++The postgres wire protocol supports ["simple"](https://www.postgresql.org/docs/current/protocol-flow.html#id-1.10.6.7.4) and ["extended"](https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY) queries. "simple" queries supports multiple statements, but does not support any dynamic parameters. "extended" queries support parameters but only one statement. To use "simple" queries you can use+```sql``.simple()```. That will create it as a simple query.++```js+await sql`select 1; select 2;`.simple()+```++### Copy to/from as Streams++Postgres.js supports [`COPY ...`](https://www.postgresql.org/docs/14/sql-copy.html) queries, which are exposed as [Node.js streams](https://nodejs.org/api/stream.html).++#### ```await sql`copy ... from stdin`.writable() -> Writable```++```js+import { pipeline } from 'node:stream/promises'++// Stream of users with the default tab delimitated cells and new-line delimitated rows+const userStream = Readable.from([+ 'Murray\t68\n',+ 'Walter\t80\n'+])++const query = await sql`copy users (name, age) from stdin`.writable()+await pipeline(userStream, query);+```++#### ```await sql`copy ... to stdout`.readable() -> Readable```++##### Using Stream Pipeline+```js+import { pipeline } from 'node:stream/promises'+import { createWriteStream } from 'node:fs'++const readableStream = await sql`copy users (name, age) to stdout`.readable()+await pipeline(readableStream, createWriteStream('output.tsv'))+// output.tsv content: `Murray\t68\nWalter\t80\n`+```++##### Using `for await...of`+```js+const readableStream = await sql`+ copy (+ select name, age+ from users+ where age = 68+ ) to stdout+`.readable()+for await (const chunk of readableStream) {+ // chunk.toString() === `Murray\t68\n`+}+```++> **NOTE** This is a low-level API which does not provide any type safety. To make this work, you must match your [`copy query` parameters](https://www.postgresql.org/docs/14/sql-copy.html) correctly to your [Node.js stream read or write](https://nodejs.org/api/stream.html) code. Ensure [Node.js stream backpressure](https://nodejs.org/en/learn/modules/backpressuring-in-streams) is handled correctly to avoid memory exhaustion.++### Canceling Queries in Progress++Postgres.js supports, [canceling queries in progress](https://www.postgresql.org/docs/7.1/protocol-protocol.html#AEN39000). It works by opening a new connection with a protocol level startup message to cancel the current query running on a specific connection. That means there is no guarantee that the query will be canceled, and due to the possible race conditions it might even result in canceling another query. This is fine for long running queries, but in the case of high load and fast queries it might be better to simply ignore results instead of canceling.++```js+const query = sql`select pg_sleep 100`.execute()+setTimeout(() => query.cancel(), 100)+const result = await query+```++### Execute++#### ```await sql``.execute()```++The lazy Promise implementation in Postgres.js is what allows it to distinguish [Nested Fragments](#building-queries) from the main outer query. This also means that queries are always executed at the earliest in the following tick. If you have a specific need to execute the query in the same tick, you can call `.execute()`++### Unsafe raw string queries++<details>+<summary>Advanced unsafe use cases</summary>++### `await sql.unsafe(query, [args], [options]) -> Result[]`++If you know what you're doing, you can use `unsafe` to pass any string you'd like to postgres. Please note that this can lead to SQL injection if you're not careful.++```js+sql.unsafe('select ' + danger + ' from users where id = ' + dragons)+```++By default, `sql.unsafe` assumes the `query` string is sufficiently dynamic that prepared statements do not make sense, and so defaults them to off. If you'd like to re-enable prepared statements, you can pass `{ prepare: true }`.++You can also nest `sql.unsafe` within a safe `sql` expression. This is useful if only part of your fraction has unsafe elements.++```js+const triggerName = 'friend_created'+const triggerFnName = 'on_friend_created'+const eventType = 'insert'+const schema_name = 'app'+const table_name = 'friends'++await sql`+ create or replace trigger ${sql(triggerName)}+ after ${sql.unsafe(eventType)} on ${sql.unsafe(`${schema_name}.${table_name}`)}+ for each row+ execute function ${sql(triggerFnName)}()+`++await sql`+ create role friend_service with login password ${sql.unsafe(`'${password}'`)}+`+```++</details>++## Transactions++#### BEGIN / COMMIT `await sql.begin([options = ''], fn) -> fn()`++Use `sql.begin` to start a new transaction. Postgres.js will reserve a connection for the transaction and supply a scoped `sql` instance for all transaction uses in the callback function. `sql.begin` will resolve with the returned value from the callback function.++`BEGIN` is automatically sent with the optional options, and if anything fails `ROLLBACK` will be called so the connection can be released and execution can continue.++```js+const [user, account] = await sql.begin(async sql => {+ const [user] = await sql`+ insert into users (+ name+ ) values (+ 'Murray'+ )+ returning *+ `++ const [account] = await sql`+ insert into accounts (+ user_id+ ) values (+ ${ user.user_id }+ )+ returning *+ `++ return [user, account]+})+```++Do note that you can often achieve the same result using [`WITH` queries (Common Table Expressions)](https://www.postgresql.org/docs/current/queries-with.html) instead of using transactions.++It's also possible to pipeline the requests in a transaction if needed by returning an array with queries from the callback function like this:++```js+const result = await sql.begin(sql => [+ sql`update ...`,+ sql`update ...`,+ sql`insert ...`+])+```++#### SAVEPOINT `await sql.savepoint([name], fn) -> fn()`++```js+sql.begin('read write', async sql => {+ const [user] = await sql`+ insert into users (+ name+ ) values (+ 'Murray'+ )+ `++ const [account] = (await sql.savepoint(sql =>+ sql`+ insert into accounts (+ user_id+ ) values (+ ${ user.user_id }+ )+ `+ ).catch(err => {+ // Account could not be created. ROLLBACK SAVEPOINT is called because we caught the rejection.+ })) || []++ return [user, account]+})+.then(([user, account]) => {+ // great success - COMMIT succeeded+})+.catch(() => {+ // not so good - ROLLBACK was called+})+```+++#### PREPARE TRANSACTION `await sql.prepare([name]) -> fn()`++Indicates that the transactions should be prepared using the [`PREPARE TRANSACTION [NAME]`](https://www.postgresql.org/docs/current/sql-prepare-transaction.html) statement+instead of being committed.++```js+sql.begin('read write', async sql => {+ const [user] = await sql`+ insert into users (+ name+ ) values (+ 'Murray'+ )+ `++ await sql.prepare('tx1')+})+```++## Data Transformation++Postgres.js allows for transformation of the data passed to or returned from a query by using the `transform` option.++Built in transformation functions are:++* For camelCase - `postgres.camel`, `postgres.toCamel`, `postgres.fromCamel`+* For PascalCase - `postgres.pascal`, `postgres.toPascal`, `postgres.fromPascal`+* For Kebab-Case - `postgres.kebab`, `postgres.toKebab`, `postgres.fromKebab`++These built in transformations will only convert to/from snake_case. For example, using `{ transform: postgres.toCamel }` will convert the column names to camelCase only if the column names are in snake_case to begin with. `{ transform: postgres.fromCamel }` will convert camelCase only to snake_case.++By default, using `postgres.camel`, `postgres.pascal` and `postgres.kebab` will perform a two-way transformation - both the data passed to the query and the data returned by the query will be transformed:++```js+// Transform the column names to and from camel case+const sql = postgres({ transform: postgres.camel })++await sql`CREATE TABLE IF NOT EXISTS camel_case (a_test INTEGER, b_test TEXT)`+await sql`INSERT INTO camel_case ${ sql([{ aTest: 1, bTest: 1 }]) }`+const data = await sql`SELECT ${ sql('aTest', 'bTest') } FROM camel_case`++console.log(data) // [ { aTest: 1, bTest: '1' } ]+```++To only perform half of the transformation (eg. only the transformation **to** or **from** camel case), use the other transformation functions:++```js+// Transform the column names only to camel case+// (for the results that are returned from the query)+postgres({ transform: postgres.toCamel })++await sql`CREATE TABLE IF NOT EXISTS camel_case (a_test INTEGER)`+await sql`INSERT INTO camel_case ${ sql([{ a_test: 1 }]) }`+const data = await sql`SELECT a_test FROM camel_case`++console.log(data) // [ { aTest: 1 } ]+```++```js+// Transform the column names only from camel case+// (for interpolated inserts, updates, and selects)+const sql = postgres({ transform: postgres.fromCamel })++await sql`CREATE TABLE IF NOT EXISTS camel_case (a_test INTEGER)`+await sql`INSERT INTO camel_case ${ sql([{ aTest: 1 }]) }`+const data = await sql`SELECT ${ sql('aTest') } FROM camel_case`++console.log(data) // [ { a_test: 1 } ]+```++> Note that Postgres.js does not rewrite the static parts of the tagged template strings. So to transform column names in your queries, the `sql()` helper must be used - eg. `${ sql('columnName') }` as in the examples above.++### Transform `undefined` Values++By default, Postgres.js will throw the error `UNDEFINED_VALUE: Undefined values are not allowed` when undefined values are passed++```js+// Transform the column names to and from camel case+const sql = postgres({+ transform: {+ undefined: null+ }+})++await sql`CREATE TABLE IF NOT EXISTS transform_undefined (a_test INTEGER)`+await sql`INSERT INTO transform_undefined ${ sql([{ a_test: undefined }]) }`+const data = await sql`SELECT a_test FROM transform_undefined`++console.log(data) // [ { a_test: null } ]+```++To combine with the built in transform functions, spread the transform in the `transform` object:++```js+// Transform the column names to and from camel case+const sql = postgres({+ transform: {+ ...postgres.camel,+ undefined: null+ }+})++await sql`CREATE TABLE IF NOT EXISTS transform_undefined (a_test INTEGER)`+await sql`INSERT INTO transform_undefined ${ sql([{ aTest: undefined }]) }`+const data = await sql`SELECT ${ sql('aTest') } FROM transform_undefined`++console.log(data) // [ { aTest: null } ]+```++### Custom Transform Functions++To specify your own transformation functions, you can use the `column`, `value` and `row` options inside of `transform`, each an object possibly including `to` and `from` keys:++* `to`: The function to transform the outgoing query column name to, i.e `SELECT ${ sql('aName') }` to `SELECT a_name` when using `postgres.toCamel`.+* `from`: The function to transform the incoming query result column name to, see example below.++> Both parameters are optional, if not provided, the default transformation function will be used.++```js+// Implement your own functions, look at postgres.toCamel, etc+// as a reference:+// https://github.com/porsager/postgres/blob/4241824ffd7aa94ffb482e54ca9f585d9d0a4eea/src/types.js#L310-L328+function transformColumnToDatabase() { /* ... */ }+function transformColumnFromDatabase() { /* ... */ }++const sql = postgres({+ transform: {+ column: {+ to: transformColumnToDatabase,+ from: transformColumnFromDatabase,+ },+ value: { /* ... */ },+ row: { /* ... */ }+ }+})+```++## Listen & notify++When you call `.listen`, a dedicated connection will be created to ensure that you receive notifications instantly. This connection will be used for any further calls to `.listen`. The connection will automatically reconnect according to a backoff reconnection pattern to not overload the database server.++### Listen `await sql.listen(channel, onnotify, [onlisten]) -> { state }`+`.listen` takes the channel name, a function to handle each notify, and an optional function to run every time listen is registered and ready (happens on initial connect and reconnects). It returns a promise which resolves once the `LISTEN` query to Postgres completes, or if there is already a listener active.++```js+await sql.listen('news', payload => {+ const json = JSON.parse(payload)+ console.log(json.this) // logs 'is'+})+```++The optional `onlisten` method is great to use for a very simply queue mechanism:++```js+await sql.listen(+ 'jobs',+ (x) => run(JSON.parse(x)),+ ( ) => sql`select unfinished_jobs()`.forEach(run)+)++function run(job) {+ // And here you do the work you please+}+```+### Notify `await sql.notify(channel, payload) -> Result[]`+Notify can be done as usual in SQL, or by using the `sql.notify` method.+```js+sql.notify('news', JSON.stringify({ no: 'this', is: 'news' }))+```++## Realtime subscribe++Postgres.js implements the logical replication protocol of PostgreSQL to support subscription to real-time updates of `insert`, `update` and `delete` operations.++> **NOTE** To make this work you must [create the proper publications in your database](https://www.postgresql.org/docs/current/sql-createpublication.html), enable logical replication by setting `wal_level = logical` in `postgresql.conf` and connect using either a replication or superuser.++### Quick start++#### Create a publication (eg. in migration)+```sql+CREATE PUBLICATION alltables FOR ALL TABLES+```++#### Subscribe to updates+```js+const sql = postgres({ publications: 'alltables' })++const { unsubscribe } = await sql.subscribe(+ 'insert:events',+ (row, { command, relation, key, old }) => {+ // Callback function for each row change+ // tell about new event row over eg. websockets or do something else+ },+ () => {+ // Callback on initial connect and potential reconnects+ }+)+```++### Subscribe pattern++You can subscribe to specific operations, tables, or even rows with primary keys.++#### `operation` `:` `schema` `.` `table` `=` `primary_key`++**`operation`** is one of ``` * | insert | update | delete ``` and defaults to `*`++**`schema`** defaults to `public`++**`table`** is a specific table name and defaults to `*`++**`primary_key`** can be used to only subscribe to specific rows++### Examples++```js+sql.subscribe('*', () => /* everything */ )+sql.subscribe('insert', () => /* all inserts */ )+sql.subscribe('*:users', () => /* all operations on the public.users table */ )+sql.subscribe('delete:users', () => /* all deletes on the public.users table */ )+sql.subscribe('update:users=1', () => /* all updates on the users row with a primary key = 1 */ )+```++## Numbers, bigint, numeric++`Number` in javascript is only able to represent 2<sup>53</sup>-1 safely which means that types in PostgreSQLs like `bigint` and `numeric` won't fit into `Number`.++Since Node.js v10.4 we can use [`BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) to match the PostgreSQL type `bigint` which is returned for eg. `count(*)`. Unfortunately, it doesn't work with `JSON.stringify` out of the box, so Postgres.js will return it as a string.++If you want to use `BigInt` you can add this custom type:++```js+const sql = postgres({+ types: {+ bigint: postgres.BigInt+ }+})+```++There is currently no guaranteed way to handle `numeric` / `decimal` types in native Javascript. **These [and similar] types will be returned as a `string`**. The best way in this case is to use [custom types](#custom-types).++## Result Array++The `Result` Array returned from queries is a custom array allowing for easy destructuring or passing on directly to JSON.stringify or general Array usage. It includes the following properties.++### .count++The `count` property is the number of affected rows returned by the database. This is useful for insert, update and delete operations to know the number of rows since .length will be 0 in these cases if not using `RETURNING ...`.++### .command++The `command` run by the query - eg. one of `SELECT`, `UPDATE`, `INSERT`, `DELETE`++### .columns++The `columns` returned by the query useful to determine types, or map to the result values when using `.values()`++```js+{+ name : String, // Column name,+ type : oid, // PostgreSQL oid column type+ parser: Function // The function used by Postgres.js for parsing+}+```++### .statement++The `statement` contains information about the statement implicitly created by Postgres.js.++```js+{+ name : String, // The auto generated statement name+ string : String, // The actual query string executed+ types : [oid], // An array of oid expected as input parameters+ columns : [Column] // Array of columns - same as Result.columns+}+```++### .state++This is the state `{ pid, secret }` of the connection that executed the query.++## Connection details++### All Postgres options++```js+const sql = postgres('postgres://username:password@host:port/database', {+ host : '', // Postgres ip address[es] or domain name[s]+ port : 5432, // Postgres server port[s]+ path : '', // unix socket path (usually '/tmp')+ database : '', // Name of database to connect to+ username : '', // Username of database user+ password : '', // Password of database user+ ssl : false, // true, prefer, require, tls.connect options+ sslnegotiation : null, // direct+ max : 10, // Max number of connections+ max_lifetime : null, // Max lifetime in seconds (more info below)+ idle_timeout : 0, // Idle connection timeout in seconds+ connect_timeout : 30, // Connect timeout in seconds+ prepare : true, // Automatic creation of prepared statements+ types : [], // Array of custom types, see more below+ onnotice : fn, // Default console.log, set false to silence NOTICE+ onparameter : fn, // (key, value) when server param change+ debug : fn, // Is called with (connection, query, params, types)+ socket : fn, // fn returning custom socket to use+ transform : {+ undefined : undefined, // Transforms undefined values (eg. to null)+ column : fn, // Transforms incoming column names+ value : fn, // Transforms incoming row values+ row : fn // Transforms entire rows+ },+ connection : {+ application_name : 'postgres.js', // Default application_name+ ... // Other connection parameters, see https://www.postgresql.org/docs/current/runtime-config-client.html+ },+ target_session_attrs : null, // Use 'read-write' with multiple hosts to+ // ensure only connecting to primary+ fetch_types : true, // Automatically fetches types on connect+ // on initial connection.+})+```++Note that `max_lifetime = 60 * (30 + Math.random() * 30)` by default. This resolves to an interval between 30 and 60 minutes to optimize for the benefits of prepared statements **and** working nicely with Linux's OOM killer.++### Dynamic passwords++When clients need to use alternative authentication schemes such as access tokens or connections to databases with rotating passwords, provide either a synchronous or asynchronous function that will resolve the dynamic password value at connection time.++```js+const sql = postgres(url, {+ // Other connection config+ ...+ // Password function for the database user+ password : async () => await signer.getAuthToken(),+})+```++### SSL++Although [vulnerable to MITM attacks](https://security.stackexchange.com/a/229297/174913), a common configuration for the `ssl` option for some cloud providers is to set `rejectUnauthorized` to `false` (if `NODE_ENV` is `production`):++```js+const sql =+ process.env.NODE_ENV === 'production'+ ? // "Unless you're using a Private or Shield Heroku Postgres database, Heroku Postgres does not currently support verifiable certificates"+ // https://help.heroku.com/3DELT3RK/why-can-t-my-third-party-utility-connect-to-heroku-postgres-with-ssl+ postgres({ ssl: { rejectUnauthorized: false } })+ : postgres()+```++For more information regarding `ssl` with `postgres`, check out the [Node.js documentation for tls](https://nodejs.org/dist/latest-v16.x/docs/api/tls.html#new-tlstlssocketsocket-options).+++### Multi-host connections - High Availability (HA)++Multiple connection strings can be passed to `postgres()` in the form of `postgres('postgres://localhost:5432,localhost:5433', ...)`. This works the same as native the `psql` command. Read more at [multiple host URIs](https://www.postgresql.org/docs/13/libpq-connect.html#LIBPQ-MULTIPLE-HOSTS).++Connections will be attempted in order of the specified hosts/ports. On a successful connection, all retries will be reset. This ensures that hosts can come up and down seamlessly.++If you specify `target_session_attrs: 'primary'` or `PGTARGETSESSIONATTRS=primary` Postgres.js will only connect to the primary host, allowing for zero downtime failovers.++### The Connection Pool++Connections are created lazily once a query is created. This means that simply doing const `sql = postgres(...)` won't have any effect other than instantiating a new `sql` instance.++> No connection will be made until a query is made.++For example:++```js+const sql = postgres() // no connections are opened++await sql`...` // one connection is now opened+await sql`...` // previous opened connection is reused++// two connections are opened now+await Promise.all([+ sql`...`,+ sql`...`+])+```++> When there are high amount of concurrent queries, `postgres` will open as many connections as needed up until `max` number of connections is reached. By default `max` is 10. This can be changed by setting `max` in the `postgres()` call. Example - `postgres('connectionURL', { max: 20 })`.++This means that we get a much simpler story for error handling and reconnections. Queries will be sent over the wire immediately on the next available connection in the pool. Connections are automatically taken out of the pool if you start a transaction using `sql.begin()`, and automatically returned to the pool once your transaction is done.++Any query which was already sent over the wire will be rejected if the connection is lost. It'll automatically defer to the error handling you have for that query, and since connections are lazy it'll automatically try to reconnect the next time a query is made. The benefit of this is no weird generic "onerror" handler that tries to get things back to normal, and also simpler application code since you don't have to handle errors out of context.++There are no guarantees about queries executing in order unless using a transaction with `sql.begin()` or setting `max: 1`. Of course doing a series of queries, one awaiting the other will work as expected, but that's just due to the nature of js async/promise handling, so it's not necessary for this library to be concerned with ordering.++Since this library automatically creates prepared statements, it also has a default max lifetime for connections to prevent memory bloat on the database itself. This is a random interval for each connection between 45 and 90 minutes. This allows multiple connections to independently come up and down without affecting the service.++### Connection timeout++By default, connections will not close until `.end()` is called. However, it may be useful to have them close automatically when:++- re-instantiating multiple ` sql`` ` instances+- using Postgres.js in a Serverless environment (Lambda, etc.)+- using Postgres.js with a database service that automatically closes connections after some time (see [`ECONNRESET` issue](https://github.com/porsager/postgres/issues/179))++This can be done using the `idle_timeout` or `max_lifetime` options. These configuration options specify the number of seconds to wait before automatically closing an idle connection and the maximum time a connection can exist, respectively.++For example, to close a connection that has either been idle for 20 seconds or existed for more than 30 minutes:++```js+const sql = postgres({+ idle_timeout: 20,+ max_lifetime: 60 * 30+})+```++### Cloudflare Workers support++Postgres.js has built-in support for the [TCP socket API](https://developers.cloudflare.com/workers/runtime-apis/tcp-sockets/) in Cloudflare Workers, which is [on-track](https://github.com/wintercg/proposal-sockets-api) to be standardized and adopted in Node.js and other JavaScript runtimes, such as Deno.++You can use Postgres.js directly in a Worker, or to benefit from connection pooling and query caching, via the [Hyperdrive](https://developers.cloudflare.com/hyperdrive/learning/connect-to-postgres/#driver-examples) service available to Workers by passing the Hyperdrive `connectionString` when creating a new `postgres` client as follows:++```ts+// Requires Postgres.js 3.4.0 or later+import postgres from 'postgres'++interface Env {+ HYPERDRIVE: Hyperdrive;+}++export default async fetch(req: Request, env: Env, ctx: ExecutionContext) {+ // The Postgres.js library accepts a connection string directly+ const sql = postgres(env.HYPERDRIVE.connectionString)+ const results = await sql`SELECT * FROM users LIMIT 10`+ return Response.json(results)+}+```++In `wrangler.toml` you will need to enable the `nodejs_compat` compatibility flag to allow Postgres.js to operate in the Workers environment:++```toml+compatibility_flags = ["nodejs_compat"]+```++### Auto fetching of array types++Postgres.js will automatically fetch table/array-type information when it first connects to a database.++If you have revoked access to `pg_catalog` this feature will no longer work and will need to be disabled.++You can disable this feature by setting `fetch_types` to `false`.++### Environmental variables++It is also possible to connect to the database without a connection string or any options. Postgres.js will fall back to the common environment variables used by `psql` as in the table below:++```js+const sql = postgres()+```++| Option | Environment Variables |+| ------------------ | ------------------------ |+| `host` | `PGHOST` |+| `port` | `PGPORT` |+| `database` | `PGDATABASE` |+| `username` | `PGUSERNAME` or `PGUSER` |+| `password` | `PGPASSWORD` |+| `application_name` | `PGAPPNAME` |+| `idle_timeout` | `PGIDLE_TIMEOUT` |+| `connect_timeout` | `PGCONNECT_TIMEOUT` |++### Prepared statements++Prepared statements will automatically be created for any queries where it can be inferred that the query is static. This can be disabled by using the `prepare: false` option. For instance — this is useful when [using PGBouncer in `transaction mode`](https://github.com/porsager/postgres/issues/93#issuecomment-656290493).++**update**: [since 1.21.0](https://www.pgbouncer.org/2023/10/pgbouncer-1-21-0)+PGBouncer supports protocol-level named prepared statements when [configured+properly](https://www.pgbouncer.org/config.html#max_prepared_statements)++## Custom Types++You can add ergonomic support for custom types, or simply use `sql.typed(value, type)` inline, where type is the PostgreSQL `oid` for the type and the correctly serialized string. _(`oid` values for types can be found in the `pg_catalog.pg_type` table.)_++Adding Query helpers is the cleanest approach which can be done like this:++```js+const sql = postgres({+ types: {+ rect: {+ // The pg_types oid to pass to the db along with the serialized value.+ to : 1337,++ // An array of pg_types oids to handle when parsing values coming from the db.+ from : [1337],++ //Function that transform values before sending them to the db.+ serialize : ({ x, y, width, height }) => [x, y, width, height],++ // Function that transforms values coming from the db.+ parse : ([x, y, width, height]) => { x, y, width, height }+ }+ }+})++// Now you can use sql.typed.rect() as specified above+const [custom] = await sql`+ insert into rectangles (+ name,+ rect+ ) values (+ 'wat',+ ${ sql.typed.rect({ x: 13, y: 37, width: 42, height: 80 }) }+ )+ returning *+`++// custom = { name: 'wat', rect: { x: 13, y: 37, width: 42, height: 80 } }++```++### Custom socket++Easily do in-process ssh tunneling to your database by providing a custom socket for Postgres.js to use. The function (optionally async) must return a socket-like duplex stream.++Here's a sample using [ssh2](https://github.com/mscdex/ssh2)++```js+import ssh2 from 'ssh2'++const sql = postgres({+ ...options,+ socket: ({ host: [host], port: [port] }) => new Promise((resolve, reject) => {+ const ssh = new ssh2.Client()+ ssh+ .on('error', reject)+ .on('ready', () =>+ ssh.forwardOut('127.0.0.1', 12345, host, port,+ (err, socket) => err ? reject(err) : resolve(socket)+ )+ )+ .connect(sshOptions)+ })+})+```++## Teardown / Cleanup++To ensure proper teardown and cleanup on server restarts use `await sql.end()` before `process.exit()`.++Calling `sql.end()` will reject new queries and return a Promise which resolves when all queries are finished and the underlying connections are closed. If a `{ timeout }` option is provided any pending queries will be rejected once the timeout (in seconds) is reached and the connections will be destroyed.++#### Sample shutdown using [Prexit](https://github.com/porsager/prexit)++```js+import prexit from 'prexit'++prexit(async () => {+ await sql.end({ timeout: 5 })+ await new Promise(r => server.close(r))+})+```++## Reserving connections++### `await sql.reserve()`++The `reserve` method pulls out a connection from the pool, and returns a client that wraps the single connection. This can be used for running queries on an isolated connection.++```ts+const reserved = await sql.reserve()+await reserved`select * from users`+await reserved.release()+```++### `reserved.release()`++Once you have finished with the reserved connection, call `release` to add it back to the pool.++## Error handling++Errors are all thrown to related queries and never globally. Errors coming from database itself are always in the [native Postgres format](https://www.postgresql.org/docs/current/errcodes-appendix.html), and the same goes for any [Node.js errors](https://nodejs.org/api/errors.html#errors_common_system_errors) eg. coming from the underlying connection.++Query errors will contain a stored error with the origin of the query to aid in tracing errors.++Query errors will also contain the `query` string and the `parameters`. These are not enumerable to avoid accidentally leaking confidential information in logs. To log these it is required to specifically access `error.query` and `error.parameters`, or set `debug: true` in options.++There are also the following errors specifically for this library.++##### UNSAFE_TRANSACTION+> Only use sql.begin or max: 1++To ensure statements in a transaction runs on the same connection (which is required for them to run inside the transaction), you must use [`sql.begin(...)`](#transactions) or only allow a single connection in options (`max: 1`).++##### UNDEFINED_VALUE+> Undefined values are not allowed++Postgres.js won't accept `undefined` as values in tagged template queries since it becomes ambiguous what to do with the value. If you want to set something to null, use `null` explicitly.++##### MESSAGE_NOT_SUPPORTED+> X (X) is not supported++Whenever a message is received from Postgres which is not supported by this library. Feel free to file an issue if you think something is missing.++##### MAX_PARAMETERS_EXCEEDED+> Max number of parameters (65534) exceeded++The postgres protocol doesn't allow more than 65534 (16bit) parameters. If you run into this issue there are various workarounds such as using `sql([...])` to escape values instead of passing them as parameters.++##### SASL_SIGNATURE_MISMATCH+> Message type X not supported++When using SASL authentication the server responds with a signature at the end of the authentication flow which needs to match the one on the client. This is to avoid [man-in-the-middle attacks](https://en.wikipedia.org/wiki/Man-in-the-middle_attack). If you receive this error the connection was canceled because the server did not reply with the expected signature.++##### NOT_TAGGED_CALL+> Query not called as a tagged template literal++Making queries has to be done using the sql function as a [tagged template](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates). This is to ensure parameters are serialized and passed to Postgres as query parameters with correct types and to avoid SQL injection.++##### AUTH_TYPE_NOT_IMPLEMENTED+> Auth type X not implemented++Postgres supports many different authentication types. This one is not supported.++##### CONNECTION_CLOSED+> write CONNECTION_CLOSED host:port++This error is thrown if the connection was closed without an error. This should not happen during normal operations, so please create an issue if this was unexpected.++##### CONNECTION_ENDED+> write CONNECTION_ENDED host:port++This error is thrown if the user has called [`sql.end()`](#teardown--cleanup) and performed a query afterward.++##### CONNECTION_DESTROYED+> write CONNECTION_DESTROYED host:port++This error is thrown for any queries that were pending when the timeout to [`sql.end({ timeout: X })`](#teardown--cleanup) was reached.++##### CONNECT_TIMEOUT+> write CONNECT_TIMEOUT host:port++This error is thrown if the startup phase of the connection (tcp, protocol negotiation, and auth) took more than the default 30 seconds or what was specified using `connect_timeout` or `PGCONNECT_TIMEOUT`.++##### COPY_IN_PROGRESS+> You cannot execute queries during copy++This error is thrown if trying to run a query during a copy operation (writable / readable).++## TypeScript support++`postgres` has TypeScript support. You can pass a row list type for your queries in this way:+```ts+interface User {+ id: number+ name: string+}++const users = await sql<User[]>`SELECT * FROM users`+users[0].id // ok => number+users[1].name // ok => string+users[0].invalid // fails: `invalid` does not exists on `User`+```++However, be sure to check the array length to avoid accessing properties of `undefined` rows:+```ts+const users = await sql<User[]>`SELECT * FROM users WHERE id = ${id}`+if (!users.length)+ throw new Error('Not found')+return users[0]+```++You can also prefer destructuring when you only care about a fixed number of rows.+In this case, we recommend you to prefer using tuples to handle `undefined` properly:+```ts+const [user]: [User?] = await sql`SELECT * FROM users WHERE id = ${id}`+if (!user) // => User | undefined+ throw new Error('Not found')+return user // => User++// NOTE:+const [first, second]: [User?] = await sql`SELECT * FROM users WHERE id = ${id}` // fails: `second` does not exist on `[User?]`+const [first, second] = await sql<[User?]>`SELECT * FROM users WHERE id = ${id}` // don't fail : `second: User | undefined`+```++We do our best to type all the public API, however types are not always updated when features are added or changed. Feel free to open an issue if you have trouble with types.++## Migration tools++Postgres.js doesn't come with any migration solution since it's way out of scope, but here are some modules that support Postgres.js for migrations:++- https://github.com/porsager/postgres-shift+- https://github.com/lukeed/ley+- https://github.com/JAForbes/pgmg++## Thank you++A really big thank you to [@JAForbes](https://twitter.com/jmsfbs) who introduced me to Postgres and still holds my hand navigating all the great opportunities we have.++Thanks to [@ACXgit](https://twitter.com/andreacoiutti) for initial tests and dogfooding.++Also thanks to [Ryan Dahl](https://github.com/ry) for letting me have the `postgres` npm package name.diff --git a/vendor/postgres/UNLICENSE b/vendor/postgres/UNLICENSEnew file mode 100644index 0000000000..efb9808816--- /dev/null+++ b/vendor/postgres/UNLICENSE@@ -0,0 +1,24 @@+This is free and unencumbered software released into the public domain.++Anyone is free to copy, modify, publish, use, compile, sell, or+distribute this software, either in source code form or as a compiled+binary, for any purpose, commercial or non-commercial, and by any+means.++In jurisdictions that recognize copyright laws, the author or authors+of this software dedicate any and all copyright interest in the+software to the public domain. We make this dedication for the benefit+of the public at large and to the detriment of our heirs and+successors. We intend this dedication to be an overt act of+relinquishment in perpetuity of all present and future rights to this+software under copyright law.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR+OTHER DEALINGS IN THE SOFTWARE.++For more information, please refer to <https://unlicense.org/>diff --git a/vendor/postgres/cf/polyfills.js b/vendor/postgres/cf/polyfills.jsnew file mode 100644index 0000000000..53c5203dd5--- /dev/null+++ b/vendor/postgres/cf/polyfills.js@@ -0,0 +1,233 @@+import { EventEmitter } from 'node:events'+import { Buffer } from 'node:buffer'++const Crypto = globalThis.crypto++let ids = 1+const tasks = new Set()++const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'+const v4Str = `(${v4Seg}[.]){3}${v4Seg}`+const IPv4Reg = new RegExp(`^${v4Str}$`)++const v6Seg = '(?:[0-9a-fA-F]{1,4})'+const IPv6Reg = new RegExp(+ '^(' ++ `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` ++ `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` ++ `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` ++ `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` ++ `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` ++ `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` ++ `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` ++ `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` ++ ')(%[0-9a-zA-Z-.:]{1,})?$'+)++const textEncoder = new TextEncoder()+export const crypto = {+ randomBytes: l => Crypto.getRandomValues(Buffer.alloc(l)),+ pbkdf2Sync: async(password, salt, iterations, keylen) =>+ Crypto.subtle.deriveBits(+ {+ name: 'PBKDF2',+ hash: 'SHA-256',+ salt,+ iterations+ },+ await Crypto.subtle.importKey(+ 'raw',+ textEncoder.encode(password),+ 'PBKDF2',+ false,+ ['deriveBits']+ ),+ keylen * 8,+ ['deriveBits']+ ),+ createHash: type => ({+ update: x => ({+ digest: encoding => {+ if (!(x instanceof Uint8Array)) {+ x = textEncoder.encode(x)+ }+ let prom+ if (type === 'sha256') {+ prom = Crypto.subtle.digest('SHA-256', x)+ } else if (type === 'md5') {+ prom = Crypto.subtle.digest('md5', x)+ } else {+ throw Error('createHash only supports sha256 or md5 in this environment, not ${type}.')+ }+ if (encoding === 'hex') {+ return prom.then((arrayBuf) => Buffer.from(arrayBuf).toString('hex'))+ } else if (encoding) {+ throw Error(`createHash only supports hex encoding or unencoded in this environment, not ${encoding}`)+ } else {+ return prom+ }+ }+ })+ }),+ createHmac: (type, key) => ({+ update: x => ({+ digest: async() =>+ Buffer.from(+ await Crypto.subtle.sign(+ 'HMAC',+ await Crypto.subtle.importKey('raw', key, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']),+ textEncoder.encode(x)+ )+ )+ })+ })+}++export const performance = globalThis.performance++export const process = {+ env: {}+}++export const os = {+ userInfo() {+ return { username: 'postgres' }+ }+}++export const fs = {+ readFile() {+ throw new Error('Reading files not supported on CloudFlare')+ }+}++export const net = {+ isIP: (x) => IPv4Reg.test(x) ? 4 : IPv6Reg.test(x) ? 6 : 0,+ Socket+}++export { setImmediate, clearImmediate }++export const tls = {+ connect({ socket: tcp, servername }) {+ tcp.writer.releaseLock()+ tcp.reader.releaseLock()+ tcp.readyState = 'upgrading'+ tcp.raw = tcp.raw.startTls({ servername })+ tcp.raw.closed.then(+ () => tcp.emit('close'),+ (e) => tcp.emit('error', e)+ )+ tcp.writer = tcp.raw.writable.getWriter()+ tcp.reader = tcp.raw.readable.getReader()++ tcp.writer.ready.then(() => {+ tcp.read()+ tcp.readyState = 'upgrade'+ })+ return tcp+ }+}++function Socket() {+ const tcp = Object.assign(new EventEmitter(), {+ readyState: 'open',+ raw: null,+ writer: null,+ reader: null,+ connect,+ write,+ end,+ destroy,+ read+ })++ return tcp++ async function connect(port, host) {+ try {+ tcp.readyState = 'opening'+ const { connect } = await import('cloudflare:sockets')+ tcp.raw = connect(host + ':' + port, tcp.ssl ? { secureTransport: 'starttls' } : {})+ tcp.raw.closed.then(+ () => {+ tcp.readyState !== 'upgrade'+ ? close()+ : ((tcp.readyState = 'open'), tcp.emit('secureConnect'))+ },+ (e) => tcp.emit('error', e)+ )+ tcp.writer = tcp.raw.writable.getWriter()+ tcp.reader = tcp.raw.readable.getReader()++ tcp.ssl ? readFirst() : read()+ tcp.writer.ready.then(() => {+ tcp.readyState = 'open'+ tcp.emit('connect')+ })+ } catch (err) {+ error(err)+ }+ }++ function close() {+ if (tcp.readyState === 'closed')+ return++ tcp.readyState = 'closed'+ tcp.emit('close')+ }++ function write(data, cb) {+ tcp.writer.write(data).then(cb, error)+ return true+ }++ function end(data) {+ return data+ ? tcp.write(data, () => tcp.raw.close())+ : tcp.raw.close()+ }++ function destroy() {+ tcp.destroyed = true+ tcp.end()+ }++ async function read() {+ try {+ let done+ , value+ while (({ done, value } = await tcp.reader.read(), !done))+ tcp.emit('data', Buffer.from(value))+ } catch (err) {+ error(err)+ }+ }++ async function readFirst() {+ const { value } = await tcp.reader.read()+ tcp.emit('data', Buffer.from(value))+ }++ function error(err) {+ tcp.emit('error', err)+ tcp.emit('close')+ }+}++function setImmediate(fn) {+ const id = ids+++ tasks.add(id)+ queueMicrotask(() => {+ if (tasks.has(id)) {+ fn()+ tasks.delete(id)+ }+ })+ return id+}++function clearImmediate(id) {+ tasks.delete(id)+}diff --git a/vendor/postgres/cf/src/bytes.js b/vendor/postgres/cf/src/bytes.jsnew file mode 100644index 0000000000..48b6f98360--- /dev/null+++ b/vendor/postgres/cf/src/bytes.js@@ -0,0 +1,79 @@+import { Buffer } from 'node:buffer'+const size = 256+let buffer = Buffer.allocUnsafe(size)++const messages = 'BCcDdEFfHPpQSX'.split('').reduce((acc, x) => {+ const v = x.charCodeAt(0)+ acc[x] = () => {+ buffer[0] = v+ b.i = 5+ return b+ }+ return acc+}, {})++const b = Object.assign(reset, messages, {+ N: String.fromCharCode(0),+ i: 0,+ inc(x) {+ b.i += x+ return b+ },+ str(x) {+ const length = Buffer.byteLength(x)+ fit(length)+ b.i += buffer.write(x, b.i, length, 'utf8')+ return b+ },+ i16(x) {+ fit(2)+ buffer.writeUInt16BE(x, b.i)+ b.i += 2+ return b+ },+ i32(x, i) {+ if (i || i === 0) {+ buffer.writeUInt32BE(x, i)+ return b+ }+ fit(4)+ buffer.writeUInt32BE(x, b.i)+ b.i += 4+ return b+ },+ z(x) {+ fit(x)+ buffer.fill(0, b.i, b.i + x)+ b.i += x+ return b+ },+ raw(x) {+ buffer = Buffer.concat([buffer.subarray(0, b.i), x])+ b.i = buffer.length+ return b+ },+ end(at = 1) {+ buffer.writeUInt32BE(b.i - at, at)+ const out = buffer.subarray(0, b.i)+ b.i = 0+ buffer = Buffer.allocUnsafe(size)+ return out+ }+})++export default b++function fit(x) {+ if (buffer.length - b.i < x) {+ const prev = buffer+ , length = prev.length++ buffer = Buffer.allocUnsafe(length + (length >> 1) + x)+ prev.copy(buffer)+ }+}++function reset() {+ b.i = 0+ return b+}diff --git a/vendor/postgres/cf/src/connection.js b/vendor/postgres/cf/src/connection.jsnew file mode 100644index 0000000000..1be82d1976--- /dev/null+++ b/vendor/postgres/cf/src/connection.js@@ -0,0 +1,1081 @@+import { Buffer } from 'node:buffer'+import { setImmediate, clearImmediate } from '../polyfills.js'+import { net } from '../polyfills.js'+import { tls } from '../polyfills.js'+import { crypto } from '../polyfills.js'+import Stream from 'node:stream'+import { performance } from '../polyfills.js'++import { stringify, handleValue, arrayParser, arraySerializer } from './types.js'+import { Errors } from './errors.js'+import Result from './result.js'+import Queue from './queue.js'+import { Query, CLOSE } from './query.js'+import b from './bytes.js'++export default Connection++let uid = 1++const Sync = b().S().end()+ , Flush = b().H().end()+ , SSLRequest = b().i32(8).i32(80877103).end(8)+ , ExecuteUnnamed = Buffer.concat([b().E().str(b.N).i32(0).end(), Sync])+ , DescribeUnnamed = b().D().str('S').str(b.N).end()+ , noop = () => { /* noop */ }++const retryRoutines = new Set([+ 'FetchPreparedStatement',+ 'RevalidateCachedQuery',+ 'transformAssignedExpr'+])++const errorFields = {+ 83 : 'severity_local', // S+ 86 : 'severity', // V+ 67 : 'code', // C+ 77 : 'message', // M+ 68 : 'detail', // D+ 72 : 'hint', // H+ 80 : 'position', // P+ 112 : 'internal_position', // p+ 113 : 'internal_query', // q+ 87 : 'where', // W+ 115 : 'schema_name', // s+ 116 : 'table_name', // t+ 99 : 'column_name', // c+ 100 : 'data type_name', // d+ 110 : 'constraint_name', // n+ 70 : 'file', // F+ 76 : 'line', // L+ 82 : 'routine' // R+}++function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) {+ const {+ sslnegotiation,+ ssl,+ max,+ user,+ host,+ port,+ database,+ parsers,+ transform,+ onnotice,+ onnotify,+ onparameter,+ max_pipeline,+ keep_alive,+ backoff,+ target_session_attrs+ } = options++ const sent = Queue()+ , id = uid+++ , backend = { pid: null, secret: null }+ , idleTimer = timer(end, options.idle_timeout)+ , lifeTimer = timer(end, options.max_lifetime)+ , connectTimer = timer(connectTimedOut, options.connect_timeout)++ let socket = null+ , cancelMessage+ , cancelResolve+ , cancelReject+ , cancelError+ , errorResponse = null+ , result = new Result()+ , incoming = Buffer.alloc(0)+ , needsTypes = options.fetch_types+ , backendParameters = {}+ , statements = {}+ , statementId = Math.random().toString(36).slice(2)+ , statementCount = 1+ , closedTime = 0+ , remaining = 0+ , hostIndex = 0+ , retries = 0+ , length = 0+ , delay = 0+ , rows = 0+ , serverSignature = null+ , nextWriteTimer = null+ , terminated = false+ , incomings = null+ , results = null+ , initial = null+ , ending = null+ , stream = null+ , chunk = null+ , ended = null+ , nonce = null+ , query = null+ , final = null++ const connection = {+ queue: queues.closed,+ idleTimer,+ connect(query) {+ initial = query+ reconnect()+ },+ terminate,+ execute,+ cancel,+ end,+ count: 0,+ id+ }++ queues.closed && queues.closed.push(connection)++ return connection++ async function createSocket() {+ let x+ try {+ x = options.socket+ ? (await Promise.resolve(options.socket(options)))+ : new net.Socket()+ } catch (e) {+ error(e)+ return+ }+ x.on('error', error)+ x.on('close', closed)+ x.on('drain', drain)+ return x+ }++ async function cancel({ pid, secret }, resolve, reject) {+ cancelResolve = resolve+ cancelReject = reject+ try {+ cancelMessage = b().i32(16).i32(80877102).i32(pid).i32(secret).end(16)+ await connect()+ if (!socket)+ reject(cancelError || Errors.connection('CONNECTION_CLOSED', options))+ } catch (error) {+ reject(error)+ }+ }++ function execute(q) {+ if (terminated)+ return queryError(q, Errors.connection('CONNECTION_DESTROYED', options))++ if (stream)+ return queryError(q, Errors.generic('COPY_IN_PROGRESS', 'You cannot execute queries during copy'))++ if (q.cancelled)+ return++ try {+ q.state = backend+ query+ ? sent.push(q)+ : (query = q, query.active = true)++ build(q)+ const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)+ return write(toBuffer(q))+ && !q.describeFirst+ && !q.cursorFn+ && sent.length < max_pipeline+ && mayPipeline+ } catch (error) {+ sent.length === 0 && write(Sync)+ errored(error)+ return true+ }+ }++ function toBuffer(q) {+ if (q.parameters.length >= 65534)+ throw Errors.generic('MAX_PARAMETERS_EXCEEDED', 'Max number of parameters (65534) exceeded')++ return q.options.simple+ ? b().Q().str(q.statement.string + b.N).end()+ : q.describeFirst+ ? Buffer.concat([describe(q), Flush])+ : q.prepare+ ? q.prepared+ ? prepared(q)+ : Buffer.concat([describe(q), prepared(q)])+ : unnamed(q)+ }++ function describe(q) {+ return Buffer.concat([+ Parse(q.statement.string, q.parameters, q.statement.types, q.statement.name),+ Describe('S', q.statement.name)+ ])+ }++ function prepared(q) {+ return Buffer.concat([+ Bind(q.parameters, q.statement.types, q.statement.name, q.cursorName),+ q.cursorFn+ ? Execute('', q.cursorRows)+ : ExecuteUnnamed+ ])+ }++ function unnamed(q) {+ return Buffer.concat([+ Parse(q.statement.string, q.parameters, q.statement.types),+ DescribeUnnamed,+ prepared(q)+ ])+ }++ function build(q) {+ const parameters = []+ , types = []++ const string = stringify(q, q.strings[0], q.args[0], parameters, types, options)++ !q.tagged && q.args.forEach(x => handleValue(x, parameters, types, options))++ q.prepare = options.prepare && ('prepare' in q.options ? q.options.prepare : true)+ q.string = string+ q.signature = q.prepare && types + string+ q.onlyDescribe && (delete statements[q.signature])+ q.parameters = q.parameters || parameters+ q.prepared = q.prepare && q.signature in statements+ q.describeFirst = q.onlyDescribe || (parameters.length && !q.prepared)+ q.statement = q.prepared+ ? statements[q.signature]+ : { string, types, name: q.prepare ? statementId + statementCount++ : '' }++ typeof options.debug === 'function' && options.debug(id, string, parameters, types)+ }++ function write(x, fn) {+ chunk = chunk ? Buffer.concat([chunk, x]) : Buffer.from(x)+ if (fn || chunk.length >= 1024)+ return nextWrite(fn)+ nextWriteTimer === null && (nextWriteTimer = setImmediate(nextWrite))+ return true+ }++ function nextWrite(fn) {+ const x = socket.write(chunk, fn)+ nextWriteTimer !== null && clearImmediate(nextWriteTimer)+ chunk = nextWriteTimer = null+ return x+ }++ function connectTimedOut() {+ errored(Errors.connection('CONNECT_TIMEOUT', options, socket))+ socket.destroy()+ }++ async function secure() {+ if (sslnegotiation !== 'direct') {+ write(SSLRequest)+ const canSSL = await new Promise(r => socket.once('data', x => r(x[0] === 83))) // S++ if (!canSSL && ssl === 'prefer')+ return connected()+ }++ const options = {+ socket,+ servername: net.isIP(socket.host) ? undefined : socket.host+ }++ if (sslnegotiation === 'direct')+ options.ALPNProtocols = ['postgresql']++ if (ssl === 'require' || ssl === 'allow' || ssl === 'prefer')+ options.rejectUnauthorized = false+ else if (typeof ssl === 'object')+ Object.assign(options, ssl)++ socket.removeAllListeners()+ socket = tls.connect(options)+ socket.on('secureConnect', connected)+ socket.on('error', error)+ socket.on('close', closed)+ socket.on('drain', drain)+ }++ /* c8 ignore next 3 */+ function drain() {+ !query && !connection.reserved && onopen(connection)+ }++ function data(x) {+ if (incomings) {+ incomings.push(x)+ remaining -= x.length+ if (remaining > 0)+ return+ }++ incoming = incomings+ ? Buffer.concat(incomings, length - remaining)+ : incoming.length === 0+ ? x+ : Buffer.concat([incoming, x], incoming.length + x.length)++ while (incoming.length > 4) {+ length = incoming.readUInt32BE(1)+ if (length >= incoming.length) {+ remaining = length - incoming.length+ incomings = [incoming]+ break+ }++ try {+ handle(incoming.subarray(0, length + 1))+ } catch (e) {+ query && (query.cursorFn || query.describeFirst) && write(Sync)+ errored(e)+ }+ incoming = incoming.subarray(length + 1)+ remaining = 0+ incomings = null+ }+ }++ async function connect() {+ terminated = false+ backendParameters = {}+ socket || (socket = await createSocket())++ if (!socket)+ return++ connectTimer.start()++ if (options.socket)+ return ssl ? secure() : connected()++ socket.on('connect', ssl ? secure : connected)++ if (options.path)+ return socket.connect(options.path)++ socket.ssl = ssl+ socket.connect(port[hostIndex], host[hostIndex])+ socket.host = host[hostIndex]+ socket.port = port[hostIndex]++ hostIndex = (hostIndex + 1) % port.length+ }++ function reconnect() {+ setTimeout(connect, closedTime ? Math.max(0, closedTime + delay - performance.now()) : 0)+ }++ function connected() {+ try {+ statements = {}+ needsTypes = options.fetch_types+ statementId = Math.random().toString(36).slice(2)+ statementCount = 1+ lifeTimer.start()+ socket.on('data', data)+ keep_alive && socket.setKeepAlive && socket.setKeepAlive(true, 1000 * keep_alive)+ const s = StartupMessage()+ write(s)+ } catch (err) {+ error(err)+ }+ }++ function error(err) {+ if (cancelMessage)+ cancelError = err+ if (connection.queue === queues.connecting && options.host[retries + 1])+ return++ errored(err)+ while (sent.length)+ queryError(sent.shift(), err)+ }++ function errored(err) {+ if (cancelMessage)+ cancelError = err+ stream && (stream.destroy(err), stream = null)+ query && queryError(query, err)+ initial && (queryError(initial, err), initial = null)+ }++ function queryError(query, err) {+ if (query.reserve)+ return query.reject(err)++ if (!err || typeof err !== 'object')+ err = new Error(err)++ 'query' in err || 'parameters' in err || Object.defineProperties(err, {+ stack: { value: err.stack + query.origin.replace(/.*\n/, '\n'), enumerable: options.debug },+ query: { value: query.string, enumerable: options.debug },+ parameters: { value: query.parameters, enumerable: options.debug },+ args: { value: query.args, enumerable: options.debug },+ types: { value: query.statement && query.statement.types, enumerable: options.debug }+ })+ query.reject(err)+ }++ function end() {+ return ending || (+ !connection.reserved && onend(connection),+ !connection.reserved && !initial && !query && sent.length === 0+ ? (terminate(), new Promise(r => socket && socket.readyState !== 'closed' ? socket.once('close', r) : r()))+ : ending = new Promise(r => ended = r)+ )+ }++ function terminate() {+ terminated = true+ if (stream || query || initial || sent.length)+ error(Errors.connection('CONNECTION_DESTROYED', options))++ clearImmediate(nextWriteTimer)+ if (socket) {+ socket.removeListener('data', data)+ socket.removeListener('connect', connected)+ socket.readyState === 'open' && socket.end(b().X().end())+ }+ ended && (ended(), ending = ended = null)+ }++ async function closed(hadError) {+ incoming = Buffer.alloc(0)+ remaining = 0+ incomings = null+ clearImmediate(nextWriteTimer)+ socket.removeListener('data', data)+ socket.removeListener('connect', connected)+ idleTimer.cancel()+ lifeTimer.cancel()+ connectTimer.cancel()++ socket.removeAllListeners()+ socket = null++ if (cancelMessage)+ return cancelError || hadError+ ? cancelReject(cancelError || Errors.connection('CONNECTION_CLOSED', options))+ : cancelResolve()++ if (initial)+ return reconnect()++ !hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))+ closedTime = performance.now()+ hadError && options.shared.retries+++ delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000+ onclose(connection, Errors.connection('CONNECTION_CLOSED', options, socket))+ }++ /* Handlers */+ function handle(xs, x = xs[0]) {+ (+ x === 68 ? DataRow : // D+ x === 100 ? CopyData : // d+ x === 65 ? NotificationResponse : // A+ x === 83 ? ParameterStatus : // S+ x === 90 ? ReadyForQuery : // Z+ x === 67 ? CommandComplete : // C+ x === 50 ? BindComplete : // 2+ x === 49 ? ParseComplete : // 1+ x === 116 ? ParameterDescription : // t+ x === 84 ? RowDescription : // T+ x === 82 ? Authentication : // R+ x === 110 ? NoData : // n+ x === 75 ? BackendKeyData : // K+ x === 69 ? ErrorResponse : // E+ x === 115 ? PortalSuspended : // s+ x === 51 ? CloseComplete : // 3+ x === 71 ? CopyInResponse : // G+ x === 78 ? NoticeResponse : // N+ x === 72 ? CopyOutResponse : // H+ x === 99 ? CopyDone : // c+ x === 73 ? EmptyQueryResponse : // I+ x === 86 ? FunctionCallResponse : // V+ x === 118 ? NegotiateProtocolVersion : // v+ x === 87 ? CopyBothResponse : // W+ /* c8 ignore next */+ UnknownMessage+ )(xs)+ }++ function DataRow(x) {+ let index = 7+ let length+ let column+ let value++ const row = query.isRaw ? new Array(query.statement.columns.length) : {}+ for (let i = 0; i < query.statement.columns.length; i++) {+ column = query.statement.columns[i]+ length = x.readInt32BE(index)+ index += 4++ value = length === -1+ ? null+ : query.isRaw === true+ ? x.subarray(index, index += length)+ : column.parser === undefined+ ? x.toString('utf8', index, index += length)+ : column.parser.array === true+ ? column.parser(x.toString('utf8', index + 1, index += length))+ : column.parser(x.toString('utf8', index, index += length))++ query.isRaw+ ? (row[i] = query.isRaw === true+ ? value+ : transform.value.from ? transform.value.from(value, column) : value)+ : (row[column.name] = transform.value.from ? transform.value.from(value, column) : value)+ }++ query.forEachFn+ ? query.forEachFn(transform.row.from ? transform.row.from(row) : row, result)+ : (result[rows++] = transform.row.from ? transform.row.from(row) : row)+ }++ function ParameterStatus(x) {+ const [k, v] = x.toString('utf8', 5, x.length - 1).split(b.N)+ backendParameters[k] = v+ if (options.parameters[k] !== v) {+ options.parameters[k] = v+ onparameter && onparameter(k, v)+ }+ }++ function ReadyForQuery(x) {+ if (query) {+ if (errorResponse) {+ query.retried+ ? errored(query.retried)+ : query.prepared && retryRoutines.has(errorResponse.routine)+ ? retry(query, errorResponse)+ : errored(errorResponse)+ } else {+ query.resolve(results || result)+ }+ } else if (errorResponse) {+ errored(errorResponse)+ }++ query = results = errorResponse = null+ result = new Result()+ connectTimer.cancel()++ if (initial) {+ if (target_session_attrs) {+ if (!backendParameters.in_hot_standby || !backendParameters.default_transaction_read_only)+ return fetchState()+ else if (tryNext(target_session_attrs, backendParameters))+ return terminate()+ }++ if (needsTypes) {+ initial.reserve && (initial = null)+ return fetchArrayTypes()+ }++ const reserving = initial && initial.reserve+ initial && !reserving && execute(initial)+ options.shared.retries = retries = 0+ initial = null+ if (!reserving)+ return+ }++ while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))+ Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)++ if (query)+ return // Consider opening if able and sent.length < 50++ connection.reserved+ ? !connection.reserved.release && x[5] === 73 // I+ ? ending+ ? terminate()+ : connection.reserved(true)+ : connection.reserved()+ : ending+ ? terminate()+ : onopen(connection)+ }++ function CommandComplete(x) {+ rows = 0++ for (let i = x.length - 1; i > 0; i--) {+ if (x[i] === 32 && x[i + 1] < 58 && result.count === null)+ result.count = +x.toString('utf8', i + 1, x.length - 1)+ if (x[i - 1] >= 65) {+ result.command = x.toString('utf8', 5, i)+ result.state = backend+ break+ }+ }++ final && (final(), final = null)++ if (result.command === 'BEGIN' && max !== 1 && !connection.reserved)+ return errored(Errors.generic('UNSAFE_TRANSACTION', 'Only use sql.begin, sql.reserved or max: 1'))++ if (query.options.simple)+ return BindComplete()++ if (query.cursorFn) {+ result.count && query.cursorFn(result)+ write(Sync)+ }+ }++ function ParseComplete() {+ query.parsing = false+ }++ function BindComplete() {+ !result.statement && (result.statement = query.statement)+ result.columns = query.statement.columns+ }++ function ParameterDescription(x) {+ const length = x.readUInt16BE(5)++ for (let i = 0; i < length; ++i)+ !query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))++ query.prepare && (statements[query.signature] = query.statement)+ query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false)+ }++ function RowDescription(x) {+ if (result.command) {+ results = results || [result]+ results.push(result = new Result())+ result.count = null+ query.statement.columns = null+ }++ const length = x.readUInt16BE(5)+ let index = 7+ let start++ query.statement.columns = Array(length)++ for (let i = 0; i < length; ++i) {+ start = index+ while (x[index++] !== 0);+ const table = x.readUInt32BE(index)+ const number = x.readUInt16BE(index + 4)+ const type = x.readUInt32BE(index + 6)+ query.statement.columns[i] = {+ name: transform.column.from+ ? transform.column.from(x.toString('utf8', start, index - 1))+ : x.toString('utf8', start, index - 1),+ parser: parsers[type],+ table,+ number,+ type+ }+ index += 18+ }++ result.statement = query.statement+ if (query.onlyDescribe)+ return (query.resolve(query.statement), write(Sync))+ }++ async function Authentication(x, type = x.readUInt32BE(5)) {+ (+ type === 3 ? AuthenticationCleartextPassword :+ type === 5 ? AuthenticationMD5Password :+ type === 10 ? SASL :+ type === 11 ? SASLContinue :+ type === 12 ? SASLFinal :+ type !== 0 ? UnknownAuth :+ noop+ )(x, type)+ }++ /* c8 ignore next 5 */+ async function AuthenticationCleartextPassword() {+ const payload = await Pass()+ write(+ b().p().str(payload).z(1).end()+ )+ }++ async function AuthenticationMD5Password(x) {+ const payload = 'md5' + (+ await md5(+ Buffer.concat([+ Buffer.from(await md5((await Pass()) + user)),+ x.subarray(9)+ ])+ )+ )+ write(+ b().p().str(payload).z(1).end()+ )+ }++ async function SASL() {+ nonce = (await crypto.randomBytes(18)).toString('base64')+ b().p().str('SCRAM-SHA-256' + b.N)+ const i = b.i+ write(b.inc(4).str('n,,n=*,r=' + nonce).i32(b.i - i - 4, i).end())+ }++ async function SASLContinue(x) {+ const res = x.toString('utf8', 9).split(',').reduce((acc, x) => (acc[x[0]] = x.slice(2), acc), {})++ const saltedPassword = await crypto.pbkdf2Sync(+ await Pass(),+ Buffer.from(res.s, 'base64'),+ parseInt(res.i), 32,+ 'sha256'+ )++ const clientKey = await hmac(saltedPassword, 'Client Key')++ const auth = 'n=*,r=' + nonce + ','+ + 'r=' + res.r + ',s=' + res.s + ',i=' + res.i+ + ',c=biws,r=' + res.r++ serverSignature = (await hmac(await hmac(saltedPassword, 'Server Key'), auth)).toString('base64')++ const payload = 'c=biws,r=' + res.r + ',p=' + xor(+ clientKey, Buffer.from(await hmac(await sha256(clientKey), auth))+ ).toString('base64')++ write(+ b().p().str(payload).end()+ )+ }++ function SASLFinal(x) {+ if (x.toString('utf8', 9).split(b.N, 1)[0].slice(2) === serverSignature)+ return+ /* c8 ignore next 5 */+ errored(Errors.generic('SASL_SIGNATURE_MISMATCH', 'The server did not return the correct signature'))+ socket.destroy()+ }++ function Pass() {+ return Promise.resolve(typeof options.pass === 'function'+ ? options.pass()+ : options.pass+ )+ }++ function NoData() {+ result.statement = query.statement+ result.statement.columns = []+ if (query.onlyDescribe)+ return (query.resolve(query.statement), write(Sync))+ }++ function BackendKeyData(x) {+ backend.pid = x.readUInt32BE(5)+ backend.secret = x.readUInt32BE(9)+ }++ async function fetchArrayTypes() {+ needsTypes = false+ const types = await new Query([`+ select b.oid, b.typarray+ from pg_catalog.pg_type a+ left join pg_catalog.pg_type b on b.oid = a.typelem+ where a.typcategory = 'A'+ group by b.oid, b.typarray+ order by b.oid+ `], [], execute)+ types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))+ }++ function addArrayType(oid, typarray) {+ if (!!options.parsers[typarray] && !!options.serializers[typarray]) return+ const parser = options.parsers[oid]+ options.shared.typeArrayMap[oid] = typarray+ options.parsers[typarray] = (xs) => arrayParser(xs, parser, typarray)+ options.parsers[typarray].array = true+ options.serializers[typarray] = (xs) => arraySerializer(xs, options.serializers[oid], options, typarray)+ }++ function tryNext(x, xs) {+ return (+ (x === 'read-write' && xs.default_transaction_read_only === 'on') ||+ (x === 'read-only' && xs.default_transaction_read_only === 'off') ||+ (x === 'primary' && xs.in_hot_standby === 'on') ||+ (x === 'standby' && xs.in_hot_standby === 'off') ||+ (x === 'prefer-standby' && xs.in_hot_standby === 'off' && options.host[retries])+ )+ }++ function fetchState() {+ const query = new Query([`+ show transaction_read_only;+ select pg_catalog.pg_is_in_recovery()+ `], [], execute, null, { simple: true })+ query.resolve = ([[a], [b]]) => {+ backendParameters.default_transaction_read_only = a.transaction_read_only+ backendParameters.in_hot_standby = b.pg_is_in_recovery ? 'on' : 'off'+ }+ query.execute()+ }++ function ErrorResponse(x) {+ if (query) {+ (query.cursorFn || query.describeFirst) && write(Sync)+ errorResponse = Errors.postgres(parseError(x))+ } else {+ errored(Errors.postgres(parseError(x)))+ }+ }++ function retry(q, error) {+ delete statements[q.signature]+ q.retried = error+ execute(q)+ }++ function NotificationResponse(x) {+ if (!onnotify)+ return++ let index = 9+ while (x[index++] !== 0);+ onnotify(+ x.toString('utf8', 9, index - 1),+ x.toString('utf8', index, x.length - 1)+ )+ }++ async function PortalSuspended() {+ try {+ const x = await Promise.resolve(query.cursorFn(result))+ rows = 0+ x === CLOSE+ ? write(Close(query.portal))+ : (result = new Result(), write(Execute('', query.cursorRows)))+ } catch (err) {+ write(Sync)+ query.reject(err)+ }+ }++ function CloseComplete() {+ result.count && query.cursorFn(result)+ query.resolve(result)+ }++ function CopyInResponse() {+ stream = new Stream.Writable({+ autoDestroy: true,+ write(chunk, encoding, callback) {+ socket.write(b().d().raw(chunk).end(), callback)+ },+ destroy(error, callback) {+ callback(error)+ socket.write(b().f().str(error + b.N).end())+ stream = null+ },+ final(callback) {+ socket.write(b().c().end())+ final = callback+ stream = null+ }+ })+ query.resolve(stream)+ }++ function CopyOutResponse() {+ stream = new Stream.Readable({+ read() { socket.resume() }+ })+ query.resolve(stream)+ }++ /* c8 ignore next 3 */+ function CopyBothResponse() {+ stream = new Stream.Duplex({+ autoDestroy: true,+ read() { socket.resume() },+ /* c8 ignore next 11 */+ write(chunk, encoding, callback) {+ socket.write(b().d().raw(chunk).end(), callback)+ },+ destroy(error, callback) {+ callback(error)+ socket.write(b().f().str(error + b.N).end())+ stream = null+ },+ final(callback) {+ socket.write(b().c().end())+ final = callback+ }+ })+ query.resolve(stream)+ }++ function CopyData(x) {+ stream && (stream.push(x.subarray(5)) || socket.pause())+ }++ function CopyDone() {+ stream && stream.push(null)+ stream = null+ }++ function NoticeResponse(x) {+ onnotice+ ? onnotice(parseError(x))+ : console.log(parseError(x)) // eslint-disable-line++ }++ /* c8 ignore next 3 */+ function EmptyQueryResponse() {+ /* noop */+ }++ /* c8 ignore next 3 */+ function FunctionCallResponse() {+ errored(Errors.notSupported('FunctionCallResponse'))+ }++ /* c8 ignore next 3 */+ function NegotiateProtocolVersion() {+ errored(Errors.notSupported('NegotiateProtocolVersion'))+ }++ /* c8 ignore next 3 */+ function UnknownMessage(x) {+ console.error('Postgres.js : Unknown Message:', x[0]) // eslint-disable-line+ }++ /* c8 ignore next 3 */+ function UnknownAuth(x, type) {+ console.error('Postgres.js : Unknown Auth:', type) // eslint-disable-line+ }++ /* Messages */+ function Bind(parameters, types, statement = '', portal = '') {+ let prev+ , type++ b().B().str(portal + b.N).str(statement + b.N).i16(0).i16(parameters.length)++ parameters.forEach((x, i) => {+ if (x === null)+ return b.i32(0xFFFFFFFF)++ type = types[i]+ parameters[i] = x = type in options.serializers+ ? options.serializers[type](x)+ : '' + x++ prev = b.i+ b.inc(4).str(x).i32(b.i - prev - 4, prev)+ })++ b.i16(0)++ return b.end()+ }++ function Parse(str, parameters, types, name = '') {+ b().P().str(name + b.N).str(str + b.N).i16(parameters.length)+ parameters.forEach((x, i) => b.i32(types[i] || 0))+ return b.end()+ }++ function Describe(x, name = '') {+ return b().D().str(x).str(name + b.N).end()+ }++ function Execute(portal = '', rows = 0) {+ return Buffer.concat([+ b().E().str(portal + b.N).i32(rows).end(),+ Flush+ ])+ }++ function Close(portal = '') {+ return Buffer.concat([+ b().C().str('P').str(portal + b.N).end(),+ b().S().end()+ ])+ }++ function StartupMessage() {+ return cancelMessage || b().inc(4).i16(3).z(2).str(+ Object.entries(Object.assign({+ user,+ database,+ client_encoding: 'UTF8'+ },+ options.connection+ )).filter(([, v]) => v).map(([k, v]) => k + b.N + v).join(b.N)+ ).z(2).end(0)+ }++}++function parseError(x) {+ const error = {}+ let start = 5+ for (let i = 5; i < x.length - 1; i++) {+ if (x[i] === 0) {+ error[errorFields[x[start]]] = x.toString('utf8', start + 1, i)+ start = i + 1+ }+ }+ return error+}++function md5(x) {+ return crypto.createHash('md5').update(x).digest('hex')+}++function hmac(key, x) {+ return crypto.createHmac('sha256', key).update(x).digest()+}++function sha256(x) {+ return crypto.createHash('sha256').update(x).digest()+}++function xor(a, b) {+ const length = Math.max(a.length, b.length)+ const buffer = Buffer.allocUnsafe(length)+ for (let i = 0; i < length; i++)+ buffer[i] = a[i] ^ b[i]+ return buffer+}++function timer(fn, seconds) {+ seconds = typeof seconds === 'function' ? seconds() : seconds+ if (!seconds)+ return { cancel: noop, start: noop }++ let timer+ return {+ cancel() {+ timer && (clearTimeout(timer), timer = null)+ },+ start() {+ timer && clearTimeout(timer)+ timer = setTimeout(done, seconds * 1000, arguments)+ }+ }++ function done(args) {+ fn.apply(null, args)+ timer = null+ }+}diff --git a/vendor/postgres/cf/src/errors.js b/vendor/postgres/cf/src/errors.jsnew file mode 100644index 0000000000..0ff83c428b--- /dev/null+++ b/vendor/postgres/cf/src/errors.js@@ -0,0 +1,53 @@+export class PostgresError extends Error {+ constructor(x) {+ super(x.message)+ this.name = this.constructor.name+ Object.assign(this, x)+ }+}++export const Errors = {+ connection,+ postgres,+ generic,+ notSupported+}++function connection(x, options, socket) {+ const { host, port } = socket || options+ const error = Object.assign(+ new Error(('write ' + x + ' ' + (options.path || (host + ':' + port)))),+ {+ code: x,+ errno: x,+ address: options.path || host+ }, options.path ? {} : { port: port }+ )+ Error.captureStackTrace(error, connection)+ return error+}++function postgres(x) {+ const error = new PostgresError(x)+ Error.captureStackTrace(error, postgres)+ return error+}++function generic(code, message) {+ const error = Object.assign(new Error(code + ': ' + message), { code })+ Error.captureStackTrace(error, generic)+ return error+}++/* c8 ignore next 10 */+function notSupported(x) {+ const error = Object.assign(+ new Error(x + ' (B) is not supported'),+ {+ code: 'MESSAGE_NOT_SUPPORTED',+ name: x+ }+ )+ Error.captureStackTrace(error, notSupported)+ return error+}diff --git a/vendor/postgres/cf/src/index.js b/vendor/postgres/cf/src/index.jsnew file mode 100644index 0000000000..43b8b091a8--- /dev/null+++ b/vendor/postgres/cf/src/index.js@@ -0,0 +1,681 @@+import { process } from '../polyfills.js'+import { os } from '../polyfills.js'+import { fs } from '../polyfills.js'++import {+ mergeUserTypes,+ inferType,+ Parameter,+ Identifier,+ Builder,+ toPascal,+ pascal,+ toCamel,+ camel,+ toKebab,+ kebab,+ fromPascal,+ fromCamel,+ fromKebab+} from './types.js'++import Connection from './connection.js'+import { Query, CLOSE } from './query.js'+import Queue from './queue.js'+import { Errors, PostgresError } from './errors.js'+import Subscribe from './subscribe.js'+import largeObject from './large.js'++Object.assign(Postgres, {+ PostgresError,+ toPascal,+ pascal,+ toCamel,+ camel,+ toKebab,+ kebab,+ fromPascal,+ fromCamel,+ fromKebab,+ BigInt: {+ to: 20,+ from: [20],+ parse: x => BigInt(x), // eslint-disable-line+ serialize: x => x.toString()+ }+})++export default Postgres++function Postgres(a, b) {+ const options = parseOptions(a, b)+ , subscribe = options.no_subscribe || Subscribe(Postgres, { ...options })++ let ending = false++ const queries = Queue()+ , connecting = Queue()+ , reserved = Queue()+ , closed = Queue()+ , ended = Queue()+ , open = Queue()+ , busy = Queue()+ , full = Queue()+ , queues = { connecting, reserved, closed, ended, open, busy, full }++ const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose }))++ const sql = Sql(handler)++ Object.assign(sql, {+ get parameters() { return options.parameters },+ largeObject: largeObject.bind(null, sql),+ subscribe,+ CLOSE,+ END: CLOSE,+ PostgresError,+ options,+ reserve,+ listen,+ begin,+ close,+ end+ })++ return sql++ function Sql(handler) {+ handler.debug = options.debug++ Object.entries(options.types).reduce((acc, [name, type]) => {+ acc[name] = (x) => new Parameter(x, type.to)+ return acc+ }, typed)++ Object.assign(sql, {+ types: typed,+ typed,+ unsafe,+ notify,+ array,+ json,+ file+ })++ return sql++ function typed(value, type) {+ return new Parameter(value, type)+ }++ function sql(strings, ...args) {+ const query = strings && Array.isArray(strings.raw)+ ? new Query(strings, args, handler, cancel)+ : typeof strings === 'string' && !args.length+ ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings)+ : new Builder(strings, args)+ return query+ }++ function unsafe(string, args = [], options = {}) {+ arguments.length === 2 && !Array.isArray(args) && (options = args, args = [])+ const query = new Query([string], args, handler, cancel, {+ prepare: false,+ ...options,+ simple: 'simple' in options ? options.simple : args.length === 0+ })+ return query+ }++ function file(path, args = [], options = {}) {+ arguments.length === 2 && !Array.isArray(args) && (options = args, args = [])+ const query = new Query([], args, (query) => {+ fs.readFile(path, 'utf8', (err, string) => {+ if (err)+ return query.reject(err)++ query.strings = [string]+ handler(query)+ })+ }, cancel, {+ ...options,+ simple: 'simple' in options ? options.simple : args.length === 0+ })+ return query+ }+ }++ async function listen(name, fn, onlisten) {+ const listener = { fn, onlisten }++ const sql = listen.sql || (listen.sql = Postgres({+ ...options,+ max: 1,+ idle_timeout: null,+ max_lifetime: null,+ fetch_types: false,+ onclose() {+ Object.entries(listen.channels).forEach(([name, { listeners }]) => {+ delete listen.channels[name]+ Promise.all(listeners.map(l => listen(name, l.fn, l.onlisten).catch(() => { /* noop */ })))+ })+ },+ onnotify(c, x) {+ c in listen.channels && listen.channels[c].listeners.forEach(l => l.fn(x))+ }+ }))++ const channels = listen.channels || (listen.channels = {})+ , exists = name in channels++ if (exists) {+ channels[name].listeners.push(listener)+ const result = await channels[name].result+ listener.onlisten && listener.onlisten()+ return { state: result.state, unlisten }+ }++ channels[name] = { result: sql`listen ${+ sql.unsafe('"' + name.replace(/"/g, '""') + '"')+ }`, listeners: [listener] }+ const result = await channels[name].result+ listener.onlisten && listener.onlisten()+ return { state: result.state, unlisten }++ async function unlisten() {+ if (name in channels === false)+ return++ channels[name].listeners = channels[name].listeners.filter(x => x !== listener)+ if (channels[name].listeners.length)+ return++ delete channels[name]+ return sql`unlisten ${+ sql.unsafe('"' + name.replace(/"/g, '""') + '"')+ }`+ }+ }++ async function notify(channel, payload) {+ return await sql`select pg_notify(${ channel }, ${ '' + payload })`+ }++ function own(c) {+ const queue = Queue()+ let busy = false, fence = null, holding = null, releasing = false+ const reservation = c.reserved = (ended = false) => {+ if (c.reserved !== reservation)+ return+ busy = false+ if (ended) {+ releasing = true+ reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction has ended'))+ }+ const completed = fence+ fence = null+ if (completed && completed.cancelPromise) {+ holding = completed+ completed.cancelPromise.then(() => {+ if (c.reserved !== reservation || holding !== completed)+ return+ holding = null+ pump()+ }, reservation.discard)+ } else {+ pump()+ }+ }+ reservation.enqueue = q => {+ if (c.reserved !== reservation || releasing)+ return q.reject(Errors.generic('CONNECTION_CLOSED', 'Connection is no longer owned'))+ queue.push(q)+ pump()+ }+ reservation.reject = error => {+ while (queue.length)+ queue.shift().reject(error)+ }+ reservation.discard = () => {+ if (c.reserved !== reservation)+ return+ c.reserved = null+ reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Connection was discarded'))+ c.terminate()+ }+ reservation.releaseConnection = () => {+ if (c.reserved !== reservation)+ return+ releasing = true+ pump()+ }+ return reservation++ function pump() {+ if (c.reserved !== reservation || holding || fence)+ return+ while (queue.length) {+ const q = queue.peek()+ if (q.cancelled) {+ queue.shift()+ continue+ }+ if (busy && (q.options.cancelFence || c.queue === full))+ return+ queue.shift()+ busy = true+ if (q.options.cancelFence)+ fence = q+ const ready = c.execute(q)+ move(c, ready ? reserved : full)+ if (fence || !ready)+ return+ }+ if (!busy) {+ if (releasing) {+ c.reserved = null+ onopen(c)+ } else {+ move(c, reserved)+ }+ }+ }+ }++ async function reserve({ signal } = {}) {+ signal && signal.throwIfAborted()+ if (ending)+ throw Errors.connection('CONNECTION_ENDED', options, options)+ const sql = open.length+ ? claim(open.shift())+ : await new Promise((resolve, reject) => {+ let settled = false+ const query = {+ reserve: c => { if (settle()) resolve(claim(c)) },+ reject: error => { if (settle()) reject(error) }+ }+ const abort = () => query.reject(signal.reason)+ function settle() {+ if (settled)+ return false+ settled = true+ queries.remove(query)+ signal && signal.removeEventListener('abort', abort)+ return true+ }+ if (signal)+ signal.addEventListener('abort', abort, { once: true })+ queries.push(query)+ closed.length && connect(closed.shift(), query)+ })++ if (signal && signal.aborted) {+ sql.release()+ signal.throwIfAborted()+ }++ return sql++ function claim(c) {+ move(c, reserved)+ const reservation = own(c)+ reservation.release = true+ const sql = Sql(reservation.enqueue)+ sql.release = reservation.releaseConnection+ sql.discard = reservation.discard+ return sql+ }+ }++ async function begin(options, fn) {+ !fn && (fn = options, options = '')+ let savepoints = 0+ , connection+ , prepare = null++ try {+ await sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()+ return await Promise.race([+ scope(connection, fn),+ new Promise((_, reject) => connection.onclose = reject)+ ])+ } catch (error) {+ throw error+ }++ async function scope(c, fn, name) {+ const reservation = c.reserved+ if (!reservation)+ throw Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned')+ const sql = Sql(handler)+ sql.savepoint = savepoint+ sql.prepare = x => prepare = x.replace(/[^a-z0-9$-_. ]/gi)+ sql.discard = reservation.discard+ let uncaughtError+ , result++ name && await sql`savepoint ${ sql(name) }`+ try {+ result = await new Promise((resolve, reject) => {+ const x = fn(sql)+ Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject)+ })++ if (uncaughtError)+ throw uncaughtError+ } catch (e) {+ await (name+ ? sql`rollback to ${ sql(name) }`+ : sql`rollback`+ )+ throw e instanceof PostgresError && e.code === '25P02' && uncaughtError || e+ }++ if (!name) {+ prepare+ ? await sql`prepare transaction '${ sql.unsafe(prepare) }'`+ : await sql`commit`+ }++ return result++ function savepoint(name, fn) {+ if (c.reserved !== reservation)+ return Promise.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))+ if (name && Array.isArray(name.raw))+ return savepoint(sql => sql.apply(sql, arguments))++ arguments.length === 1 && (fn = name, name = null)+ return scope(c, fn, 's' + savepoints++ + (name ? '_' + name : ''))+ }++ function handler(q) {+ q.catch(e => uncaughtError || (uncaughtError = e))+ if (!reservation || c.reserved !== reservation)+ return q.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))+ reservation.enqueue(q)+ }+ }++ function onexecute(c) {+ connection = c+ move(c, reserved)+ own(c)+ }+ }++ function move(c, queue) {+ c.queue.remove(c)+ queue.push(c)+ c.queue = queue+ queue === open+ ? c.idleTimer.start()+ : c.idleTimer.cancel()+ return c+ }++ function json(x) {+ return new Parameter(x, 3802)+ }++ function array(x, type) {+ if (!Array.isArray(x))+ return array(Array.from(arguments))++ return new Parameter(x, type || (x.length ? inferType(x) || 25 : 0), options.shared.typeArrayMap)+ }++ function handler(query) {+ if (ending)+ return query.reject(Errors.connection('CONNECTION_ENDED', options, options))++ if (open.length)+ return go(open.shift(), query)++ if (closed.length)+ return connect(closed.shift(), query)++ busy.length+ ? go(busy.shift(), query)+ : queries.push(query)+ }++ function go(c, query) {+ return c.execute(query)+ ? move(c, busy)+ : move(c, full)+ }++ function cancel(query) {+ return new Promise((resolve, reject) => {+ query.state+ ? query.active+ ? Connection(options).cancel(query.state, resolve, reject)+ : query.cancelled = { resolve, reject }+ : (+ queries.remove(query),+ query.cancelled = true,+ query.reject(Errors.generic('57014', 'canceling statement due to user request')),+ resolve()+ )+ })+ }++ async function end({ timeout = null } = {}) {+ if (ending)+ return ending++ await 1+ let timer+ return ending = Promise.race([+ new Promise(r => timeout !== null && (timer = setTimeout(destroy, timeout * 1000, r))),+ Promise.all(connections.map(c => c.end()).concat(+ listen.sql ? listen.sql.end({ timeout: 0 }) : [],+ subscribe.sql ? subscribe.sql.end({ timeout: 0 }) : []+ ))+ ]).then(() => clearTimeout(timer))+ }++ async function close() {+ await Promise.all(connections.map(c => c.end()))+ }++ async function destroy(resolve) {+ await Promise.all(connections.map(c => c.terminate()))+ while (queries.length)+ queries.shift().reject(Errors.connection('CONNECTION_DESTROYED', options))+ resolve()+ }++ function connect(c, query) {+ move(c, connecting)+ c.connect(query)+ return c+ }++ function onend(c) {+ move(c, ended)+ }++ function onopen(c) {+ if (ending) {+ while (queries.length)+ queries.shift().reject(Errors.connection('CONNECTION_ENDED', options))+ return c.terminate()+ }+ if (queries.length === 0)+ return move(c, open)++ let max = Math.ceil(queries.length / (connecting.length + 1))+ , ready = true++ while (ready && queries.length && max-- > 0) {+ const query = queries.shift()+ if (query.reserve)+ return query.reserve(c)++ ready = c.execute(query)+ }++ ready+ ? move(c, busy)+ : move(c, full)+ }++ function onclose(c, e) {+ move(c, closed)+ const reservation = c.reserved+ c.reserved = null+ reservation && reservation.reject(e)+ c.onclose && (c.onclose(e), c.onclose = null)+ options.onclose && options.onclose(c.id)+ if (ending) {+ while (queries.length)+ queries.shift().reject(Errors.connection('CONNECTION_ENDED', options))+ return+ }+ if (queries.length) {+ const query = queries.peek()+ connect(c, query.reserve ? query : queries.shift())+ }+ }+}++function parseOptions(a, b) {+ if (a && a.shared)+ return a++ const env = process.env // eslint-disable-line+ , o = (!a || typeof a === 'string' ? b : a) || {}+ , { url, multihost } = parseUrl(a)+ , query = [...url.searchParams].reduce((a, [b, c]) => (a[b] = c, a), {})+ , host = o.hostname || o.host || multihost || url.hostname || env.PGHOST || 'localhost'+ , port = o.port || url.port || env.PGPORT || 5432+ , user = o.user || o.username || url.username || env.PGUSERNAME || env.PGUSER || osUsername()++ o.no_prepare && (o.prepare = false)+ query.sslmode && (query.ssl = query.sslmode, delete query.sslmode)+ 'timeout' in o && (console.log('The timeout option is deprecated, use idle_timeout instead'), o.idle_timeout = o.timeout) // eslint-disable-line+ query.sslrootcert === 'system' && (query.ssl = 'verify-full')++ const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive']+ const defaults = {+ max : globalThis.Cloudflare ? 3 : 10,+ ssl : false,+ sslnegotiation : null,+ idle_timeout : null,+ connect_timeout : 30,+ max_lifetime : max_lifetime,+ max_pipeline : 100,+ backoff : backoff,+ keep_alive : 60,+ prepare : true,+ debug : false,+ fetch_types : true,+ publications : 'alltables',+ target_session_attrs: null+ }++ return {+ host : Array.isArray(host) ? host : host.split(',').map(x => x.split(':')[0]),+ port : Array.isArray(port) ? port : host.split(',').map(x => parseInt(x.split(':')[1] || port)),+ path : o.path || host.indexOf('/') > -1 && host + '/.s.PGSQL.' + port,+ database : o.database || o.db || (url.pathname || '').slice(1) || env.PGDATABASE || user,+ user : user,+ pass : o.pass || o.password || url.password || env.PGPASSWORD || '',+ ...Object.entries(defaults).reduce(+ (acc, [k, d]) => {+ const value = k in o ? o[k] : k in query+ ? (query[k] === 'disable' || query[k] === 'false' ? false : query[k])+ : env['PG' + k.toUpperCase()] || d+ acc[k] = typeof value === 'string' && ints.includes(k)+ ? +value+ : value+ return acc+ },+ {}+ ),+ connection : {+ application_name: env.PGAPPNAME || 'postgres.js',+ ...o.connection,+ ...Object.entries(query).reduce((acc, [k, v]) => (k in defaults || (acc[k] = v), acc), {})+ },+ types : o.types || {},+ target_session_attrs: tsa(o, url, env),+ onnotice : o.onnotice,+ onnotify : o.onnotify,+ onclose : o.onclose,+ onparameter : o.onparameter,+ socket : o.socket,+ transform : parseTransform(o.transform || { undefined: undefined }),+ parameters : {},+ shared : { retries: 0, typeArrayMap: {} },+ ...mergeUserTypes(o.types)+ }+}++function tsa(o, url, env) {+ const x = o.target_session_attrs || url.searchParams.get('target_session_attrs') || env.PGTARGETSESSIONATTRS+ if (!x || ['read-write', 'read-only', 'primary', 'standby', 'prefer-standby'].includes(x))+ return x++ throw new Error('target_session_attrs ' + x + ' is not supported')+}++function backoff(retries) {+ return (0.5 + Math.random() / 2) * Math.min(3 ** retries / 100, 20)+}++function max_lifetime() {+ return 60 * (30 + Math.random() * 30)+}++function parseTransform(x) {+ return {+ undefined: x.undefined,+ column: {+ from: typeof x.column === 'function' ? x.column : x.column && x.column.from,+ to: x.column && x.column.to+ },+ value: {+ from: typeof x.value === 'function' ? x.value : x.value && x.value.from,+ to: x.value && x.value.to+ },+ row: {+ from: typeof x.row === 'function' ? x.row : x.row && x.row.from,+ to: x.row && x.row.to+ }+ }+}++function parseUrl(url) {+ if (!url || typeof url !== 'string')+ return { url: { searchParams: new Map() } }++ let host = url+ host = host.slice(host.indexOf('://') + 3).split(/[?/]/)[0]+ host = decodeURIComponent(host.slice(host.indexOf('@') + 1))++ const urlObj = new URL(url.replace(host, host.split(',')[0]))++ return {+ url: {+ username: decodeURIComponent(urlObj.username),+ password: decodeURIComponent(urlObj.password),+ host: urlObj.host,+ hostname: urlObj.hostname,+ port: urlObj.port,+ pathname: urlObj.pathname,+ searchParams: urlObj.searchParams+ },+ multihost: host.indexOf(',') > -1 && host+ }+}++function osUsername() {+ try {+ return os.userInfo().username // eslint-disable-line+ } catch (_) {+ return process.env.USERNAME || process.env.USER || process.env.LOGNAME // eslint-disable-line+ }+}diff --git a/vendor/postgres/cf/src/large.js b/vendor/postgres/cf/src/large.jsnew file mode 100644index 0000000000..8ae150ddfd--- /dev/null+++ b/vendor/postgres/cf/src/large.js@@ -0,0 +1,70 @@+import Stream from 'node:stream'++export default function largeObject(sql, oid, mode = 0x00020000 | 0x00040000) {+ return new Promise(async(resolve, reject) => {+ await sql.begin(async sql => {+ let finish+ !oid && ([{ oid }] = await sql`select lo_creat(-1) as oid`)+ const [{ fd }] = await sql`select lo_open(${ oid }, ${ mode }) as fd`++ const lo = {+ writable,+ readable,+ close : () => sql`select lo_close(${ fd })`.then(finish),+ tell : () => sql`select lo_tell64(${ fd })`,+ read : (x) => sql`select loread(${ fd }, ${ x }) as data`,+ write : (x) => sql`select lowrite(${ fd }, ${ x })`,+ truncate : (x) => sql`select lo_truncate64(${ fd }, ${ x })`,+ seek : (x, whence = 0) => sql`select lo_lseek64(${ fd }, ${ x }, ${ whence })`,+ size : () => sql`+ select+ lo_lseek64(${ fd }, location, 0) as position,+ seek.size+ from (+ select+ lo_lseek64($1, 0, 2) as size,+ tell.location+ from (select lo_tell64($1) as location) tell+ ) seek+ `+ }++ resolve(lo)++ return new Promise(async r => finish = r)++ async function readable({+ highWaterMark = 2048 * 8,+ start = 0,+ end = Infinity+ } = {}) {+ let max = end - start+ start && await lo.seek(start)+ return new Stream.Readable({+ highWaterMark,+ async read(size) {+ const l = size > max ? size - max : size+ max -= size+ const [{ data }] = await lo.read(l)+ this.push(data)+ if (data.length < size)+ this.push(null)+ }+ })+ }++ async function writable({+ highWaterMark = 2048 * 8,+ start = 0+ } = {}) {+ start && await lo.seek(start)+ return new Stream.Writable({+ highWaterMark,+ write(chunk, encoding, callback) {+ lo.write(chunk).then(() => callback(), callback)+ }+ })+ }+ }).catch(reject)+ })+}diff --git a/vendor/postgres/cf/src/query.js b/vendor/postgres/cf/src/query.jsnew file mode 100644index 0000000000..96967780bd--- /dev/null+++ b/vendor/postgres/cf/src/query.js@@ -0,0 +1,179 @@+const originCache = new Map()+ , originStackCache = new Map()+ , originError = Symbol('OriginError')++export const CLOSE = {}+export class Query extends Promise {+ constructor(strings, args, handler, canceller, options = {}) {+ let resolve+ , reject++ super((a, b) => {+ resolve = a+ reject = b+ })++ this.tagged = Array.isArray(strings.raw)+ this.strings = strings+ this.args = args+ this.handler = handler+ this.canceller = canceller+ this.options = options++ this.state = null+ this.statement = null++ this.resolve = x => (this.active = false, this.canceller = null, resolve(x))+ this.reject = x => (this.active = false, this.canceller = null, reject(x))++ this.active = false+ this.cancelled = null+ this.cancelPromise = null+ this.executed = false+ this.signature = ''++ this[originError] = this.handler.debug+ ? new Error()+ : this.tagged && cachedError(this.strings)+ }++ get origin() {+ return (this.handler.debug+ ? this[originError].stack+ : this.tagged && originStackCache.has(this.strings)+ ? originStackCache.get(this.strings)+ : originStackCache.set(this.strings, this[originError].stack).get(this.strings)+ ) || ''+ }++ static get [Symbol.species]() {+ return Promise+ }++ cancel() {+ if (this.cancelPromise)+ return this.cancelPromise++ const canceller = this.canceller+ this.canceller = null+ return this.cancelPromise = canceller ? canceller(this) : Promise.resolve()+ }++ simple() {+ this.options.simple = true+ this.options.prepare = false+ return this+ }++ async readable() {+ this.simple()+ this.streaming = true+ return this+ }++ async writable() {+ this.simple()+ this.streaming = true+ return this+ }++ cursor(rows = 1, fn) {+ this.options.simple = false+ if (typeof rows === 'function') {+ fn = rows+ rows = 1+ }++ this.cursorRows = rows++ if (typeof fn === 'function')+ return (this.cursorFn = fn, this)++ let prev+ return {+ [Symbol.asyncIterator]: () => ({+ next: () => {+ if (this.executed && !this.active)+ return { done: true }++ prev && prev()+ const promise = new Promise((resolve, reject) => {+ this.cursorFn = value => {+ resolve({ value, done: false })+ return new Promise(r => prev = r)+ }+ this.resolve = () => (this.active = false, this.canceller = null, resolve({ done: true }))+ this.reject = x => (this.active = false, this.canceller = null, reject(x))+ })+ this.execute()+ return promise+ },+ return() {+ prev && prev(CLOSE)+ return { done: true }+ }+ })+ }+ }++ describe() {+ this.options.simple = false+ this.onlyDescribe = this.options.prepare = true+ return this+ }++ stream() {+ throw new Error('.stream has been renamed to .forEach')+ }++ forEach(fn) {+ this.forEachFn = fn+ this.handle()+ return this+ }++ raw() {+ this.isRaw = true+ return this+ }++ values() {+ this.isRaw = 'values'+ return this+ }++ async handle() {+ !this.executed && (this.executed = true) && await 1 && this.handler(this)+ }++ execute() {+ this.handle()+ return this+ }++ then() {+ this.handle()+ return super.then.apply(this, arguments)+ }++ catch() {+ this.handle()+ return super.catch.apply(this, arguments)+ }++ finally() {+ this.handle()+ return super.finally.apply(this, arguments)+ }+}++function cachedError(xs) {+ if (originCache.has(xs))+ return originCache.get(xs)++ const x = Error.stackTraceLimit+ Error.stackTraceLimit = 4+ originCache.set(xs, new Error())+ Error.stackTraceLimit = x+ return originCache.get(xs)+}diff --git a/vendor/postgres/cf/src/queue.js b/vendor/postgres/cf/src/queue.jsnew file mode 100644index 0000000000..8fba891b87--- /dev/null+++ b/vendor/postgres/cf/src/queue.js@@ -0,0 +1,32 @@+export default Queue++function Queue(initial = []) {+ let xs = initial.slice()+ let index = 0++ return {+ get length() {+ return xs.length - index+ },+ remove: (x) => {+ const index = xs.indexOf(x)+ return index === -1+ ? null+ : (xs.splice(index, 1), x)+ },+ push: (x) => (xs.push(x), x),+ peek: () => xs[index],+ shift: () => {+ const out = xs[index++]++ if (index === xs.length) {+ index = 0+ xs = []+ } else {+ xs[index - 1] = undefined+ }++ return out+ }+ }+}diff --git a/vendor/postgres/cf/src/result.js b/vendor/postgres/cf/src/result.jsnew file mode 100644index 0000000000..3101428471--- /dev/null+++ b/vendor/postgres/cf/src/result.js@@ -0,0 +1,16 @@+export default class Result extends Array {+ constructor() {+ super()+ Object.defineProperties(this, {+ count: { value: null, writable: true },+ state: { value: null, writable: true },+ command: { value: null, writable: true },+ columns: { value: null, writable: true },+ statement: { value: null, writable: true }+ })+ }++ static get [Symbol.species]() {+ return Array+ }+}diff --git a/vendor/postgres/cf/src/subscribe.js b/vendor/postgres/cf/src/subscribe.jsnew file mode 100644index 0000000000..8716100e87--- /dev/null+++ b/vendor/postgres/cf/src/subscribe.js@@ -0,0 +1,278 @@+import { Buffer } from 'node:buffer'+const noop = () => { /* noop */ }++export default function Subscribe(postgres, options) {+ const subscribers = new Map()+ , slot = 'postgresjs_' + Math.random().toString(36).slice(2)+ , state = {}++ let connection+ , stream+ , ended = false++ const sql = subscribe.sql = postgres({+ ...options,+ transform: { column: {}, value: {}, row: {} },+ max: 1,+ fetch_types: false,+ idle_timeout: null,+ max_lifetime: null,+ connection: {+ ...options.connection,+ replication: 'database'+ },+ onclose: async function() {+ if (ended)+ return+ stream = null+ state.pid = state.secret = undefined+ connected(await init(sql, slot, options.publications))+ subscribers.forEach(event => event.forEach(({ onsubscribe }) => onsubscribe()))+ },+ no_subscribe: true+ })++ const end = sql.end+ , close = sql.close++ sql.end = async() => {+ ended = true+ stream && (await new Promise(r => (stream.once('close', r), stream.end())))+ return end()+ }++ sql.close = async() => {+ stream && (await new Promise(r => (stream.once('close', r), stream.end())))+ return close()+ }++ return subscribe++ async function subscribe(event, fn, onsubscribe = noop, onerror = noop) {+ event = parseEvent(event)++ if (!connection)+ connection = init(sql, slot, options.publications)++ const subscriber = { fn, onsubscribe }+ const fns = subscribers.has(event)+ ? subscribers.get(event).add(subscriber)+ : subscribers.set(event, new Set([subscriber])).get(event)++ const unsubscribe = () => {+ fns.delete(subscriber)+ fns.size === 0 && subscribers.delete(event)+ }++ return connection.then(x => {+ connected(x)+ onsubscribe()+ stream && stream.on('error', onerror)+ return { unsubscribe, state, sql }+ })+ }++ function connected(x) {+ stream = x.stream+ state.pid = x.state.pid+ state.secret = x.state.secret+ }++ async function init(sql, slot, publications) {+ if (!publications)+ throw new Error('Missing publication names')++ const xs = await sql.unsafe(+ `CREATE_REPLICATION_SLOT ${ slot } TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`+ )++ const [x] = xs++ const stream = await sql.unsafe(+ `START_REPLICATION SLOT ${ slot } LOGICAL ${+ x.consistent_point+ } (proto_version '1', publication_names '${ publications }')`+ ).writable()++ const state = {+ lsn: Buffer.concat(x.consistent_point.split('/').map(x => Buffer.from(('00000000' + x).slice(-8), 'hex')))+ }++ stream.on('data', data)+ stream.on('error', error)+ stream.on('close', sql.close)++ return { stream, state: xs.state }++ function error(e) {+ console.error('Unexpected error during logical streaming - reconnecting', e) // eslint-disable-line+ }++ function data(x) {+ if (x[0] === 0x77) {+ parse(x.subarray(25), state, sql.options.parsers, handle, options.transform)+ } else if (x[0] === 0x6b && x[17]) {+ state.lsn = x.subarray(1, 9)+ pong()+ }+ }++ function handle(a, b) {+ const path = b.relation.schema + '.' + b.relation.table+ call('*', a, b)+ call('*:' + path, a, b)+ b.relation.keys.length && call('*:' + path + '=' + b.relation.keys.map(x => a[x.name]), a, b)+ call(b.command, a, b)+ call(b.command + ':' + path, a, b)+ b.relation.keys.length && call(b.command + ':' + path + '=' + b.relation.keys.map(x => a[x.name]), a, b)+ }++ function pong() {+ const x = Buffer.alloc(34)+ x[0] = 'r'.charCodeAt(0)+ x.fill(state.lsn, 1)+ x.writeBigInt64BE(BigInt(Date.now() - Date.UTC(2000, 0, 1)) * BigInt(1000), 25)+ stream.write(x)+ }+ }++ function call(x, a, b) {+ subscribers.has(x) && subscribers.get(x).forEach(({ fn }) => fn(a, b, x))+ }+}++function Time(x) {+ return new Date(Date.UTC(2000, 0, 1) + Number(x / BigInt(1000)))+}++function parse(x, state, parsers, handle, transform) {+ const char = (acc, [k, v]) => (acc[k.charCodeAt(0)] = v, acc)++ Object.entries({+ R: x => { // Relation+ let i = 1+ const r = state[x.readUInt32BE(i)] = {+ schema: x.toString('utf8', i += 4, i = x.indexOf(0, i)) || 'pg_catalog',+ table: x.toString('utf8', i + 1, i = x.indexOf(0, i + 1)),+ columns: Array(x.readUInt16BE(i += 2)),+ keys: []+ }+ i += 2++ let columnIndex = 0+ , column++ while (i < x.length) {+ column = r.columns[columnIndex++] = {+ key: x[i++],+ name: transform.column.from+ ? transform.column.from(x.toString('utf8', i, i = x.indexOf(0, i)))+ : x.toString('utf8', i, i = x.indexOf(0, i)),+ type: x.readUInt32BE(i += 1),+ parser: parsers[x.readUInt32BE(i)],+ atttypmod: x.readUInt32BE(i += 4)+ }++ column.key && r.keys.push(column)+ i += 4+ }+ },+ Y: () => { /* noop */ }, // Type+ O: () => { /* noop */ }, // Origin+ B: x => { // Begin+ state.date = Time(x.readBigInt64BE(9))+ state.lsn = x.subarray(1, 9)+ },+ I: x => { // Insert+ let i = 1+ const relation = state[x.readUInt32BE(i)]+ const { row } = tuples(x, relation.columns, i += 7, transform)++ handle(row, {+ command: 'insert',+ relation+ })+ },+ D: x => { // Delete+ let i = 1+ const relation = state[x.readUInt32BE(i)]+ i += 4+ const key = x[i] === 75+ handle(key || x[i] === 79+ ? tuples(x, relation.columns, i += 3, transform).row+ : null+ , {+ command: 'delete',+ relation,+ key+ })+ },+ U: x => { // Update+ let i = 1+ const relation = state[x.readUInt32BE(i)]+ i += 4+ const key = x[i] === 75+ const xs = key || x[i] === 79+ ? tuples(x, relation.columns, i += 3, transform)+ : null++ xs && (i = xs.i)++ const { row } = tuples(x, relation.columns, i + 3, transform)++ handle(row, {+ command: 'update',+ relation,+ key,+ old: xs && xs.row+ })+ },+ T: () => { /* noop */ }, // Truncate,+ C: () => { /* noop */ } // Commit+ }).reduce(char, {})[x[0]](x)+}++function tuples(x, columns, xi, transform) {+ let type+ , column+ , value++ const row = transform.raw ? new Array(columns.length) : {}+ for (let i = 0; i < columns.length; i++) {+ type = x[xi++]+ column = columns[i]+ value = type === 110 // n+ ? null+ : type === 117 // u+ ? undefined+ : column.parser === undefined+ ? x.toString('utf8', xi + 4, xi += 4 + x.readUInt32BE(xi))+ : column.parser.array === true+ ? column.parser(x.toString('utf8', xi + 5, xi += 4 + x.readUInt32BE(xi)))+ : column.parser(x.toString('utf8', xi + 4, xi += 4 + x.readUInt32BE(xi)))++ transform.raw+ ? (row[i] = transform.raw === true+ ? value+ : transform.value.from ? transform.value.from(value, column) : value)+ : (row[column.name] = transform.value.from+ ? transform.value.from(value, column)+ : value+ )+ }++ return { i: xi, row: transform.row.from ? transform.row.from(row) : row }+}++function parseEvent(x) {+ const xs = x.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i) || []++ if (!xs)+ throw new Error('Malformed subscribe pattern: ' + x)++ const [, command, path, key] = xs++ return (command || '*')+ + (path ? ':' + (path.indexOf('.') === -1 ? 'public.' + path : path) : '')+ + (key ? '=' + key : '')+}diff --git a/vendor/postgres/cf/src/types.js b/vendor/postgres/cf/src/types.jsnew file mode 100644index 0000000000..aa2ead29fa--- /dev/null+++ b/vendor/postgres/cf/src/types.js@@ -0,0 +1,368 @@+import { Buffer } from 'node:buffer'+import { Query } from './query.js'+import { Errors } from './errors.js'++export const types = {+ string: {+ to: 25,+ from: null, // defaults to string+ serialize: x => '' + x+ },+ number: {+ to: 0,+ from: [21, 23, 26, 700, 701],+ serialize: x => '' + x,+ parse: x => +x+ },+ json: {+ to: 114,+ from: [114, 3802],+ serialize: x => JSON.stringify(x),+ parse: x => JSON.parse(x)+ },+ boolean: {+ to: 16,+ from: 16,+ serialize: x => x === true ? 't' : 'f',+ parse: x => x === 't'+ },+ date: {+ to: 1184,+ from: [1082, 1114, 1184],+ serialize: x => (x instanceof Date ? x : new Date(x)).toISOString(),+ parse: x => new Date(x)+ },+ bytea: {+ to: 17,+ from: 17,+ serialize: x => '\\x' + Buffer.from(x).toString('hex'),+ parse: x => Buffer.from(x.slice(2), 'hex')+ }+}++class NotTagged { then() { notTagged() } catch() { notTagged() } finally() { notTagged() }}++export class Identifier extends NotTagged {+ constructor(value) {+ super()+ this.value = escapeIdentifier(value)+ }+}++export class Parameter extends NotTagged {+ constructor(value, type, array) {+ super()+ this.value = value+ this.type = type+ this.array = array+ }+}++export class Builder extends NotTagged {+ constructor(first, rest) {+ super()+ this.first = first+ this.rest = rest+ }++ build(before, parameters, types, options) {+ const keyword = builders.map(([x, fn]) => ({ fn, i: before.search(x) })).sort((a, b) => a.i - b.i).pop()+ return keyword.i === -1+ ? escapeIdentifiers(this.first, options)+ : keyword.fn(this.first, this.rest, parameters, types, options)+ }+}++export function handleValue(x, parameters, types, options) {+ let value = x instanceof Parameter ? x.value : x+ if (value === undefined) {+ x instanceof Parameter+ ? x.value = options.transform.undefined+ : value = x = options.transform.undefined++ if (value === undefined)+ throw Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed')+ }++ return '$' + (types.push(+ x instanceof Parameter+ ? (parameters.push(x.value), x.array+ ? x.array[x.type || inferType(x.value)] || x.type || firstIsString(x.value)+ : x.type+ )+ : (parameters.push(x), inferType(x))+ ))+}++const defaultHandlers = typeHandlers(types)++export function stringify(q, string, value, parameters, types, options) { // eslint-disable-line+ for (let i = 1; i < q.strings.length; i++) {+ string += (stringifyValue(string, value, parameters, types, options)) + q.strings[i]+ value = q.args[i]+ }++ return string+}++function stringifyValue(string, value, parameters, types, o) {+ return (+ value instanceof Builder ? value.build(string, parameters, types, o) :+ value instanceof Query ? fragment(value, parameters, types, o) :+ value instanceof Identifier ? value.value :+ value && value[0] instanceof Query ? value.reduce((acc, x) => acc + ' ' + fragment(x, parameters, types, o), '') :+ handleValue(value, parameters, types, o)+ )+}++function fragment(q, parameters, types, options) {+ q.fragment = true+ return stringify(q, q.strings[0], q.args[0], parameters, types, options)+}++function valuesBuilder(first, parameters, types, columns, options) {+ return first.map(row =>+ '(' + columns.map(column =>+ stringifyValue('values', row[column], parameters, types, options)+ ).join(',') + ')'+ ).join(',')+}++function values(first, rest, parameters, types, options) {+ const multi = Array.isArray(first[0])+ const columns = rest.length ? rest.flat() : Object.keys(multi ? first[0] : first)+ return valuesBuilder(multi ? first : [first], parameters, types, columns, options)+}++function select(first, rest, parameters, types, options) {+ typeof first === 'string' && (first = [first].concat(rest))+ if (Array.isArray(first))+ return escapeIdentifiers(first, options)++ let value+ const columns = rest.length ? rest.flat() : Object.keys(first)+ return columns.map(x => {+ value = first[x]+ return (+ value instanceof Query ? fragment(value, parameters, types, options) :+ value instanceof Identifier ? value.value :+ handleValue(value, parameters, types, options)+ ) + ' as ' + escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x)+ }).join(',')+}++const builders = Object.entries({+ values,+ in: (...xs) => {+ const x = values(...xs)+ return x === '()' ? '(null)' : x+ },+ select,+ as: select,+ returning: select,+ '\\(': select,++ update(first, rest, parameters, types, options) {+ return (rest.length ? rest.flat() : Object.keys(first)).map(x =>+ escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x) ++ '=' + stringifyValue('values', first[x], parameters, types, options)+ )+ },++ insert(first, rest, parameters, types, options) {+ const columns = rest.length ? rest.flat() : Object.keys(Array.isArray(first) ? first[0] : first)+ return '(' + escapeIdentifiers(columns, options) + ')values' ++ valuesBuilder(Array.isArray(first) ? first : [first], parameters, types, columns, options)+ }+}).map(([x, fn]) => ([new RegExp('((?:^|[\\s(])' + x + '(?:$|[\\s(]))(?![\\s\\S]*\\1)', 'i'), fn]))++function notTagged() {+ throw Errors.generic('NOT_TAGGED_CALL', 'Query not called as a tagged template literal')+}++export const serializers = defaultHandlers.serializers+export const parsers = defaultHandlers.parsers++export const END = {}++function firstIsString(x) {+ if (Array.isArray(x))+ return firstIsString(x[0])+ return typeof x === 'string' ? 1009 : 0+}++export const mergeUserTypes = function(types) {+ const user = typeHandlers(types || {})+ return {+ serializers: Object.assign({}, serializers, user.serializers),+ parsers: Object.assign({}, parsers, user.parsers)+ }+}++function typeHandlers(types) {+ return Object.keys(types).reduce((acc, k) => {+ types[k].from && [].concat(types[k].from).forEach(x => acc.parsers[x] = types[k].parse)+ if (types[k].serialize) {+ acc.serializers[types[k].to] = types[k].serialize+ types[k].from && [].concat(types[k].from).forEach(x => acc.serializers[x] = types[k].serialize)+ }+ return acc+ }, { parsers: {}, serializers: {} })+}++function escapeIdentifiers(xs, { transform: { column } }) {+ return xs.map(x => escapeIdentifier(column.to ? column.to(x) : x)).join(',')+}++export const escapeIdentifier = function escape(str) {+ return '"' + str.replace(/"/g, '""').replace(/\./g, '"."') + '"'+}++export const inferType = function inferType(x) {+ return (+ x instanceof Parameter ? x.type :+ x instanceof Date ? 1184 :+ x instanceof Uint8Array ? 17 :+ (x === true || x === false) ? 16 :+ typeof x === 'bigint' ? 20 :+ Array.isArray(x) ? inferType(x[0]) :+ 0+ )+}++const escapeBackslash = /\\/g+const escapeQuote = /"/g++function arrayEscape(x) {+ return x+ .replace(escapeBackslash, '\\\\')+ .replace(escapeQuote, '\\"')+}++export const arraySerializer = function arraySerializer(xs, serializer, options, typarray) {+ if (Array.isArray(xs) === false)+ return xs++ if (!xs.length)+ return '{}'++ const first = xs[0]+ // Only _box (1020) has the ';' delimiter for arrays, all other types use the ',' delimiter+ const delimiter = typarray === 1020 ? ';' : ','++ if (Array.isArray(first) && !first.type)+ return '{' + xs.map(x => arraySerializer(x, serializer, options, typarray)).join(delimiter) + '}'++ return '{' + xs.map(x => {+ if (x === undefined) {+ x = options.transform.undefined+ if (x === undefined)+ throw Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed')+ }++ return x === null+ ? 'null'+ : '"' + arrayEscape(serializer ? serializer(x.type ? x.value : x) : '' + x) + '"'+ }).join(delimiter) + '}'+}++const arrayParserState = {+ i: 0,+ char: null,+ str: '',+ quoted: false,+ last: 0+}++export const arrayParser = function arrayParser(x, parser, typarray) {+ arrayParserState.i = arrayParserState.last = 0+ return arrayParserLoop(arrayParserState, x, parser, typarray)+}++function arrayParserLoop(s, x, parser, typarray) {+ const xs = []+ // Only _box (1020) has the ';' delimiter for arrays, all other types use the ',' delimiter+ const delimiter = typarray === 1020 ? ';' : ','+ for (; s.i < x.length; s.i++) {+ s.char = x[s.i]+ if (s.quoted) {+ if (s.char === '\\') {+ s.str += x[++s.i]+ } else if (s.char === '"') {+ xs.push(parser ? parser(s.str) : s.str)+ s.str = ''+ s.quoted = x[s.i + 1] === '"'+ s.last = s.i + 2+ } else {+ s.str += s.char+ }+ } else if (s.char === '"') {+ s.quoted = true+ } else if (s.char === '{') {+ s.last = ++s.i+ xs.push(arrayParserLoop(s, x, parser, typarray))+ } else if (s.char === '}') {+ s.quoted = false+ s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i))+ s.last = s.i + 1+ break+ } else if (s.char === delimiter && s.p !== '}' && s.p !== '"') {+ xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i))+ s.last = s.i + 1+ }+ s.p = s.char+ }+ s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i + 1)) : x.slice(s.last, s.i + 1))+ return xs+}++export const toCamel = x => {+ let str = x[0]+ for (let i = 1; i < x.length; i++)+ str += x[i] === '_' ? x[++i].toUpperCase() : x[i]+ return str+}++export const toPascal = x => {+ let str = x[0].toUpperCase()+ for (let i = 1; i < x.length; i++)+ str += x[i] === '_' ? x[++i].toUpperCase() : x[i]+ return str+}++export const toKebab = x => x.replace(/_/g, '-')++export const fromCamel = x => x.replace(/([A-Z])/g, '_$1').toLowerCase()+export const fromPascal = x => (x.slice(0, 1) + x.slice(1).replace(/([A-Z])/g, '_$1')).toLowerCase()+export const fromKebab = x => x.replace(/-/g, '_')++function createJsonTransform(fn) {+ return function jsonTransform(x, column) {+ return typeof x === 'object' && x !== null && (column.type === 114 || column.type === 3802)+ ? Array.isArray(x)+ ? x.map(x => jsonTransform(x, column))+ : Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: jsonTransform(v, column) }), {})+ : x+ }+}++toCamel.column = { from: toCamel }+toCamel.value = { from: createJsonTransform(toCamel) }+fromCamel.column = { to: fromCamel }++export const camel = { ...toCamel }+camel.column.to = fromCamel++toPascal.column = { from: toPascal }+toPascal.value = { from: createJsonTransform(toPascal) }+fromPascal.column = { to: fromPascal }++export const pascal = { ...toPascal }+pascal.column.to = fromPascal++toKebab.column = { from: toKebab }+toKebab.value = { from: createJsonTransform(toKebab) }+fromKebab.column = { to: fromKebab }++export const kebab = { ...toKebab }+kebab.column.to = fromKebabdiff --git a/vendor/postgres/cjs/package.json b/vendor/postgres/cjs/package.jsonnew file mode 100644index 0000000000..0292b9956f--- /dev/null+++ b/vendor/postgres/cjs/package.json@@ -0,0 +1 @@+{"type":"commonjs"}\ No newline at end of filediff --git a/vendor/postgres/cjs/src/bytes.js b/vendor/postgres/cjs/src/bytes.jsnew file mode 100644index 0000000000..41be82c230--- /dev/null+++ b/vendor/postgres/cjs/src/bytes.js@@ -0,0 +1,78 @@+const size = 256+let buffer = Buffer.allocUnsafe(size)++const messages = 'BCcDdEFfHPpQSX'.split('').reduce((acc, x) => {+ const v = x.charCodeAt(0)+ acc[x] = () => {+ buffer[0] = v+ b.i = 5+ return b+ }+ return acc+}, {})++const b = Object.assign(reset, messages, {+ N: String.fromCharCode(0),+ i: 0,+ inc(x) {+ b.i += x+ return b+ },+ str(x) {+ const length = Buffer.byteLength(x)+ fit(length)+ b.i += buffer.write(x, b.i, length, 'utf8')+ return b+ },+ i16(x) {+ fit(2)+ buffer.writeUInt16BE(x, b.i)+ b.i += 2+ return b+ },+ i32(x, i) {+ if (i || i === 0) {+ buffer.writeUInt32BE(x, i)+ return b+ }+ fit(4)+ buffer.writeUInt32BE(x, b.i)+ b.i += 4+ return b+ },+ z(x) {+ fit(x)+ buffer.fill(0, b.i, b.i + x)+ b.i += x+ return b+ },+ raw(x) {+ buffer = Buffer.concat([buffer.subarray(0, b.i), x])+ b.i = buffer.length+ return b+ },+ end(at = 1) {+ buffer.writeUInt32BE(b.i - at, at)+ const out = buffer.subarray(0, b.i)+ b.i = 0+ buffer = Buffer.allocUnsafe(size)+ return out+ }+})++module.exports = b++function fit(x) {+ if (buffer.length - b.i < x) {+ const prev = buffer+ , length = prev.length++ buffer = Buffer.allocUnsafe(length + (length >> 1) + x)+ prev.copy(buffer)+ }+}++function reset() {+ b.i = 0+ return b+}diff --git a/vendor/postgres/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.jsnew file mode 100644index 0000000000..be36dfd08e--- /dev/null+++ b/vendor/postgres/cjs/src/connection.js@@ -0,0 +1,1079 @@+const net = require('net')+const tls = require('tls')+const crypto = require('crypto')+const Stream = require('stream')+const { performance } = require('perf_hooks')++const { stringify, handleValue, arrayParser, arraySerializer } = require('./types.js')+const { Errors } = require('./errors.js')+const Result = require('./result.js')+const Queue = require('./queue.js')+const { Query, CLOSE } = require('./query.js')+const b = require('./bytes.js')++module.exports = Connection++let uid = 1++const Sync = b().S().end()+ , Flush = b().H().end()+ , SSLRequest = b().i32(8).i32(80877103).end(8)+ , ExecuteUnnamed = Buffer.concat([b().E().str(b.N).i32(0).end(), Sync])+ , DescribeUnnamed = b().D().str('S').str(b.N).end()+ , noop = () => { /* noop */ }++const retryRoutines = new Set([+ 'FetchPreparedStatement',+ 'RevalidateCachedQuery',+ 'transformAssignedExpr'+])++const errorFields = {+ 83 : 'severity_local', // S+ 86 : 'severity', // V+ 67 : 'code', // C+ 77 : 'message', // M+ 68 : 'detail', // D+ 72 : 'hint', // H+ 80 : 'position', // P+ 112 : 'internal_position', // p+ 113 : 'internal_query', // q+ 87 : 'where', // W+ 115 : 'schema_name', // s+ 116 : 'table_name', // t+ 99 : 'column_name', // c+ 100 : 'data type_name', // d+ 110 : 'constraint_name', // n+ 70 : 'file', // F+ 76 : 'line', // L+ 82 : 'routine' // R+}++function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) {+ const {+ sslnegotiation,+ ssl,+ max,+ user,+ host,+ port,+ database,+ parsers,+ transform,+ onnotice,+ onnotify,+ onparameter,+ max_pipeline,+ keep_alive,+ backoff,+ target_session_attrs+ } = options++ const sent = Queue()+ , id = uid+++ , backend = { pid: null, secret: null }+ , idleTimer = timer(end, options.idle_timeout)+ , lifeTimer = timer(end, options.max_lifetime)+ , connectTimer = timer(connectTimedOut, options.connect_timeout)++ let socket = null+ , cancelMessage+ , cancelResolve+ , cancelReject+ , cancelError+ , errorResponse = null+ , result = new Result()+ , incoming = Buffer.alloc(0)+ , needsTypes = options.fetch_types+ , backendParameters = {}+ , statements = {}+ , statementId = Math.random().toString(36).slice(2)+ , statementCount = 1+ , closedTime = 0+ , remaining = 0+ , hostIndex = 0+ , retries = 0+ , length = 0+ , delay = 0+ , rows = 0+ , serverSignature = null+ , nextWriteTimer = null+ , terminated = false+ , incomings = null+ , results = null+ , initial = null+ , ending = null+ , stream = null+ , chunk = null+ , ended = null+ , nonce = null+ , query = null+ , final = null++ const connection = {+ queue: queues.closed,+ idleTimer,+ connect(query) {+ initial = query+ reconnect()+ },+ terminate,+ execute,+ cancel,+ end,+ count: 0,+ id+ }++ queues.closed && queues.closed.push(connection)++ return connection++ async function createSocket() {+ let x+ try {+ x = options.socket+ ? (await Promise.resolve(options.socket(options)))+ : new net.Socket()+ } catch (e) {+ error(e)+ return+ }+ x.on('error', error)+ x.on('close', closed)+ x.on('drain', drain)+ return x+ }++ async function cancel({ pid, secret }, resolve, reject) {+ cancelResolve = resolve+ cancelReject = reject+ try {+ cancelMessage = b().i32(16).i32(80877102).i32(pid).i32(secret).end(16)+ await connect()+ if (!socket)+ reject(cancelError || Errors.connection('CONNECTION_CLOSED', options))+ } catch (error) {+ reject(error)+ }+ }++ function execute(q) {+ if (terminated)+ return queryError(q, Errors.connection('CONNECTION_DESTROYED', options))++ if (stream)+ return queryError(q, Errors.generic('COPY_IN_PROGRESS', 'You cannot execute queries during copy'))++ if (q.cancelled)+ return++ try {+ q.state = backend+ query+ ? sent.push(q)+ : (query = q, query.active = true)++ build(q)+ const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)+ return write(toBuffer(q))+ && !q.describeFirst+ && !q.cursorFn+ && sent.length < max_pipeline+ && mayPipeline+ } catch (error) {+ sent.length === 0 && write(Sync)+ errored(error)+ return true+ }+ }++ function toBuffer(q) {+ if (q.parameters.length >= 65534)+ throw Errors.generic('MAX_PARAMETERS_EXCEEDED', 'Max number of parameters (65534) exceeded')++ return q.options.simple+ ? b().Q().str(q.statement.string + b.N).end()+ : q.describeFirst+ ? Buffer.concat([describe(q), Flush])+ : q.prepare+ ? q.prepared+ ? prepared(q)+ : Buffer.concat([describe(q), prepared(q)])+ : unnamed(q)+ }++ function describe(q) {+ return Buffer.concat([+ Parse(q.statement.string, q.parameters, q.statement.types, q.statement.name),+ Describe('S', q.statement.name)+ ])+ }++ function prepared(q) {+ return Buffer.concat([+ Bind(q.parameters, q.statement.types, q.statement.name, q.cursorName),+ q.cursorFn+ ? Execute('', q.cursorRows)+ : ExecuteUnnamed+ ])+ }++ function unnamed(q) {+ return Buffer.concat([+ Parse(q.statement.string, q.parameters, q.statement.types),+ DescribeUnnamed,+ prepared(q)+ ])+ }++ function build(q) {+ const parameters = []+ , types = []++ const string = stringify(q, q.strings[0], q.args[0], parameters, types, options)++ !q.tagged && q.args.forEach(x => handleValue(x, parameters, types, options))++ q.prepare = options.prepare && ('prepare' in q.options ? q.options.prepare : true)+ q.string = string+ q.signature = q.prepare && types + string+ q.onlyDescribe && (delete statements[q.signature])+ q.parameters = q.parameters || parameters+ q.prepared = q.prepare && q.signature in statements+ q.describeFirst = q.onlyDescribe || (parameters.length && !q.prepared)+ q.statement = q.prepared+ ? statements[q.signature]+ : { string, types, name: q.prepare ? statementId + statementCount++ : '' }++ typeof options.debug === 'function' && options.debug(id, string, parameters, types)+ }++ function write(x, fn) {+ chunk = chunk ? Buffer.concat([chunk, x]) : Buffer.from(x)+ if (fn || chunk.length >= 1024)+ return nextWrite(fn)+ nextWriteTimer === null && (nextWriteTimer = setImmediate(nextWrite))+ return true+ }++ function nextWrite(fn) {+ const x = socket.write(chunk, fn)+ nextWriteTimer !== null && clearImmediate(nextWriteTimer)+ chunk = nextWriteTimer = null+ return x+ }++ function connectTimedOut() {+ errored(Errors.connection('CONNECT_TIMEOUT', options, socket))+ socket.destroy()+ }++ async function secure() {+ if (sslnegotiation !== 'direct') {+ write(SSLRequest)+ const canSSL = await new Promise(r => socket.once('data', x => r(x[0] === 83))) // S++ if (!canSSL && ssl === 'prefer')+ return connected()+ }++ const options = {+ socket,+ servername: net.isIP(socket.host) ? undefined : socket.host+ }++ if (sslnegotiation === 'direct')+ options.ALPNProtocols = ['postgresql']++ if (ssl === 'require' || ssl === 'allow' || ssl === 'prefer')+ options.rejectUnauthorized = false+ else if (typeof ssl === 'object')+ Object.assign(options, ssl)++ socket.removeAllListeners()+ socket = tls.connect(options)+ socket.on('secureConnect', connected)+ socket.on('error', error)+ socket.on('close', closed)+ socket.on('drain', drain)+ }++ /* c8 ignore next 3 */+ function drain() {+ !query && !connection.reserved && onopen(connection)+ }++ function data(x) {+ if (incomings) {+ incomings.push(x)+ remaining -= x.length+ if (remaining > 0)+ return+ }++ incoming = incomings+ ? Buffer.concat(incomings, length - remaining)+ : incoming.length === 0+ ? x+ : Buffer.concat([incoming, x], incoming.length + x.length)++ while (incoming.length > 4) {+ length = incoming.readUInt32BE(1)+ if (length >= incoming.length) {+ remaining = length - incoming.length+ incomings = [incoming]+ break+ }++ try {+ handle(incoming.subarray(0, length + 1))+ } catch (e) {+ query && (query.cursorFn || query.describeFirst) && write(Sync)+ errored(e)+ }+ incoming = incoming.subarray(length + 1)+ remaining = 0+ incomings = null+ }+ }++ async function connect() {+ terminated = false+ backendParameters = {}+ socket || (socket = await createSocket())++ if (!socket)+ return++ connectTimer.start()++ if (options.socket)+ return ssl ? secure() : connected()++ socket.on('connect', ssl ? secure : connected)++ if (options.path)+ return socket.connect(options.path)++ socket.ssl = ssl+ socket.connect(port[hostIndex], host[hostIndex])+ socket.host = host[hostIndex]+ socket.port = port[hostIndex]++ hostIndex = (hostIndex + 1) % port.length+ }++ function reconnect() {+ setTimeout(connect, closedTime ? Math.max(0, closedTime + delay - performance.now()) : 0)+ }++ function connected() {+ try {+ statements = {}+ needsTypes = options.fetch_types+ statementId = Math.random().toString(36).slice(2)+ statementCount = 1+ lifeTimer.start()+ socket.on('data', data)+ keep_alive && socket.setKeepAlive && socket.setKeepAlive(true, 1000 * keep_alive)+ const s = StartupMessage()+ write(s)+ } catch (err) {+ error(err)+ }+ }++ function error(err) {+ if (cancelMessage)+ cancelError = err+ if (connection.queue === queues.connecting && options.host[retries + 1])+ return++ errored(err)+ while (sent.length)+ queryError(sent.shift(), err)+ }++ function errored(err) {+ if (cancelMessage)+ cancelError = err+ stream && (stream.destroy(err), stream = null)+ query && queryError(query, err)+ initial && (queryError(initial, err), initial = null)+ }++ function queryError(query, err) {+ if (query.reserve)+ return query.reject(err)++ if (!err || typeof err !== 'object')+ err = new Error(err)++ 'query' in err || 'parameters' in err || Object.defineProperties(err, {+ stack: { value: err.stack + query.origin.replace(/.*\n/, '\n'), enumerable: options.debug },+ query: { value: query.string, enumerable: options.debug },+ parameters: { value: query.parameters, enumerable: options.debug },+ args: { value: query.args, enumerable: options.debug },+ types: { value: query.statement && query.statement.types, enumerable: options.debug }+ })+ query.reject(err)+ }++ function end() {+ return ending || (+ !connection.reserved && onend(connection),+ !connection.reserved && !initial && !query && sent.length === 0+ ? (terminate(), new Promise(r => socket && socket.readyState !== 'closed' ? socket.once('close', r) : r()))+ : ending = new Promise(r => ended = r)+ )+ }++ function terminate() {+ terminated = true+ if (stream || query || initial || sent.length)+ error(Errors.connection('CONNECTION_DESTROYED', options))++ clearImmediate(nextWriteTimer)+ if (socket) {+ socket.removeListener('data', data)+ socket.removeListener('connect', connected)+ socket.readyState === 'open' && socket.end(b().X().end())+ }+ ended && (ended(), ending = ended = null)+ }++ async function closed(hadError) {+ incoming = Buffer.alloc(0)+ remaining = 0+ incomings = null+ clearImmediate(nextWriteTimer)+ socket.removeListener('data', data)+ socket.removeListener('connect', connected)+ idleTimer.cancel()+ lifeTimer.cancel()+ connectTimer.cancel()++ socket.removeAllListeners()+ socket = null++ if (cancelMessage)+ return cancelError || hadError+ ? cancelReject(cancelError || Errors.connection('CONNECTION_CLOSED', options))+ : cancelResolve()++ if (initial)+ return reconnect()++ !hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))+ closedTime = performance.now()+ hadError && options.shared.retries+++ delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000+ onclose(connection, Errors.connection('CONNECTION_CLOSED', options, socket))+ }++ /* Handlers */+ function handle(xs, x = xs[0]) {+ (+ x === 68 ? DataRow : // D+ x === 100 ? CopyData : // d+ x === 65 ? NotificationResponse : // A+ x === 83 ? ParameterStatus : // S+ x === 90 ? ReadyForQuery : // Z+ x === 67 ? CommandComplete : // C+ x === 50 ? BindComplete : // 2+ x === 49 ? ParseComplete : // 1+ x === 116 ? ParameterDescription : // t+ x === 84 ? RowDescription : // T+ x === 82 ? Authentication : // R+ x === 110 ? NoData : // n+ x === 75 ? BackendKeyData : // K+ x === 69 ? ErrorResponse : // E+ x === 115 ? PortalSuspended : // s+ x === 51 ? CloseComplete : // 3+ x === 71 ? CopyInResponse : // G+ x === 78 ? NoticeResponse : // N+ x === 72 ? CopyOutResponse : // H+ x === 99 ? CopyDone : // c+ x === 73 ? EmptyQueryResponse : // I+ x === 86 ? FunctionCallResponse : // V+ x === 118 ? NegotiateProtocolVersion : // v+ x === 87 ? CopyBothResponse : // W+ /* c8 ignore next */+ UnknownMessage+ )(xs)+ }++ function DataRow(x) {+ let index = 7+ let length+ let column+ let value++ const row = query.isRaw ? new Array(query.statement.columns.length) : {}+ for (let i = 0; i < query.statement.columns.length; i++) {+ column = query.statement.columns[i]+ length = x.readInt32BE(index)+ index += 4++ value = length === -1+ ? null+ : query.isRaw === true+ ? x.subarray(index, index += length)+ : column.parser === undefined+ ? x.toString('utf8', index, index += length)+ : column.parser.array === true+ ? column.parser(x.toString('utf8', index + 1, index += length))+ : column.parser(x.toString('utf8', index, index += length))++ query.isRaw+ ? (row[i] = query.isRaw === true+ ? value+ : transform.value.from ? transform.value.from(value, column) : value)+ : (row[column.name] = transform.value.from ? transform.value.from(value, column) : value)+ }++ query.forEachFn+ ? query.forEachFn(transform.row.from ? transform.row.from(row) : row, result)+ : (result[rows++] = transform.row.from ? transform.row.from(row) : row)+ }++ function ParameterStatus(x) {+ const [k, v] = x.toString('utf8', 5, x.length - 1).split(b.N)+ backendParameters[k] = v+ if (options.parameters[k] !== v) {+ options.parameters[k] = v+ onparameter && onparameter(k, v)+ }+ }++ function ReadyForQuery(x) {+ if (query) {+ if (errorResponse) {+ query.retried+ ? errored(query.retried)+ : query.prepared && retryRoutines.has(errorResponse.routine)+ ? retry(query, errorResponse)+ : errored(errorResponse)+ } else {+ query.resolve(results || result)+ }+ } else if (errorResponse) {+ errored(errorResponse)+ }++ query = results = errorResponse = null+ result = new Result()+ connectTimer.cancel()++ if (initial) {+ if (target_session_attrs) {+ if (!backendParameters.in_hot_standby || !backendParameters.default_transaction_read_only)+ return fetchState()+ else if (tryNext(target_session_attrs, backendParameters))+ return terminate()+ }++ if (needsTypes) {+ initial.reserve && (initial = null)+ return fetchArrayTypes()+ }++ const reserving = initial && initial.reserve+ initial && !reserving && execute(initial)+ options.shared.retries = retries = 0+ initial = null+ if (!reserving)+ return+ }++ while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))+ Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)++ if (query)+ return // Consider opening if able and sent.length < 50++ connection.reserved+ ? !connection.reserved.release && x[5] === 73 // I+ ? ending+ ? terminate()+ : connection.reserved(true)+ : connection.reserved()+ : ending+ ? terminate()+ : onopen(connection)+ }++ function CommandComplete(x) {+ rows = 0++ for (let i = x.length - 1; i > 0; i--) {+ if (x[i] === 32 && x[i + 1] < 58 && result.count === null)+ result.count = +x.toString('utf8', i + 1, x.length - 1)+ if (x[i - 1] >= 65) {+ result.command = x.toString('utf8', 5, i)+ result.state = backend+ break+ }+ }++ final && (final(), final = null)++ if (result.command === 'BEGIN' && max !== 1 && !connection.reserved)+ return errored(Errors.generic('UNSAFE_TRANSACTION', 'Only use sql.begin, sql.reserved or max: 1'))++ if (query.options.simple)+ return BindComplete()++ if (query.cursorFn) {+ result.count && query.cursorFn(result)+ write(Sync)+ }+ }++ function ParseComplete() {+ query.parsing = false+ }++ function BindComplete() {+ !result.statement && (result.statement = query.statement)+ result.columns = query.statement.columns+ }++ function ParameterDescription(x) {+ const length = x.readUInt16BE(5)++ for (let i = 0; i < length; ++i)+ !query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))++ query.prepare && (statements[query.signature] = query.statement)+ query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false)+ }++ function RowDescription(x) {+ if (result.command) {+ results = results || [result]+ results.push(result = new Result())+ result.count = null+ query.statement.columns = null+ }++ const length = x.readUInt16BE(5)+ let index = 7+ let start++ query.statement.columns = Array(length)++ for (let i = 0; i < length; ++i) {+ start = index+ while (x[index++] !== 0);+ const table = x.readUInt32BE(index)+ const number = x.readUInt16BE(index + 4)+ const type = x.readUInt32BE(index + 6)+ query.statement.columns[i] = {+ name: transform.column.from+ ? transform.column.from(x.toString('utf8', start, index - 1))+ : x.toString('utf8', start, index - 1),+ parser: parsers[type],+ table,+ number,+ type+ }+ index += 18+ }++ result.statement = query.statement+ if (query.onlyDescribe)+ return (query.resolve(query.statement), write(Sync))+ }++ async function Authentication(x, type = x.readUInt32BE(5)) {+ (+ type === 3 ? AuthenticationCleartextPassword :+ type === 5 ? AuthenticationMD5Password :+ type === 10 ? SASL :+ type === 11 ? SASLContinue :+ type === 12 ? SASLFinal :+ type !== 0 ? UnknownAuth :+ noop+ )(x, type)+ }++ /* c8 ignore next 5 */+ async function AuthenticationCleartextPassword() {+ const payload = await Pass()+ write(+ b().p().str(payload).z(1).end()+ )+ }++ async function AuthenticationMD5Password(x) {+ const payload = 'md5' + (+ await md5(+ Buffer.concat([+ Buffer.from(await md5((await Pass()) + user)),+ x.subarray(9)+ ])+ )+ )+ write(+ b().p().str(payload).z(1).end()+ )+ }++ async function SASL() {+ nonce = (await crypto.randomBytes(18)).toString('base64')+ b().p().str('SCRAM-SHA-256' + b.N)+ const i = b.i+ write(b.inc(4).str('n,,n=*,r=' + nonce).i32(b.i - i - 4, i).end())+ }++ async function SASLContinue(x) {+ const res = x.toString('utf8', 9).split(',').reduce((acc, x) => (acc[x[0]] = x.slice(2), acc), {})++ const saltedPassword = await crypto.pbkdf2Sync(+ await Pass(),+ Buffer.from(res.s, 'base64'),+ parseInt(res.i), 32,+ 'sha256'+ )++ const clientKey = await hmac(saltedPassword, 'Client Key')++ const auth = 'n=*,r=' + nonce + ','+ + 'r=' + res.r + ',s=' + res.s + ',i=' + res.i+ + ',c=biws,r=' + res.r++ serverSignature = (await hmac(await hmac(saltedPassword, 'Server Key'), auth)).toString('base64')++ const payload = 'c=biws,r=' + res.r + ',p=' + xor(+ clientKey, Buffer.from(await hmac(await sha256(clientKey), auth))+ ).toString('base64')++ write(+ b().p().str(payload).end()+ )+ }++ function SASLFinal(x) {+ if (x.toString('utf8', 9).split(b.N, 1)[0].slice(2) === serverSignature)+ return+ /* c8 ignore next 5 */+ errored(Errors.generic('SASL_SIGNATURE_MISMATCH', 'The server did not return the correct signature'))+ socket.destroy()+ }++ function Pass() {+ return Promise.resolve(typeof options.pass === 'function'+ ? options.pass()+ : options.pass+ )+ }++ function NoData() {+ result.statement = query.statement+ result.statement.columns = []+ if (query.onlyDescribe)+ return (query.resolve(query.statement), write(Sync))+ }++ function BackendKeyData(x) {+ backend.pid = x.readUInt32BE(5)+ backend.secret = x.readUInt32BE(9)+ }++ async function fetchArrayTypes() {+ needsTypes = false+ const types = await new Query([`+ select b.oid, b.typarray+ from pg_catalog.pg_type a+ left join pg_catalog.pg_type b on b.oid = a.typelem+ where a.typcategory = 'A'+ group by b.oid, b.typarray+ order by b.oid+ `], [], execute)+ types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))+ }++ function addArrayType(oid, typarray) {+ if (!!options.parsers[typarray] && !!options.serializers[typarray]) return+ const parser = options.parsers[oid]+ options.shared.typeArrayMap[oid] = typarray+ options.parsers[typarray] = (xs) => arrayParser(xs, parser, typarray)+ options.parsers[typarray].array = true+ options.serializers[typarray] = (xs) => arraySerializer(xs, options.serializers[oid], options, typarray)+ }++ function tryNext(x, xs) {+ return (+ (x === 'read-write' && xs.default_transaction_read_only === 'on') ||+ (x === 'read-only' && xs.default_transaction_read_only === 'off') ||+ (x === 'primary' && xs.in_hot_standby === 'on') ||+ (x === 'standby' && xs.in_hot_standby === 'off') ||+ (x === 'prefer-standby' && xs.in_hot_standby === 'off' && options.host[retries])+ )+ }++ function fetchState() {+ const query = new Query([`+ show transaction_read_only;+ select pg_catalog.pg_is_in_recovery()+ `], [], execute, null, { simple: true })+ query.resolve = ([[a], [b]]) => {+ backendParameters.default_transaction_read_only = a.transaction_read_only+ backendParameters.in_hot_standby = b.pg_is_in_recovery ? 'on' : 'off'+ }+ query.execute()+ }++ function ErrorResponse(x) {+ if (query) {+ (query.cursorFn || query.describeFirst) && write(Sync)+ errorResponse = Errors.postgres(parseError(x))+ } else {+ errored(Errors.postgres(parseError(x)))+ }+ }++ function retry(q, error) {+ delete statements[q.signature]+ q.retried = error+ execute(q)+ }++ function NotificationResponse(x) {+ if (!onnotify)+ return++ let index = 9+ while (x[index++] !== 0);+ onnotify(+ x.toString('utf8', 9, index - 1),+ x.toString('utf8', index, x.length - 1)+ )+ }++ async function PortalSuspended() {+ try {+ const x = await Promise.resolve(query.cursorFn(result))+ rows = 0+ x === CLOSE+ ? write(Close(query.portal))+ : (result = new Result(), write(Execute('', query.cursorRows)))+ } catch (err) {+ write(Sync)+ query.reject(err)+ }+ }++ function CloseComplete() {+ result.count && query.cursorFn(result)+ query.resolve(result)+ }++ function CopyInResponse() {+ stream = new Stream.Writable({+ autoDestroy: true,+ write(chunk, encoding, callback) {+ socket.write(b().d().raw(chunk).end(), callback)+ },+ destroy(error, callback) {+ callback(error)+ socket.write(b().f().str(error + b.N).end())+ stream = null+ },+ final(callback) {+ socket.write(b().c().end())+ final = callback+ stream = null+ }+ })+ query.resolve(stream)+ }++ function CopyOutResponse() {+ stream = new Stream.Readable({+ read() { socket.resume() }+ })+ query.resolve(stream)+ }++ /* c8 ignore next 3 */+ function CopyBothResponse() {+ stream = new Stream.Duplex({+ autoDestroy: true,+ read() { socket.resume() },+ /* c8 ignore next 11 */+ write(chunk, encoding, callback) {+ socket.write(b().d().raw(chunk).end(), callback)+ },+ destroy(error, callback) {+ callback(error)+ socket.write(b().f().str(error + b.N).end())+ stream = null+ },+ final(callback) {+ socket.write(b().c().end())+ final = callback+ }+ })+ query.resolve(stream)+ }++ function CopyData(x) {+ stream && (stream.push(x.subarray(5)) || socket.pause())+ }++ function CopyDone() {+ stream && stream.push(null)+ stream = null+ }++ function NoticeResponse(x) {+ onnotice+ ? onnotice(parseError(x))+ : console.log(parseError(x)) // eslint-disable-line++ }++ /* c8 ignore next 3 */+ function EmptyQueryResponse() {+ /* noop */+ }++ /* c8 ignore next 3 */+ function FunctionCallResponse() {+ errored(Errors.notSupported('FunctionCallResponse'))+ }++ /* c8 ignore next 3 */+ function NegotiateProtocolVersion() {+ errored(Errors.notSupported('NegotiateProtocolVersion'))+ }++ /* c8 ignore next 3 */+ function UnknownMessage(x) {+ console.error('Postgres.js : Unknown Message:', x[0]) // eslint-disable-line+ }++ /* c8 ignore next 3 */+ function UnknownAuth(x, type) {+ console.error('Postgres.js : Unknown Auth:', type) // eslint-disable-line+ }++ /* Messages */+ function Bind(parameters, types, statement = '', portal = '') {+ let prev+ , type++ b().B().str(portal + b.N).str(statement + b.N).i16(0).i16(parameters.length)++ parameters.forEach((x, i) => {+ if (x === null)+ return b.i32(0xFFFFFFFF)++ type = types[i]+ parameters[i] = x = type in options.serializers+ ? options.serializers[type](x)+ : '' + x++ prev = b.i+ b.inc(4).str(x).i32(b.i - prev - 4, prev)+ })++ b.i16(0)++ return b.end()+ }++ function Parse(str, parameters, types, name = '') {+ b().P().str(name + b.N).str(str + b.N).i16(parameters.length)+ parameters.forEach((x, i) => b.i32(types[i] || 0))+ return b.end()+ }++ function Describe(x, name = '') {+ return b().D().str(x).str(name + b.N).end()+ }++ function Execute(portal = '', rows = 0) {+ return Buffer.concat([+ b().E().str(portal + b.N).i32(rows).end(),+ Flush+ ])+ }++ function Close(portal = '') {+ return Buffer.concat([+ b().C().str('P').str(portal + b.N).end(),+ b().S().end()+ ])+ }++ function StartupMessage() {+ return cancelMessage || b().inc(4).i16(3).z(2).str(+ Object.entries(Object.assign({+ user,+ database,+ client_encoding: 'UTF8'+ },+ options.connection+ )).filter(([, v]) => v).map(([k, v]) => k + b.N + v).join(b.N)+ ).z(2).end(0)+ }++}++function parseError(x) {+ const error = {}+ let start = 5+ for (let i = 5; i < x.length - 1; i++) {+ if (x[i] === 0) {+ error[errorFields[x[start]]] = x.toString('utf8', start + 1, i)+ start = i + 1+ }+ }+ return error+}++function md5(x) {+ return crypto.createHash('md5').update(x).digest('hex')+}++function hmac(key, x) {+ return crypto.createHmac('sha256', key).update(x).digest()+}++function sha256(x) {+ return crypto.createHash('sha256').update(x).digest()+}++function xor(a, b) {+ const length = Math.max(a.length, b.length)+ const buffer = Buffer.allocUnsafe(length)+ for (let i = 0; i < length; i++)+ buffer[i] = a[i] ^ b[i]+ return buffer+}++function timer(fn, seconds) {+ seconds = typeof seconds === 'function' ? seconds() : seconds+ if (!seconds)+ return { cancel: noop, start: noop }++ let timer+ return {+ cancel() {+ timer && (clearTimeout(timer), timer = null)+ },+ start() {+ timer && clearTimeout(timer)+ timer = setTimeout(done, seconds * 1000, arguments)+ }+ }++ function done(args) {+ fn.apply(null, args)+ timer = null+ }+}diff --git a/vendor/postgres/cjs/src/errors.js b/vendor/postgres/cjs/src/errors.jsnew file mode 100644index 0000000000..ef66149ab6--- /dev/null+++ b/vendor/postgres/cjs/src/errors.js@@ -0,0 +1,53 @@+const PostgresError = module.exports.PostgresError = class PostgresError extends Error {+ constructor(x) {+ super(x.message)+ this.name = this.constructor.name+ Object.assign(this, x)+ }+}++const Errors = module.exports.Errors = {+ connection,+ postgres,+ generic,+ notSupported+}++function connection(x, options, socket) {+ const { host, port } = socket || options+ const error = Object.assign(+ new Error(('write ' + x + ' ' + (options.path || (host + ':' + port)))),+ {+ code: x,+ errno: x,+ address: options.path || host+ }, options.path ? {} : { port: port }+ )+ Error.captureStackTrace(error, connection)+ return error+}++function postgres(x) {+ const error = new PostgresError(x)+ Error.captureStackTrace(error, postgres)+ return error+}++function generic(code, message) {+ const error = Object.assign(new Error(code + ': ' + message), { code })+ Error.captureStackTrace(error, generic)+ return error+}++/* c8 ignore next 10 */+function notSupported(x) {+ const error = Object.assign(+ new Error(x + ' (B) is not supported'),+ {+ code: 'MESSAGE_NOT_SUPPORTED',+ name: x+ }+ )+ Error.captureStackTrace(error, notSupported)+ return error+}diff --git a/vendor/postgres/cjs/src/index.js b/vendor/postgres/cjs/src/index.jsnew file mode 100644index 0000000000..9dc0c7a230--- /dev/null+++ b/vendor/postgres/cjs/src/index.js@@ -0,0 +1,680 @@+const os = require('os')+const fs = require('fs')++const {+ mergeUserTypes,+ inferType,+ Parameter,+ Identifier,+ Builder,+ toPascal,+ pascal,+ toCamel,+ camel,+ toKebab,+ kebab,+ fromPascal,+ fromCamel,+ fromKebab+} = require('./types.js')++const Connection = require('./connection.js')+const { Query, CLOSE } = require('./query.js')+const Queue = require('./queue.js')+const { Errors, PostgresError } = require('./errors.js')+const Subscribe = require('./subscribe.js')+const largeObject = require('./large.js')++Object.assign(Postgres, {+ PostgresError,+ toPascal,+ pascal,+ toCamel,+ camel,+ toKebab,+ kebab,+ fromPascal,+ fromCamel,+ fromKebab,+ BigInt: {+ to: 20,+ from: [20],+ parse: x => BigInt(x), // eslint-disable-line+ serialize: x => x.toString()+ }+})++module.exports = Postgres++function Postgres(a, b) {+ const options = parseOptions(a, b)+ , subscribe = options.no_subscribe || Subscribe(Postgres, { ...options })++ let ending = false++ const queries = Queue()+ , connecting = Queue()+ , reserved = Queue()+ , closed = Queue()+ , ended = Queue()+ , open = Queue()+ , busy = Queue()+ , full = Queue()+ , queues = { connecting, reserved, closed, ended, open, busy, full }++ const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose }))++ const sql = Sql(handler)++ Object.assign(sql, {+ get parameters() { return options.parameters },+ largeObject: largeObject.bind(null, sql),+ subscribe,+ CLOSE,+ END: CLOSE,+ PostgresError,+ options,+ reserve,+ listen,+ begin,+ close,+ end+ })++ return sql++ function Sql(handler) {+ handler.debug = options.debug++ Object.entries(options.types).reduce((acc, [name, type]) => {+ acc[name] = (x) => new Parameter(x, type.to)+ return acc+ }, typed)++ Object.assign(sql, {+ types: typed,+ typed,+ unsafe,+ notify,+ array,+ json,+ file+ })++ return sql++ function typed(value, type) {+ return new Parameter(value, type)+ }++ function sql(strings, ...args) {+ const query = strings && Array.isArray(strings.raw)+ ? new Query(strings, args, handler, cancel)+ : typeof strings === 'string' && !args.length+ ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings)+ : new Builder(strings, args)+ return query+ }++ function unsafe(string, args = [], options = {}) {+ arguments.length === 2 && !Array.isArray(args) && (options = args, args = [])+ const query = new Query([string], args, handler, cancel, {+ prepare: false,+ ...options,+ simple: 'simple' in options ? options.simple : args.length === 0+ })+ return query+ }++ function file(path, args = [], options = {}) {+ arguments.length === 2 && !Array.isArray(args) && (options = args, args = [])+ const query = new Query([], args, (query) => {+ fs.readFile(path, 'utf8', (err, string) => {+ if (err)+ return query.reject(err)++ query.strings = [string]+ handler(query)+ })+ }, cancel, {+ ...options,+ simple: 'simple' in options ? options.simple : args.length === 0+ })+ return query+ }+ }++ async function listen(name, fn, onlisten) {+ const listener = { fn, onlisten }++ const sql = listen.sql || (listen.sql = Postgres({+ ...options,+ max: 1,+ idle_timeout: null,+ max_lifetime: null,+ fetch_types: false,+ onclose() {+ Object.entries(listen.channels).forEach(([name, { listeners }]) => {+ delete listen.channels[name]+ Promise.all(listeners.map(l => listen(name, l.fn, l.onlisten).catch(() => { /* noop */ })))+ })+ },+ onnotify(c, x) {+ c in listen.channels && listen.channels[c].listeners.forEach(l => l.fn(x))+ }+ }))++ const channels = listen.channels || (listen.channels = {})+ , exists = name in channels++ if (exists) {+ channels[name].listeners.push(listener)+ const result = await channels[name].result+ listener.onlisten && listener.onlisten()+ return { state: result.state, unlisten }+ }++ channels[name] = { result: sql`listen ${+ sql.unsafe('"' + name.replace(/"/g, '""') + '"')+ }`, listeners: [listener] }+ const result = await channels[name].result+ listener.onlisten && listener.onlisten()+ return { state: result.state, unlisten }++ async function unlisten() {+ if (name in channels === false)+ return++ channels[name].listeners = channels[name].listeners.filter(x => x !== listener)+ if (channels[name].listeners.length)+ return++ delete channels[name]+ return sql`unlisten ${+ sql.unsafe('"' + name.replace(/"/g, '""') + '"')+ }`+ }+ }++ async function notify(channel, payload) {+ return await sql`select pg_notify(${ channel }, ${ '' + payload })`+ }++ function own(c) {+ const queue = Queue()+ let busy = false, fence = null, holding = null, releasing = false+ const reservation = c.reserved = (ended = false) => {+ if (c.reserved !== reservation)+ return+ busy = false+ if (ended) {+ releasing = true+ reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction has ended'))+ }+ const completed = fence+ fence = null+ if (completed && completed.cancelPromise) {+ holding = completed+ completed.cancelPromise.then(() => {+ if (c.reserved !== reservation || holding !== completed)+ return+ holding = null+ pump()+ }, reservation.discard)+ } else {+ pump()+ }+ }+ reservation.enqueue = q => {+ if (c.reserved !== reservation || releasing)+ return q.reject(Errors.generic('CONNECTION_CLOSED', 'Connection is no longer owned'))+ queue.push(q)+ pump()+ }+ reservation.reject = error => {+ while (queue.length)+ queue.shift().reject(error)+ }+ reservation.discard = () => {+ if (c.reserved !== reservation)+ return+ c.reserved = null+ reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Connection was discarded'))+ c.terminate()+ }+ reservation.releaseConnection = () => {+ if (c.reserved !== reservation)+ return+ releasing = true+ pump()+ }+ return reservation++ function pump() {+ if (c.reserved !== reservation || holding || fence)+ return+ while (queue.length) {+ const q = queue.peek()+ if (q.cancelled) {+ queue.shift()+ continue+ }+ if (busy && (q.options.cancelFence || c.queue === full))+ return+ queue.shift()+ busy = true+ if (q.options.cancelFence)+ fence = q+ const ready = c.execute(q)+ move(c, ready ? reserved : full)+ if (fence || !ready)+ return+ }+ if (!busy) {+ if (releasing) {+ c.reserved = null+ onopen(c)+ } else {+ move(c, reserved)+ }+ }+ }+ }++ async function reserve({ signal } = {}) {+ signal && signal.throwIfAborted()+ if (ending)+ throw Errors.connection('CONNECTION_ENDED', options, options)+ const sql = open.length+ ? claim(open.shift())+ : await new Promise((resolve, reject) => {+ let settled = false+ const query = {+ reserve: c => { if (settle()) resolve(claim(c)) },+ reject: error => { if (settle()) reject(error) }+ }+ const abort = () => query.reject(signal.reason)+ function settle() {+ if (settled)+ return false+ settled = true+ queries.remove(query)+ signal && signal.removeEventListener('abort', abort)+ return true+ }+ if (signal)+ signal.addEventListener('abort', abort, { once: true })+ queries.push(query)+ closed.length && connect(closed.shift(), query)+ })++ if (signal && signal.aborted) {+ sql.release()+ signal.throwIfAborted()+ }++ return sql++ function claim(c) {+ move(c, reserved)+ const reservation = own(c)+ reservation.release = true+ const sql = Sql(reservation.enqueue)+ sql.release = reservation.releaseConnection+ sql.discard = reservation.discard+ return sql+ }+ }++ async function begin(options, fn) {+ !fn && (fn = options, options = '')+ let savepoints = 0+ , connection+ , prepare = null++ try {+ await sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()+ return await Promise.race([+ scope(connection, fn),+ new Promise((_, reject) => connection.onclose = reject)+ ])+ } catch (error) {+ throw error+ }++ async function scope(c, fn, name) {+ const reservation = c.reserved+ if (!reservation)+ throw Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned')+ const sql = Sql(handler)+ sql.savepoint = savepoint+ sql.prepare = x => prepare = x.replace(/[^a-z0-9$-_. ]/gi)+ sql.discard = reservation.discard+ let uncaughtError+ , result++ name && await sql`savepoint ${ sql(name) }`+ try {+ result = await new Promise((resolve, reject) => {+ const x = fn(sql)+ Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject)+ })++ if (uncaughtError)+ throw uncaughtError+ } catch (e) {+ await (name+ ? sql`rollback to ${ sql(name) }`+ : sql`rollback`+ )+ throw e instanceof PostgresError && e.code === '25P02' && uncaughtError || e+ }++ if (!name) {+ prepare+ ? await sql`prepare transaction '${ sql.unsafe(prepare) }'`+ : await sql`commit`+ }++ return result++ function savepoint(name, fn) {+ if (c.reserved !== reservation)+ return Promise.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))+ if (name && Array.isArray(name.raw))+ return savepoint(sql => sql.apply(sql, arguments))++ arguments.length === 1 && (fn = name, name = null)+ return scope(c, fn, 's' + savepoints++ + (name ? '_' + name : ''))+ }++ function handler(q) {+ q.catch(e => uncaughtError || (uncaughtError = e))+ if (!reservation || c.reserved !== reservation)+ return q.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))+ reservation.enqueue(q)+ }+ }++ function onexecute(c) {+ connection = c+ move(c, reserved)+ own(c)+ }+ }++ function move(c, queue) {+ c.queue.remove(c)+ queue.push(c)+ c.queue = queue+ queue === open+ ? c.idleTimer.start()+ : c.idleTimer.cancel()+ return c+ }++ function json(x) {+ return new Parameter(x, 3802)+ }++ function array(x, type) {+ if (!Array.isArray(x))+ return array(Array.from(arguments))++ return new Parameter(x, type || (x.length ? inferType(x) || 25 : 0), options.shared.typeArrayMap)+ }++ function handler(query) {+ if (ending)+ return query.reject(Errors.connection('CONNECTION_ENDED', options, options))++ if (open.length)+ return go(open.shift(), query)++ if (closed.length)+ return connect(closed.shift(), query)++ busy.length+ ? go(busy.shift(), query)+ : queries.push(query)+ }++ function go(c, query) {+ return c.execute(query)+ ? move(c, busy)+ : move(c, full)+ }++ function cancel(query) {+ return new Promise((resolve, reject) => {+ query.state+ ? query.active+ ? Connection(options).cancel(query.state, resolve, reject)+ : query.cancelled = { resolve, reject }+ : (+ queries.remove(query),+ query.cancelled = true,+ query.reject(Errors.generic('57014', 'canceling statement due to user request')),+ resolve()+ )+ })+ }++ async function end({ timeout = null } = {}) {+ if (ending)+ return ending++ await 1+ let timer+ return ending = Promise.race([+ new Promise(r => timeout !== null && (timer = setTimeout(destroy, timeout * 1000, r))),+ Promise.all(connections.map(c => c.end()).concat(+ listen.sql ? listen.sql.end({ timeout: 0 }) : [],+ subscribe.sql ? subscribe.sql.end({ timeout: 0 }) : []+ ))+ ]).then(() => clearTimeout(timer))+ }++ async function close() {+ await Promise.all(connections.map(c => c.end()))+ }++ async function destroy(resolve) {+ await Promise.all(connections.map(c => c.terminate()))+ while (queries.length)+ queries.shift().reject(Errors.connection('CONNECTION_DESTROYED', options))+ resolve()+ }++ function connect(c, query) {+ move(c, connecting)+ c.connect(query)+ return c+ }++ function onend(c) {+ move(c, ended)+ }++ function onopen(c) {+ if (ending) {+ while (queries.length)+ queries.shift().reject(Errors.connection('CONNECTION_ENDED', options))+ return c.terminate()+ }+ if (queries.length === 0)+ return move(c, open)++ let max = Math.ceil(queries.length / (connecting.length + 1))+ , ready = true++ while (ready && queries.length && max-- > 0) {+ const query = queries.shift()+ if (query.reserve)+ return query.reserve(c)++ ready = c.execute(query)+ }++ ready+ ? move(c, busy)+ : move(c, full)+ }++ function onclose(c, e) {+ move(c, closed)+ const reservation = c.reserved+ c.reserved = null+ reservation && reservation.reject(e)+ c.onclose && (c.onclose(e), c.onclose = null)+ options.onclose && options.onclose(c.id)+ if (ending) {+ while (queries.length)+ queries.shift().reject(Errors.connection('CONNECTION_ENDED', options))+ return+ }+ if (queries.length) {+ const query = queries.peek()+ connect(c, query.reserve ? query : queries.shift())+ }+ }+}++function parseOptions(a, b) {+ if (a && a.shared)+ return a++ const env = process.env // eslint-disable-line+ , o = (!a || typeof a === 'string' ? b : a) || {}+ , { url, multihost } = parseUrl(a)+ , query = [...url.searchParams].reduce((a, [b, c]) => (a[b] = c, a), {})+ , host = o.hostname || o.host || multihost || url.hostname || env.PGHOST || 'localhost'+ , port = o.port || url.port || env.PGPORT || 5432+ , user = o.user || o.username || url.username || env.PGUSERNAME || env.PGUSER || osUsername()++ o.no_prepare && (o.prepare = false)+ query.sslmode && (query.ssl = query.sslmode, delete query.sslmode)+ 'timeout' in o && (console.log('The timeout option is deprecated, use idle_timeout instead'), o.idle_timeout = o.timeout) // eslint-disable-line+ query.sslrootcert === 'system' && (query.ssl = 'verify-full')++ const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive']+ const defaults = {+ max : globalThis.Cloudflare ? 3 : 10,+ ssl : false,+ sslnegotiation : null,+ idle_timeout : null,+ connect_timeout : 30,+ max_lifetime : max_lifetime,+ max_pipeline : 100,+ backoff : backoff,+ keep_alive : 60,+ prepare : true,+ debug : false,+ fetch_types : true,+ publications : 'alltables',+ target_session_attrs: null+ }++ return {+ host : Array.isArray(host) ? host : host.split(',').map(x => x.split(':')[0]),+ port : Array.isArray(port) ? port : host.split(',').map(x => parseInt(x.split(':')[1] || port)),+ path : o.path || host.indexOf('/') > -1 && host + '/.s.PGSQL.' + port,+ database : o.database || o.db || (url.pathname || '').slice(1) || env.PGDATABASE || user,+ user : user,+ pass : o.pass || o.password || url.password || env.PGPASSWORD || '',+ ...Object.entries(defaults).reduce(+ (acc, [k, d]) => {+ const value = k in o ? o[k] : k in query+ ? (query[k] === 'disable' || query[k] === 'false' ? false : query[k])+ : env['PG' + k.toUpperCase()] || d+ acc[k] = typeof value === 'string' && ints.includes(k)+ ? +value+ : value+ return acc+ },+ {}+ ),+ connection : {+ application_name: env.PGAPPNAME || 'postgres.js',+ ...o.connection,+ ...Object.entries(query).reduce((acc, [k, v]) => (k in defaults || (acc[k] = v), acc), {})+ },+ types : o.types || {},+ target_session_attrs: tsa(o, url, env),+ onnotice : o.onnotice,+ onnotify : o.onnotify,+ onclose : o.onclose,+ onparameter : o.onparameter,+ socket : o.socket,+ transform : parseTransform(o.transform || { undefined: undefined }),+ parameters : {},+ shared : { retries: 0, typeArrayMap: {} },+ ...mergeUserTypes(o.types)+ }+}++function tsa(o, url, env) {+ const x = o.target_session_attrs || url.searchParams.get('target_session_attrs') || env.PGTARGETSESSIONATTRS+ if (!x || ['read-write', 'read-only', 'primary', 'standby', 'prefer-standby'].includes(x))+ return x++ throw new Error('target_session_attrs ' + x + ' is not supported')+}++function backoff(retries) {+ return (0.5 + Math.random() / 2) * Math.min(3 ** retries / 100, 20)+}++function max_lifetime() {+ return 60 * (30 + Math.random() * 30)+}++function parseTransform(x) {+ return {+ undefined: x.undefined,+ column: {+ from: typeof x.column === 'function' ? x.column : x.column && x.column.from,+ to: x.column && x.column.to+ },+ value: {+ from: typeof x.value === 'function' ? x.value : x.value && x.value.from,+ to: x.value && x.value.to+ },+ row: {+ from: typeof x.row === 'function' ? x.row : x.row && x.row.from,+ to: x.row && x.row.to+ }+ }+}++function parseUrl(url) {+ if (!url || typeof url !== 'string')+ return { url: { searchParams: new Map() } }++ let host = url+ host = host.slice(host.indexOf('://') + 3).split(/[?/]/)[0]+ host = decodeURIComponent(host.slice(host.indexOf('@') + 1))++ const urlObj = new URL(url.replace(host, host.split(',')[0]))++ return {+ url: {+ username: decodeURIComponent(urlObj.username),+ password: decodeURIComponent(urlObj.password),+ host: urlObj.host,+ hostname: urlObj.hostname,+ port: urlObj.port,+ pathname: urlObj.pathname,+ searchParams: urlObj.searchParams+ },+ multihost: host.indexOf(',') > -1 && host+ }+}++function osUsername() {+ try {+ return os.userInfo().username // eslint-disable-line+ } catch (_) {+ return process.env.USERNAME || process.env.USER || process.env.LOGNAME // eslint-disable-line+ }+}diff --git a/vendor/postgres/cjs/src/large.js b/vendor/postgres/cjs/src/large.jsnew file mode 100644index 0000000000..281b088a06--- /dev/null+++ b/vendor/postgres/cjs/src/large.js@@ -0,0 +1,70 @@+const Stream = require('stream')++module.exports = largeObject;function largeObject(sql, oid, mode = 0x00020000 | 0x00040000) {+ return new Promise(async(resolve, reject) => {+ await sql.begin(async sql => {+ let finish+ !oid && ([{ oid }] = await sql`select lo_creat(-1) as oid`)+ const [{ fd }] = await sql`select lo_open(${ oid }, ${ mode }) as fd`++ const lo = {+ writable,+ readable,+ close : () => sql`select lo_close(${ fd })`.then(finish),+ tell : () => sql`select lo_tell64(${ fd })`,+ read : (x) => sql`select loread(${ fd }, ${ x }) as data`,+ write : (x) => sql`select lowrite(${ fd }, ${ x })`,+ truncate : (x) => sql`select lo_truncate64(${ fd }, ${ x })`,+ seek : (x, whence = 0) => sql`select lo_lseek64(${ fd }, ${ x }, ${ whence })`,+ size : () => sql`+ select+ lo_lseek64(${ fd }, location, 0) as position,+ seek.size+ from (+ select+ lo_lseek64($1, 0, 2) as size,+ tell.location+ from (select lo_tell64($1) as location) tell+ ) seek+ `+ }++ resolve(lo)++ return new Promise(async r => finish = r)++ async function readable({+ highWaterMark = 2048 * 8,+ start = 0,+ end = Infinity+ } = {}) {+ let max = end - start+ start && await lo.seek(start)+ return new Stream.Readable({+ highWaterMark,+ async read(size) {+ const l = size > max ? size - max : size+ max -= size+ const [{ data }] = await lo.read(l)+ this.push(data)+ if (data.length < size)+ this.push(null)+ }+ })+ }++ async function writable({+ highWaterMark = 2048 * 8,+ start = 0+ } = {}) {+ start && await lo.seek(start)+ return new Stream.Writable({+ highWaterMark,+ write(chunk, encoding, callback) {+ lo.write(chunk).then(() => callback(), callback)+ }+ })+ }+ }).catch(reject)+ })+}diff --git a/vendor/postgres/cjs/src/query.js b/vendor/postgres/cjs/src/query.jsnew file mode 100644index 0000000000..1d092504ac--- /dev/null+++ b/vendor/postgres/cjs/src/query.js@@ -0,0 +1,179 @@+const originCache = new Map()+ , originStackCache = new Map()+ , originError = Symbol('OriginError')++const CLOSE = module.exports.CLOSE = {}+const Query = module.exports.Query = class Query extends Promise {+ constructor(strings, args, handler, canceller, options = {}) {+ let resolve+ , reject++ super((a, b) => {+ resolve = a+ reject = b+ })++ this.tagged = Array.isArray(strings.raw)+ this.strings = strings+ this.args = args+ this.handler = handler+ this.canceller = canceller+ this.options = options++ this.state = null+ this.statement = null++ this.resolve = x => (this.active = false, this.canceller = null, resolve(x))+ this.reject = x => (this.active = false, this.canceller = null, reject(x))++ this.active = false+ this.cancelled = null+ this.cancelPromise = null+ this.executed = false+ this.signature = ''++ this[originError] = this.handler.debug+ ? new Error()+ : this.tagged && cachedError(this.strings)+ }++ get origin() {+ return (this.handler.debug+ ? this[originError].stack+ : this.tagged && originStackCache.has(this.strings)+ ? originStackCache.get(this.strings)+ : originStackCache.set(this.strings, this[originError].stack).get(this.strings)+ ) || ''+ }++ static get [Symbol.species]() {+ return Promise+ }++ cancel() {+ if (this.cancelPromise)+ return this.cancelPromise++ const canceller = this.canceller+ this.canceller = null+ return this.cancelPromise = canceller ? canceller(this) : Promise.resolve()+ }++ simple() {+ this.options.simple = true+ this.options.prepare = false+ return this+ }++ async readable() {+ this.simple()+ this.streaming = true+ return this+ }++ async writable() {+ this.simple()+ this.streaming = true+ return this+ }++ cursor(rows = 1, fn) {+ this.options.simple = false+ if (typeof rows === 'function') {+ fn = rows+ rows = 1+ }++ this.cursorRows = rows++ if (typeof fn === 'function')+ return (this.cursorFn = fn, this)++ let prev+ return {+ [Symbol.asyncIterator]: () => ({+ next: () => {+ if (this.executed && !this.active)+ return { done: true }++ prev && prev()+ const promise = new Promise((resolve, reject) => {+ this.cursorFn = value => {+ resolve({ value, done: false })+ return new Promise(r => prev = r)+ }+ this.resolve = () => (this.active = false, this.canceller = null, resolve({ done: true }))+ this.reject = x => (this.active = false, this.canceller = null, reject(x))+ })+ this.execute()+ return promise+ },+ return() {+ prev && prev(CLOSE)+ return { done: true }+ }+ })+ }+ }++ describe() {+ this.options.simple = false+ this.onlyDescribe = this.options.prepare = true+ return this+ }++ stream() {+ throw new Error('.stream has been renamed to .forEach')+ }++ forEach(fn) {+ this.forEachFn = fn+ this.handle()+ return this+ }++ raw() {+ this.isRaw = true+ return this+ }++ values() {+ this.isRaw = 'values'+ return this+ }++ async handle() {+ !this.executed && (this.executed = true) && await 1 && this.handler(this)+ }++ execute() {+ this.handle()+ return this+ }++ then() {+ this.handle()+ return super.then.apply(this, arguments)+ }++ catch() {+ this.handle()+ return super.catch.apply(this, arguments)+ }++ finally() {+ this.handle()+ return super.finally.apply(this, arguments)+ }+}++function cachedError(xs) {+ if (originCache.has(xs))+ return originCache.get(xs)++ const x = Error.stackTraceLimit+ Error.stackTraceLimit = 4+ originCache.set(xs, new Error())+ Error.stackTraceLimit = x+ return originCache.get(xs)+}diff --git a/vendor/postgres/cjs/src/queue.js b/vendor/postgres/cjs/src/queue.jsnew file mode 100644index 0000000000..c444310ff8--- /dev/null+++ b/vendor/postgres/cjs/src/queue.js@@ -0,0 +1,32 @@+module.exports = Queue++function Queue(initial = []) {+ let xs = initial.slice()+ let index = 0++ return {+ get length() {+ return xs.length - index+ },+ remove: (x) => {+ const index = xs.indexOf(x)+ return index === -1+ ? null+ : (xs.splice(index, 1), x)+ },+ push: (x) => (xs.push(x), x),+ peek: () => xs[index],+ shift: () => {+ const out = xs[index++]++ if (index === xs.length) {+ index = 0+ xs = []+ } else {+ xs[index - 1] = undefined+ }++ return out+ }+ }+}diff --git a/vendor/postgres/cjs/src/result.js b/vendor/postgres/cjs/src/result.jsnew file mode 100644index 0000000000..6146daa287--- /dev/null+++ b/vendor/postgres/cjs/src/result.js@@ -0,0 +1,16 @@+module.exports = class Result extends Array {+ constructor() {+ super()+ Object.defineProperties(this, {+ count: { value: null, writable: true },+ state: { value: null, writable: true },+ command: { value: null, writable: true },+ columns: { value: null, writable: true },+ statement: { value: null, writable: true }+ })+ }++ static get [Symbol.species]() {+ return Array+ }+}diff --git a/vendor/postgres/cjs/src/subscribe.js b/vendor/postgres/cjs/src/subscribe.jsnew file mode 100644index 0000000000..6aaa8962ce--- /dev/null+++ b/vendor/postgres/cjs/src/subscribe.js@@ -0,0 +1,277 @@+const noop = () => { /* noop */ }++module.exports = Subscribe;function Subscribe(postgres, options) {+ const subscribers = new Map()+ , slot = 'postgresjs_' + Math.random().toString(36).slice(2)+ , state = {}++ let connection+ , stream+ , ended = false++ const sql = subscribe.sql = postgres({+ ...options,+ transform: { column: {}, value: {}, row: {} },+ max: 1,+ fetch_types: false,+ idle_timeout: null,+ max_lifetime: null,+ connection: {+ ...options.connection,+ replication: 'database'+ },+ onclose: async function() {+ if (ended)+ return+ stream = null+ state.pid = state.secret = undefined+ connected(await init(sql, slot, options.publications))+ subscribers.forEach(event => event.forEach(({ onsubscribe }) => onsubscribe()))+ },+ no_subscribe: true+ })++ const end = sql.end+ , close = sql.close++ sql.end = async() => {+ ended = true+ stream && (await new Promise(r => (stream.once('close', r), stream.end())))+ return end()+ }++ sql.close = async() => {+ stream && (await new Promise(r => (stream.once('close', r), stream.end())))+ return close()+ }++ return subscribe++ async function subscribe(event, fn, onsubscribe = noop, onerror = noop) {+ event = parseEvent(event)++ if (!connection)+ connection = init(sql, slot, options.publications)++ const subscriber = { fn, onsubscribe }+ const fns = subscribers.has(event)+ ? subscribers.get(event).add(subscriber)+ : subscribers.set(event, new Set([subscriber])).get(event)++ const unsubscribe = () => {+ fns.delete(subscriber)+ fns.size === 0 && subscribers.delete(event)+ }++ return connection.then(x => {+ connected(x)+ onsubscribe()+ stream && stream.on('error', onerror)+ return { unsubscribe, state, sql }+ })+ }++ function connected(x) {+ stream = x.stream+ state.pid = x.state.pid+ state.secret = x.state.secret+ }++ async function init(sql, slot, publications) {+ if (!publications)+ throw new Error('Missing publication names')++ const xs = await sql.unsafe(+ `CREATE_REPLICATION_SLOT ${ slot } TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`+ )++ const [x] = xs++ const stream = await sql.unsafe(+ `START_REPLICATION SLOT ${ slot } LOGICAL ${+ x.consistent_point+ } (proto_version '1', publication_names '${ publications }')`+ ).writable()++ const state = {+ lsn: Buffer.concat(x.consistent_point.split('/').map(x => Buffer.from(('00000000' + x).slice(-8), 'hex')))+ }++ stream.on('data', data)+ stream.on('error', error)+ stream.on('close', sql.close)++ return { stream, state: xs.state }++ function error(e) {+ console.error('Unexpected error during logical streaming - reconnecting', e) // eslint-disable-line+ }++ function data(x) {+ if (x[0] === 0x77) {+ parse(x.subarray(25), state, sql.options.parsers, handle, options.transform)+ } else if (x[0] === 0x6b && x[17]) {+ state.lsn = x.subarray(1, 9)+ pong()+ }+ }++ function handle(a, b) {+ const path = b.relation.schema + '.' + b.relation.table+ call('*', a, b)+ call('*:' + path, a, b)+ b.relation.keys.length && call('*:' + path + '=' + b.relation.keys.map(x => a[x.name]), a, b)+ call(b.command, a, b)+ call(b.command + ':' + path, a, b)+ b.relation.keys.length && call(b.command + ':' + path + '=' + b.relation.keys.map(x => a[x.name]), a, b)+ }++ function pong() {+ const x = Buffer.alloc(34)+ x[0] = 'r'.charCodeAt(0)+ x.fill(state.lsn, 1)+ x.writeBigInt64BE(BigInt(Date.now() - Date.UTC(2000, 0, 1)) * BigInt(1000), 25)+ stream.write(x)+ }+ }++ function call(x, a, b) {+ subscribers.has(x) && subscribers.get(x).forEach(({ fn }) => fn(a, b, x))+ }+}++function Time(x) {+ return new Date(Date.UTC(2000, 0, 1) + Number(x / BigInt(1000)))+}++function parse(x, state, parsers, handle, transform) {+ const char = (acc, [k, v]) => (acc[k.charCodeAt(0)] = v, acc)++ Object.entries({+ R: x => { // Relation+ let i = 1+ const r = state[x.readUInt32BE(i)] = {+ schema: x.toString('utf8', i += 4, i = x.indexOf(0, i)) || 'pg_catalog',+ table: x.toString('utf8', i + 1, i = x.indexOf(0, i + 1)),+ columns: Array(x.readUInt16BE(i += 2)),+ keys: []+ }+ i += 2++ let columnIndex = 0+ , column++ while (i < x.length) {+ column = r.columns[columnIndex++] = {+ key: x[i++],+ name: transform.column.from+ ? transform.column.from(x.toString('utf8', i, i = x.indexOf(0, i)))+ : x.toString('utf8', i, i = x.indexOf(0, i)),+ type: x.readUInt32BE(i += 1),+ parser: parsers[x.readUInt32BE(i)],+ atttypmod: x.readUInt32BE(i += 4)+ }++ column.key && r.keys.push(column)+ i += 4+ }+ },+ Y: () => { /* noop */ }, // Type+ O: () => { /* noop */ }, // Origin+ B: x => { // Begin+ state.date = Time(x.readBigInt64BE(9))+ state.lsn = x.subarray(1, 9)+ },+ I: x => { // Insert+ let i = 1+ const relation = state[x.readUInt32BE(i)]+ const { row } = tuples(x, relation.columns, i += 7, transform)++ handle(row, {+ command: 'insert',+ relation+ })+ },+ D: x => { // Delete+ let i = 1+ const relation = state[x.readUInt32BE(i)]+ i += 4+ const key = x[i] === 75+ handle(key || x[i] === 79+ ? tuples(x, relation.columns, i += 3, transform).row+ : null+ , {+ command: 'delete',+ relation,+ key+ })+ },+ U: x => { // Update+ let i = 1+ const relation = state[x.readUInt32BE(i)]+ i += 4+ const key = x[i] === 75+ const xs = key || x[i] === 79+ ? tuples(x, relation.columns, i += 3, transform)+ : null++ xs && (i = xs.i)++ const { row } = tuples(x, relation.columns, i + 3, transform)++ handle(row, {+ command: 'update',+ relation,+ key,+ old: xs && xs.row+ })+ },+ T: () => { /* noop */ }, // Truncate,+ C: () => { /* noop */ } // Commit+ }).reduce(char, {})[x[0]](x)+}++function tuples(x, columns, xi, transform) {+ let type+ , column+ , value++ const row = transform.raw ? new Array(columns.length) : {}+ for (let i = 0; i < columns.length; i++) {+ type = x[xi++]+ column = columns[i]+ value = type === 110 // n+ ? null+ : type === 117 // u+ ? undefined+ : column.parser === undefined+ ? x.toString('utf8', xi + 4, xi += 4 + x.readUInt32BE(xi))+ : column.parser.array === true+ ? column.parser(x.toString('utf8', xi + 5, xi += 4 + x.readUInt32BE(xi)))+ : column.parser(x.toString('utf8', xi + 4, xi += 4 + x.readUInt32BE(xi)))++ transform.raw+ ? (row[i] = transform.raw === true+ ? value+ : transform.value.from ? transform.value.from(value, column) : value)+ : (row[column.name] = transform.value.from+ ? transform.value.from(value, column)+ : value+ )+ }++ return { i: xi, row: transform.row.from ? transform.row.from(row) : row }+}++function parseEvent(x) {+ const xs = x.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i) || []++ if (!xs)+ throw new Error('Malformed subscribe pattern: ' + x)++ const [, command, path, key] = xs++ return (command || '*')+ + (path ? ':' + (path.indexOf('.') === -1 ? 'public.' + path : path) : '')+ + (key ? '=' + key : '')+}diff --git a/vendor/postgres/cjs/src/types.js b/vendor/postgres/cjs/src/types.jsnew file mode 100644index 0000000000..0578284c5a--- /dev/null+++ b/vendor/postgres/cjs/src/types.js@@ -0,0 +1,367 @@+const { Query } = require('./query.js')+const { Errors } = require('./errors.js')++const types = module.exports.types = {+ string: {+ to: 25,+ from: null, // defaults to string+ serialize: x => '' + x+ },+ number: {+ to: 0,+ from: [21, 23, 26, 700, 701],+ serialize: x => '' + x,+ parse: x => +x+ },+ json: {+ to: 114,+ from: [114, 3802],+ serialize: x => JSON.stringify(x),+ parse: x => JSON.parse(x)+ },+ boolean: {+ to: 16,+ from: 16,+ serialize: x => x === true ? 't' : 'f',+ parse: x => x === 't'+ },+ date: {+ to: 1184,+ from: [1082, 1114, 1184],+ serialize: x => (x instanceof Date ? x : new Date(x)).toISOString(),+ parse: x => new Date(x)+ },+ bytea: {+ to: 17,+ from: 17,+ serialize: x => '\\x' + Buffer.from(x).toString('hex'),+ parse: x => Buffer.from(x.slice(2), 'hex')+ }+}++class NotTagged { then() { notTagged() } catch() { notTagged() } finally() { notTagged() }}++const Identifier = module.exports.Identifier = class Identifier extends NotTagged {+ constructor(value) {+ super()+ this.value = escapeIdentifier(value)+ }+}++const Parameter = module.exports.Parameter = class Parameter extends NotTagged {+ constructor(value, type, array) {+ super()+ this.value = value+ this.type = type+ this.array = array+ }+}++const Builder = module.exports.Builder = class Builder extends NotTagged {+ constructor(first, rest) {+ super()+ this.first = first+ this.rest = rest+ }++ build(before, parameters, types, options) {+ const keyword = builders.map(([x, fn]) => ({ fn, i: before.search(x) })).sort((a, b) => a.i - b.i).pop()+ return keyword.i === -1+ ? escapeIdentifiers(this.first, options)+ : keyword.fn(this.first, this.rest, parameters, types, options)+ }+}++module.exports.handleValue = handleValue;function handleValue(x, parameters, types, options) {+ let value = x instanceof Parameter ? x.value : x+ if (value === undefined) {+ x instanceof Parameter+ ? x.value = options.transform.undefined+ : value = x = options.transform.undefined++ if (value === undefined)+ throw Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed')+ }++ return '$' + (types.push(+ x instanceof Parameter+ ? (parameters.push(x.value), x.array+ ? x.array[x.type || inferType(x.value)] || x.type || firstIsString(x.value)+ : x.type+ )+ : (parameters.push(x), inferType(x))+ ))+}++const defaultHandlers = typeHandlers(types)++module.exports.stringify = stringify;function stringify(q, string, value, parameters, types, options) { // eslint-disable-line+ for (let i = 1; i < q.strings.length; i++) {+ string += (stringifyValue(string, value, parameters, types, options)) + q.strings[i]+ value = q.args[i]+ }++ return string+}++function stringifyValue(string, value, parameters, types, o) {+ return (+ value instanceof Builder ? value.build(string, parameters, types, o) :+ value instanceof Query ? fragment(value, parameters, types, o) :+ value instanceof Identifier ? value.value :+ value && value[0] instanceof Query ? value.reduce((acc, x) => acc + ' ' + fragment(x, parameters, types, o), '') :+ handleValue(value, parameters, types, o)+ )+}++function fragment(q, parameters, types, options) {+ q.fragment = true+ return stringify(q, q.strings[0], q.args[0], parameters, types, options)+}++function valuesBuilder(first, parameters, types, columns, options) {+ return first.map(row =>+ '(' + columns.map(column =>+ stringifyValue('values', row[column], parameters, types, options)+ ).join(',') + ')'+ ).join(',')+}++function values(first, rest, parameters, types, options) {+ const multi = Array.isArray(first[0])+ const columns = rest.length ? rest.flat() : Object.keys(multi ? first[0] : first)+ return valuesBuilder(multi ? first : [first], parameters, types, columns, options)+}++function select(first, rest, parameters, types, options) {+ typeof first === 'string' && (first = [first].concat(rest))+ if (Array.isArray(first))+ return escapeIdentifiers(first, options)++ let value+ const columns = rest.length ? rest.flat() : Object.keys(first)+ return columns.map(x => {+ value = first[x]+ return (+ value instanceof Query ? fragment(value, parameters, types, options) :+ value instanceof Identifier ? value.value :+ handleValue(value, parameters, types, options)+ ) + ' as ' + escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x)+ }).join(',')+}++const builders = Object.entries({+ values,+ in: (...xs) => {+ const x = values(...xs)+ return x === '()' ? '(null)' : x+ },+ select,+ as: select,+ returning: select,+ '\\(': select,++ update(first, rest, parameters, types, options) {+ return (rest.length ? rest.flat() : Object.keys(first)).map(x =>+ escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x) ++ '=' + stringifyValue('values', first[x], parameters, types, options)+ )+ },++ insert(first, rest, parameters, types, options) {+ const columns = rest.length ? rest.flat() : Object.keys(Array.isArray(first) ? first[0] : first)+ return '(' + escapeIdentifiers(columns, options) + ')values' ++ valuesBuilder(Array.isArray(first) ? first : [first], parameters, types, columns, options)+ }+}).map(([x, fn]) => ([new RegExp('((?:^|[\\s(])' + x + '(?:$|[\\s(]))(?![\\s\\S]*\\1)', 'i'), fn]))++function notTagged() {+ throw Errors.generic('NOT_TAGGED_CALL', 'Query not called as a tagged template literal')+}++const serializers = module.exports.serializers = defaultHandlers.serializers+const parsers = module.exports.parsers = defaultHandlers.parsers++const END = module.exports.END = {}++function firstIsString(x) {+ if (Array.isArray(x))+ return firstIsString(x[0])+ return typeof x === 'string' ? 1009 : 0+}++const mergeUserTypes = module.exports.mergeUserTypes = function(types) {+ const user = typeHandlers(types || {})+ return {+ serializers: Object.assign({}, serializers, user.serializers),+ parsers: Object.assign({}, parsers, user.parsers)+ }+}++function typeHandlers(types) {+ return Object.keys(types).reduce((acc, k) => {+ types[k].from && [].concat(types[k].from).forEach(x => acc.parsers[x] = types[k].parse)+ if (types[k].serialize) {+ acc.serializers[types[k].to] = types[k].serialize+ types[k].from && [].concat(types[k].from).forEach(x => acc.serializers[x] = types[k].serialize)+ }+ return acc+ }, { parsers: {}, serializers: {} })+}++function escapeIdentifiers(xs, { transform: { column } }) {+ return xs.map(x => escapeIdentifier(column.to ? column.to(x) : x)).join(',')+}++const escapeIdentifier = module.exports.escapeIdentifier = function escape(str) {+ return '"' + str.replace(/"/g, '""').replace(/\./g, '"."') + '"'+}++const inferType = module.exports.inferType = function inferType(x) {+ return (+ x instanceof Parameter ? x.type :+ x instanceof Date ? 1184 :+ x instanceof Uint8Array ? 17 :+ (x === true || x === false) ? 16 :+ typeof x === 'bigint' ? 20 :+ Array.isArray(x) ? inferType(x[0]) :+ 0+ )+}++const escapeBackslash = /\\/g+const escapeQuote = /"/g++function arrayEscape(x) {+ return x+ .replace(escapeBackslash, '\\\\')+ .replace(escapeQuote, '\\"')+}++const arraySerializer = module.exports.arraySerializer = function arraySerializer(xs, serializer, options, typarray) {+ if (Array.isArray(xs) === false)+ return xs++ if (!xs.length)+ return '{}'++ const first = xs[0]+ // Only _box (1020) has the ';' delimiter for arrays, all other types use the ',' delimiter+ const delimiter = typarray === 1020 ? ';' : ','++ if (Array.isArray(first) && !first.type)+ return '{' + xs.map(x => arraySerializer(x, serializer, options, typarray)).join(delimiter) + '}'++ return '{' + xs.map(x => {+ if (x === undefined) {+ x = options.transform.undefined+ if (x === undefined)+ throw Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed')+ }++ return x === null+ ? 'null'+ : '"' + arrayEscape(serializer ? serializer(x.type ? x.value : x) : '' + x) + '"'+ }).join(delimiter) + '}'+}++const arrayParserState = {+ i: 0,+ char: null,+ str: '',+ quoted: false,+ last: 0+}++const arrayParser = module.exports.arrayParser = function arrayParser(x, parser, typarray) {+ arrayParserState.i = arrayParserState.last = 0+ return arrayParserLoop(arrayParserState, x, parser, typarray)+}++function arrayParserLoop(s, x, parser, typarray) {+ const xs = []+ // Only _box (1020) has the ';' delimiter for arrays, all other types use the ',' delimiter+ const delimiter = typarray === 1020 ? ';' : ','+ for (; s.i < x.length; s.i++) {+ s.char = x[s.i]+ if (s.quoted) {+ if (s.char === '\\') {+ s.str += x[++s.i]+ } else if (s.char === '"') {+ xs.push(parser ? parser(s.str) : s.str)+ s.str = ''+ s.quoted = x[s.i + 1] === '"'+ s.last = s.i + 2+ } else {+ s.str += s.char+ }+ } else if (s.char === '"') {+ s.quoted = true+ } else if (s.char === '{') {+ s.last = ++s.i+ xs.push(arrayParserLoop(s, x, parser, typarray))+ } else if (s.char === '}') {+ s.quoted = false+ s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i))+ s.last = s.i + 1+ break+ } else if (s.char === delimiter && s.p !== '}' && s.p !== '"') {+ xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i))+ s.last = s.i + 1+ }+ s.p = s.char+ }+ s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i + 1)) : x.slice(s.last, s.i + 1))+ return xs+}++const toCamel = module.exports.toCamel = x => {+ let str = x[0]+ for (let i = 1; i < x.length; i++)+ str += x[i] === '_' ? x[++i].toUpperCase() : x[i]+ return str+}++const toPascal = module.exports.toPascal = x => {+ let str = x[0].toUpperCase()+ for (let i = 1; i < x.length; i++)+ str += x[i] === '_' ? x[++i].toUpperCase() : x[i]+ return str+}++const toKebab = module.exports.toKebab = x => x.replace(/_/g, '-')++const fromCamel = module.exports.fromCamel = x => x.replace(/([A-Z])/g, '_$1').toLowerCase()+const fromPascal = module.exports.fromPascal = x => (x.slice(0, 1) + x.slice(1).replace(/([A-Z])/g, '_$1')).toLowerCase()+const fromKebab = module.exports.fromKebab = x => x.replace(/-/g, '_')++function createJsonTransform(fn) {+ return function jsonTransform(x, column) {+ return typeof x === 'object' && x !== null && (column.type === 114 || column.type === 3802)+ ? Array.isArray(x)+ ? x.map(x => jsonTransform(x, column))+ : Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: jsonTransform(v, column) }), {})+ : x+ }+}++toCamel.column = { from: toCamel }+toCamel.value = { from: createJsonTransform(toCamel) }+fromCamel.column = { to: fromCamel }++const camel = module.exports.camel = { ...toCamel }+camel.column.to = fromCamel++toPascal.column = { from: toPascal }+toPascal.value = { from: createJsonTransform(toPascal) }+fromPascal.column = { to: fromPascal }++const pascal = module.exports.pascal = { ...toPascal }+pascal.column.to = fromPascal++toKebab.column = { from: toKebab }+toKebab.value = { from: createJsonTransform(toKebab) }+fromKebab.column = { to: fromKebab }++const kebab = module.exports.kebab = { ...toKebab }+kebab.column.to = fromKebabdiff --git a/vendor/postgres/package.json b/vendor/postgres/package.jsonnew file mode 100644index 0000000000..c3b76a1a61--- /dev/null+++ b/vendor/postgres/package.json@@ -0,0 +1,63 @@+{+ "name": "postgres",+ "version": "3.4.9",+ "description": "Fastest full featured PostgreSQL client for Node.js",+ "type": "module",+ "module": "src/index.js",+ "main": "cjs/src/index.js",+ "exports": {+ "types": "./types/index.d.ts",+ "bun": "./src/index.js",+ "workerd": "./cf/src/index.js",+ "import": "./src/index.js",+ "default": "./cjs/src/index.js"+ },+ "types": "types/index.d.ts",+ "typings": "types/index.d.ts",+ "engines": {+ "node": ">=12"+ },+ "scripts": {+ "build": "npm run build:cjs && npm run build:deno && npm run build:cf",+ "build:cjs": "node transpile.cjs",+ "build:deno": "node transpile.deno.js",+ "build:cf": "node transpile.cf.js",+ "test": "npm run test:esm && npm run test:cjs && npm run test:deno",+ "test:esm": "node tests/index.js",+ "test:cjs": "npm run build:cjs && cd cjs/tests && node index.js && cd ../../",+ "test:deno": "npm run build:deno && cd deno/tests && deno run --no-lock --allow-all --unsafely-ignore-certificate-errors index.js && cd ../../",+ "lint": "eslint src && eslint tests",+ "prepare": "npm run build",+ "prepublishOnly": "npm run lint"+ },+ "files": [+ "/cf/src",+ "/cf/polyfills.js",+ "/cjs/src",+ "/cjs/package.json",+ "/src",+ "/types"+ ],+ "author": "Rasmus Porsager <[email protected]> (https://www.porsager.com)",+ "funding": {+ "type": "individual",+ "url": "https://github.com/sponsors/porsager"+ },+ "license": "Unlicense",+ "repository": "porsager/postgres",+ "homepage": "https://github.com/porsager/postgres",+ "bugs": "https://github.com/porsager/postgres/issues",+ "keywords": [+ "driver",+ "postgresql",+ "postgres.js",+ "postgres",+ "postrges",+ "postgre",+ "client",+ "sql",+ "db",+ "pg",+ "database"+ ]+}diff --git a/vendor/postgres/src/bytes.js b/vendor/postgres/src/bytes.jsnew file mode 100644index 0000000000..fa48786744--- /dev/null+++ b/vendor/postgres/src/bytes.js@@ -0,0 +1,78 @@+const size = 256+let buffer = Buffer.allocUnsafe(size)++const messages = 'BCcDdEFfHPpQSX'.split('').reduce((acc, x) => {+ const v = x.charCodeAt(0)+ acc[x] = () => {+ buffer[0] = v+ b.i = 5+ return b+ }+ return acc+}, {})++const b = Object.assign(reset, messages, {+ N: String.fromCharCode(0),+ i: 0,+ inc(x) {+ b.i += x+ return b+ },+ str(x) {+ const length = Buffer.byteLength(x)+ fit(length)+ b.i += buffer.write(x, b.i, length, 'utf8')+ return b+ },+ i16(x) {+ fit(2)+ buffer.writeUInt16BE(x, b.i)+ b.i += 2+ return b+ },+ i32(x, i) {+ if (i || i === 0) {+ buffer.writeUInt32BE(x, i)+ return b+ }+ fit(4)+ buffer.writeUInt32BE(x, b.i)+ b.i += 4+ return b+ },+ z(x) {+ fit(x)+ buffer.fill(0, b.i, b.i + x)+ b.i += x+ return b+ },+ raw(x) {+ buffer = Buffer.concat([buffer.subarray(0, b.i), x])+ b.i = buffer.length+ return b+ },+ end(at = 1) {+ buffer.writeUInt32BE(b.i - at, at)+ const out = buffer.subarray(0, b.i)+ b.i = 0+ buffer = Buffer.allocUnsafe(size)+ return out+ }+})++export default b++function fit(x) {+ if (buffer.length - b.i < x) {+ const prev = buffer+ , length = prev.length++ buffer = Buffer.allocUnsafe(length + (length >> 1) + x)+ prev.copy(buffer)+ }+}++function reset() {+ b.i = 0+ return b+}diff --git a/vendor/postgres/src/connection.js b/vendor/postgres/src/connection.jsnew file mode 100644index 0000000000..617335d1b0--- /dev/null+++ b/vendor/postgres/src/connection.js@@ -0,0 +1,1079 @@+import net from 'net'+import tls from 'tls'+import crypto from 'crypto'+import Stream from 'stream'+import { performance } from 'perf_hooks'++import { stringify, handleValue, arrayParser, arraySerializer } from './types.js'+import { Errors } from './errors.js'+import Result from './result.js'+import Queue from './queue.js'+import { Query, CLOSE } from './query.js'+import b from './bytes.js'++export default Connection++let uid = 1++const Sync = b().S().end()+ , Flush = b().H().end()+ , SSLRequest = b().i32(8).i32(80877103).end(8)+ , ExecuteUnnamed = Buffer.concat([b().E().str(b.N).i32(0).end(), Sync])+ , DescribeUnnamed = b().D().str('S').str(b.N).end()+ , noop = () => { /* noop */ }++const retryRoutines = new Set([+ 'FetchPreparedStatement',+ 'RevalidateCachedQuery',+ 'transformAssignedExpr'+])++const errorFields = {+ 83 : 'severity_local', // S+ 86 : 'severity', // V+ 67 : 'code', // C+ 77 : 'message', // M+ 68 : 'detail', // D+ 72 : 'hint', // H+ 80 : 'position', // P+ 112 : 'internal_position', // p+ 113 : 'internal_query', // q+ 87 : 'where', // W+ 115 : 'schema_name', // s+ 116 : 'table_name', // t+ 99 : 'column_name', // c+ 100 : 'data type_name', // d+ 110 : 'constraint_name', // n+ 70 : 'file', // F+ 76 : 'line', // L+ 82 : 'routine' // R+}++function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) {+ const {+ sslnegotiation,+ ssl,+ max,+ user,+ host,+ port,+ database,+ parsers,+ transform,+ onnotice,+ onnotify,+ onparameter,+ max_pipeline,+ keep_alive,+ backoff,+ target_session_attrs+ } = options++ const sent = Queue()+ , id = uid+++ , backend = { pid: null, secret: null }+ , idleTimer = timer(end, options.idle_timeout)+ , lifeTimer = timer(end, options.max_lifetime)+ , connectTimer = timer(connectTimedOut, options.connect_timeout)++ let socket = null+ , cancelMessage+ , cancelResolve+ , cancelReject+ , cancelError+ , errorResponse = null+ , result = new Result()+ , incoming = Buffer.alloc(0)+ , needsTypes = options.fetch_types+ , backendParameters = {}+ , statements = {}+ , statementId = Math.random().toString(36).slice(2)+ , statementCount = 1+ , closedTime = 0+ , remaining = 0+ , hostIndex = 0+ , retries = 0+ , length = 0+ , delay = 0+ , rows = 0+ , serverSignature = null+ , nextWriteTimer = null+ , terminated = false+ , incomings = null+ , results = null+ , initial = null+ , ending = null+ , stream = null+ , chunk = null+ , ended = null+ , nonce = null+ , query = null+ , final = null++ const connection = {+ queue: queues.closed,+ idleTimer,+ connect(query) {+ initial = query+ reconnect()+ },+ terminate,+ execute,+ cancel,+ end,+ count: 0,+ id+ }++ queues.closed && queues.closed.push(connection)++ return connection++ async function createSocket() {+ let x+ try {+ x = options.socket+ ? (await Promise.resolve(options.socket(options)))+ : new net.Socket()+ } catch (e) {+ error(e)+ return+ }+ x.on('error', error)+ x.on('close', closed)+ x.on('drain', drain)+ return x+ }++ async function cancel({ pid, secret }, resolve, reject) {+ cancelResolve = resolve+ cancelReject = reject+ try {+ cancelMessage = b().i32(16).i32(80877102).i32(pid).i32(secret).end(16)+ await connect()+ if (!socket)+ reject(cancelError || Errors.connection('CONNECTION_CLOSED', options))+ } catch (error) {+ reject(error)+ }+ }++ function execute(q) {+ if (terminated)+ return queryError(q, Errors.connection('CONNECTION_DESTROYED', options))++ if (stream)+ return queryError(q, Errors.generic('COPY_IN_PROGRESS', 'You cannot execute queries during copy'))++ if (q.cancelled)+ return++ try {+ q.state = backend+ query+ ? sent.push(q)+ : (query = q, query.active = true)++ build(q)+ const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)+ return write(toBuffer(q))+ && !q.describeFirst+ && !q.cursorFn+ && sent.length < max_pipeline+ && mayPipeline+ } catch (error) {+ sent.length === 0 && write(Sync)+ errored(error)+ return true+ }+ }++ function toBuffer(q) {+ if (q.parameters.length >= 65534)+ throw Errors.generic('MAX_PARAMETERS_EXCEEDED', 'Max number of parameters (65534) exceeded')++ return q.options.simple+ ? b().Q().str(q.statement.string + b.N).end()+ : q.describeFirst+ ? Buffer.concat([describe(q), Flush])+ : q.prepare+ ? q.prepared+ ? prepared(q)+ : Buffer.concat([describe(q), prepared(q)])+ : unnamed(q)+ }++ function describe(q) {+ return Buffer.concat([+ Parse(q.statement.string, q.parameters, q.statement.types, q.statement.name),+ Describe('S', q.statement.name)+ ])+ }++ function prepared(q) {+ return Buffer.concat([+ Bind(q.parameters, q.statement.types, q.statement.name, q.cursorName),+ q.cursorFn+ ? Execute('', q.cursorRows)+ : ExecuteUnnamed+ ])+ }++ function unnamed(q) {+ return Buffer.concat([+ Parse(q.statement.string, q.parameters, q.statement.types),+ DescribeUnnamed,+ prepared(q)+ ])+ }++ function build(q) {+ const parameters = []+ , types = []++ const string = stringify(q, q.strings[0], q.args[0], parameters, types, options)++ !q.tagged && q.args.forEach(x => handleValue(x, parameters, types, options))++ q.prepare = options.prepare && ('prepare' in q.options ? q.options.prepare : true)+ q.string = string+ q.signature = q.prepare && types + string+ q.onlyDescribe && (delete statements[q.signature])+ q.parameters = q.parameters || parameters+ q.prepared = q.prepare && q.signature in statements+ q.describeFirst = q.onlyDescribe || (parameters.length && !q.prepared)+ q.statement = q.prepared+ ? statements[q.signature]+ : { string, types, name: q.prepare ? statementId + statementCount++ : '' }++ typeof options.debug === 'function' && options.debug(id, string, parameters, types)+ }++ function write(x, fn) {+ chunk = chunk ? Buffer.concat([chunk, x]) : Buffer.from(x)+ if (fn || chunk.length >= 1024)+ return nextWrite(fn)+ nextWriteTimer === null && (nextWriteTimer = setImmediate(nextWrite))+ return true+ }++ function nextWrite(fn) {+ const x = socket.write(chunk, fn)+ nextWriteTimer !== null && clearImmediate(nextWriteTimer)+ chunk = nextWriteTimer = null+ return x+ }++ function connectTimedOut() {+ errored(Errors.connection('CONNECT_TIMEOUT', options, socket))+ socket.destroy()+ }++ async function secure() {+ if (sslnegotiation !== 'direct') {+ write(SSLRequest)+ const canSSL = await new Promise(r => socket.once('data', x => r(x[0] === 83))) // S++ if (!canSSL && ssl === 'prefer')+ return connected()+ }++ const options = {+ socket,+ servername: net.isIP(socket.host) ? undefined : socket.host+ }++ if (sslnegotiation === 'direct')+ options.ALPNProtocols = ['postgresql']++ if (ssl === 'require' || ssl === 'allow' || ssl === 'prefer')+ options.rejectUnauthorized = false+ else if (typeof ssl === 'object')+ Object.assign(options, ssl)++ socket.removeAllListeners()+ socket = tls.connect(options)+ socket.on('secureConnect', connected)+ socket.on('error', error)+ socket.on('close', closed)+ socket.on('drain', drain)+ }++ /* c8 ignore next 3 */+ function drain() {+ !query && !connection.reserved && onopen(connection)+ }++ function data(x) {+ if (incomings) {+ incomings.push(x)+ remaining -= x.length+ if (remaining > 0)+ return+ }++ incoming = incomings+ ? Buffer.concat(incomings, length - remaining)+ : incoming.length === 0+ ? x+ : Buffer.concat([incoming, x], incoming.length + x.length)++ while (incoming.length > 4) {+ length = incoming.readUInt32BE(1)+ if (length >= incoming.length) {+ remaining = length - incoming.length+ incomings = [incoming]+ break+ }++ try {+ handle(incoming.subarray(0, length + 1))+ } catch (e) {+ query && (query.cursorFn || query.describeFirst) && write(Sync)+ errored(e)+ }+ incoming = incoming.subarray(length + 1)+ remaining = 0+ incomings = null+ }+ }++ async function connect() {+ terminated = false+ backendParameters = {}+ socket || (socket = await createSocket())++ if (!socket)+ return++ connectTimer.start()++ if (options.socket)+ return ssl ? secure() : connected()++ socket.on('connect', ssl ? secure : connected)++ if (options.path)+ return socket.connect(options.path)++ socket.ssl = ssl+ socket.connect(port[hostIndex], host[hostIndex])+ socket.host = host[hostIndex]+ socket.port = port[hostIndex]++ hostIndex = (hostIndex + 1) % port.length+ }++ function reconnect() {+ setTimeout(connect, closedTime ? Math.max(0, closedTime + delay - performance.now()) : 0)+ }++ function connected() {+ try {+ statements = {}+ needsTypes = options.fetch_types+ statementId = Math.random().toString(36).slice(2)+ statementCount = 1+ lifeTimer.start()+ socket.on('data', data)+ keep_alive && socket.setKeepAlive && socket.setKeepAlive(true, 1000 * keep_alive)+ const s = StartupMessage()+ write(s)+ } catch (err) {+ error(err)+ }+ }++ function error(err) {+ if (cancelMessage)+ cancelError = err+ if (connection.queue === queues.connecting && options.host[retries + 1])+ return++ errored(err)+ while (sent.length)+ queryError(sent.shift(), err)+ }++ function errored(err) {+ if (cancelMessage)+ cancelError = err+ stream && (stream.destroy(err), stream = null)+ query && queryError(query, err)+ initial && (queryError(initial, err), initial = null)+ }++ function queryError(query, err) {+ if (query.reserve)+ return query.reject(err)++ if (!err || typeof err !== 'object')+ err = new Error(err)++ 'query' in err || 'parameters' in err || Object.defineProperties(err, {+ stack: { value: err.stack + query.origin.replace(/.*\n/, '\n'), enumerable: options.debug },+ query: { value: query.string, enumerable: options.debug },+ parameters: { value: query.parameters, enumerable: options.debug },+ args: { value: query.args, enumerable: options.debug },+ types: { value: query.statement && query.statement.types, enumerable: options.debug }+ })+ query.reject(err)+ }++ function end() {+ return ending || (+ !connection.reserved && onend(connection),+ !connection.reserved && !initial && !query && sent.length === 0+ ? (terminate(), new Promise(r => socket && socket.readyState !== 'closed' ? socket.once('close', r) : r()))+ : ending = new Promise(r => ended = r)+ )+ }++ function terminate() {+ terminated = true+ if (stream || query || initial || sent.length)+ error(Errors.connection('CONNECTION_DESTROYED', options))++ clearImmediate(nextWriteTimer)+ if (socket) {+ socket.removeListener('data', data)+ socket.removeListener('connect', connected)+ socket.readyState === 'open' && socket.end(b().X().end())+ }+ ended && (ended(), ending = ended = null)+ }++ async function closed(hadError) {+ incoming = Buffer.alloc(0)+ remaining = 0+ incomings = null+ clearImmediate(nextWriteTimer)+ socket.removeListener('data', data)+ socket.removeListener('connect', connected)+ idleTimer.cancel()+ lifeTimer.cancel()+ connectTimer.cancel()++ socket.removeAllListeners()+ socket = null++ if (cancelMessage)+ return cancelError || hadError+ ? cancelReject(cancelError || Errors.connection('CONNECTION_CLOSED', options))+ : cancelResolve()++ if (initial)+ return reconnect()++ !hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))+ closedTime = performance.now()+ hadError && options.shared.retries+++ delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000+ onclose(connection, Errors.connection('CONNECTION_CLOSED', options, socket))+ }++ /* Handlers */+ function handle(xs, x = xs[0]) {+ (+ x === 68 ? DataRow : // D+ x === 100 ? CopyData : // d+ x === 65 ? NotificationResponse : // A+ x === 83 ? ParameterStatus : // S+ x === 90 ? ReadyForQuery : // Z+ x === 67 ? CommandComplete : // C+ x === 50 ? BindComplete : // 2+ x === 49 ? ParseComplete : // 1+ x === 116 ? ParameterDescription : // t+ x === 84 ? RowDescription : // T+ x === 82 ? Authentication : // R+ x === 110 ? NoData : // n+ x === 75 ? BackendKeyData : // K+ x === 69 ? ErrorResponse : // E+ x === 115 ? PortalSuspended : // s+ x === 51 ? CloseComplete : // 3+ x === 71 ? CopyInResponse : // G+ x === 78 ? NoticeResponse : // N+ x === 72 ? CopyOutResponse : // H+ x === 99 ? CopyDone : // c+ x === 73 ? EmptyQueryResponse : // I+ x === 86 ? FunctionCallResponse : // V+ x === 118 ? NegotiateProtocolVersion : // v+ x === 87 ? CopyBothResponse : // W+ /* c8 ignore next */+ UnknownMessage+ )(xs)+ }++ function DataRow(x) {+ let index = 7+ let length+ let column+ let value++ const row = query.isRaw ? new Array(query.statement.columns.length) : {}+ for (let i = 0; i < query.statement.columns.length; i++) {+ column = query.statement.columns[i]+ length = x.readInt32BE(index)+ index += 4++ value = length === -1+ ? null+ : query.isRaw === true+ ? x.subarray(index, index += length)+ : column.parser === undefined+ ? x.toString('utf8', index, index += length)+ : column.parser.array === true+ ? column.parser(x.toString('utf8', index + 1, index += length))+ : column.parser(x.toString('utf8', index, index += length))++ query.isRaw+ ? (row[i] = query.isRaw === true+ ? value+ : transform.value.from ? transform.value.from(value, column) : value)+ : (row[column.name] = transform.value.from ? transform.value.from(value, column) : value)+ }++ query.forEachFn+ ? query.forEachFn(transform.row.from ? transform.row.from(row) : row, result)+ : (result[rows++] = transform.row.from ? transform.row.from(row) : row)+ }++ function ParameterStatus(x) {+ const [k, v] = x.toString('utf8', 5, x.length - 1).split(b.N)+ backendParameters[k] = v+ if (options.parameters[k] !== v) {+ options.parameters[k] = v+ onparameter && onparameter(k, v)+ }+ }++ function ReadyForQuery(x) {+ if (query) {+ if (errorResponse) {+ query.retried+ ? errored(query.retried)+ : query.prepared && retryRoutines.has(errorResponse.routine)+ ? retry(query, errorResponse)+ : errored(errorResponse)+ } else {+ query.resolve(results || result)+ }+ } else if (errorResponse) {+ errored(errorResponse)+ }++ query = results = errorResponse = null+ result = new Result()+ connectTimer.cancel()++ if (initial) {+ if (target_session_attrs) {+ if (!backendParameters.in_hot_standby || !backendParameters.default_transaction_read_only)+ return fetchState()+ else if (tryNext(target_session_attrs, backendParameters))+ return terminate()+ }++ if (needsTypes) {+ initial.reserve && (initial = null)+ return fetchArrayTypes()+ }++ const reserving = initial && initial.reserve+ initial && !reserving && execute(initial)+ options.shared.retries = retries = 0+ initial = null+ if (!reserving)+ return+ }++ while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))+ Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)++ if (query)+ return // Consider opening if able and sent.length < 50++ connection.reserved+ ? !connection.reserved.release && x[5] === 73 // I+ ? ending+ ? terminate()+ : connection.reserved(true)+ : connection.reserved()+ : ending+ ? terminate()+ : onopen(connection)+ }++ function CommandComplete(x) {+ rows = 0++ for (let i = x.length - 1; i > 0; i--) {+ if (x[i] === 32 && x[i + 1] < 58 && result.count === null)+ result.count = +x.toString('utf8', i + 1, x.length - 1)+ if (x[i - 1] >= 65) {+ result.command = x.toString('utf8', 5, i)+ result.state = backend+ break+ }+ }++ final && (final(), final = null)++ if (result.command === 'BEGIN' && max !== 1 && !connection.reserved)+ return errored(Errors.generic('UNSAFE_TRANSACTION', 'Only use sql.begin, sql.reserved or max: 1'))++ if (query.options.simple)+ return BindComplete()++ if (query.cursorFn) {+ result.count && query.cursorFn(result)+ write(Sync)+ }+ }++ function ParseComplete() {+ query.parsing = false+ }++ function BindComplete() {+ !result.statement && (result.statement = query.statement)+ result.columns = query.statement.columns+ }++ function ParameterDescription(x) {+ const length = x.readUInt16BE(5)++ for (let i = 0; i < length; ++i)+ !query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))++ query.prepare && (statements[query.signature] = query.statement)+ query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false)+ }++ function RowDescription(x) {+ if (result.command) {+ results = results || [result]+ results.push(result = new Result())+ result.count = null+ query.statement.columns = null+ }++ const length = x.readUInt16BE(5)+ let index = 7+ let start++ query.statement.columns = Array(length)++ for (let i = 0; i < length; ++i) {+ start = index+ while (x[index++] !== 0);+ const table = x.readUInt32BE(index)+ const number = x.readUInt16BE(index + 4)+ const type = x.readUInt32BE(index + 6)+ query.statement.columns[i] = {+ name: transform.column.from+ ? transform.column.from(x.toString('utf8', start, index - 1))+ : x.toString('utf8', start, index - 1),+ parser: parsers[type],+ table,+ number,+ type+ }+ index += 18+ }++ result.statement = query.statement+ if (query.onlyDescribe)+ return (query.resolve(query.statement), write(Sync))+ }++ async function Authentication(x, type = x.readUInt32BE(5)) {+ (+ type === 3 ? AuthenticationCleartextPassword :+ type === 5 ? AuthenticationMD5Password :+ type === 10 ? SASL :+ type === 11 ? SASLContinue :+ type === 12 ? SASLFinal :+ type !== 0 ? UnknownAuth :+ noop+ )(x, type)+ }++ /* c8 ignore next 5 */+ async function AuthenticationCleartextPassword() {+ const payload = await Pass()+ write(+ b().p().str(payload).z(1).end()+ )+ }++ async function AuthenticationMD5Password(x) {+ const payload = 'md5' + (+ await md5(+ Buffer.concat([+ Buffer.from(await md5((await Pass()) + user)),+ x.subarray(9)+ ])+ )+ )+ write(+ b().p().str(payload).z(1).end()+ )+ }++ async function SASL() {+ nonce = (await crypto.randomBytes(18)).toString('base64')+ b().p().str('SCRAM-SHA-256' + b.N)+ const i = b.i+ write(b.inc(4).str('n,,n=*,r=' + nonce).i32(b.i - i - 4, i).end())+ }++ async function SASLContinue(x) {+ const res = x.toString('utf8', 9).split(',').reduce((acc, x) => (acc[x[0]] = x.slice(2), acc), {})++ const saltedPassword = await crypto.pbkdf2Sync(+ await Pass(),+ Buffer.from(res.s, 'base64'),+ parseInt(res.i), 32,+ 'sha256'+ )++ const clientKey = await hmac(saltedPassword, 'Client Key')++ const auth = 'n=*,r=' + nonce + ','+ + 'r=' + res.r + ',s=' + res.s + ',i=' + res.i+ + ',c=biws,r=' + res.r++ serverSignature = (await hmac(await hmac(saltedPassword, 'Server Key'), auth)).toString('base64')++ const payload = 'c=biws,r=' + res.r + ',p=' + xor(+ clientKey, Buffer.from(await hmac(await sha256(clientKey), auth))+ ).toString('base64')++ write(+ b().p().str(payload).end()+ )+ }++ function SASLFinal(x) {+ if (x.toString('utf8', 9).split(b.N, 1)[0].slice(2) === serverSignature)+ return+ /* c8 ignore next 5 */+ errored(Errors.generic('SASL_SIGNATURE_MISMATCH', 'The server did not return the correct signature'))+ socket.destroy()+ }++ function Pass() {+ return Promise.resolve(typeof options.pass === 'function'+ ? options.pass()+ : options.pass+ )+ }++ function NoData() {+ result.statement = query.statement+ result.statement.columns = []+ if (query.onlyDescribe)+ return (query.resolve(query.statement), write(Sync))+ }++ function BackendKeyData(x) {+ backend.pid = x.readUInt32BE(5)+ backend.secret = x.readUInt32BE(9)+ }++ async function fetchArrayTypes() {+ needsTypes = false+ const types = await new Query([`+ select b.oid, b.typarray+ from pg_catalog.pg_type a+ left join pg_catalog.pg_type b on b.oid = a.typelem+ where a.typcategory = 'A'+ group by b.oid, b.typarray+ order by b.oid+ `], [], execute)+ types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))+ }++ function addArrayType(oid, typarray) {+ if (!!options.parsers[typarray] && !!options.serializers[typarray]) return+ const parser = options.parsers[oid]+ options.shared.typeArrayMap[oid] = typarray+ options.parsers[typarray] = (xs) => arrayParser(xs, parser, typarray)+ options.parsers[typarray].array = true+ options.serializers[typarray] = (xs) => arraySerializer(xs, options.serializers[oid], options, typarray)+ }++ function tryNext(x, xs) {+ return (+ (x === 'read-write' && xs.default_transaction_read_only === 'on') ||+ (x === 'read-only' && xs.default_transaction_read_only === 'off') ||+ (x === 'primary' && xs.in_hot_standby === 'on') ||+ (x === 'standby' && xs.in_hot_standby === 'off') ||+ (x === 'prefer-standby' && xs.in_hot_standby === 'off' && options.host[retries])+ )+ }++ function fetchState() {+ const query = new Query([`+ show transaction_read_only;+ select pg_catalog.pg_is_in_recovery()+ `], [], execute, null, { simple: true })+ query.resolve = ([[a], [b]]) => {+ backendParameters.default_transaction_read_only = a.transaction_read_only+ backendParameters.in_hot_standby = b.pg_is_in_recovery ? 'on' : 'off'+ }+ query.execute()+ }++ function ErrorResponse(x) {+ if (query) {+ (query.cursorFn || query.describeFirst) && write(Sync)+ errorResponse = Errors.postgres(parseError(x))+ } else {+ errored(Errors.postgres(parseError(x)))+ }+ }++ function retry(q, error) {+ delete statements[q.signature]+ q.retried = error+ execute(q)+ }++ function NotificationResponse(x) {+ if (!onnotify)+ return++ let index = 9+ while (x[index++] !== 0);+ onnotify(+ x.toString('utf8', 9, index - 1),+ x.toString('utf8', index, x.length - 1)+ )+ }++ async function PortalSuspended() {+ try {+ const x = await Promise.resolve(query.cursorFn(result))+ rows = 0+ x === CLOSE+ ? write(Close(query.portal))+ : (result = new Result(), write(Execute('', query.cursorRows)))+ } catch (err) {+ write(Sync)+ query.reject(err)+ }+ }++ function CloseComplete() {+ result.count && query.cursorFn(result)+ query.resolve(result)+ }++ function CopyInResponse() {+ stream = new Stream.Writable({+ autoDestroy: true,+ write(chunk, encoding, callback) {+ socket.write(b().d().raw(chunk).end(), callback)+ },+ destroy(error, callback) {+ callback(error)+ socket.write(b().f().str(error + b.N).end())+ stream = null+ },+ final(callback) {+ socket.write(b().c().end())+ final = callback+ stream = null+ }+ })+ query.resolve(stream)+ }++ function CopyOutResponse() {+ stream = new Stream.Readable({+ read() { socket.resume() }+ })+ query.resolve(stream)+ }++ /* c8 ignore next 3 */+ function CopyBothResponse() {+ stream = new Stream.Duplex({+ autoDestroy: true,+ read() { socket.resume() },+ /* c8 ignore next 11 */+ write(chunk, encoding, callback) {+ socket.write(b().d().raw(chunk).end(), callback)+ },+ destroy(error, callback) {+ callback(error)+ socket.write(b().f().str(error + b.N).end())+ stream = null+ },+ final(callback) {+ socket.write(b().c().end())+ final = callback+ }+ })+ query.resolve(stream)+ }++ function CopyData(x) {+ stream && (stream.push(x.subarray(5)) || socket.pause())+ }++ function CopyDone() {+ stream && stream.push(null)+ stream = null+ }++ function NoticeResponse(x) {+ onnotice+ ? onnotice(parseError(x))+ : console.log(parseError(x)) // eslint-disable-line++ }++ /* c8 ignore next 3 */+ function EmptyQueryResponse() {+ /* noop */+ }++ /* c8 ignore next 3 */+ function FunctionCallResponse() {+ errored(Errors.notSupported('FunctionCallResponse'))+ }++ /* c8 ignore next 3 */+ function NegotiateProtocolVersion() {+ errored(Errors.notSupported('NegotiateProtocolVersion'))+ }++ /* c8 ignore next 3 */+ function UnknownMessage(x) {+ console.error('Postgres.js : Unknown Message:', x[0]) // eslint-disable-line+ }++ /* c8 ignore next 3 */+ function UnknownAuth(x, type) {+ console.error('Postgres.js : Unknown Auth:', type) // eslint-disable-line+ }++ /* Messages */+ function Bind(parameters, types, statement = '', portal = '') {+ let prev+ , type++ b().B().str(portal + b.N).str(statement + b.N).i16(0).i16(parameters.length)++ parameters.forEach((x, i) => {+ if (x === null)+ return b.i32(0xFFFFFFFF)++ type = types[i]+ parameters[i] = x = type in options.serializers+ ? options.serializers[type](x)+ : '' + x++ prev = b.i+ b.inc(4).str(x).i32(b.i - prev - 4, prev)+ })++ b.i16(0)++ return b.end()+ }++ function Parse(str, parameters, types, name = '') {+ b().P().str(name + b.N).str(str + b.N).i16(parameters.length)+ parameters.forEach((x, i) => b.i32(types[i] || 0))+ return b.end()+ }++ function Describe(x, name = '') {+ return b().D().str(x).str(name + b.N).end()+ }++ function Execute(portal = '', rows = 0) {+ return Buffer.concat([+ b().E().str(portal + b.N).i32(rows).end(),+ Flush+ ])+ }++ function Close(portal = '') {+ return Buffer.concat([+ b().C().str('P').str(portal + b.N).end(),+ b().S().end()+ ])+ }++ function StartupMessage() {+ return cancelMessage || b().inc(4).i16(3).z(2).str(+ Object.entries(Object.assign({+ user,+ database,+ client_encoding: 'UTF8'+ },+ options.connection+ )).filter(([, v]) => v).map(([k, v]) => k + b.N + v).join(b.N)+ ).z(2).end(0)+ }++}++function parseError(x) {+ const error = {}+ let start = 5+ for (let i = 5; i < x.length - 1; i++) {+ if (x[i] === 0) {+ error[errorFields[x[start]]] = x.toString('utf8', start + 1, i)+ start = i + 1+ }+ }+ return error+}++function md5(x) {+ return crypto.createHash('md5').update(x).digest('hex')+}++function hmac(key, x) {+ return crypto.createHmac('sha256', key).update(x).digest()+}++function sha256(x) {+ return crypto.createHash('sha256').update(x).digest()+}++function xor(a, b) {+ const length = Math.max(a.length, b.length)+ const buffer = Buffer.allocUnsafe(length)+ for (let i = 0; i < length; i++)+ buffer[i] = a[i] ^ b[i]+ return buffer+}++function timer(fn, seconds) {+ seconds = typeof seconds === 'function' ? seconds() : seconds+ if (!seconds)+ return { cancel: noop, start: noop }++ let timer+ return {+ cancel() {+ timer && (clearTimeout(timer), timer = null)+ },+ start() {+ timer && clearTimeout(timer)+ timer = setTimeout(done, seconds * 1000, arguments)+ }+ }++ function done(args) {+ fn.apply(null, args)+ timer = null+ }+}diff --git a/vendor/postgres/src/errors.js b/vendor/postgres/src/errors.jsnew file mode 100644index 0000000000..0ff83c428b--- /dev/null+++ b/vendor/postgres/src/errors.js@@ -0,0 +1,53 @@+export class PostgresError extends Error {+ constructor(x) {+ super(x.message)+ this.name = this.constructor.name+ Object.assign(this, x)+ }+}++export const Errors = {+ connection,+ postgres,+ generic,+ notSupported+}++function connection(x, options, socket) {+ const { host, port } = socket || options+ const error = Object.assign(+ new Error(('write ' + x + ' ' + (options.path || (host + ':' + port)))),+ {+ code: x,+ errno: x,+ address: options.path || host+ }, options.path ? {} : { port: port }+ )+ Error.captureStackTrace(error, connection)+ return error+}++function postgres(x) {+ const error = new PostgresError(x)+ Error.captureStackTrace(error, postgres)+ return error+}++function generic(code, message) {+ const error = Object.assign(new Error(code + ': ' + message), { code })+ Error.captureStackTrace(error, generic)+ return error+}++/* c8 ignore next 10 */+function notSupported(x) {+ const error = Object.assign(+ new Error(x + ' (B) is not supported'),+ {+ code: 'MESSAGE_NOT_SUPPORTED',+ name: x+ }+ )+ Error.captureStackTrace(error, notSupported)+ return error+}diff --git a/vendor/postgres/src/index.js b/vendor/postgres/src/index.jsnew file mode 100644index 0000000000..4c9192680a--- /dev/null+++ b/vendor/postgres/src/index.js@@ -0,0 +1,680 @@+import os from 'os'+import fs from 'fs'++import {+ mergeUserTypes,+ inferType,+ Parameter,+ Identifier,+ Builder,+ toPascal,+ pascal,+ toCamel,+ camel,+ toKebab,+ kebab,+ fromPascal,+ fromCamel,+ fromKebab+} from './types.js'++import Connection from './connection.js'+import { Query, CLOSE } from './query.js'+import Queue from './queue.js'+import { Errors, PostgresError } from './errors.js'+import Subscribe from './subscribe.js'+import largeObject from './large.js'++Object.assign(Postgres, {+ PostgresError,+ toPascal,+ pascal,+ toCamel,+ camel,+ toKebab,+ kebab,+ fromPascal,+ fromCamel,+ fromKebab,+ BigInt: {+ to: 20,+ from: [20],+ parse: x => BigInt(x), // eslint-disable-line+ serialize: x => x.toString()+ }+})++export default Postgres++function Postgres(a, b) {+ const options = parseOptions(a, b)+ , subscribe = options.no_subscribe || Subscribe(Postgres, { ...options })++ let ending = false++ const queries = Queue()+ , connecting = Queue()+ , reserved = Queue()+ , closed = Queue()+ , ended = Queue()+ , open = Queue()+ , busy = Queue()+ , full = Queue()+ , queues = { connecting, reserved, closed, ended, open, busy, full }++ const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose }))++ const sql = Sql(handler)++ Object.assign(sql, {+ get parameters() { return options.parameters },+ largeObject: largeObject.bind(null, sql),+ subscribe,+ CLOSE,+ END: CLOSE,+ PostgresError,+ options,+ reserve,+ listen,+ begin,+ close,+ end+ })++ return sql++ function Sql(handler) {+ handler.debug = options.debug++ Object.entries(options.types).reduce((acc, [name, type]) => {+ acc[name] = (x) => new Parameter(x, type.to)+ return acc+ }, typed)++ Object.assign(sql, {+ types: typed,+ typed,+ unsafe,+ notify,+ array,+ json,+ file+ })++ return sql++ function typed(value, type) {+ return new Parameter(value, type)+ }++ function sql(strings, ...args) {+ const query = strings && Array.isArray(strings.raw)+ ? new Query(strings, args, handler, cancel)+ : typeof strings === 'string' && !args.length+ ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings)+ : new Builder(strings, args)+ return query+ }++ function unsafe(string, args = [], options = {}) {+ arguments.length === 2 && !Array.isArray(args) && (options = args, args = [])+ const query = new Query([string], args, handler, cancel, {+ prepare: false,+ ...options,+ simple: 'simple' in options ? options.simple : args.length === 0+ })+ return query+ }++ function file(path, args = [], options = {}) {+ arguments.length === 2 && !Array.isArray(args) && (options = args, args = [])+ const query = new Query([], args, (query) => {+ fs.readFile(path, 'utf8', (err, string) => {+ if (err)+ return query.reject(err)++ query.strings = [string]+ handler(query)+ })+ }, cancel, {+ ...options,+ simple: 'simple' in options ? options.simple : args.length === 0+ })+ return query+ }+ }++ async function listen(name, fn, onlisten) {+ const listener = { fn, onlisten }++ const sql = listen.sql || (listen.sql = Postgres({+ ...options,+ max: 1,+ idle_timeout: null,+ max_lifetime: null,+ fetch_types: false,+ onclose() {+ Object.entries(listen.channels).forEach(([name, { listeners }]) => {+ delete listen.channels[name]+ Promise.all(listeners.map(l => listen(name, l.fn, l.onlisten).catch(() => { /* noop */ })))+ })+ },+ onnotify(c, x) {+ c in listen.channels && listen.channels[c].listeners.forEach(l => l.fn(x))+ }+ }))++ const channels = listen.channels || (listen.channels = {})+ , exists = name in channels++ if (exists) {+ channels[name].listeners.push(listener)+ const result = await channels[name].result+ listener.onlisten && listener.onlisten()+ return { state: result.state, unlisten }+ }++ channels[name] = { result: sql`listen ${+ sql.unsafe('"' + name.replace(/"/g, '""') + '"')+ }`, listeners: [listener] }+ const result = await channels[name].result+ listener.onlisten && listener.onlisten()+ return { state: result.state, unlisten }++ async function unlisten() {+ if (name in channels === false)+ return++ channels[name].listeners = channels[name].listeners.filter(x => x !== listener)+ if (channels[name].listeners.length)+ return++ delete channels[name]+ return sql`unlisten ${+ sql.unsafe('"' + name.replace(/"/g, '""') + '"')+ }`+ }+ }++ async function notify(channel, payload) {+ return await sql`select pg_notify(${ channel }, ${ '' + payload })`+ }++ function own(c) {+ const queue = Queue()+ let busy = false, fence = null, holding = null, releasing = false+ const reservation = c.reserved = (ended = false) => {+ if (c.reserved !== reservation)+ return+ busy = false+ if (ended) {+ releasing = true+ reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction has ended'))+ }+ const completed = fence+ fence = null+ if (completed && completed.cancelPromise) {+ holding = completed+ completed.cancelPromise.then(() => {+ if (c.reserved !== reservation || holding !== completed)+ return+ holding = null+ pump()+ }, reservation.discard)+ } else {+ pump()+ }+ }+ reservation.enqueue = q => {+ if (c.reserved !== reservation || releasing)+ return q.reject(Errors.generic('CONNECTION_CLOSED', 'Connection is no longer owned'))+ queue.push(q)+ pump()+ }+ reservation.reject = error => {+ while (queue.length)+ queue.shift().reject(error)+ }+ reservation.discard = () => {+ if (c.reserved !== reservation)+ return+ c.reserved = null+ reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Connection was discarded'))+ c.terminate()+ }+ reservation.releaseConnection = () => {+ if (c.reserved !== reservation)+ return+ releasing = true+ pump()+ }+ return reservation++ function pump() {+ if (c.reserved !== reservation || holding || fence)+ return+ while (queue.length) {+ const q = queue.peek()+ if (q.cancelled) {+ queue.shift()+ continue+ }+ if (busy && (q.options.cancelFence || c.queue === full))+ return+ queue.shift()+ busy = true+ if (q.options.cancelFence)+ fence = q+ const ready = c.execute(q)+ move(c, ready ? reserved : full)+ if (fence || !ready)+ return+ }+ if (!busy) {+ if (releasing) {+ c.reserved = null+ onopen(c)+ } else {+ move(c, reserved)+ }+ }+ }+ }++ async function reserve({ signal } = {}) {+ signal && signal.throwIfAborted()+ if (ending)+ throw Errors.connection('CONNECTION_ENDED', options, options)+ const sql = open.length+ ? claim(open.shift())+ : await new Promise((resolve, reject) => {+ let settled = false+ const query = {+ reserve: c => { if (settle()) resolve(claim(c)) },+ reject: error => { if (settle()) reject(error) }+ }+ const abort = () => query.reject(signal.reason)+ function settle() {+ if (settled)+ return false+ settled = true+ queries.remove(query)+ signal && signal.removeEventListener('abort', abort)+ return true+ }+ if (signal)+ signal.addEventListener('abort', abort, { once: true })+ queries.push(query)+ closed.length && connect(closed.shift(), query)+ })++ if (signal && signal.aborted) {+ sql.release()+ signal.throwIfAborted()+ }++ return sql++ function claim(c) {+ move(c, reserved)+ const reservation = own(c)+ reservation.release = true+ const sql = Sql(reservation.enqueue)+ sql.release = reservation.releaseConnection+ sql.discard = reservation.discard+ return sql+ }+ }++ async function begin(options, fn) {+ !fn && (fn = options, options = '')+ let savepoints = 0+ , connection+ , prepare = null++ try {+ await sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()+ return await Promise.race([+ scope(connection, fn),+ new Promise((_, reject) => connection.onclose = reject)+ ])+ } catch (error) {+ throw error+ }++ async function scope(c, fn, name) {+ const reservation = c.reserved+ if (!reservation)+ throw Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned')+ const sql = Sql(handler)+ sql.savepoint = savepoint+ sql.prepare = x => prepare = x.replace(/[^a-z0-9$-_. ]/gi)+ sql.discard = reservation.discard+ let uncaughtError+ , result++ name && await sql`savepoint ${ sql(name) }`+ try {+ result = await new Promise((resolve, reject) => {+ const x = fn(sql)+ Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject)+ })++ if (uncaughtError)+ throw uncaughtError+ } catch (e) {+ await (name+ ? sql`rollback to ${ sql(name) }`+ : sql`rollback`+ )+ throw e instanceof PostgresError && e.code === '25P02' && uncaughtError || e+ }++ if (!name) {+ prepare+ ? await sql`prepare transaction '${ sql.unsafe(prepare) }'`+ : await sql`commit`+ }++ return result++ function savepoint(name, fn) {+ if (c.reserved !== reservation)+ return Promise.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))+ if (name && Array.isArray(name.raw))+ return savepoint(sql => sql.apply(sql, arguments))++ arguments.length === 1 && (fn = name, name = null)+ return scope(c, fn, 's' + savepoints++ + (name ? '_' + name : ''))+ }++ function handler(q) {+ q.catch(e => uncaughtError || (uncaughtError = e))+ if (!reservation || c.reserved !== reservation)+ return q.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))+ reservation.enqueue(q)+ }+ }++ function onexecute(c) {+ connection = c+ move(c, reserved)+ own(c)+ }+ }++ function move(c, queue) {+ c.queue.remove(c)+ queue.push(c)+ c.queue = queue+ queue === open+ ? c.idleTimer.start()+ : c.idleTimer.cancel()+ return c+ }++ function json(x) {+ return new Parameter(x, 3802)+ }++ function array(x, type) {+ if (!Array.isArray(x))+ return array(Array.from(arguments))++ return new Parameter(x, type || (x.length ? inferType(x) || 25 : 0), options.shared.typeArrayMap)+ }++ function handler(query) {+ if (ending)+ return query.reject(Errors.connection('CONNECTION_ENDED', options, options))++ if (open.length)+ return go(open.shift(), query)++ if (closed.length)+ return connect(closed.shift(), query)++ busy.length+ ? go(busy.shift(), query)+ : queries.push(query)+ }++ function go(c, query) {+ return c.execute(query)+ ? move(c, busy)+ : move(c, full)+ }++ function cancel(query) {+ return new Promise((resolve, reject) => {+ query.state+ ? query.active+ ? Connection(options).cancel(query.state, resolve, reject)+ : query.cancelled = { resolve, reject }+ : (+ queries.remove(query),+ query.cancelled = true,+ query.reject(Errors.generic('57014', 'canceling statement due to user request')),+ resolve()+ )+ })+ }++ async function end({ timeout = null } = {}) {+ if (ending)+ return ending++ await 1+ let timer+ return ending = Promise.race([+ new Promise(r => timeout !== null && (timer = setTimeout(destroy, timeout * 1000, r))),+ Promise.all(connections.map(c => c.end()).concat(+ listen.sql ? listen.sql.end({ timeout: 0 }) : [],+ subscribe.sql ? subscribe.sql.end({ timeout: 0 }) : []+ ))+ ]).then(() => clearTimeout(timer))+ }++ async function close() {+ await Promise.all(connections.map(c => c.end()))+ }++ async function destroy(resolve) {+ await Promise.all(connections.map(c => c.terminate()))+ while (queries.length)+ queries.shift().reject(Errors.connection('CONNECTION_DESTROYED', options))+ resolve()+ }++ function connect(c, query) {+ move(c, connecting)+ c.connect(query)+ return c+ }++ function onend(c) {+ move(c, ended)+ }++ function onopen(c) {+ if (ending) {+ while (queries.length)+ queries.shift().reject(Errors.connection('CONNECTION_ENDED', options))+ return c.terminate()+ }+ if (queries.length === 0)+ return move(c, open)++ let max = Math.ceil(queries.length / (connecting.length + 1))+ , ready = true++ while (ready && queries.length && max-- > 0) {+ const query = queries.shift()+ if (query.reserve)+ return query.reserve(c)++ ready = c.execute(query)+ }++ ready+ ? move(c, busy)+ : move(c, full)+ }++ function onclose(c, e) {+ move(c, closed)+ const reservation = c.reserved+ c.reserved = null+ reservation && reservation.reject(e)+ c.onclose && (c.onclose(e), c.onclose = null)+ options.onclose && options.onclose(c.id)+ if (ending) {+ while (queries.length)+ queries.shift().reject(Errors.connection('CONNECTION_ENDED', options))+ return+ }+ if (queries.length) {+ const query = queries.peek()+ connect(c, query.reserve ? query : queries.shift())+ }+ }+}++function parseOptions(a, b) {+ if (a && a.shared)+ return a++ const env = process.env // eslint-disable-line+ , o = (!a || typeof a === 'string' ? b : a) || {}+ , { url, multihost } = parseUrl(a)+ , query = [...url.searchParams].reduce((a, [b, c]) => (a[b] = c, a), {})+ , host = o.hostname || o.host || multihost || url.hostname || env.PGHOST || 'localhost'+ , port = o.port || url.port || env.PGPORT || 5432+ , user = o.user || o.username || url.username || env.PGUSERNAME || env.PGUSER || osUsername()++ o.no_prepare && (o.prepare = false)+ query.sslmode && (query.ssl = query.sslmode, delete query.sslmode)+ 'timeout' in o && (console.log('The timeout option is deprecated, use idle_timeout instead'), o.idle_timeout = o.timeout) // eslint-disable-line+ query.sslrootcert === 'system' && (query.ssl = 'verify-full')++ const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive']+ const defaults = {+ max : globalThis.Cloudflare ? 3 : 10,+ ssl : false,+ sslnegotiation : null,+ idle_timeout : null,+ connect_timeout : 30,+ max_lifetime : max_lifetime,+ max_pipeline : 100,+ backoff : backoff,+ keep_alive : 60,+ prepare : true,+ debug : false,+ fetch_types : true,+ publications : 'alltables',+ target_session_attrs: null+ }++ return {+ host : Array.isArray(host) ? host : host.split(',').map(x => x.split(':')[0]),+ port : Array.isArray(port) ? port : host.split(',').map(x => parseInt(x.split(':')[1] || port)),+ path : o.path || host.indexOf('/') > -1 && host + '/.s.PGSQL.' + port,+ database : o.database || o.db || (url.pathname || '').slice(1) || env.PGDATABASE || user,+ user : user,+ pass : o.pass || o.password || url.password || env.PGPASSWORD || '',+ ...Object.entries(defaults).reduce(+ (acc, [k, d]) => {+ const value = k in o ? o[k] : k in query+ ? (query[k] === 'disable' || query[k] === 'false' ? false : query[k])+ : env['PG' + k.toUpperCase()] || d+ acc[k] = typeof value === 'string' && ints.includes(k)+ ? +value+ : value+ return acc+ },+ {}+ ),+ connection : {+ application_name: env.PGAPPNAME || 'postgres.js',+ ...o.connection,+ ...Object.entries(query).reduce((acc, [k, v]) => (k in defaults || (acc[k] = v), acc), {})+ },+ types : o.types || {},+ target_session_attrs: tsa(o, url, env),+ onnotice : o.onnotice,+ onnotify : o.onnotify,+ onclose : o.onclose,+ onparameter : o.onparameter,+ socket : o.socket,+ transform : parseTransform(o.transform || { undefined: undefined }),+ parameters : {},+ shared : { retries: 0, typeArrayMap: {} },+ ...mergeUserTypes(o.types)+ }+}++function tsa(o, url, env) {+ const x = o.target_session_attrs || url.searchParams.get('target_session_attrs') || env.PGTARGETSESSIONATTRS+ if (!x || ['read-write', 'read-only', 'primary', 'standby', 'prefer-standby'].includes(x))+ return x++ throw new Error('target_session_attrs ' + x + ' is not supported')+}++function backoff(retries) {+ return (0.5 + Math.random() / 2) * Math.min(3 ** retries / 100, 20)+}++function max_lifetime() {+ return 60 * (30 + Math.random() * 30)+}++function parseTransform(x) {+ return {+ undefined: x.undefined,+ column: {+ from: typeof x.column === 'function' ? x.column : x.column && x.column.from,+ to: x.column && x.column.to+ },+ value: {+ from: typeof x.value === 'function' ? x.value : x.value && x.value.from,+ to: x.value && x.value.to+ },+ row: {+ from: typeof x.row === 'function' ? x.row : x.row && x.row.from,+ to: x.row && x.row.to+ }+ }+}++function parseUrl(url) {+ if (!url || typeof url !== 'string')+ return { url: { searchParams: new Map() } }++ let host = url+ host = host.slice(host.indexOf('://') + 3).split(/[?/]/)[0]+ host = decodeURIComponent(host.slice(host.indexOf('@') + 1))++ const urlObj = new URL(url.replace(host, host.split(',')[0]))++ return {+ url: {+ username: decodeURIComponent(urlObj.username),+ password: decodeURIComponent(urlObj.password),+ host: urlObj.host,+ hostname: urlObj.hostname,+ port: urlObj.port,+ pathname: urlObj.pathname,+ searchParams: urlObj.searchParams+ },+ multihost: host.indexOf(',') > -1 && host+ }+}++function osUsername() {+ try {+ return os.userInfo().username // eslint-disable-line+ } catch (_) {+ return process.env.USERNAME || process.env.USER || process.env.LOGNAME // eslint-disable-line+ }+}diff --git a/vendor/postgres/src/large.js b/vendor/postgres/src/large.jsnew file mode 100644index 0000000000..f46329677c--- /dev/null+++ b/vendor/postgres/src/large.js@@ -0,0 +1,70 @@+import Stream from 'stream'++export default function largeObject(sql, oid, mode = 0x00020000 | 0x00040000) {+ return new Promise(async(resolve, reject) => {+ await sql.begin(async sql => {+ let finish+ !oid && ([{ oid }] = await sql`select lo_creat(-1) as oid`)+ const [{ fd }] = await sql`select lo_open(${ oid }, ${ mode }) as fd`++ const lo = {+ writable,+ readable,+ close : () => sql`select lo_close(${ fd })`.then(finish),+ tell : () => sql`select lo_tell64(${ fd })`,+ read : (x) => sql`select loread(${ fd }, ${ x }) as data`,+ write : (x) => sql`select lowrite(${ fd }, ${ x })`,+ truncate : (x) => sql`select lo_truncate64(${ fd }, ${ x })`,+ seek : (x, whence = 0) => sql`select lo_lseek64(${ fd }, ${ x }, ${ whence })`,+ size : () => sql`+ select+ lo_lseek64(${ fd }, location, 0) as position,+ seek.size+ from (+ select+ lo_lseek64($1, 0, 2) as size,+ tell.location+ from (select lo_tell64($1) as location) tell+ ) seek+ `+ }++ resolve(lo)++ return new Promise(async r => finish = r)++ async function readable({+ highWaterMark = 2048 * 8,+ start = 0,+ end = Infinity+ } = {}) {+ let max = end - start+ start && await lo.seek(start)+ return new Stream.Readable({+ highWaterMark,+ async read(size) {+ const l = size > max ? size - max : size+ max -= size+ const [{ data }] = await lo.read(l)+ this.push(data)+ if (data.length < size)+ this.push(null)+ }+ })+ }++ async function writable({+ highWaterMark = 2048 * 8,+ start = 0+ } = {}) {+ start && await lo.seek(start)+ return new Stream.Writable({+ highWaterMark,+ write(chunk, encoding, callback) {+ lo.write(chunk).then(() => callback(), callback)+ }+ })+ }+ }).catch(reject)+ })+}diff --git a/vendor/postgres/src/query.js b/vendor/postgres/src/query.jsnew file mode 100644index 0000000000..96967780bd--- /dev/null+++ b/vendor/postgres/src/query.js@@ -0,0 +1,179 @@+const originCache = new Map()+ , originStackCache = new Map()+ , originError = Symbol('OriginError')++export const CLOSE = {}+export class Query extends Promise {+ constructor(strings, args, handler, canceller, options = {}) {+ let resolve+ , reject++ super((a, b) => {+ resolve = a+ reject = b+ })++ this.tagged = Array.isArray(strings.raw)+ this.strings = strings+ this.args = args+ this.handler = handler+ this.canceller = canceller+ this.options = options++ this.state = null+ this.statement = null++ this.resolve = x => (this.active = false, this.canceller = null, resolve(x))+ this.reject = x => (this.active = false, this.canceller = null, reject(x))++ this.active = false+ this.cancelled = null+ this.cancelPromise = null+ this.executed = false+ this.signature = ''++ this[originError] = this.handler.debug+ ? new Error()+ : this.tagged && cachedError(this.strings)+ }++ get origin() {+ return (this.handler.debug+ ? this[originError].stack+ : this.tagged && originStackCache.has(this.strings)+ ? originStackCache.get(this.strings)+ : originStackCache.set(this.strings, this[originError].stack).get(this.strings)+ ) || ''+ }++ static get [Symbol.species]() {+ return Promise+ }++ cancel() {+ if (this.cancelPromise)+ return this.cancelPromise++ const canceller = this.canceller+ this.canceller = null+ return this.cancelPromise = canceller ? canceller(this) : Promise.resolve()+ }++ simple() {+ this.options.simple = true+ this.options.prepare = false+ return this+ }++ async readable() {+ this.simple()+ this.streaming = true+ return this+ }++ async writable() {+ this.simple()+ this.streaming = true+ return this+ }++ cursor(rows = 1, fn) {+ this.options.simple = false+ if (typeof rows === 'function') {+ fn = rows+ rows = 1+ }++ this.cursorRows = rows++ if (typeof fn === 'function')+ return (this.cursorFn = fn, this)++ let prev+ return {+ [Symbol.asyncIterator]: () => ({+ next: () => {+ if (this.executed && !this.active)+ return { done: true }++ prev && prev()+ const promise = new Promise((resolve, reject) => {+ this.cursorFn = value => {+ resolve({ value, done: false })+ return new Promise(r => prev = r)+ }+ this.resolve = () => (this.active = false, this.canceller = null, resolve({ done: true }))+ this.reject = x => (this.active = false, this.canceller = null, reject(x))+ })+ this.execute()+ return promise+ },+ return() {+ prev && prev(CLOSE)+ return { done: true }+ }+ })+ }+ }++ describe() {+ this.options.simple = false+ this.onlyDescribe = this.options.prepare = true+ return this+ }++ stream() {+ throw new Error('.stream has been renamed to .forEach')+ }++ forEach(fn) {+ this.forEachFn = fn+ this.handle()+ return this+ }++ raw() {+ this.isRaw = true+ return this+ }++ values() {+ this.isRaw = 'values'+ return this+ }++ async handle() {+ !this.executed && (this.executed = true) && await 1 && this.handler(this)+ }++ execute() {+ this.handle()+ return this+ }++ then() {+ this.handle()+ return super.then.apply(this, arguments)+ }++ catch() {+ this.handle()+ return super.catch.apply(this, arguments)+ }++ finally() {+ this.handle()+ return super.finally.apply(this, arguments)+ }+}++function cachedError(xs) {+ if (originCache.has(xs))+ return originCache.get(xs)++ const x = Error.stackTraceLimit+ Error.stackTraceLimit = 4+ originCache.set(xs, new Error())+ Error.stackTraceLimit = x+ return originCache.get(xs)+}diff --git a/vendor/postgres/src/queue.js b/vendor/postgres/src/queue.jsnew file mode 100644index 0000000000..8fba891b87--- /dev/null+++ b/vendor/postgres/src/queue.js@@ -0,0 +1,32 @@+export default Queue++function Queue(initial = []) {+ let xs = initial.slice()+ let index = 0++ return {+ get length() {+ return xs.length - index+ },+ remove: (x) => {+ const index = xs.indexOf(x)+ return index === -1+ ? null+ : (xs.splice(index, 1), x)+ },+ push: (x) => (xs.push(x), x),+ peek: () => xs[index],+ shift: () => {+ const out = xs[index++]++ if (index === xs.length) {+ index = 0+ xs = []+ } else {+ xs[index - 1] = undefined+ }++ return out+ }+ }+}diff --git a/vendor/postgres/src/result.js b/vendor/postgres/src/result.jsnew file mode 100644index 0000000000..3101428471--- /dev/null+++ b/vendor/postgres/src/result.js@@ -0,0 +1,16 @@+export default class Result extends Array {+ constructor() {+ super()+ Object.defineProperties(this, {+ count: { value: null, writable: true },+ state: { value: null, writable: true },+ command: { value: null, writable: true },+ columns: { value: null, writable: true },+ statement: { value: null, writable: true }+ })+ }++ static get [Symbol.species]() {+ return Array+ }+}diff --git a/vendor/postgres/src/subscribe.js b/vendor/postgres/src/subscribe.jsnew file mode 100644index 0000000000..4f8934cc82--- /dev/null+++ b/vendor/postgres/src/subscribe.js@@ -0,0 +1,277 @@+const noop = () => { /* noop */ }++export default function Subscribe(postgres, options) {+ const subscribers = new Map()+ , slot = 'postgresjs_' + Math.random().toString(36).slice(2)+ , state = {}++ let connection+ , stream+ , ended = false++ const sql = subscribe.sql = postgres({+ ...options,+ transform: { column: {}, value: {}, row: {} },+ max: 1,+ fetch_types: false,+ idle_timeout: null,+ max_lifetime: null,+ connection: {+ ...options.connection,+ replication: 'database'+ },+ onclose: async function() {+ if (ended)+ return+ stream = null+ state.pid = state.secret = undefined+ connected(await init(sql, slot, options.publications))+ subscribers.forEach(event => event.forEach(({ onsubscribe }) => onsubscribe()))+ },+ no_subscribe: true+ })++ const end = sql.end+ , close = sql.close++ sql.end = async() => {+ ended = true+ stream && (await new Promise(r => (stream.once('close', r), stream.end())))+ return end()+ }++ sql.close = async() => {+ stream && (await new Promise(r => (stream.once('close', r), stream.end())))+ return close()+ }++ return subscribe++ async function subscribe(event, fn, onsubscribe = noop, onerror = noop) {+ event = parseEvent(event)++ if (!connection)+ connection = init(sql, slot, options.publications)++ const subscriber = { fn, onsubscribe }+ const fns = subscribers.has(event)+ ? subscribers.get(event).add(subscriber)+ : subscribers.set(event, new Set([subscriber])).get(event)++ const unsubscribe = () => {+ fns.delete(subscriber)+ fns.size === 0 && subscribers.delete(event)+ }++ return connection.then(x => {+ connected(x)+ onsubscribe()+ stream && stream.on('error', onerror)+ return { unsubscribe, state, sql }+ })+ }++ function connected(x) {+ stream = x.stream+ state.pid = x.state.pid+ state.secret = x.state.secret+ }++ async function init(sql, slot, publications) {+ if (!publications)+ throw new Error('Missing publication names')++ const xs = await sql.unsafe(+ `CREATE_REPLICATION_SLOT ${ slot } TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`+ )++ const [x] = xs++ const stream = await sql.unsafe(+ `START_REPLICATION SLOT ${ slot } LOGICAL ${+ x.consistent_point+ } (proto_version '1', publication_names '${ publications }')`+ ).writable()++ const state = {+ lsn: Buffer.concat(x.consistent_point.split('/').map(x => Buffer.from(('00000000' + x).slice(-8), 'hex')))+ }++ stream.on('data', data)+ stream.on('error', error)+ stream.on('close', sql.close)++ return { stream, state: xs.state }++ function error(e) {+ console.error('Unexpected error during logical streaming - reconnecting', e) // eslint-disable-line+ }++ function data(x) {+ if (x[0] === 0x77) {+ parse(x.subarray(25), state, sql.options.parsers, handle, options.transform)+ } else if (x[0] === 0x6b && x[17]) {+ state.lsn = x.subarray(1, 9)+ pong()+ }+ }++ function handle(a, b) {+ const path = b.relation.schema + '.' + b.relation.table+ call('*', a, b)+ call('*:' + path, a, b)+ b.relation.keys.length && call('*:' + path + '=' + b.relation.keys.map(x => a[x.name]), a, b)+ call(b.command, a, b)+ call(b.command + ':' + path, a, b)+ b.relation.keys.length && call(b.command + ':' + path + '=' + b.relation.keys.map(x => a[x.name]), a, b)+ }++ function pong() {+ const x = Buffer.alloc(34)+ x[0] = 'r'.charCodeAt(0)+ x.fill(state.lsn, 1)+ x.writeBigInt64BE(BigInt(Date.now() - Date.UTC(2000, 0, 1)) * BigInt(1000), 25)+ stream.write(x)+ }+ }++ function call(x, a, b) {+ subscribers.has(x) && subscribers.get(x).forEach(({ fn }) => fn(a, b, x))+ }+}++function Time(x) {+ return new Date(Date.UTC(2000, 0, 1) + Number(x / BigInt(1000)))+}++function parse(x, state, parsers, handle, transform) {+ const char = (acc, [k, v]) => (acc[k.charCodeAt(0)] = v, acc)++ Object.entries({+ R: x => { // Relation+ let i = 1+ const r = state[x.readUInt32BE(i)] = {+ schema: x.toString('utf8', i += 4, i = x.indexOf(0, i)) || 'pg_catalog',+ table: x.toString('utf8', i + 1, i = x.indexOf(0, i + 1)),+ columns: Array(x.readUInt16BE(i += 2)),+ keys: []+ }+ i += 2++ let columnIndex = 0+ , column++ while (i < x.length) {+ column = r.columns[columnIndex++] = {+ key: x[i++],+ name: transform.column.from+ ? transform.column.from(x.toString('utf8', i, i = x.indexOf(0, i)))+ : x.toString('utf8', i, i = x.indexOf(0, i)),+ type: x.readUInt32BE(i += 1),+ parser: parsers[x.readUInt32BE(i)],+ atttypmod: x.readUInt32BE(i += 4)+ }++ column.key && r.keys.push(column)+ i += 4+ }+ },+ Y: () => { /* noop */ }, // Type+ O: () => { /* noop */ }, // Origin+ B: x => { // Begin+ state.date = Time(x.readBigInt64BE(9))+ state.lsn = x.subarray(1, 9)+ },+ I: x => { // Insert+ let i = 1+ const relation = state[x.readUInt32BE(i)]+ const { row } = tuples(x, relation.columns, i += 7, transform)++ handle(row, {+ command: 'insert',+ relation+ })+ },+ D: x => { // Delete+ let i = 1+ const relation = state[x.readUInt32BE(i)]+ i += 4+ const key = x[i] === 75+ handle(key || x[i] === 79+ ? tuples(x, relation.columns, i += 3, transform).row+ : null+ , {+ command: 'delete',+ relation,+ key+ })+ },+ U: x => { // Update+ let i = 1+ const relation = state[x.readUInt32BE(i)]+ i += 4+ const key = x[i] === 75+ const xs = key || x[i] === 79+ ? tuples(x, relation.columns, i += 3, transform)+ : null++ xs && (i = xs.i)++ const { row } = tuples(x, relation.columns, i + 3, transform)++ handle(row, {+ command: 'update',+ relation,+ key,+ old: xs && xs.row+ })+ },+ T: () => { /* noop */ }, // Truncate,+ C: () => { /* noop */ } // Commit+ }).reduce(char, {})[x[0]](x)+}++function tuples(x, columns, xi, transform) {+ let type+ , column+ , value++ const row = transform.raw ? new Array(columns.length) : {}+ for (let i = 0; i < columns.length; i++) {+ type = x[xi++]+ column = columns[i]+ value = type === 110 // n+ ? null+ : type === 117 // u+ ? undefined+ : column.parser === undefined+ ? x.toString('utf8', xi + 4, xi += 4 + x.readUInt32BE(xi))+ : column.parser.array === true+ ? column.parser(x.toString('utf8', xi + 5, xi += 4 + x.readUInt32BE(xi)))+ : column.parser(x.toString('utf8', xi + 4, xi += 4 + x.readUInt32BE(xi)))++ transform.raw+ ? (row[i] = transform.raw === true+ ? value+ : transform.value.from ? transform.value.from(value, column) : value)+ : (row[column.name] = transform.value.from+ ? transform.value.from(value, column)+ : value+ )+ }++ return { i: xi, row: transform.row.from ? transform.row.from(row) : row }+}++function parseEvent(x) {+ const xs = x.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i) || []++ if (!xs)+ throw new Error('Malformed subscribe pattern: ' + x)++ const [, command, path, key] = xs++ return (command || '*')+ + (path ? ':' + (path.indexOf('.') === -1 ? 'public.' + path : path) : '')+ + (key ? '=' + key : '')+}diff --git a/vendor/postgres/src/types.js b/vendor/postgres/src/types.jsnew file mode 100644index 0000000000..7c7c2b9309--- /dev/null+++ b/vendor/postgres/src/types.js@@ -0,0 +1,367 @@+import { Query } from './query.js'+import { Errors } from './errors.js'++export const types = {+ string: {+ to: 25,+ from: null, // defaults to string+ serialize: x => '' + x+ },+ number: {+ to: 0,+ from: [21, 23, 26, 700, 701],+ serialize: x => '' + x,+ parse: x => +x+ },+ json: {+ to: 114,+ from: [114, 3802],+ serialize: x => JSON.stringify(x),+ parse: x => JSON.parse(x)+ },+ boolean: {+ to: 16,+ from: 16,+ serialize: x => x === true ? 't' : 'f',+ parse: x => x === 't'+ },+ date: {+ to: 1184,+ from: [1082, 1114, 1184],+ serialize: x => (x instanceof Date ? x : new Date(x)).toISOString(),+ parse: x => new Date(x)+ },+ bytea: {+ to: 17,+ from: 17,+ serialize: x => '\\x' + Buffer.from(x).toString('hex'),+ parse: x => Buffer.from(x.slice(2), 'hex')+ }+}++class NotTagged { then() { notTagged() } catch() { notTagged() } finally() { notTagged() }}++export class Identifier extends NotTagged {+ constructor(value) {+ super()+ this.value = escapeIdentifier(value)+ }+}++export class Parameter extends NotTagged {+ constructor(value, type, array) {+ super()+ this.value = value+ this.type = type+ this.array = array+ }+}++export class Builder extends NotTagged {+ constructor(first, rest) {+ super()+ this.first = first+ this.rest = rest+ }++ build(before, parameters, types, options) {+ const keyword = builders.map(([x, fn]) => ({ fn, i: before.search(x) })).sort((a, b) => a.i - b.i).pop()+ return keyword.i === -1+ ? escapeIdentifiers(this.first, options)+ : keyword.fn(this.first, this.rest, parameters, types, options)+ }+}++export function handleValue(x, parameters, types, options) {+ let value = x instanceof Parameter ? x.value : x+ if (value === undefined) {+ x instanceof Parameter+ ? x.value = options.transform.undefined+ : value = x = options.transform.undefined++ if (value === undefined)+ throw Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed')+ }++ return '$' + (types.push(+ x instanceof Parameter+ ? (parameters.push(x.value), x.array+ ? x.array[x.type || inferType(x.value)] || x.type || firstIsString(x.value)+ : x.type+ )+ : (parameters.push(x), inferType(x))+ ))+}++const defaultHandlers = typeHandlers(types)++export function stringify(q, string, value, parameters, types, options) { // eslint-disable-line+ for (let i = 1; i < q.strings.length; i++) {+ string += (stringifyValue(string, value, parameters, types, options)) + q.strings[i]+ value = q.args[i]+ }++ return string+}++function stringifyValue(string, value, parameters, types, o) {+ return (+ value instanceof Builder ? value.build(string, parameters, types, o) :+ value instanceof Query ? fragment(value, parameters, types, o) :+ value instanceof Identifier ? value.value :+ value && value[0] instanceof Query ? value.reduce((acc, x) => acc + ' ' + fragment(x, parameters, types, o), '') :+ handleValue(value, parameters, types, o)+ )+}++function fragment(q, parameters, types, options) {+ q.fragment = true+ return stringify(q, q.strings[0], q.args[0], parameters, types, options)+}++function valuesBuilder(first, parameters, types, columns, options) {+ return first.map(row =>+ '(' + columns.map(column =>+ stringifyValue('values', row[column], parameters, types, options)+ ).join(',') + ')'+ ).join(',')+}++function values(first, rest, parameters, types, options) {+ const multi = Array.isArray(first[0])+ const columns = rest.length ? rest.flat() : Object.keys(multi ? first[0] : first)+ return valuesBuilder(multi ? first : [first], parameters, types, columns, options)+}++function select(first, rest, parameters, types, options) {+ typeof first === 'string' && (first = [first].concat(rest))+ if (Array.isArray(first))+ return escapeIdentifiers(first, options)++ let value+ const columns = rest.length ? rest.flat() : Object.keys(first)+ return columns.map(x => {+ value = first[x]+ return (+ value instanceof Query ? fragment(value, parameters, types, options) :+ value instanceof Identifier ? value.value :+ handleValue(value, parameters, types, options)+ ) + ' as ' + escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x)+ }).join(',')+}++const builders = Object.entries({+ values,+ in: (...xs) => {+ const x = values(...xs)+ return x === '()' ? '(null)' : x+ },+ select,+ as: select,+ returning: select,+ '\\(': select,++ update(first, rest, parameters, types, options) {+ return (rest.length ? rest.flat() : Object.keys(first)).map(x =>+ escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x) ++ '=' + stringifyValue('values', first[x], parameters, types, options)+ )+ },++ insert(first, rest, parameters, types, options) {+ const columns = rest.length ? rest.flat() : Object.keys(Array.isArray(first) ? first[0] : first)+ return '(' + escapeIdentifiers(columns, options) + ')values' ++ valuesBuilder(Array.isArray(first) ? first : [first], parameters, types, columns, options)+ }+}).map(([x, fn]) => ([new RegExp('((?:^|[\\s(])' + x + '(?:$|[\\s(]))(?![\\s\\S]*\\1)', 'i'), fn]))++function notTagged() {+ throw Errors.generic('NOT_TAGGED_CALL', 'Query not called as a tagged template literal')+}++export const serializers = defaultHandlers.serializers+export const parsers = defaultHandlers.parsers++export const END = {}++function firstIsString(x) {+ if (Array.isArray(x))+ return firstIsString(x[0])+ return typeof x === 'string' ? 1009 : 0+}++export const mergeUserTypes = function(types) {+ const user = typeHandlers(types || {})+ return {+ serializers: Object.assign({}, serializers, user.serializers),+ parsers: Object.assign({}, parsers, user.parsers)+ }+}++function typeHandlers(types) {+ return Object.keys(types).reduce((acc, k) => {+ types[k].from && [].concat(types[k].from).forEach(x => acc.parsers[x] = types[k].parse)+ if (types[k].serialize) {+ acc.serializers[types[k].to] = types[k].serialize+ types[k].from && [].concat(types[k].from).forEach(x => acc.serializers[x] = types[k].serialize)+ }+ return acc+ }, { parsers: {}, serializers: {} })+}++function escapeIdentifiers(xs, { transform: { column } }) {+ return xs.map(x => escapeIdentifier(column.to ? column.to(x) : x)).join(',')+}++export const escapeIdentifier = function escape(str) {+ return '"' + str.replace(/"/g, '""').replace(/\./g, '"."') + '"'+}++export const inferType = function inferType(x) {+ return (+ x instanceof Parameter ? x.type :+ x instanceof Date ? 1184 :+ x instanceof Uint8Array ? 17 :+ (x === true || x === false) ? 16 :+ typeof x === 'bigint' ? 20 :+ Array.isArray(x) ? inferType(x[0]) :+ 0+ )+}++const escapeBackslash = /\\/g+const escapeQuote = /"/g++function arrayEscape(x) {+ return x+ .replace(escapeBackslash, '\\\\')+ .replace(escapeQuote, '\\"')+}++export const arraySerializer = function arraySerializer(xs, serializer, options, typarray) {+ if (Array.isArray(xs) === false)+ return xs++ if (!xs.length)+ return '{}'++ const first = xs[0]+ // Only _box (1020) has the ';' delimiter for arrays, all other types use the ',' delimiter+ const delimiter = typarray === 1020 ? ';' : ','++ if (Array.isArray(first) && !first.type)+ return '{' + xs.map(x => arraySerializer(x, serializer, options, typarray)).join(delimiter) + '}'++ return '{' + xs.map(x => {+ if (x === undefined) {+ x = options.transform.undefined+ if (x === undefined)+ throw Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed')+ }++ return x === null+ ? 'null'+ : '"' + arrayEscape(serializer ? serializer(x.type ? x.value : x) : '' + x) + '"'+ }).join(delimiter) + '}'+}++const arrayParserState = {+ i: 0,+ char: null,+ str: '',+ quoted: false,+ last: 0+}++export const arrayParser = function arrayParser(x, parser, typarray) {+ arrayParserState.i = arrayParserState.last = 0+ return arrayParserLoop(arrayParserState, x, parser, typarray)+}++function arrayParserLoop(s, x, parser, typarray) {+ const xs = []+ // Only _box (1020) has the ';' delimiter for arrays, all other types use the ',' delimiter+ const delimiter = typarray === 1020 ? ';' : ','+ for (; s.i < x.length; s.i++) {+ s.char = x[s.i]+ if (s.quoted) {+ if (s.char === '\\') {+ s.str += x[++s.i]+ } else if (s.char === '"') {+ xs.push(parser ? parser(s.str) : s.str)+ s.str = ''+ s.quoted = x[s.i + 1] === '"'+ s.last = s.i + 2+ } else {+ s.str += s.char+ }+ } else if (s.char === '"') {+ s.quoted = true+ } else if (s.char === '{') {+ s.last = ++s.i+ xs.push(arrayParserLoop(s, x, parser, typarray))+ } else if (s.char === '}') {+ s.quoted = false+ s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i))+ s.last = s.i + 1+ break+ } else if (s.char === delimiter && s.p !== '}' && s.p !== '"') {+ xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i))+ s.last = s.i + 1+ }+ s.p = s.char+ }+ s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i + 1)) : x.slice(s.last, s.i + 1))+ return xs+}++export const toCamel = x => {+ let str = x[0]+ for (let i = 1; i < x.length; i++)+ str += x[i] === '_' ? x[++i].toUpperCase() : x[i]+ return str+}++export const toPascal = x => {+ let str = x[0].toUpperCase()+ for (let i = 1; i < x.length; i++)+ str += x[i] === '_' ? x[++i].toUpperCase() : x[i]+ return str+}++export const toKebab = x => x.replace(/_/g, '-')++export const fromCamel = x => x.replace(/([A-Z])/g, '_$1').toLowerCase()+export const fromPascal = x => (x.slice(0, 1) + x.slice(1).replace(/([A-Z])/g, '_$1')).toLowerCase()+export const fromKebab = x => x.replace(/-/g, '_')++function createJsonTransform(fn) {+ return function jsonTransform(x, column) {+ return typeof x === 'object' && x !== null && (column.type === 114 || column.type === 3802)+ ? Array.isArray(x)+ ? x.map(x => jsonTransform(x, column))+ : Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: jsonTransform(v, column) }), {})+ : x+ }+}++toCamel.column = { from: toCamel }+toCamel.value = { from: createJsonTransform(toCamel) }+fromCamel.column = { to: fromCamel }++export const camel = { ...toCamel }+camel.column.to = fromCamel++toPascal.column = { from: toPascal }+toPascal.value = { from: createJsonTransform(toPascal) }+fromPascal.column = { to: fromPascal }++export const pascal = { ...toPascal }+pascal.column.to = fromPascal++toKebab.column = { from: toKebab }+toKebab.value = { from: createJsonTransform(toKebab) }+fromKebab.column = { to: fromKebab }++export const kebab = { ...toKebab }+kebab.column.to = fromKebabdiff --git a/vendor/postgres/types/index.d.ts b/vendor/postgres/types/index.d.tsnew file mode 100644index 0000000000..5d8903e324--- /dev/null+++ b/vendor/postgres/types/index.d.ts@@ -0,0 +1,738 @@+import { Readable, Writable } from 'node:stream'++/**+ * Establish a connection to a PostgreSQL server.+ * @param options Connection options - default to the same as psql+ * @returns An utility function to make queries to the server+ */+declare function postgres<T extends Record<string, postgres.PostgresType> = {}>(options?: postgres.Options<T> | undefined): postgres.Sql<Record<string, postgres.PostgresType> extends T ? {} : { [type in keyof T]: T[type] extends {+ serialize: (value: infer R) => any,+ parse: (raw: any) => infer R+} ? R : never }>+/**+ * Establish a connection to a PostgreSQL server.+ * @param url Connection string used for authentication+ * @param options Connection options - default to the same as psql+ * @returns An utility function to make queries to the server+ */+declare function postgres<T extends Record<string, postgres.PostgresType> = {}>(url: string, options?: postgres.Options<T> | undefined): postgres.Sql<Record<string, postgres.PostgresType> extends T ? {} : { [type in keyof T]: T[type] extends {+ serialize: (value: infer R) => any,+ parse: (raw: any) => infer R+} ? R : never }>++/**+ * Connection options of Postgres.+ */+interface BaseOptions<T extends Record<string, postgres.PostgresType>> {+ /** Postgres ip address[s] or domain name[s] */+ host: string | string[] | undefined;+ /** Postgres server[s] port[s] */+ port: number | number[] | undefined;+ /** unix socket path (usually '/tmp') */+ path: string | undefined;+ /**+ * Name of database to connect to+ * @default process.env['PGDATABASE'] || options.user+ */+ database: string;+ /**+ * Username of database user+ * @default process.env['PGUSERNAME'] || process.env['PGUSER'] || require('os').userInfo().username+ */+ user: string;+ /**+ * How to deal with ssl (can be a tls.connect option object)+ * @default false+ */+ ssl: 'require' | 'allow' | 'prefer' | 'verify-full' | boolean | object;+ /**+ * Max number of connections+ * @default 10+ */+ max: number;+ /**+ * Idle connection timeout in seconds+ * @default process.env['PGIDLE_TIMEOUT']+ */+ idle_timeout: number | undefined;+ /**+ * Connect timeout in seconds+ * @default process.env['PGCONNECT_TIMEOUT']+ */+ connect_timeout: number;+ /** Array of custom types; see more in the README */+ types: T;+ /**+ * Enables prepare mode.+ * @default true+ */+ prepare: boolean;+ /**+ * Called when a notice is received+ * @default console.log+ */+ onnotice: (notice: postgres.Notice) => void;+ /** (key; value) when a server param change */+ onparameter: (key: string, value: any) => void;+ /** Is called with (connection; query; parameters) */+ debug: boolean | ((connection: number, query: string, parameters: any[], paramTypes: any[]) => void);+ /** Transform hooks */+ transform: {+ /** Transforms outcoming undefined values */+ undefined?: any++ /** Transforms incoming and outgoing column names */+ column?: ((column: string) => string) | {+ /** Transform function for column names in result rows */+ from?: ((column: string) => string) | undefined;+ /** Transform function for column names in interpolated values passed to tagged template literal */+ to?: ((column: string) => string) | undefined;+ } | undefined;+ /** Transforms incoming and outgoing row values */+ value?: ((value: any) => any) | {+ /** Transform function for values in result rows */+ from?: ((value: unknown, column: postgres.Column<string>) => any) | undefined;+ // to?: ((value: unknown) => any) | undefined; // unused+ } | undefined;+ /** Transforms entire rows */+ row?: ((row: postgres.Row) => any) | {+ /** Transform function for entire result rows */+ from?: ((row: postgres.Row) => any) | undefined;+ // to?: ((row: postgres.Row) => any) | undefined; // unused+ } | undefined;+ };+ /** Connection parameters */+ connection: Partial<postgres.ConnectionParameters>;+ /**+ * Use 'read-write' with multiple hosts to ensure only connecting to primary+ * @default process.env['PGTARGETSESSIONATTRS']+ */+ target_session_attrs: undefined | 'read-write' | 'read-only' | 'primary' | 'standby' | 'prefer-standby';+ /**+ * Automatically fetches types on connect+ * @default true+ */+ fetch_types: boolean;+ /**+ * Publications to subscribe to (only relevant when calling `sql.subscribe()`)+ * @default 'alltables'+ */+ publications: string+ onclose: (connId: number) => void;+ backoff: boolean | ((attemptNum: number) => number);+ max_lifetime: number | null;+ keep_alive: number | null;+}+++declare const PRIVATE: unique symbol;++declare class NotAPromise {+ private [PRIVATE]: never; // prevent user-side interface implementation++ /**+ * @deprecated This object isn't an SQL query, and therefore not a Promise; use the tagged template string syntax instead: ```await sql\`...\`;```+ * @throws NOT_TAGGED_CALL+ */+ private then(): never;+ /**+ * @deprecated This object isn't an SQL query, and therefore not a Promise; use the tagged template string syntax instead: ```await sql\`...\`;```+ * @throws NOT_TAGGED_CALL+ */+ private catch(): never;+ /**+ * @deprecated This object isn't an SQL query, and therefore not a Promise; use the tagged template string syntax instead: ```await sql\`...\`;```+ * @throws NOT_TAGGED_CALL+ */+ private finally(): never;+}++type UnwrapPromiseArray<T> = T extends any[] ? {+ [k in keyof T]: T[k] extends Promise<infer R> ? R : T[k]+} : T;++type Keys = string++type SerializableObject<T, K extends readonly any[], TT> =+ number extends K['length'] ? {} :+ Partial<(Record<Keys & (keyof T) & (K['length'] extends 0 ? string : K[number]), postgres.ParameterOrJSON<TT> | undefined> & Record<string, any>)>++type First<T, K extends readonly any[], TT> =+ // Tagged template string call+ T extends TemplateStringsArray ? TemplateStringsArray :+ // Identifiers helper+ T extends string ? string :+ // Dynamic values helper (depth 2)+ T extends readonly any[][] ? readonly postgres.EscapableArray[] :+ // Insert/update helper (depth 2)+ T extends readonly (object & infer R)[] ? (R extends postgres.SerializableParameter<TT> ? readonly postgres.SerializableParameter<TT>[] : readonly SerializableObject<R, K, TT>[]) :+ // Dynamic values/ANY helper (depth 1)+ T extends readonly any[] ? (readonly postgres.SerializableParameter<TT>[]) :+ // Insert/update helper (depth 1)+ T extends object ? SerializableObject<T, K, TT> :+ // Unexpected type+ never++type Rest<T> =+ T extends TemplateStringsArray ? never : // force fallback to the tagged template function overload+ T extends string ? readonly string[] :+ T extends readonly any[][] ? readonly [] :+ T extends readonly (object & infer R)[] ? (+ readonly (Keys & keyof R)[] // sql(data, "prop", "prop2") syntax+ |+ [readonly (Keys & keyof R)[]] // sql(data, ["prop", "prop2"]) syntax+ ) :+ T extends readonly any[] ? readonly [] :+ T extends object ? (+ readonly (Keys & keyof T)[] // sql(data, "prop", "prop2") syntax+ |+ [readonly (Keys & keyof T)[]] // sql(data, ["prop", "prop2"]) syntax+ ) :+ any++type Return<T, K extends readonly any[]> =+ [T] extends [TemplateStringsArray] ?+ [unknown] extends [T] ? postgres.Helper<T, K> : // ensure no `PendingQuery` with `any` types+ [TemplateStringsArray] extends [T] ? postgres.PendingQuery<postgres.Row[]> :+ postgres.Helper<T, K> :+ postgres.Helper<T, K>++declare namespace postgres {+ class PostgresError extends Error {+ name: 'PostgresError';+ severity_local: string;+ severity: string;+ code: string;+ position: string;+ file: string;+ line: string;+ routine: string;++ detail?: string | undefined;+ hint?: string | undefined;+ internal_position?: string | undefined;+ internal_query?: string | undefined;+ where?: string | undefined;+ schema_name?: string | undefined;+ table_name?: string | undefined;+ column_name?: string | undefined;+ data?: string | undefined;+ type_name?: string | undefined;+ constraint_name?: string | undefined;++ /** Only set when debug is enabled */+ query: string;+ /** Only set when debug is enabled */+ parameters: any[];+ }++ /**+ * Convert a snake_case string to PascalCase.+ * @param str The string from snake_case to convert+ * @returns The new string in PascalCase+ */+ function toPascal(str: string): string;+ namespace toPascal {+ namespace column { function from(str: string): string; }+ namespace value { function from(str: unknown, column: Column<string>): string }+ }+ /**+ * Convert a PascalCase string to snake_case.+ * @param str The string from snake_case to convert+ * @returns The new string in snake_case+ */+ function fromPascal(str: string): string;+ namespace fromPascal {+ namespace column { function to(str: string): string }+ }+ /**+ * Convert snake_case to and from PascalCase.+ */+ namespace pascal {+ namespace column {+ function from(str: string): string;+ function to(str: string): string;+ }+ namespace value { function from(str: unknown, column: Column<string>): string }+ }+ /**+ * Convert a snake_case string to camelCase.+ * @param str The string from snake_case to convert+ * @returns The new string in camelCase+ */+ function toCamel(str: string): string;+ namespace toCamel {+ namespace column { function from(str: string): string; }+ namespace value { function from(str: unknown, column: Column<string>): string }+ }+ /**+ * Convert a camelCase string to snake_case.+ * @param str The string from snake_case to convert+ * @returns The new string in snake_case+ */+ function fromCamel(str: string): string;+ namespace fromCamel {+ namespace column { function to(str: string): string }+ }+ /**+ * Convert snake_case to and from camelCase.+ */+ namespace camel {+ namespace column {+ function from(str: string): string;+ function to(str: string): string;+ }+ namespace value { function from(str: unknown, column: Column<string>): string }+ }+ /**+ * Convert a snake_case string to kebab-case.+ * @param str The string from snake_case to convert+ * @returns The new string in kebab-case+ */+ function toKebab(str: string): string;+ namespace toKebab {+ namespace column { function from(str: string): string; }+ namespace value { function from(str: unknown, column: Column<string>): string }+ }+ /**+ * Convert a kebab-case string to snake_case.+ * @param str The string from snake_case to convert+ * @returns The new string in snake_case+ */+ function fromKebab(str: string): string;+ namespace fromKebab {+ namespace column { function to(str: string): string }+ }+ /**+ * Convert snake_case to and from kebab-case.+ */+ namespace kebab {+ namespace column {+ function from(str: string): string;+ function to(str: string): string;+ }+ namespace value { function from(str: unknown, column: Column<string>): string }+ }++ const BigInt: PostgresType<bigint>;++ interface PostgresType<T = any> {+ to: number;+ from: number[];+ serialize: (value: T) => unknown;+ parse: (raw: any) => T;+ }++ interface ConnectionParameters {+ /**+ * Default application_name+ * @default 'postgres.js'+ */+ application_name: string;+ default_transaction_isolation: 'read uncommitted' | 'read committed' | 'repeatable read' | 'serializable',+ default_transaction_read_only: boolean,+ default_transaction_deferrable: boolean,+ statement_timeout: number,+ lock_timeout: number,+ idle_in_transaction_session_timeout: number,+ idle_session_timeout: number,+ DateStyle: string,+ IntervalStyle: string,+ TimeZone: string,+ /** Other connection parameters */+ [name: string]: string | number | boolean;+ }++ interface Options<T extends Record<string, postgres.PostgresType>> extends Partial<BaseOptions<T>> {+ /** @inheritdoc */+ host?: string | undefined;+ /** @inheritdoc */+ port?: number | undefined;+ /** @inheritdoc */+ path?: string | undefined;+ /** Password of database user (an alias for `password`) */+ pass?: Options<T>['password'] | undefined;+ /**+ * Password of database user+ * @default process.env['PGPASSWORD']+ */+ password?: string | (() => string | Promise<string>) | undefined;+ /** Name of database to connect to (an alias for `database`) */+ db?: Options<T>['database'] | undefined;+ /** Username of database user (an alias for `user`) */+ username?: Options<T>['user'] | undefined;+ /** Postgres ip address or domain name (an alias for `host`) */+ hostname?: Options<T>['host'] | undefined;+ /**+ * Disable prepared mode+ * @deprecated use "prepare" option instead+ */+ no_prepare?: boolean | undefined;+ /**+ * Idle connection timeout in seconds+ * @deprecated use "idle_timeout" option instead+ */+ timeout?: Options<T>['idle_timeout'] | undefined;+ }++ interface ParsedOptions<T extends Record<string, unknown> = {}> extends BaseOptions<{ [name in keyof T]: PostgresType<T[name]> }> {+ /** @inheritdoc */+ host: string[];+ /** @inheritdoc */+ port: number[];+ /** @inheritdoc */+ pass: null;+ /** @inheritdoc */+ transform: Transform;+ serializers: Record<number, (value: any) => unknown>;+ parsers: Record<number, (value: any) => unknown>;+ }++ interface Transform {+ /** Transforms outcoming undefined values */+ undefined: any++ column: {+ /** Transform function for column names in result rows */+ from: ((column: string) => string) | undefined;+ /** Transform function for column names in interpolated values passed to tagged template literal */+ to: ((column: string) => string) | undefined;+ };+ value: {+ /** Transform function for values in result rows */+ from: ((value: any, column?: Column<string>) => any) | undefined;+ /** Transform function for interpolated values passed to tagged template literal */+ to: undefined; // (value: any) => any+ };+ row: {+ /** Transform function for entire result rows */+ from: ((row: postgres.Row) => any) | undefined;+ to: undefined; // (row: postgres.Row) => any+ };+ }++ interface Notice {+ [field: string]: string;+ }++ interface Parameter<T = SerializableParameter> extends NotAPromise {+ /**+ * PostgreSQL OID of the type+ */+ type: number;+ /**+ * Serialized value+ */+ value: string | null;+ /**+ * Raw value to serialize+ */+ raw: T | null;+ }++ interface ArrayParameter<T extends readonly any[] = readonly any[]> extends Parameter<T | T[]> {+ array: true;+ }++ interface ConnectionError extends globalThis.Error {+ code:+ | 'CONNECTION_DESTROYED'+ | 'CONNECT_TIMEOUT'+ | 'CONNECTION_CLOSED'+ | 'CONNECTION_ENDED';+ errno: this['code'];+ address: string;+ port?: number | undefined;+ }++ interface NotSupportedError extends globalThis.Error {+ code: 'MESSAGE_NOT_SUPPORTED';+ name: string;+ }++ interface GenericError extends globalThis.Error {+ code:+ | '57014' // canceling statement due to user request+ | 'NOT_TAGGED_CALL'+ | 'UNDEFINED_VALUE'+ | 'MAX_PARAMETERS_EXCEEDED'+ | 'SASL_SIGNATURE_MISMATCH'+ | 'UNSAFE_TRANSACTION';+ message: string;+ }++ interface AuthNotImplementedError extends globalThis.Error {+ code: 'AUTH_TYPE_NOT_IMPLEMENTED';+ type: number | string;+ message: string;+ }++ type Error = never+ | PostgresError+ | ConnectionError+ | NotSupportedError+ | GenericError+ | AuthNotImplementedError;++ interface ColumnInfo {+ key: number;+ name: string;+ type: number;+ parser?(raw: string): unknown;+ atttypmod: number;+ }++ interface RelationInfo {+ schema: string;+ table: string;+ columns: ColumnInfo[];+ keys: ColumnInfo[];+ }++ type ReplicationEvent =+ | { command: 'insert', relation: RelationInfo }+ | { command: 'delete', relation: RelationInfo, key: boolean }+ | { command: 'update', relation: RelationInfo, key: boolean, old: Row | null };++ interface SubscriptionHandle {+ unsubscribe(): void;+ }++ interface LargeObject {+ writable(options?: {+ highWaterMark?: number | undefined,+ start?: number | undefined+ } | undefined): Promise<Writable>;+ readable(options?: {+ highWaterMark?: number | undefined,+ start?: number | undefined,+ end?: number | undefined+ } | undefined): Promise<Readable>;++ close(): Promise<void>;+ tell(): Promise<void>;+ read(size: number): Promise<void>;+ write(buffer: Uint8Array): Promise<[{ data: Uint8Array }]>;+ truncate(size: number): Promise<void>;+ seek(offset: number, whence?: number | undefined): Promise<void>;+ size(): Promise<[{ position: bigint, size: bigint }]>;+ }++ type EscapableArray = (string | number)[]++ type Serializable = never+ | null+ | boolean+ | number+ | string+ | Date+ | Uint8Array;++ type SerializableParameter<T = never> = never+ | T+ | Serializable+ | Helper<any>+ | Parameter<any>+ | ArrayParameter+ | readonly SerializableParameter<T>[];++ type JSONValue = // using a dedicated type to detect symbols, bigints, and other non serializable types+ | null+ | string+ | number+ | boolean+ | Date // serialized as `string`+ | readonly JSONValue[]+ | { toJSON(): any } // `toJSON` called by `JSON.stringify`; not typing the return type, types definition is strict enough anyway+ | {+ readonly [prop: string | number]:+ | undefined+ | JSONValue+ | ((...args: any) => any) // serialized as `undefined`+ };++ interface Row {+ [column: string]: any;+ }++ type MaybeRow = Row | undefined;++ interface Column<T extends string> {+ name: T;+ type: number;+ table: number;+ number: number;+ parser?: ((raw: string) => unknown) | undefined;+ }++ type ColumnList<T> = (T extends string ? Column<T> : never)[];++ interface State {+ status: string;+ pid: number;+ secret: number;+ }++ interface Statement {+ /** statement unique name */+ name: string;+ /** sql query */+ string: string;+ /** parameters types */+ types: number[];+ columns: ColumnList<string>;+ }++ interface ResultMeta<T extends number | null> {+ count: T; // For tuples+ command: string;+ statement: Statement;+ state: State;+ }++ interface ResultQueryMeta<T extends number | null, U> extends ResultMeta<T> {+ columns: ColumnList<U>;+ }++ type ExecutionResult<T> = [] & ResultQueryMeta<number, keyof NonNullable<T>>;+ type ValuesRowList<T extends readonly any[]> = T[number][keyof T[number]][][] & ResultQueryMeta<T['length'], keyof T[number]>;+ type RawRowList<T extends readonly any[]> = Buffer[][] & Iterable<Buffer[][]> & ResultQueryMeta<T['length'], keyof T[number]>;+ type RowList<T extends readonly any[]> = T & Iterable<NonNullable<T[number]>> & ResultQueryMeta<T['length'], keyof T[number]>;++ interface PendingQueryModifiers<TRow extends readonly any[]> {+ simple(): this;+ readable(): Promise<Readable>;+ writable(): Promise<Writable>;++ execute(): this;+ cancel(): Promise<void>;++ /**+ * @deprecated `.stream` has been renamed to `.forEach`+ * @throws+ */+ stream(cb: (row: NonNullable<TRow[number]>, result: ExecutionResult<TRow[number]>) => void): never;+ forEach(cb: (row: NonNullable<TRow[number]>, result: ExecutionResult<TRow[number]>) => void): Promise<ExecutionResult<TRow[number]>>;++ cursor(rows?: number | undefined): AsyncIterable<NonNullable<TRow[number]>[]>;+ cursor(cb: (row: [NonNullable<TRow[number]>]) => void): Promise<ExecutionResult<TRow[number]>>;+ cursor(rows: number, cb: (rows: NonNullable<TRow[number]>[]) => void): Promise<ExecutionResult<TRow[number]>>;+ }++ interface PendingDescribeQuery extends Promise<Statement> {+ }++ interface PendingValuesQuery<TRow extends readonly MaybeRow[]> extends Promise<ValuesRowList<TRow>>, PendingQueryModifiers<TRow[number][keyof TRow[number]][][]> {+ describe(): PendingDescribeQuery;+ }++ interface PendingRawQuery<TRow extends readonly MaybeRow[]> extends Promise<RawRowList<TRow>>, PendingQueryModifiers<Buffer[][]> {+ }++ interface PendingQuery<TRow extends readonly MaybeRow[]> extends Promise<RowList<TRow>>, PendingQueryModifiers<TRow> {+ describe(): PendingDescribeQuery;+ values(): PendingValuesQuery<TRow>;+ raw(): PendingRawQuery<TRow>;+ }++ interface PendingRequest extends Promise<[] & ResultMeta<null>> { }++ interface ListenRequest extends Promise<ListenMeta> { }+ interface ListenMeta extends ResultMeta<null> {+ unlisten(): Promise<void>+ }++ interface Helper<T, U extends readonly any[] = T[]> extends NotAPromise {+ first: T;+ rest: U;+ }++ type Fragment = PendingQuery<any>++ type ParameterOrJSON<T> =+ | SerializableParameter<T>+ | JSONValue++ type ParameterOrFragment<T> =+ | SerializableParameter<T>+ | Fragment+ | Fragment[]++ interface UnsafeQueryOptions {+ cancelFence?: boolean;+ /**+ * When executes query as prepared statement.+ * @default false+ */+ prepare?: boolean | undefined;+ }++ interface ISql<TTypes extends Record<string, unknown> = {}> {+ /**+ * Query helper+ * @param first Define how the helper behave+ * @param rest Other optional arguments, depending on the helper type+ * @returns An helper object usable as tagged template parameter in sql queries+ */+ <T, K extends Rest<T>>(first: T & First<T, K, TTypes[keyof TTypes]>, ...rest: K): Return<T, K>;++ /**+ * Execute the SQL query passed as a template string. Can only be used as template string tag.+ * @param template The template generated from the template string+ * @param parameters Interpoled values of the template string+ * @returns A promise resolving to the result of your query+ */+ <T extends readonly (object | undefined)[] = Row[]>(template: TemplateStringsArray, ...parameters: readonly (ParameterOrFragment<TTypes[keyof TTypes]>)[]): PendingQuery<T>;++ types: this['typed'];+ typed: (<T>(value: T, oid: number) => Parameter<T>) & {+ [name in keyof TTypes]: (value: TTypes[name]) => postgres.Parameter<TTypes[name]>+ };++ unsafe<T extends any[] = (Row & Iterable<Row>)[]>(query: string, parameters?: (ParameterOrJSON<TTypes[keyof TTypes]>)[] | undefined, queryOptions?: UnsafeQueryOptions | undefined): PendingQuery<T>;++ notify(channel: string, payload: string): PendingRequest;++ array<T extends SerializableParameter<TTypes[keyof TTypes]>[] = SerializableParameter<TTypes[keyof TTypes]>[]>(value: T, type?: number | undefined): ArrayParameter<T>;+ file<T extends readonly any[] = Row[]>(path: string | Buffer | URL | number, options?: { cache?: boolean | undefined } | undefined): PendingQuery<T>;+ file<T extends readonly any[] = Row[]>(path: string | Buffer | URL | number, args: (ParameterOrJSON<TTypes[keyof TTypes]>)[], options?: { cache?: boolean | undefined } | undefined): PendingQuery<T>;+ json(value: JSONValue): Parameter;+ }++ interface Sql<TTypes extends Record<string, unknown> = {}> extends ISql<TTypes> {+ CLOSE: {};+ END: this['CLOSE'];+ PostgresError: typeof PostgresError;++ options: ParsedOptions<TTypes>;+ parameters: ConnectionParameters;++ end(options?: { timeout?: number | undefined } | undefined): Promise<void>;++ listen(channel: string, onnotify: (value: string) => void, onlisten?: (() => void) | undefined): ListenRequest;++ subscribe(event: string, cb: (row: Row | null, info: ReplicationEvent) => void, onsubscribe?: (() => void), onerror?: (() => any)): Promise<SubscriptionHandle>;++ largeObject(oid?: number | undefined, /** @default 0x00020000 | 0x00040000 */ mode?: number | undefined): Promise<LargeObject>;++ begin<T>(cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;+ begin<T>(options: string, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;++ reserve(options?: { signal?: AbortSignal }): Promise<ReservedSql<TTypes>>+ }++ interface TransactionSql<TTypes extends Record<string, unknown> = {}> extends ISql<TTypes> {+ discard(): void;+ savepoint<T>(cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;+ savepoint<T>(name: string, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;++ prepare<T>(name: string): Promise<UnwrapPromiseArray<T>>;+ }++ interface ReservedSql<TTypes extends Record<string, unknown> = {}> extends Sql<TTypes> {+ discard(): void;+ release(): void;+ }+}++export = postgres;diff --git a/vendor/postgres/types/package.json b/vendor/postgres/types/package.jsonnew file mode 100644index 0000000000..49a279aa74--- /dev/null+++ b/vendor/postgres/types/package.json@@ -0,0 +1,5 @@+{+ "devDependencies": {+ "@types/node": "^16"+ }+}diff --git a/vendor/postgres/types/tsconfig.json b/vendor/postgres/types/tsconfig.jsonnew file mode 100644index 0000000000..42586e2c41--- /dev/null+++ b/vendor/postgres/types/tsconfig.json@@ -0,0 +1,14 @@+{+ "compilerOptions": {+ "lib": [+ "ES2015"+ ],+ "types": [+ "node"+ ],+ "esModuleInterop": true,+ "strict": true,+ "noImplicitAny": true,+ "exactOptionalPropertyTypes": true+ }+}\ No newline at end of filediff --git a/vendor/update-postgres.sh b/vendor/update-postgres.shnew file mode 100644index 0000000000..a5e07fe5a9--- /dev/null+++ b/vendor/update-postgres.sh@@ -0,0 +1,25 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "$0")/.." && pwd)"+WORK="$(mktemp -d)"+trap 'rm -rf "$WORK"' EXIT+curl -fsSL https://registry.npmjs.org/postgres/-/postgres-3.4.9.tgz -o "$WORK/upstream.tgz"+echo '183dea741d31d73f7180523a71d443eb1bb64a9d9608e1287b79ad9f207911ed17aeb2f93def9ee020a726b44c9cbd7362d44366641055bbceb6d2e72832e76b upstream.tgz' | (cd "$WORK" && sha512sum -c -)+mkdir "$WORK/postgres"+tar -xzf "$WORK/upstream.tgz" --strip-components=1 -C "$WORK/postgres"+patch --no-backup-if-mismatch -d "$WORK/postgres" -p1 < "$ROOT/patches/[email protected]"+awk '/^diff --git / { keep = ($3 ~ /^a\/src\//) } keep' "$ROOT/patches/[email protected]" |+ sed 's|a/src/|a/cf/src/|g; s|b/src/|b/cf/src/|g' > "$WORK/cf.patch"+patch --no-backup-if-mismatch -d "$WORK/postgres" -p1 < "$WORK/cf.patch"+curl -fsSL https://raw.githubusercontent.com/porsager/postgres/v3.4.9/UNLICENSE -o "$WORK/postgres/UNLICENSE"+echo 'b5065838cbac452dfc855ba6e6e031481ad2c68406f70d21ead9321374653e6c UNLICENSE' | (cd "$WORK/postgres" && sha256sum -c -)+if [[ "${1:-}" == '--check' ]]; then+ diff -ru "$ROOT/vendor/postgres" "$WORK/postgres"+elif [[ $# -eq 0 ]]; then+ rm -rf "$ROOT/vendor/postgres"+ cp -R "$WORK/postgres" "$ROOT/vendor/postgres"+else+ echo 'Usage: bash vendor/update-postgres.sh [--check]' >&2+ exit 2+fi