Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.46.26.0 fix(dream): private-queue lifecycle wave — adopt #4361 + recovery-lane hardening + full coverage (#4332) (#4390)

Garry Tan69aea15e8098
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index b538614b85..bc16c78778 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.46.25.0",
+ "version": "0.46.26.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.json
index c95fe4e6e9..b800c64667 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.46.25.0",
+ "version": "0.46.26.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/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index 7e8622ebf8..951d179ca8 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -174,6 +174,26 @@ jobs:
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test
GBRAIN_TEST_ALLOW_DATABASE_URL: '1'
+ - name: Create isolated database for the bootstrap suite
+ # The bootstrap suite rewinds the schema ledger and replays every
+ # migration; replayed constraint-adds (e.g. facts_source_id_fkey)
+ # break on rows earlier tier1 suites legitimately leave in
+ # gbrain_test (the suite's own TRUNCATE list predates facts). The
+ # nightly lane masks this via preceding files' TRUNCATE CASCADE —
+ # here it gets a database of its own instead.
+ run: PGPASSWORD=postgres psql -h localhost -U postgres -d gbrain_test -c 'CREATE DATABASE gbrain_bootstrap_test'
+ - name: Run Postgres bootstrap suite
+ # Forward-reference bootstrap on REAL Postgres (#366/#375/#378, the
+ # v121/#2626 wedge class, v0.46.26 private-queue lifecycle incl. the
+ # token-only probe). Previously reachable only via the nightly
+ # coverage-full-e2e glob, so a broken PostgresEngine bootstrap block
+ # could reach master with every PR lane green. Own invocation line
+ # and its OWN database (see the step above). Named files only, no glob.
+ run: bun test --timeout=60000 test/e2e/postgres-bootstrap.test.ts
+ env:
+ DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_bootstrap_test
+ # #3485 preload guard: this job intentionally tests against a DB.
+ GBRAIN_TEST_ALLOW_DATABASE_URL: '1'
- name: Run serve-delegated sync suite
# Serve-delegated sync (PGLite): a real `gbrain serve` owns the
# single-writer lock while real `gbrain sync` subprocesses delegate
@@ -183,6 +203,12 @@ jobs:
# would flip the sandboxed brain to Postgres; the file also
# self-strips). Named files only, no glob.
run: bun test --timeout=240000 test/e2e/sync-delegation-under-serve.serial.test.ts
+ - name: Run PGLite inline subagent drain suite
+ # dream-synthesize-pglite pins the inline drain's per-child lease
+ # keepalive (v0.46.26 private-queue lifecycle) — previously nightly-
+ # glob-only, where the keepalive pin broke silently. Deliberately NO
+ # DATABASE_URL: the suite is PGLite-only. Named files only, no glob.
+ run: bun test --timeout=120000 test/e2e/dream-synthesize-pglite.test.ts
tier2:
name: Tier 2 (LLM Skills)
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 916f74f8ee..974e848f85 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.46.25.0 -->
+<!-- gbrain-runbook-stamp: 0.46.26.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dffd79fe37..9f0f262f43 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,79 @@
All notable changes to GBrain will be documented in this file.
+## [0.46.26.0] - 2026-08-20
+
+**Dream fan-out can no longer strand work in queues nobody owns.** The
+production incident: dead parent runs left thousands of waiting jobs in
+private `dream-inline-*` queues for 16-27 hours, and every dashboard said
+"restart the worker" — advice that cannot work, because no shared worker can
+claim a private queue. This release adopts the lifecycle repair from
+PR #4361 (thank you @garrytan-agents) and hardens every recovery lane the
+review found unwired. Closes #4332.
+
+### Added
+- Private dream queues now carry an explicit owner job, owner token, and
+ renewable lease (adopted from #4361). Synthesize and patterns reconcile
+ their children on every terminal path — success, throw, timeout, abort,
+ cancellation — and startup recovery cancels provably-orphaned queues
+ (owner terminal/missing, or lease expired) while never touching live ones.
+- Recovery now runs on EVERY lane that can strand a queue: the supervisor's
+ pre-spawn hook (adopted), bare `gbrain jobs work` startup, autopilot's
+ worker spawns and crash respawns, and dream-cycle start — the last one
+ being the only possible lane on PGLite brains, which previously had no
+ recovery surface at all.
+- Reconcile cancellations are stamped with a machine-readable reason family
+ (`private_queue_reconciled: <detail>`), mirroring the waiting-TTL prefix,
+ so operators and tooling can tell reconciliation from TTL expiry.
+
+### Changed
+- Lease renewal is monotonic (a renewal can only extend, never shrink) and
+ fires from the drain loop's idle polls and fast-failure iterations too —
+ a live queue with slow or bouncing children can no longer read as orphaned
+ mid-run.
+- The maintenance lane (where synthesize/patterns actually run on
+ multi-source brains) now threads its job id as the private-queue owner, so
+ its queues get the fast owner-terminal recovery path instead of waiting
+ out the lease.
+- Doctor's `orphaned_private_queue` check now runs on PGLite too and buckets
+ findings through the same classifier recovery uses: metadata-backed
+ orphans advertise auto-recovery, legacy unowned queues advertise the
+ retriage preview, and owner-pending queues say which owner job to inspect.
+ The wedged-queue surfaces (doctor, `jobs stats`, the `get_job_stats` op)
+ never call a private queue "wedged" and never advertise a worker restart
+ for it.
+- Doctor's stale-lock hints now name only commands that exist:
+ `gbrain dream --break-lock` was advertised for years but never implemented
+ — pasting it ran a full (paid) dream cycle instead of breaking a lock. The
+ cycle-lock remediation is `gbrain doctor --fix` (dead holders on this
+ host; also swept at the next dream start), and the circular `gbrain
+ doctor` fallback hint is gone. The wedged-queue restart hint names the
+ wedged queue (`supervisor start --queue '<q>'`) instead of always bouncing
+ the default worker.
+
+### Fixed
+- Doctor's orphaned-queue check is honest about truncation on the healthy
+ path too: with more than 100 candidate queues, the never-classified
+ remainder is now reported (`unclassified_candidates`) even when everything
+ classified came back live — previously 100 live + 50 unexamined orphans
+ read as a clean bill of health. `waiting_jobs` now counts flagged queues
+ only, matching what `orphaned_private_queues` reports.
+- The upgrade bootstrap probes all three private-queue columns (owner id,
+ owner token, lease) in both engines — a partially-upgraded brain missing
+ only the token column now repairs itself instead of wedging.
+- The private-queue lease keepalive is one shared, tested helper
+ (`MinionQueue.makeThrottledLeaseRenewer`) instead of twin inline copies in
+ synthesize and patterns; the coverage wave backfills behavioral tests for
+ every recovery lane, the renewing wait, the v136 migration replay, doctor's
+ hint/bucket surfaces, and token redaction on the jobs MCP ops.
+
+To take advantage of v0.46.26.0:
+- `gbrain upgrade` (or reinstall the binary). No schema action needed beyond
+ the automatic migration that adds the owner/lease columns.
+- Existing abandoned queues from before this release are legacy-unowned:
+ `gbrain doctor` now tells you exactly which repair applies; use the
+ `gbrain dream retriage` preview for those.
+
## [0.46.25.0] - 2026-08-20
**The backlog release: 62 community pull requests merged, ~50 maintainer fixes, and 87 open issues closed in one landing.** Every pull request was individually trial-merged and tested before inclusion; every fix started from a reproduced bug and shipped with a failing-first test. The headline classes: embedding backfills can no longer quietly destroy vectors (probe-gated invalidation, honest counts, content-revision staleness, registry-aware writes end to end), sync can no longer delete the wrong page or be repointed by a foreign repo, search caching can no longer serve one source's rows to another or one query's rows to a different query, page timelines survive filesystem rebuilds, large piped CLI output is delivered to the last byte on every path, and the DB config plane is finally read at runtime.
diff --git a/TODOS.md b/TODOS.md
index 8509c0ba15..50d88a29ed 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -829,8 +829,54 @@
prefix `waiting_ttl_expired`) that turns out to have been wanted needs a
`jobs requeue` (or a retry carve-out gated on that prefix) instead of
hand-resubmitting. The data survives (cancelled rows keep payloads +
- free their idempotency keys), so this is purely a CLI surface. **Effort:**
+ free their idempotency keys), so this is purely a CLI surface. v0.46.25.0
+ adds a SECOND machine-readable family to gate on: private-queue reconcile
+ cancellations are stamped `private_queue_reconciled: <detail>`
+ (PRIVATE_QUEUE_RECONCILE_REASON_PREFIX, minions/queue.ts). A requeue of
+ those rows must strip parent/ownership metadata (parent_job_id,
+ private_queue_owner_*) and resubmit into a CLAIMABLE queue — never flip
+ status in place inside a dead dream-inline-* queue. **Effort:**
S. **Priority:** P2. (Pre-landing data-migration review, five-issue wave.)
+- [ ] **P2 — private-queue FK `ON DELETE SET NULL` erases owner evidence.**
+ **What:** purging/pruning an owner job nulls every child's
+ `private_queue_owner_job_id` (migrate.ts v136 FK), so its queue silently
+ degrades from the fast owner-terminal recovery path to legacy-unowned —
+ recovery's scan still sees the lease, but once that expires the queue needs
+ manual retriage instead of auto-cancel. Consider stamping a tombstone
+ (e.g. keep the id, mark owner_missing) or having prune reconcile the queue
+ first. Deferred from the v0.46.25.0 review (behavior change, not coverage).
+ **Effort:** M. **Priority:** P2.
+- [ ] **P2 — retry-shadow: a same-job-id retry shadows the crashed attempt's
+ private queue.** **What:** `jobs retry` reuses the job id; if the prior
+ attempt crashed owning a dream-inline queue, the retried (non-terminal)
+ owner makes the stale queue classify `live_owner` and recovery skips it
+ until the new attempt terminalizes. Options: retry clears/reconciles the
+ old private queue on transition, or recovery keys on attempt rather than
+ id. Deferred from the v0.46.25.0 review. **Effort:** M. **Priority:** P2.
+- [ ] **P3 — v136 `CREATE INDEX` is non-concurrent.** **What:** on a large
+ hosted-Postgres `minion_jobs`, migration v136's two partial indexes take a
+ write lock for the build. Fine for typical brains; a busy multi-tenant
+ install would want `CONCURRENTLY` (which needs the migration runner to
+ support non-transactional steps). **Effort:** M. **Priority:** P3.
+- [ ] **P3 — full 3-way schema-blob parity test.** **What:**
+ `pglite-schema.ts` / `schema-embedded.ts` / `schema.sql` have no general
+ drift guard; v0.46.25.0 added a private-queue-scoped parity pin
+ (test/private-queue-schema-parity.test.ts) — generalize it to the whole
+ blob surface (normalized statement diff). **Effort:** M. **Priority:** P3.
+- [ ] **P3 — `jobs work` daemon-level e2e + global stats discovery.**
+ **What:** the worker-startup recovery lane is covered at the extracted-
+ function level (maybeRunWorkerStartupRecovery); a daemon-level e2e (spawn
+ real `gbrain jobs work`, observe recovery, stop it) would close the last
+ gap, and `jobs stats` without `--queue` could surface abandoned private
+ queues globally (today doctor is the discovery surface). **Effort:** M.
+ **Priority:** P3.
+- [ ] **P3 — consider ChildWorkerSupervisor.run() catching beforeSpawn
+ errors.** **What:** today a rejecting `beforeSpawn` propagates out of
+ `run()` with no crash accounting or respawn (documented contract;
+ composers must try/catch — MinionSupervisor does). A cross-model review
+ dissent argues run() should catch hook errors so one recovery failure can
+ never stop a worker silently. Behavior change; needs its own review.
+ **Effort:** S. **Priority:** P3.
- [ ] **P2 — dream-path quota-degradation integration tests.** **What:**
live-queue integration tests for the QueueQuotaExceededError consumers:
cycle patterns → `skipped('admission_quota')`, synthesize → quota latch
diff --git a/VERSION b/VERSION
index b3fffd9a3f..1ad59821fc 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.46.25.0
\ No newline at end of file
+0.46.26.0
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index f827ff6676..077c6bcc6a 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -245,7 +245,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/quarantine.ts` — the two frontmatter markers the content-quality gate writes, sibling of `src/core/embed-skip.ts` (same marker-as-JSONB-object pattern, same JSONB `?` existence check that works on Postgres AND PGLite; no schema migration — both are frontmatter JSONB keys). `quarantine` (key `QUARANTINE_KEY`) HIDES: set ONLY for high-confidence junk, writes zero chunks, excluded from search via `quarantineFilterFragment(pageAlias)` / `QUARANTINE_FILTER_FRAGMENT` (the `p`-aliased constant), the single source of truth `buildVisibilityClause` calls so the search filter and marker key can't drift. `content_flag` (key `CONTENT_FLAG_KEY`) WARNS, does NOT hide: set for fuzzy markup-heavy / oversize, page stays searchable, marker is READ INTO search/get_page output — deliberately NO SQL filter fragment. Three distinct markers, three reasons (never overloaded): `embed_skip` = oversized-but-clean, `quarantine` = junk hidden, `content_flag` = odd-examine-still-here; a page can carry more than one (oversize → embed_skip + content_flag:oversized) and each clears independently. Exports `buildQuarantineMarker` / `isQuarantined` / `filterOutQuarantined`, `buildContentFlagMarker` / `getContentFlag` / `hasContentFlag`, plus the two key constants. Pinned by `test/quarantine.test.ts`.
- `src/commands/quarantine.ts` — `gbrain quarantine <list|clear|scan>` operator surface for the content-quality gate. `list [--json] [--include-flagged]` paginates `listPages` and reports quarantined (HIDDEN) pages, optionally also `content_flag` (FLAGGED, searchable) pages. `clear <slug> [--force] [--no-embed] [--json]` drops both markers and re-imports through the normal pipeline so the page re-chunks + re-embeds and becomes searchable; the gate re-runs on import so genuinely-junk pages re-quarantine (exit 1) unless `--force` sets `GBRAIN_NO_SANITY=1` for that one import. `scan [--limit N] [--apply] [--no-embed] [--json]` re-assesses already-ingested pages so junk predating the gate gets marked (unchanged content short-circuits normal sync, so it never re-assesses otherwise); dry-run uses the SAME effective `content_sanity` config thresholds `--apply` will use, idempotent (skips already-marked pages), `--apply` re-imports with `forceRechunk` to set markers + (for quarantine) drop chunks. Dispatched in `cli.ts`. Pinned by `test/quarantine-cli.test.ts`.
- `src/core/zombie-reap.ts` — idempotent `installSigchldHandler()` so JS-spawned children get reaped via Bun's internal `waitpid()`. Bun (like Node) only auto-reaps when a SIGCHLD listener is registered; without it, every child the worker spawns (shell jobs, embed batches, sub-agents) becomes a zombie on exit and holds connection slots. Called once at module load from `src/cli.ts` (Windows platform guard — SIGCHLD doesn't exist on Windows). Cross-file leak guard via `_uninstallSigchldHandlerForTests()`. Layer 1 of the three-layer zombie defense; Layer 2 is tini-as-PID-1 wrapping the worker subtree (via `src/core/minions/spawn-helpers.ts`); Layer 3 is the container's own tini for hard Bun crashes.
-- `src/core/minions/` — Minions job queue: BullMQ-inspired, Postgres-native (queue, worker, backoff, types, protected-names, quiet-hours, stagger, handlers/shell).
+- `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 #1972 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/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one `pg_advisory_xact_lock` namespace keyed on `(name, queue, source)`: `maxWaiting` (rate cap, counts `waiting` only, NULL-source-as-wildcard scope) and `maxPending` (single-flight, counts `waiting` + live-lock `active` rows where `lock_until > now()`, EXACT source scope via `COALESCE(data->>'sourceId', data->>'source_id')` — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted `coalesced: true` metadata on the returned job. Both filter on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other. `claim` and `renewLock` issue their UPDATE via `engine.executeRawDirect` (not `executeRaw`) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to `executeRaw`. The two terminal dead-letter paths (`handleWallClockTimeouts` wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment `attempts_made` so a long job killed there reads as an honest attempt instead of `attempts 0 / started N`; the stall path also bumps `stalled_counter`, surfaced by `gbrain jobs get` as `Attempts: M/N (started: X, stalled: S/MaxS)`. At submit, `add()` stamps a default `timeout_ms` via `defaultTimeoutMsFor(jobName)` (from `handler-timeouts.ts`) when the caller passed none, and `claim()` COALESCEs a still-NULL `timeout_ms` from `HANDLER_DEFAULT_TIMEOUT_MS` (raw-object jsonb bind) deriving `timeout_at` from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit `opts.timeout_ms` always wins. The #4145 lock lease follows the identical three-layer shape: `add()` stamps `opts.lock_duration_ms` (clamped [5s,1h] via the shared `clampLockDurationMs`; INSERT-only — an idempotency-key re-submit never mutates the first submitter's lease) else `defaultLockDurationMsFor(jobName)`; `claim()` derives `lock_until` from `COALESCE(lock_duration_ms, map, worker default)` and stamps the resolved lease, SQL-clamping the row/map-resolved value to [5s,1h] (the worker-default fallback passes through unclamped — operator-configured, and tests legitimately use sub-5s leases) so a bypass-written out-of-range row can't produce a pathological lease; `handleWallClockTimeouts`' null-timeout fallback uses `COALESCE(lock_duration_ms, worker default)`. `handleStalled(graceMsOverride?)` applies the stall-sweep reclaim grace (`GBRAIN_MINION_STALL_RECLAIM_GRACE_MS`, default 15s, 0 = legacy predicate, capped at 600s with a warn-once clamp so an oversized value can't disable stalled-job recovery) to all three sweep predicates — a lease that lapsed within the grace is a starved owner's head start, not a steal candidate. Guarded by `test/queue-lock-retry.test.ts` (claim never falls back to `executeRaw`), `test/postgres-execute-raw-direct.test.ts` (routing decision matrix), and `test/minions.test.ts` (attempt accounting + default-timeout stamping). `MinionQueue.add()` gates `subagent` jobs on capability, not provider: `data.model` is classified via `classifyCapabilities()` (lazy-imported from `src/core/ai/capabilities.ts` to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (`unusable:no_tools`) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: `model-config.ts:enforceSubagentCapable` runtime fallback + `src/commands/doctor.ts` `subagent_provider` check). Pinned by `test/agent-cli.test.ts`. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE private `killJobs(tx, rows, cause, message)` tail: it emits `child_done(outcome)` to each non-terminal parent's inbox and flips any `waiting-children` parent whose last open child just died back to `waiting` — so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST via `lockParentsOrdered` (ascending-id row locks, matching `failJob`'s parent-before-child order) so the reapers and `failJob` can never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): any `waiting-children` parent with zero non-terminal children flips back to `waiting` (single UPDATE, NOT EXISTS on an indexed FK) — self-heals every stranding class, including parents stranded before the sweep existed. Every automatic re-run path clears `started_at` (`failJob`'s delayed retry branch, the stall requeue, lease release, `promoteDelayed`, and the parent-unblock flips) so the per-attempt wall clock measures execution, not backoff/queue wait — a retried job can't be dead-lettered by the wall-clock sweep before executing a line. Pinned by `test/queue-stall-parent-unblock.test.ts` + `test/queue-started-at-retry.test.ts`. `renewLock` accepts optional `{signal}` forwarded to executeRawDirect so the renewal tick's timeout race CANCELS a hung UPDATE instead of orphaning a checked-out pool slot (best-effort — the token fence is the correctness authority; a late-landing renewal can only extend a lease nobody else claimed).
- `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 moved-out generic abort listener now 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 was the unhandledRejection crash class during PgBouncer rotation). Gaps closed: (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 now counted as `overlapSkips` telemetry) + per-call `Promise.race` timeout with best-effort AbortSignal cancellation; (3) #4145 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 can no longer 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 now 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 (#1801). 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/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`) no longer permanently gives up (#1994/#2227): 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 no longer reads a healthy supervisor as "not running" (#2227). `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 (#1801): `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 (#1815). Queue-scoped singleton (#1849): 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 (an earlier revision mixed in a config-derived DB identity, which let two supervisors on the same physical DB via different-but-equivalent URLs compute different ids and both acquire — fixed). Two supervisors with different `$HOME`/`--pid-file` against the same `(database, queue)` no longer 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 now 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 now 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).
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index caa0b4af8b..1175afe45e 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.46.25.0",
+ "version": "0.46.26.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index 1ac664565c..34aae501e8 100644
--- a/package.json
+++ b/package.json
@@ -170,7 +170,7 @@
"bun": ">=1.3.10"
},
"license": "MIT",
- "version": "0.46.25.0",
+ "version": "0.46.26.0",
"overrides": {
"@hono/node-server": "^2.0.5",
"fast-uri": "^3.1.5",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index ac380baeff..f6501a3b9a 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.46.25.0",
+ "version": "0.46.26.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 — 18 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index c74adc1ab9..813a72849b 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.46.25.0",
+ "version": "0.46.26.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 — 18 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index ff06a8ed0f..879c7600f4 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.25.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.26.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.json
index b9679ef94d..51188cc4ae 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.46.25.0",
+ "version": "0.46.26.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 — 17 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index 303f4e7356..2d4c49dc93 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.46.25.0",
+ "version": "0.46.26.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 — 17 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index ca88f37447..3da15e8872 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.25.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.26.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.md
index 947d64ab5b..9412651503 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.25.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.26.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 5777e74384..5a07e58af8 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -60,6 +60,18 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/core/cycle/synthesize.ts": [
"test/e2e/multi-source-bug-class.test.ts",
"test/e2e/synthesize-bigint-job-id-postgres.test.ts",
+ "test/e2e/dream-synthesize-pglite.test.ts",
+ ],
+ // The inline drain claims from MinionQueue, so its entry must be a SUPERSET:
+ // the drain suite plus the full minions e2e set — a narrower list would
+ // reduce coverage vs the fail-closed run-everything default for unmapped paths.
+ "src/core/cycle/inline-drain.ts": [
+ "test/e2e/dream-synthesize-pglite.test.ts",
+ "test/e2e/minions-concurrency.test.ts",
+ "test/e2e/minions-resilience.test.ts",
+ "test/e2e/minions-shell.test.ts",
+ "test/e2e/minions-shell-pglite.test.ts",
+ "test/e2e/worker-abort-recovery.test.ts",
],
"src/commands/embed.ts": [
"test/e2e/multi-source-bug-class.test.ts",
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index f1843618c1..082a29db16 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -5,26 +5,26 @@
# Columns: path max_lines policy note
src/commands/doctor.ts 4366 ratchet grown v0.46.25.0 fix waves: sunset-aware search-mode check, dead-check pruning (#3626 #1871 #4382)
src/core/operations.ts 303 ratchet peel target: containment sprint C4-C7
-src/core/postgres-engine.ts 5989 ratchet grown v0.46.25.0 fix waves: registry plane + timeline honesty + think temporal windows (#1262 #3827 #4389)
+src/core/postgres-engine.ts 6016 ratchet grown v0.46.25.0 fix waves (#1262 #3827 #4389) + v0.46.26.0: private-queue token bootstrap probe
src/core/pglite-engine.ts 5971 ratchet grown v0.46.24.0 overnight wave: registry-aware writes + stale/invalidate plane unification (#1262); peeled cjk-search (#4299)
src/core/migrate.ts 668 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted
src/commands/sync.ts 4334 ratchet grown v0.46.25.0 fix waves: delete-slug resolver + msys healing (#3942 #2955)
src/core/ai/gateway.ts 4441 ratchet grown v0.46.25.0 D2: env-key snapshot stash (#2119)
src/cli.ts 3628 ratchet grown v0.46.25.0 D2: stdout interposer install (#4383)
-src/core/cycle.ts 3099 ratchet grown v0.46.25.0 fix waves: refresher abort gating + keyless honesty (#4309 #2821) | signal feature-detect (#4309 handler shape)
+src/core/cycle.ts 3123 ratchet grown v0.46.25.0 fix waves (#4309 #2821) + v0.46.26.0: cycle-start orphan recovery
src/commands/serve-http.ts 3294 ratchet grown v0.46.25.0 D2: /mcp per-request teardown (#2844)
-src/commands/jobs.ts 3041 ratchet grown v0.46.25.0 fix waves: jobs list/get --json (#3685)
+src/commands/jobs.ts 3093 ratchet grown v0.46.25.0 (--json #3685) + v0.46.26.0: maybeRunWorkerStartupRecovery extraction + stats gating + help text
src/core/search/hybrid.ts 2703 ratchet grown v0.46.25.0 fix waves: cache scope isolation + pool floor + offset bypass (#3871 #3002)
src/core/engine.ts 2415 ratchet grown v0.46.25.0 fix waves: timeline dedup contract + registry write contract (#3827 #1262)
-src/commands/autopilot.ts 2349 ratchet grown v0.46.25.0 fix waves: positional validation (#1525) + liveness takeover (#4300)
+src/commands/autopilot.ts 2356 ratchet grown v0.46.25.0 (#1525 #4300) + v0.46.26.0: GBRAIN_SUPERVISED strip
src/commands/extract.ts 2066 ratchet lowered: timeline extractor hoisted to core/timeline-extract.ts (module-cycle fix)
src/commands/extract-conversation-facts.ts 2045 ratchet grown v0.46.x per-provider gateway-unavailable copy
src/core/import-file.ts 2016 ratchet grown v0.46.24.0 overnight wave: embedding_plane_split named error (#4287)
-src/core/cycle/synthesize.ts 2702 ratchet merged: five-issue wave + dream-wave C7 peel + C8 manifest + C9 mode/telemetry/backfill + adversarial fix batches
+src/core/cycle/synthesize.ts 2725 ratchet merged waves + v0.46.26.0: rolling lease via shared throttled renewer
src/commands/embed.ts 2046 ratchet grown v0.46.25.0 delegated wave (#3971)
src/core/types.ts 1882 ratchet grown v0.46.22.0 phone wave: supersession rerank result fields + effective-date page filters (#4056 #4389)
src/commands/skillpack.ts 1360 ratchet
-src/core/minions/queue.ts 2138 ratchet grown by #4078 subagent-loop capability fix
+src/core/minions/queue.ts 2423 ratchet grown v0.46.26.0 private-queue lifecycle: recovery classifier + monotonic lease + makeThrottledLeaseRenewer
src/commands/init.ts 1950 ratchet grown v0.46.x keyless capability notices
src/commands/integrations.ts 1733 ratchet grown v0.46.24.0 overnight wave (#3588)
src/core/minions/handlers/subagent.ts 1825 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
@@ -36,3 +36,4 @@ src/core/embedding-migration.ts 1545 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1560 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment)
src/core/bootstrap/harness.ts 1947 ratchet
src/commands/hook.ts 1550 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth
+src/core/schema-embedded.ts 1504 ratchet grown v0.46.26.0: private-queue columns + recovery indexes in the embedded blob
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index c2a163422f..64826d97af 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -19,7 +19,7 @@ test/autopilot-install.test.ts autopilot wrapper script — env source order (v0
test/autopilot-pause-marker.test.ts pause marker fences minion job pickup 1 readFileSync
test/autopilot-self-upgrade.test.ts autopilot self-upgrade static-shape regressions 4 readFileSync
test/autopilot-shutdown-engine-close.test.ts autopilot.ts graceful engine shutdown (#1872) 6 readFileSync
-test/autopilot-supervisor-wiring.test.ts autopilot.ts ↔ ChildWorkerSupervisor wiring 6 readFileSync
+test/autopilot-supervisor-wiring.test.ts autopilot.ts ↔ ChildWorkerSupervisor wiring 7 readFileSync
test/backlinks-job-default.test.ts backlinks Minion handler — empty payload defaults to check, not fix 3 readFileSync
test/book-mirror.test.ts gbrain book-mirror — source file invariants 7 readFileSync
test/bootstrap-codex-door.test.ts Codex door — rendered AGENTS.md pull protocol (Gate 3) 2 readFileSync
@@ -140,6 +140,7 @@ test/integrations.test.ts CLI integration 3 readFileSync
test/jobs-embed-background-parity.serial.test.ts embed job background parity (D7) 2 readFileSync
test/jobs-list-get-json.serial.test.ts help advertises --json on list/get/stats (#3685) 2 readFileSync
test/jobs-thin-client-date-rehydration.test.ts thin-client unpack sites route through rehydrateJobDates (source audit) 2 readFileSync
+test/jobs-worker-startup-recovery.test.ts work-handler recovery placement (structural) 1 readFileSync
test/migrate-stdout-clean.test.ts migration output stays off stdout 2 readFileSync
test/migrate.test.ts PR #356 + #363 — session timeouts applied via startup parameters 1 readFileSync
test/migrate.test.ts PR #356 — LATEST_VERSION is max(versions), not array[-1] 2 readFileSync
@@ -212,6 +213,7 @@ test/skillpack-scaffold.test.ts runScaffold — happy path 3 readFileSync
test/skillpack-scrub-legacy.test.ts runScrubLegacy 8 readFileSync
test/sources-webhook.test.ts Webhook sync job extraction contract 1 readFileSync
test/spend-off-switch.test.ts reindex / onboard off-switch dispatch (regression guards) 3 bun-file
+test/supervisor.test.ts recovery hook timeout bound (structural) 1 readFileSync
test/sync-failures.test.ts Bug 9 — doctor surfaces sync failures 2 doctor-source-helper
test/sync-failures.test.ts Bug 9 — sync.ts CLI flag wiring 6 bun-file,doctor-source-helper
test/sync.test.ts buildSyncManifest 9 bun-file
diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.ts
index c2d3326ac2..11bc2a4acc 100644
--- a/src/commands/autopilot.ts
+++ b/src/commands/autopilot.ts
@@ -654,10 +654,17 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
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).
- env: { ...process.env },
+ // 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.
+ env: { ...process.env, GBRAIN_SUPERVISED: undefined } as Record<string, string | undefined>,
maxCrashes: 5,
isStopping: () => stopping,
onMaxCrashesExceeded: (count, max) => {
diff --git a/src/commands/doctor/checks/queue-jobs.ts b/src/commands/doctor/checks/queue-jobs.ts
index 758537f045..fc41abdb53 100644
--- a/src/commands/doctor/checks/queue-jobs.ts
+++ b/src/commands/doctor/checks/queue-jobs.ts
@@ -330,6 +330,7 @@ export async function computeWedgedQueueCheck(engine: BrainEngine): Promise<Chec
GROUP BY queue`,
);
const wedged: string[] = [];
+ const wedgedQueueNames: string[] = [];
for (const r of rows) {
const activeHealthy = Number(r.active_healthy ?? 0);
const waiting = Number(r.waiting ?? 0);
@@ -338,18 +339,33 @@ export async function computeWedgedQueueCheck(engine: BrainEngine): Promise<Chec
// threshold). The null-completions case is the supervisor's job.
if (activeHealthy === 0 && waiting > 0 && mins !== null && mins > thresholdMin) {
wedged.push(`'${r.queue}' (${waiting} waiting, 0 active, ${Math.round(mins)}m since last completion)`);
+ wedgedQueueNames.push(r.queue);
}
}
if (wedged.length === 0) {
return { name: 'wedged_queue', status: 'ok', message: 'No wedged queues' };
}
+ // Queue-aware restart hint: the bare stop/start pair bounces the DEFAULT
+ // worker — for a non-default wedged queue that advice restarts the wrong
+ // process. Name the queue in the start command. Queue names are
+ // producer-controlled and this hint gets copy-pasted (by operators AND
+ // remediation agents), so embedded quotes are escaped for the shell.
+ const shellQuote = (q: string) => `'${q.replace(/'/g, String.raw`'\''`)}'`;
+ const nonDefault = wedgedQueueNames.filter(q => q !== 'default');
+ const hints: string[] = [];
+ if (nonDefault.length < wedgedQueueNames.length || nonDefault.length === 0) {
+ hints.push('`gbrain jobs supervisor stop && gbrain jobs supervisor start`');
+ }
+ for (const q of nonDefault) {
+ hints.push(`\`gbrain jobs supervisor stop && gbrain jobs supervisor start --queue ${shellQuote(q)}\``);
+ }
+ const restartHint = hints.join(', ');
return {
name: 'wedged_queue',
status: 'fail',
message:
`Wedged queue(s) — worker alive but not claiming work: ${wedged.join('; ')}. ` +
- `Restart the worker so it rebuilds a fresh DB pool: ` +
- `\`gbrain jobs supervisor stop && gbrain jobs supervisor start\`, ` +
+ `Restart the worker so it rebuilds a fresh DB pool: ${restartHint}, ` +
`then \`gbrain jobs retry <id>\` on any dead-lettered jobs.`,
details: { wedged_queues: wedged.length, threshold_minutes: thresholdMin },
};
@@ -385,9 +401,11 @@ export async function computeWedgedQueueCheck(engine: BrainEngine): Promise<Chec
* (flagging them would fail doctor with no advertised fix).
*/
export async function computeOrphanedPrivateQueueCheck(engine: BrainEngine): Promise<Check> {
- if (engine.kind !== 'postgres') {
- return { name: 'orphaned_private_queue', status: 'ok', message: 'PGLite — no private queues to check' };
- }
+ // Runs on BOTH engines: PGLite mints the same dream-inline-* queues (every
+ // child is inlined precisely because no separate worker can run), and the
+ // grouped SQL below is plain Postgres that PGLite executes unchanged. The
+ // old PGLite short-circuit hid exactly the brains with the fewest recovery
+ // lanes.
const thresholdMin = _resolveEnvNumber('GBRAIN_ORPHANED_PRIVATE_QUEUE_MINUTES', 60);
try {
const { dreamInlineQueueAgeMs } = await import('../../../core/cycle/synthesize.ts');
@@ -437,7 +455,12 @@ export async function computeOrphanedPrivateQueueCheck(engine: BrainEngine): Pro
);
const nowMs = Date.now();
const orphaned: string[] = [];
- let waitingTotal = 0;
+ const candidateQueues: string[] = [];
+ // Per-candidate waiting counts, index-aligned with candidateQueues:
+ // waiting_jobs must count FLAGGED queues only — summing during the scan
+ // would include live-lease-suppressed and cap-truncated queues that
+ // orphaned_private_queues excludes.
+ const candidateWaiting: number[] = [];
let pausedTotal = 0;
let suppressedByLiveLock = 0;
for (const r of rows) {
@@ -475,35 +498,97 @@ export async function computeOrphanedPrivateQueueCheck(engine: BrainEngine): Pro
suppressedByLiveLock++;
continue;
}
- waitingTotal += waiting;
orphaned.push(`'${r.queue}' (${waiting} waiting, oldest ${Math.round(age)}m)`);
+ candidateQueues.push(r.queue);
+ candidateWaiting.push(waiting);
+ }
+ // Bucket the survivors through the SAME classifier recovery uses, so the
+ // advertised remediation and recovery's actual behavior cannot drift:
+ // live → owner lease/lock still healthy — suppress (not an orphan);
+ // orphan → metadata-backed: auto-recovery cancels it at the next
+ // worker spawn or cycle start;
+ // unowned → legacy pre-metadata rows: retriage preview is the tool;
+ // not_orphan→ owner job non-terminal — inspect the owner, don't cancel.
+ const { MinionQueue } = await import('../../../core/minions/queue.ts');
+ const classifierQueue = new MinionQueue(engine);
+ let suppressedByLiveLease = 0;
+ const recoverable: string[] = [];
+ const legacyUnowned: string[] = [];
+ const ownerPending: string[] = [];
+ // One classify query per candidate — cap the loop so a pathological brain
+ // (hundreds of stale queues) can't turn an advisory doctor check into a
+ // hang; the count line below reports the truncation honestly.
+ const CLASSIFY_CAP = 100;
+ const truncatedCandidates = Math.max(0, candidateQueues.length - CLASSIFY_CAP);
+ candidateQueues.length = Math.min(candidateQueues.length, CLASSIFY_CAP);
+ let flaggedWaiting = 0;
+ for (let i = 0; i < candidateQueues.length; i++) {
+ const verdict = await classifierQueue.classifyPrivateQueueForRecovery(candidateQueues[i]);
+ if (verdict === 'live') { suppressedByLiveLease++; continue; }
+ if (verdict === 'orphan') recoverable.push(orphaned[i]);
+ else if (verdict === 'unowned') legacyUnowned.push(orphaned[i]);
+ else ownerPending.push(orphaned[i]);
+ flaggedWaiting += candidateWaiting[i];
}
- if (orphaned.length === 0) {
+ const flagged = recoverable.length + legacyUnowned.length + ownerPending.length;
+ if (flagged === 0) {
+ const suppressed = suppressedByLiveLock + suppressedByLiveLease;
return {
name: 'orphaned_private_queue',
status: 'ok',
- message: suppressedByLiveLock > 0
- ? `No provably-orphaned private queues (${suppressedByLiveLock} possibly owned by a live cycle)`
+ // Truncation must stay visible on the ok path too: 100 live + 50
+ // never-classified candidates is NOT a clean bill of health.
+ message: suppressed > 0 || truncatedCandidates > 0
+ ? `No provably-orphaned private queues (${suppressed} possibly owned by a live cycle` +
+ (truncatedCandidates > 0 ? `, ${truncatedCandidates} unclassified — re-run doctor to page through them` : '') + `)`
: 'No orphaned private queues',
- ...(pausedTotal > 0 || suppressedByLiveLock > 0
- ? { details: { paused_jobs: pausedTotal, suppressed_by_live_lock: suppressedByLiveLock } }
+ ...(pausedTotal > 0 || suppressed > 0 || truncatedCandidates > 0
+ ? { details: {
+ paused_jobs: pausedTotal,
+ suppressed_by_live_lock: suppressedByLiveLock,
+ suppressed_by_live_lease: suppressedByLiveLease,
+ ...(truncatedCandidates > 0 ? { unclassified_candidates: truncatedCandidates } : {}),
+ } }
: {}),
};
}
+ const remediation: string[] = [];
+ if (recoverable.length > 0) {
+ remediation.push(
+ `Auto-recovery cancels the metadata-backed queue(s) at the next worker spawn or dream-cycle start` +
+ (engine.kind === 'postgres'
+ ? ` (trigger now: \`gbrain jobs supervisor start\`)`
+ : ` (trigger now: \`gbrain dream\`)`) + `.`,
+ );
+ }
+ if (legacyUnowned.length > 0) {
+ remediation.push(
+ `Legacy unowned queue(s) need manual retriage: preview with \`gbrain dream retriage --help\` ` +
+ `and apply cancellation only after reviewing that dry run.`,
+ );
+ }
+ if (ownerPending.length > 0) {
+ remediation.push(
+ `Owner-pending queue(s) have a NON-terminal owner job — inspect it with \`gbrain jobs get <owner id>\` before cancelling anything.`,
+ );
+ }
return {
name: 'orphaned_private_queue',
status: 'fail',
message:
- `Orphaned private dream queue(s): ${orphaned.join('; ')}. ` +
- `A supervisor restart cannot consume these parent-owned queues. ` +
- `Run \`gbrain dream retriage --help\` and use its queue-reconciliation dry run; ` +
- `apply cancellation only after reviewing that preview.`,
+ `Orphaned private dream queue(s): ${[...recoverable, ...legacyUnowned, ...ownerPending].join('; ')}. ` +
+ `A supervisor restart cannot consume these parent-owned queues. ${remediation.join(' ')}`,
details: {
- orphaned_private_queues: orphaned.length,
- waiting_jobs: waitingTotal,
+ orphaned_private_queues: flagged,
+ recoverable_queues: recoverable.length,
+ legacy_unowned_queues: legacyUnowned.length,
+ owner_pending_queues: ownerPending.length,
+ waiting_jobs: flaggedWaiting,
paused_jobs: pausedTotal,
suppressed_by_live_lock: suppressedByLiveLock,
+ suppressed_by_live_lease: suppressedByLiveLease,
threshold_minutes: thresholdMin,
+ ...(truncatedCandidates > 0 ? { unclassified_candidates: truncatedCandidates } : {}),
},
};
} catch (e) {
diff --git a/src/commands/doctor/checks/routing-federation.ts b/src/commands/doctor/checks/routing-federation.ts
index 91bbc3bf84..17fd872f7e 100644
--- a/src/commands/doctor/checks/routing-federation.ts
+++ b/src/commands/doctor/checks/routing-federation.ts
@@ -408,13 +408,20 @@ export async function checkStaleLocks(
}
const lines = stale.slice(0, 10).map(s => {
const ageH = Math.floor(s.age_ms / 3600_000);
- let breakHint = 'gbrain doctor';
+ // Every hint here must be a REAL command: `gbrain dream --break-lock`
+ // was advertised for years but dream never implemented the flag —
+ // pasting the hint ran a full (paid) dream cycle instead of breaking a
+ // lock. Cycle locks: dead-holder rows on THIS host are reaped by
+ // `gbrain doctor --fix` (checkStaleLocks above) and swept automatically
+ // at the next dream-cycle start; cross-host or live-holder locks have
+ // no safe break command by design. The old fallback 'gbrain doctor' was
+ // circular (this line IS doctor output) and plain doctor reaps nothing.
+ let breakHint =
+ 'expired lock is swept at the next acquire; if it persists, inspect the gbrain_cycle_locks row';
if (s.id.startsWith('gbrain-sync:')) {
breakHint = `gbrain sync --break-lock --source ${s.id.slice('gbrain-sync:'.length)}`;
- } else if (s.id.startsWith('gbrain-cycle:')) {
- breakHint = `gbrain dream --break-lock --source ${s.id.slice('gbrain-cycle:'.length)}`;
- } else if (s.id === 'gbrain-cycle') {
- breakHint = 'gbrain dream --break-lock';
+ } else if (s.id.startsWith('gbrain-cycle:') || s.id === 'gbrain-cycle') {
+ breakHint = 'gbrain doctor --fix (reaps dead holders on this host; also swept at next dream start)';
}
return ` ${s.id} (pid ${s.holder_pid} on ${s.holder_host}, age ${ageH}h) → ${breakHint}`;
});
diff --git a/src/commands/jobs.ts b/src/commands/jobs.ts
index 38175479fc..0db3abf6ea 100644
--- a/src/commands/jobs.ts
+++ b/src/commands/jobs.ts
@@ -349,6 +349,8 @@ USAGE
gbrain jobs prune [--older-than 30d] [--dry-run]
gbrain jobs delete <id>
gbrain jobs stats [--queue Q] [--cluster-errors] [--json]
+ (dream-inline-* queues report ABANDONED/live only with an
+ explicit --queue; use \`gbrain doctor\` to discover them)
gbrain jobs smoke [--sigkill-rescue] [--wedge-rescue]
gbrain jobs watch [--json] [--follow] [--refresh-ms=N]
gbrain jobs work [--queue Q] [--concurrency N] [--max-rss MB]
@@ -558,6 +560,30 @@ 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,
+): Promise<void> {
+ if (env.GBRAIN_SUPERVISED === '1') return;
+ try {
+ const recovered = await queue.reconcileOrphanedPrivateQueues({
+ reason: 'worker startup recovery: orphaned dream-inline private queue',
+ });
+ if (recovered.cancelled_jobs > 0) {
+ console.error(
+ `[gbrain jobs] private-queue startup recovery: cancelled ${recovered.cancelled_jobs} ` +
+ `job(s) across ${recovered.cancelled_queues} orphaned queue(s)`,
+ );
+ }
+ } catch (e) {
+ console.error(`[gbrain jobs] private-queue startup recovery failed: ${e instanceof Error ? e.message : String(e)}`);
+ }
+}
+
export async function runJobs(engineOrNull: BrainEngine | null, args: string[]): Promise<void> {
const sub = args[0];
@@ -1102,8 +1128,25 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):
const mins = w.minutes_since_completion;
// Shared derivation (queue.ts deriveWedgeSignal) so this line, the
// doctor wedged_queue check, and the get_job_stats op agree (#1801).
- const { wedged, wedge_threshold_minutes: wedgeMins } = deriveWedgeSignal(w);
- if (wedged) {
+ const { wedged, wedge_threshold_minutes: wedgeMins, private_queue } = deriveWedgeSignal(w);
+ // Parent-owned dream-inline queue: no shared worker can EVER claim it,
+ // so the supervisor-restart advice below would be a dead end (the
+ // incident bug class). Gate the ABANDONED line on the SAME classifier
+ // recovery uses — a healthy mid-drain queue (active_healthy 0 in a
+ // claim gap) classifies live and must not scream.
+ const privateVerdict = private_queue && w.active_healthy === 0 && w.waiting > 0
+ ? await queue.classifyPrivateQueueForRecovery(w.queue)
+ : null;
+ if (privateVerdict === 'orphan' || privateVerdict === 'unowned') {
+ const since = mins === null ? 'no completions on record' : `${mins}m since last completion`;
+ console.log(
+ `\n ⚠ ABANDONED PRIVATE QUEUE '${w.queue}': ${w.waiting} waiting, 0 active (live-lock), ${since}.\n` +
+ ` This dream-inline queue is parent-owned; restarting a worker cannot consume it.\n` +
+ (privateVerdict === 'orphan'
+ ? ` Auto-recovery cancels it at the next worker spawn or dream-cycle start.`
+ : ` Legacy unowned queue: preview \`gbrain dream retriage --help\` before manual cancellation.`),
+ );
+ } else if (wedged) {
const since = mins === null ? 'no completions on record' : `${mins}m since last completion`;
console.log(
`\n ⚠ WEDGED QUEUE '${w.queue}': ${w.waiting} waiting, 0 active (live-lock), ${since}.\n` +
@@ -1560,6 +1603,8 @@ 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); }
+ await maybeRunWorkerStartupRecovery(queue);
+
// issue #6: the direct-pool kill switch collapses lock renewal, health
// probes, and handler workload onto ONE shared pool — silently. Make
// the collapse loud at startup so a later 'pool_starved' incident has
@@ -2609,6 +2654,7 @@ export async function registerBuiltinHandlers(
pull,
signal: job.signal, // propagate abort so cycle bails on timeout/cancel
deadlineAtMs: job.deadlineAtMs, // #2781: phases budget sub-work from remaining time
+ privateQueueOwnerJobId: job.id,
...(sourceId ? { sourceId } : {}),
...(effectivePhases !== undefined ? { phases: effectivePhases as any } : {}),
yieldBetweenPhases: async () => {
@@ -2655,6 +2701,11 @@ export async function registerBuiltinHandlers(
pull: false, // brain-wide DB/maintenance work never git-pulls
signal: job.signal,
deadlineAtMs: job.deadlineAtMs, // #2781: phases budget sub-work from remaining time
+ // The maintenance lane is where synthesize/patterns actually run on
+ // multi-source brains (per-source payloads normalize down to the
+ // freshness phases) — without the owner id its private queues would be
+ // owner-less and recovery would degrade to lease-expiry only.
+ privateQueueOwnerJobId: job.id,
phases,
forceGlobalOrphans: true,
yieldBetweenPhases: async () => { await new Promise<void>((r) => setImmediate(r)); },
@@ -2805,6 +2856,7 @@ export async function registerBuiltinHandlers(
phases: [phase as any],
signal: job.signal,
deadlineAtMs: job.deadlineAtMs, // #2781: phases budget sub-work from remaining time
+ privateQueueOwnerJobId: job.id,
});
return { phase, status: report.status, report };
};
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index eb0c0fd4f2..6126f01675 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -560,6 +560,8 @@ export interface CycleOpts {
* phases then use their configured timeouts unchanged.
*/
deadlineAtMs?: number | null;
+ /** Internal: minion job id that owns any phase-created private dream-inline queues. */
+ privateQueueOwnerJobId?: number | null;
}
// ─── Lock primitives ───────────────────────────────────────────────
@@ -2062,6 +2064,26 @@ export async function runCycle(
// Non-fatal: reaping is a backstop, never blocks the cycle.
console.warn(`[cycle] dead-holder lock reap failed (non-fatal): ${e instanceof Error ? e.message : String(e)}`);
}
+ // Orphaned-private-queue recovery at cycle start — the ONLY recovery lane
+ // on engines that never run a supervisor/worker process (PGLite inlines
+ // every child), and a cheap idempotent second net elsewhere. Same posture
+ // as the lock reap above: best-effort, never blocks the cycle; the
+ // classifier skips live queues (healthy child lock / live owner / future
+ // lease), so a concurrent cycle's queue is never touched.
+ try {
+ const { MinionQueue } = await import('./minions/queue.ts');
+ const recovered = await new MinionQueue(engine).reconcileOrphanedPrivateQueues({
+ reason: 'cycle startup recovery: orphaned dream-inline private queue',
+ });
+ if (recovered.cancelled_jobs > 0) {
+ console.warn(
+ `[cycle] private-queue startup recovery: cancelled ${recovered.cancelled_jobs} ` +
+ `job(s) across ${recovered.cancelled_queues} orphaned queue(s)`,
+ );
+ }
+ } catch (e) {
+ console.warn(`[cycle] private-queue startup recovery failed (non-fatal): ${e instanceof Error ? e.message : String(e)}`);
+ }
}
try {
@@ -2172,6 +2194,7 @@ export async function runCycle(
// job budget (same collision shape as propose_takes, cross-process
// timeout domain — clamped via the patterns.ts childBudget template).
deadlineAtMs: opts.deadlineAtMs ?? null,
+ privateQueueOwnerJobId: opts.privateQueueOwnerJobId ?? null,
}));
result.duration_ms = duration_ms;
phaseResults.push(result);
@@ -2380,6 +2403,7 @@ export async function runCycle(
yieldDuringPhase: buildYieldDuringPhase(lock, opts.yieldDuringPhase, onStolen),
once: opts.onceForPhase === 'patterns',
deadlineAtMs: opts.deadlineAtMs ?? null,
+ privateQueueOwnerJobId: opts.privateQueueOwnerJobId ?? null,
// #1586: scope pattern writes to the cycle's resolved source, same as
// synthesize above. Without it the child's put_page rows land in
// 'default' while the reverse-write drops the file into the named
diff --git a/src/core/cycle/inline-drain.ts b/src/core/cycle/inline-drain.ts
index 2479399b1c..2ce192c13e 100644
--- a/src/core/cycle/inline-drain.ts
+++ b/src/core/cycle/inline-drain.ts
@@ -232,6 +232,11 @@ async function drainLoop(
continue;
}
if (pending === 0) return;
+ // Renew the private-queue lease (and cycle lock) from the idle poll
+ // too: with every child delayed/backing off no per-child keepalive is
+ // armed, and an unrenewed lease reads as orphaned to spawn recovery —
+ // which would cancel this LIVE queue. The wrapper self-throttles (30s).
+ if (yieldDuringPhase) { try { await yieldDuringPhase(); } catch { /* best-effort */ } }
// Idle poll with backoff (1s → 5s): under a pool, idle loops must not
// hammer the queue while the last slow child drains.
await new Promise((r) => setTimeout(r, idlePollMs));
@@ -239,6 +244,10 @@ async function drainLoop(
continue;
}
idlePollMs = 1000;
+ // Same lease-liveness rationale as the idle branch, for the fast-failing
+ // child shape: a handler that dies in <60s never fires its first
+ // keepalive tick, so a claim-fail-claim loop would run lease-blind.
+ if (yieldDuringPhase) { try { await yieldDuringPhase(); } catch { /* best-effort */ } }
const abort = new AbortController();
const shutdown = new AbortController();
diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.ts
index 31b112d56c..50773be27f 100644
--- a/src/core/cycle/patterns.ts
+++ b/src/core/cycle/patterns.ts
@@ -23,9 +23,9 @@ import { mkdirSync, writeFileSync } from 'node:fs';
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
import type { PhaseResult, PhaseError } from '../cycle.ts';
-import { MinionQueue } from '../minions/queue.ts';
+import { DEFAULT_PRIVATE_QUEUE_LEASE_MS, MinionQueue } from '../minions/queue.ts';
import { isQueueQuotaExceededError } from '../minions/admission.ts';
-import { waitForCompletion, TimeoutError } from '../minions/wait-for-completion.ts';
+import { waitForCompletionRenewing, TimeoutError } from '../minions/wait-for-completion.ts';
import type { MinionJobInput, MinionJobStatus, SubagentHandlerData } from '../minions/types.ts';
import { serializeMarkdown } from '../markdown.ts';
import { truncateUtf8 } from '../text-safe.ts';
@@ -68,6 +68,8 @@ export interface PatternsPhaseOpts {
* row. Unset → legacy 'default'. Mirrors synthesize.ts's `sourceId`.
*/
sourceId?: string;
+ /** Internal: minion owner job id for private dream-inline queue recovery. */
+ privateQueueOwnerJobId?: number | null;
}
/**
@@ -122,6 +124,7 @@ export async function runPhasePatterns(
opts: PatternsPhaseOpts,
): Promise<PhaseResult> {
const start = Date.now();
+ let ownedPrivateQueue: { queue: MinionQueue; name: string } | null = null;
try {
const config = await loadPatternsConfig(engine);
@@ -204,6 +207,14 @@ export async function runPhasePatterns(
// never claim a child this parent is about to run itself. Mirrors
// synthesize.ts's childQueueName derivation exactly.
const childQueueName = `dream-inline-${Date.now()}-${randomUUID().slice(0, 8)}`;
+ ownedPrivateQueue = { queue, name: childQueueName };
+ const privateQueueOwnerToken = randomUUID();
+ // Same lease posture as synthesize: rolling 10-min default lease renewed
+ // every ≤30s (drain loop + chunked post-drain wait); the whole wrapper is
+ // 30s-throttled so idle polls cost one UPDATE per half-minute.
+ const renewPrivateQueueLease = queue.makeThrottledLeaseRenewer(
+ childQueueName, privateQueueOwnerToken, opts.yieldDuringPhase,
+ );
const data: SubagentHandlerData = {
prompt: buildPatternsPrompt(reflections, config.minEvidence, config.sourceSlugPrefix, config.outputSlugPrefix),
model: config.model,
@@ -221,6 +232,9 @@ export async function runPhasePatterns(
max_stalled: 3,
timeout_ms: budgets.timeoutMs,
queue: childQueueName,
+ private_queue_owner_job_id: opts.privateQueueOwnerJobId ?? null,
+ private_queue_owner_token: privateQueueOwnerToken,
+ private_queue_lease_ms: DEFAULT_PRIVATE_QUEUE_LEASE_MS,
};
let job: Awaited<ReturnType<typeof queue.add>>;
try {
@@ -241,13 +255,14 @@ export async function runPhasePatterns(
// the terminal state instead of polling waitForCompletion until
// subagentWaitTimeoutMs expires. Runs on BOTH engines — on Postgres the
// parent job otherwise deadlocks a fully-occupied worker (#2050).
- await runSubagentsInline(engine, queue, childQueueName, opts.yieldDuringPhase);
+ await runSubagentsInline(engine, queue, childQueueName, renewPrivateQueueLease);
let outcome: MinionJobStatus | 'timeout';
try {
- const final = await waitForCompletion(queue, job.id, {
+ const final = await waitForCompletionRenewing(queue, job.id, {
timeoutMs: budgets.waitTimeoutMs,
pollMs: 5 * 1000,
+ renew: renewPrivateQueueLease,
});
outcome = final.status;
} catch (e) {
@@ -326,6 +341,24 @@ export async function runPhasePatterns(
return failed(makeError('InternalError', 'PATTERNS_PHASE_FAIL',
e instanceof Error ? (e.message || 'patterns phase threw') : String(e)));
} finally {
+ if (ownedPrivateQueue) {
+ try {
+ const cancelled = await ownedPrivateQueue.queue.reconcilePrivateQueue(
+ ownedPrivateQueue.name,
+ 'private queue owner terminalized: patterns phase ended',
+ );
+ if (cancelled.length > 0) {
+ process.stderr.write(
+ `[dream] patterns reconciled ${cancelled.length} non-terminal child job(s) from ${ownedPrivateQueue.name}\n`,
+ );
+ }
+ } catch (cleanupError) {
+ process.stderr.write(
+ `[dream] patterns private-queue cleanup failed for ${ownedPrivateQueue.name}: ` +
+ `${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}\n`,
+ );
+ }
+ }
void start;
}
}
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index 029f7c5cca..1a4ee9428b 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.ts
@@ -51,10 +51,10 @@ import { basename, join, dirname, isAbsolute, resolve } from 'node:path';
import { parseLlmJson } from '../llm-json.ts';
import type { BrainEngine, DreamVerdict, TriageSegment } from '../engine.ts';
import type { PhaseResult, PhaseError } from '../cycle.ts';
-import { MinionQueue } from '../minions/queue.ts';
+import { DEFAULT_PRIVATE_QUEUE_LEASE_MS, MinionQueue } from '../minions/queue.ts';
import { clampSubagentBudgets, CYCLE_DEADLINE_RESERVE_MS, MIN_PATTERNS_SUBAGENT_BUDGET_MS } from './patterns.ts';
import { isQueueQuotaExceededError } from '../minions/admission.ts';
-import { waitForCompletion, TimeoutError } from '../minions/wait-for-completion.ts';
+import { waitForCompletionRenewing, TimeoutError } from '../minions/wait-for-completion.ts';
import type { MinionJobInput, SubagentHandlerData } from '../minions/types.ts';
import { runSubagentsInline, runDrainRenewalTick, percentile, INLINE_LOCK_MS } from './inline-drain.ts';
import { buildManifestContext, buildLinkManifest, type ManifestContext } from './link-manifest.ts';
@@ -330,6 +330,8 @@ export interface SynthesizePhaseOpts {
* correct (source_id, slug) row. Unset → legacy 'default'.
*/
sourceId?: string;
+ /** Internal: minion owner job id for private dream-inline queue recovery. */
+ privateQueueOwnerJobId?: number | null;
/**
* issue #2860 — `gbrain dream --phase synthesize --once`. Bypasses the
* `dream.synthesize.enabled` gate for THIS call only (does NOT bypass
@@ -344,6 +346,7 @@ export async function runPhaseSynthesize(
opts: SynthesizePhaseOpts,
): Promise<PhaseResult> {
const start = Date.now();
+ let ownedPrivateQueue: { queue: MinionQueue; name: string } | null = null;
// Normalize brainDir to an absolute path BEFORE any reverse-write. Without
// this, a relative or empty brainDir flows down to writeReversePages →
// `join(brainDir, '${slug}.md')` → relative path → resolves against cwd at
@@ -546,6 +549,17 @@ export async function runPhaseSynthesize(
// unrelated 'default'-queue jobs, and a 'default'-queue worker must never
// claim a child this parent is about to run itself.
const childQueueName = `dream-inline-${Date.now()}-${randomUUID().slice(0, 8)}`;
+ ownedPrivateQueue = { queue, name: childQueueName };
+ const privateQueueOwnerToken = randomUUID();
+ // Rolling 10-min lease renewed every ≤30s from the drain loop (idle polls,
+ // claim iterations, per-child keepalive) and the post-drain chunked wait —
+ // a crashed run's queue becomes lease-recoverable within ~10 minutes
+ // instead of a wait-timeout-sized horizon. The whole wrapper (lease AND
+ // cycle-lock refresh) is 30s-throttled so 1-5s polls cost one UPDATE per
+ // half-minute, not per poll; the cycle lock's 5-min TTL is ample at 30s.
+ const renewPrivateQueueLease = queue.makeThrottledLeaseRenewer(
+ childQueueName, privateQueueOwnerToken, opts.yieldDuringPhase,
+ );
const childIds: number[] = [];
/** Map child job_id → chunk metadata for D6 orchestrator-side slug rewrite. */
const chunkInfo = new Map<number, { idx: number; hash6: string }>();
@@ -756,6 +770,9 @@ export async function runPhaseSynthesize(
idempotency_key,
timeout_ms: perChild.timeoutMs,
queue: childQueueName,
+ private_queue_owner_job_id: opts.privateQueueOwnerJobId ?? null,
+ private_queue_owner_token: privateQueueOwnerToken,
+ private_queue_lease_ms: DEFAULT_PRIVATE_QUEUE_LEASE_MS,
};
let child: Awaited<ReturnType<typeof queue.add>>;
try {
@@ -856,7 +873,7 @@ export async function runPhaseSynthesize(
}
const drainStartedAt = Date.now();
await runSubagentsInline(
- engine, queue, childQueueName, opts.yieldDuringPhase,
+ engine, queue, childQueueName, renewPrivateQueueLease,
undefined, undefined, effectiveConcurrency, opts.deadlineAtMs ?? null,
);
// Captured HERE: everything after this line (waiters, collection,
@@ -892,9 +909,10 @@ export async function runPhaseSynthesize(
const remainingParentMs = opts.deadlineAtMs != null
? Math.max(1000, opts.deadlineAtMs - CYCLE_DEADLINE_RESERVE_MS - Date.now())
: config.subagentWaitTimeoutMs;
- const job = await waitForCompletion(queue, jobId, {
+ const job = await waitForCompletionRenewing(queue, jobId, {
timeoutMs: Math.min(config.subagentWaitTimeoutMs, remainingParentMs),
pollMs: 5 * 1000,
+ renew: renewPrivateQueueLease,
});
// Turn telemetry: surfaces max_turns cap pressure in details.synthesis
// so the 30→16 default can be re-litigated on data. #4216 adds the
@@ -1135,6 +1153,27 @@ export async function runPhaseSynthesize(
} catch (e) {
return failed(makeError('InternalError', 'SYNTH_PHASE_FAIL',
e instanceof Error ? (e.message || 'synthesize phase threw') : String(e)));
+ } finally {
+ if (ownedPrivateQueue) {
+ try {
+ const cancelled = await ownedPrivateQueue.queue.reconcilePrivateQueue(
+ ownedPrivateQueue.name,
+ 'private queue owner terminalized: synthesize phase ended',
+ );
+ if (cancelled.length > 0) {
+ process.stderr.write(
+ `[dream] synthesize reconciled ${cancelled.length} non-terminal child job(s) from ${ownedPrivateQueue.name}\n`,
+ );
+ }
+ } catch (cleanupError) {
+ // The phase result must survive a transient cleanup failure; Doctor
+ // and waiting-TTL remain delayed backstops and will surface/reap it.
+ process.stderr.write(
+ `[dream] synthesize private-queue cleanup failed for ${ownedPrivateQueue.name}: ` +
+ `${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}\n`,
+ );
+ }
+ }
}
}
diff --git a/src/core/migrate.ts b/src/core/migrate.ts
index de0c2b7358..2e279d2b18 100644
--- a/src/core/migrate.ts
+++ b/src/core/migrate.ts
@@ -6008,6 +6008,27 @@ export const MIGRATIONS: Migration[] = [
WHERE expired_at IS NULL;
`,
},
+ {
+ version: 136,
+ name: 'minion_private_queue_owner_metadata',
+ // issue #4332: durable ownership/liveness metadata for parent-owned
+ // dream-inline queues. Startup recovery uses these columns to cancel only
+ // orphaned private queues (terminal/missing owner or expired lease), never
+ // live queues and never legacy unowned rows.
+ idempotent: true,
+ sql: `
+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_owner_job_id INTEGER REFERENCES minion_jobs(id) ON DELETE SET NULL;
+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_owner_token TEXT;
+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_lease_until TIMESTAMPTZ;
+ CREATE INDEX IF NOT EXISTS idx_minion_jobs_private_queue_recovery
+ ON minion_jobs (queue, private_queue_lease_until)
+ WHERE queue LIKE 'dream-inline-%'
+ AND status IN ('waiting','active','delayed','waiting-children','paused');
+ CREATE INDEX IF NOT EXISTS idx_minion_jobs_private_queue_owner
+ ON minion_jobs (private_queue_owner_job_id)
+ WHERE private_queue_owner_job_id IS NOT NULL;
+ `,
+ },
];
export const LATEST_VERSION = MIGRATIONS.length > 0
diff --git a/src/core/minions/child-worker-supervisor.ts b/src/core/minions/child-worker-supervisor.ts
index 6b349f52d9..ed4c5d0991 100644
--- a/src/core/minions/child-worker-supervisor.ts
+++ b/src/core/minions/child-worker-supervisor.ts
@@ -145,6 +145,17 @@ export interface ChildWorkerSupervisorOpts {
/** Accessor for the composer's stopping flag; loop exits when this returns true. */
isStopping: () => boolean;
+ /**
+ * Optional fenced maintenance hook run immediately before EVERY child spawn,
+ * including crash/watchdog respawns. The composer owns error handling AND
+ * bounding: a rejection propagates out of run() with no crash accounting or
+ * respawn, and the await is not isStopping-checked — so composers must
+ * try/catch and time-bound the hook themselves (MinionSupervisor wraps its
+ * recovery hook in a 30s race and spawns on failure). Reserve a bare
+ * rethrowing hook for genuine spawn-blocking safety preconditions.
+ */
+ beforeSpawn?: () => Promise<void>;
+
/** Test seed for the clean-restart window. Defaults to Date.now. @internal */
_now?: () => number;
}
@@ -328,6 +339,8 @@ export class ChildWorkerSupervisor {
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;
diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.ts
index 4e36c77c57..507152d181 100644
--- a/src/core/minions/queue.ts
+++ b/src/core/minions/queue.ts
@@ -49,6 +49,15 @@ export interface TrustedSubmitOpts {
const MIGRATION_VERSION = 7;
const DEFAULT_MAX_SPAWN_DEPTH = 5;
+export const DREAM_INLINE_PRIVATE_QUEUE_PREFIX = 'dream-inline-';
+export const DEFAULT_PRIVATE_QUEUE_LEASE_MS = 10 * 60 * 1000;
+/**
+ * Machine-readable reason family for private-queue reconciliation, mirroring
+ * the waiting-TTL prefix convention: every reconcile cancellation is stamped
+ * `<prefix>: <detail>` by reconcilePrivateQueue itself, so jobs-stats/doctor
+ * surfaces can LIKE-match the family without chasing per-call-site strings.
+ */
+export const PRIVATE_QUEUE_RECONCILE_REASON_PREFIX = 'private_queue_reconciled';
/**
* Stall-sweep reclaim grace (#4145, CDX-7): don't reclaim a row whose
@@ -108,6 +117,28 @@ export function resolveStallReclaimGraceMs(
const DEFAULT_MAX_ATTACHMENT_BYTES = 5 * 1024 * 1024; // 5 MiB
const TERMINAL_STATUSES = ['completed', 'failed', 'dead', 'cancelled'] as const;
+const NON_TERMINAL_STATUSES: MinionJobStatus[] = ['waiting', 'active', 'delayed', 'waiting-children', 'paused'];
+/**
+ * Literal IN-list derived from the constant above, for the recovery queries:
+ * the partial indexes idx_minion_jobs_private_queue_* embed these statuses in
+ * their WHERE predicate, and a parameterized `= ANY($n)` under a generic plan
+ * cannot be proven to imply it — literals keep the queries index-eligible.
+ * Values are internal constants, never user input.
+ */
+const NON_TERMINAL_SQL_LIST = NON_TERMINAL_STATUSES.map(st => `'${st}'`).join(', ');
+
+export function isDreamInlinePrivateQueue(queueName: string): boolean {
+ return queueName.startsWith(DREAM_INLINE_PRIVATE_QUEUE_PREFIX);
+}
+
+export interface PrivateQueueRecoveryResult {
+ scanned_queues: number;
+ cancelled_queues: number;
+ cancelled_jobs: number;
+ skipped_live_queues: number;
+ skipped_unowned_queues: number;
+ skipped_non_orphan_queues: number;
+}
/** Audit payload deferred from inside the submission transaction. */
type CoalesceAuditEvent = {
@@ -549,13 +580,18 @@ export class MinionQueue {
? Math.max(1, Math.min(100, Math.floor(opts!.max_stalled as number)))
: null;
+ const privateQueueLeaseUntil = opts?.private_queue_lease_ms != null
+ ? new Date(Date.now() + Math.max(1, Math.floor(opts.private_queue_lease_ms))).toISOString()
+ : null;
+
const baseCols = `name, queue, status, priority, data, max_attempts, backoff_type,
backoff_delay, backoff_jitter, delay_until, parent_job_id, on_child_fail,
depth, max_children, timeout_ms, lock_duration_ms, remove_on_complete, remove_on_fail, idempotency_key,
- quiet_hours, stagger_key`;
+ quiet_hours, stagger_key, private_queue_owner_job_id, private_queue_owner_token, private_queue_lease_until`;
const baseVals = `$1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20::jsonb, $21`;
+ const baseValsWithOwner = `${baseVals}, $22, $23, $24`;
const cols = hasMaxStalled ? `${baseCols}, max_stalled` : baseCols;
- const vals = hasMaxStalled ? `${baseVals}, $22` : baseVals;
+ const vals = hasMaxStalled ? `${baseValsWithOwner}, $25` : baseValsWithOwner;
const insertSql = opts?.idempotency_key
? `INSERT INTO minion_jobs (${cols})
@@ -598,6 +634,9 @@ export class MinionQueue {
opts?.idempotency_key ?? null,
opts?.quiet_hours ?? null,
opts?.stagger_key ?? null,
+ opts?.private_queue_owner_job_id ?? null,
+ opts?.private_queue_owner_token ?? null,
+ privateQueueLeaseUntil,
];
if (hasMaxStalled) params.push(clampedMaxStalled);
@@ -721,6 +760,246 @@ export class MinionQueue {
return root ?? null;
}
+ /**
+ * Terminalize every non-terminal job in one private, parent-owned queue.
+ *
+ * Dream phases drain `dream-inline-*` queues themselves; the shared worker
+ * intentionally never claims them. A phase therefore owns cleanup too:
+ * every return/throw/timeout path calls this from `finally`. The method is
+ * idempotent and routes through cancelJobs() so child_done messages,
+ * descendant cancellation, active-job aborts, and aggregator unblocking all
+ * retain the queue's normal bookkeeping semantics.
+ */
+ async reconcilePrivateQueue(queueName: string, reason: string): Promise<MinionJob[]> {
+ if (!isDreamInlinePrivateQueue(queueName)) {
+ throw new Error(`refusing to reconcile non-private queue '${queueName}'`);
+ }
+ // Enforce the machine-readable family at the single choke point so the
+ // call sites (phase finally ×2, supervisor/worker spawn, cycle start,
+ // startup recovery) can never drift apart.
+ if (!reason.startsWith(PRIVATE_QUEUE_RECONCILE_REASON_PREFIX)) {
+ reason = `${PRIVATE_QUEUE_RECONCILE_REASON_PREFIX}: ${reason}`;
+ }
+ const rows = await this.engine.executeRaw<{ id: number }>(
+ `SELECT id FROM minion_jobs
+ WHERE queue = $1
+ AND status IN ('waiting','active','delayed','waiting-children','paused')
+ ORDER BY id`,
+ [queueName],
+ );
+ if (rows.length === 0) return [];
+ return this.cancelJobs(rows.map(r => r.id), {
+ reason,
+ rootStatuses: ['waiting', 'active', 'delayed', 'waiting-children', 'paused'],
+ });
+ }
+
+ /**
+ * Renew the owner lease on still-non-terminal jobs in one private queue.
+ * The owner token prevents a stale phase finally/keepalive from extending a
+ * successor queue that reused the same queue name in a test or fixture.
+ */
+ async renewPrivateQueueLease(
+ queueName: string,
+ ownerToken: string,
+ leaseMs = DEFAULT_PRIVATE_QUEUE_LEASE_MS,
+ ): Promise<number> {
+ if (!isDreamInlinePrivateQueue(queueName)) {
+ throw new Error(`refusing to renew non-private queue '${queueName}'`);
+ }
+ if (ownerToken.length === 0) {
+ throw new Error('private queue owner token cannot be empty');
+ }
+ // GREATEST: a renewal may only EXTEND the lease. A default-horizon (10min)
+ // renewal racing a creation-time horizon sized to the phase's wait timeout
+ // must never shrink the window a healthy long run still needs — shrinking
+ // is what would let startup recovery cancel a LIVE ownerless queue.
+ const rows = await this.engine.executeRaw<{ id: number }>(
+ `UPDATE minion_jobs
+ SET private_queue_lease_until = GREATEST(
+ COALESCE(private_queue_lease_until, to_timestamp(0)),
+ now() + ($3::text::interval)
+ ),
+ updated_at = now()
+ WHERE queue = $1
+ AND private_queue_owner_token = $2
+ AND status IN (${NON_TERMINAL_SQL_LIST})
+ RETURNING id`,
+ [queueName, ownerToken, `${Math.max(1, Math.floor(leaseMs))} milliseconds`],
+ );
+ return rows.length;
+ }
+
+ /**
+ * Throttled keepalive closure for a phase that owns a private queue: renews
+ * the lease at most once per `throttleMs`, then runs `onRenewed` (the cycle
+ * lock refresh rides it). The throttle gates BOTH — 1-5s drain polls cost
+ * one UPDATE per half-minute, not per poll — and the order is fixed
+ * (renew, then onRenewed) so a lock-refresh failure can't starve the lease.
+ */
+ makeThrottledLeaseRenewer(
+ queueName: string,
+ ownerToken: string,
+ onRenewed?: () => Promise<void> | void,
+ throttleMs = 30_000,
+ ): () => Promise<void> {
+ let lastRenewalAtMs = 0;
+ return async () => {
+ const nowMs = Date.now();
+ if (nowMs - lastRenewalAtMs < throttleMs) return;
+ lastRenewalAtMs = nowMs;
+ await this.renewPrivateQueueLease(queueName, ownerToken);
+ if (onRenewed) await onRenewed();
+ };
+ }
+
+ /**
+ * Startup/supervisor crash recovery for metadata-backed private dream queues.
+ * Cancels only queues that are provably orphaned:
+ * - no live child lock in the private queue;
+ * - explicit owner metadata exists; and
+ * - the owner job is terminal/missing OR the renewable lease has expired.
+ *
+ * Legacy `dream-inline-*` rows with no owner metadata are left untouched and
+ * remain a Doctor/manual-retriage concern.
+ */
+ async reconcileOrphanedPrivateQueues(opts: {
+ reason?: string;
+ maxQueues?: number;
+ } = {}): Promise<PrivateQueueRecoveryResult> {
+ const result: PrivateQueueRecoveryResult = {
+ scanned_queues: 0,
+ cancelled_queues: 0,
+ cancelled_jobs: 0,
+ skipped_live_queues: 0,
+ skipped_unowned_queues: 0,
+ skipped_non_orphan_queues: 0,
+ };
+ const maxQueues = Math.max(1, Math.floor(opts.maxQueues ?? 100));
+ // HAVING metadata: legacy unowned queues are NEVER recoverable by this
+ // lane (doctor/retriage owns them), so they must not occupy the LIMIT
+ // window — a backlog of them would otherwise starve every newer orphan
+ // out of the scan forever (the incident's exact accumulation shape).
+ const queues = await this.engine.executeRaw<{ queue: string }>(
+ `SELECT queue
+ FROM minion_jobs
+ WHERE queue LIKE '${DREAM_INLINE_PRIVATE_QUEUE_PREFIX}%'
+ AND status IN (${NON_TERMINAL_SQL_LIST})
+ GROUP BY queue
+ HAVING bool_or(private_queue_owner_job_id IS NOT NULL OR private_queue_lease_until IS NOT NULL)
+ ORDER BY min(created_at), queue
+ LIMIT $1`,
+ [maxQueues],
+ );
+ result.scanned_queues = queues.length;
+ for (const q of queues) {
+ const verdict = await this.classifyPrivateQueueForRecovery(q.queue);
+ if (verdict === 'live') {
+ result.skipped_live_queues++;
+ continue;
+ }
+ // Defensive only: the scan's HAVING bool_or(owner/lease) excludes
+ // metadata-less queues at the SQL level, so this arm is unreachable
+ // today — kept in case the scan predicate ever loosens.
+ if (verdict === 'unowned') {
+ result.skipped_unowned_queues++;
+ continue;
+ }
+ if (verdict === 'not_orphan') {
+ result.skipped_non_orphan_queues++;
+ continue;
+ }
+ // Re-verify immediately before cancelling: a child claimed (or a lease
+ // renewed) between the first classify and this point flips the verdict
+ // to live — the cancel itself must never run on a stale verdict.
+ const recheck = await this.classifyPrivateQueueForRecovery(q.queue);
+ if (recheck !== 'orphan') {
+ result.skipped_non_orphan_queues++;
+ continue;
+ }
+ const cancelled = await this.reconcilePrivateQueue(
+ q.queue,
+ opts.reason ?? 'startup recovery: orphaned dream-inline private queue',
+ );
+ if (cancelled.length > 0) {
+ result.cancelled_queues++;
+ result.cancelled_jobs += cancelled.length;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * PUBLIC (doctor shares this verdict): the orphaned_private_queue check
+ * buckets its candidates through the SAME classifier recovery uses, so the
+ * check's advertised remediation and recovery's actual behavior can't drift.
+ */
+ async classifyPrivateQueueForRecovery(
+ queueName: string,
+ ): Promise<'orphan' | 'live' | 'unowned' | 'not_orphan'> {
+ const rows = await this.engine.executeRaw<{
+ active_healthy: string | number;
+ owner_ids: unknown;
+ metadata_rows: string | number;
+ live_owner_rows: string | number;
+ nonterminal_owner_rows: string | number;
+ max_lease_until: string | null;
+ future_lease_rows: string | number;
+ recently_touched: string | number;
+ }>(
+ `WITH q AS (
+ SELECT *
+ FROM minion_jobs
+ WHERE queue = $1
+ AND status IN (${NON_TERMINAL_SQL_LIST})
+ ),
+ owner_ids AS (
+ SELECT DISTINCT private_queue_owner_job_id AS id
+ FROM q
+ WHERE private_queue_owner_job_id IS NOT NULL
+ ),
+ owners AS (
+ SELECT o.id, m.status, m.lock_until
+ FROM owner_ids o
+ LEFT JOIN minion_jobs m ON m.id = o.id
+ )
+ SELECT
+ count(*) FILTER (WHERE q.status = 'active' AND q.lock_until > now()) AS active_healthy,
+ COALESCE(jsonb_agg(DISTINCT q.private_queue_owner_job_id) FILTER (WHERE q.private_queue_owner_job_id IS NOT NULL), '[]'::jsonb) AS owner_ids,
+ count(*) FILTER (WHERE q.private_queue_owner_job_id IS NOT NULL OR q.private_queue_lease_until IS NOT NULL) AS metadata_rows,
+ (SELECT count(*) FROM owners WHERE status = 'active' AND lock_until > now()) AS live_owner_rows,
+ (SELECT count(*) FROM owners WHERE status IN ('waiting','active','delayed','waiting-children','paused')) AS nonterminal_owner_rows,
+ max(q.private_queue_lease_until)::text AS max_lease_until,
+ count(*) FILTER (WHERE q.private_queue_lease_until > now()) AS future_lease_rows,
+ count(*) FILTER (WHERE q.updated_at > now() - interval '120 seconds') AS recently_touched
+ FROM q`,
+ [queueName],
+ );
+ const r = rows[0];
+ // Defensive only: the FROM q aggregate always yields exactly one row.
+ if (!r) return 'not_orphan';
+ if (Number(r.active_healthy ?? 0) > 0 || Number(r.live_owner_rows ?? 0) > 0) {
+ return 'live';
+ }
+ if (Number(r.metadata_rows ?? 0) === 0) return 'unowned';
+ // Freshness guard BEFORE the owner-terminal fast path: any row touched in
+ // the last 2 minutes (a 30s-cadence lease renewal, a claim, a child_done)
+ // means SOMETHING is actively working this queue — even when the owner
+ // job row reads terminal (stall-swept owner whose drain loop survived a
+ // host suspend, the laptop-sleep shape). Never cancel under a live toucher;
+ // a genuinely crashed queue goes untouched and classifies orphan on the
+ // next pass ≤2 minutes later.
+ if (Number(r.recently_touched ?? 0) > 0) return 'live';
+ const ownerIds = Array.isArray(r.owner_ids)
+ ? r.owner_ids
+ : (typeof r.owner_ids === 'string' ? JSON.parse(r.owner_ids) : []);
+ const ownerTerminal = ownerIds.length > 0 && Number(r.nonterminal_owner_rows ?? 0) === 0;
+ if (ownerTerminal) return 'orphan';
+ if (Number(r.future_lease_rows ?? 0) > 0) return 'live';
+ const leaseExpired = r.max_lease_until !== null && new Date(r.max_lease_until).getTime() <= Date.now();
+ return leaseExpired ? 'orphan' : 'not_orphan';
+ }
+
/**
* Batch variant of cancelJob: cancels every root id AND its descendants in
* ONE transaction, with the full bookkeeping the single-id path carries
@@ -2125,14 +2404,20 @@ export class MinionQueue {
* check: GBRAIN_WEDGED_QUEUE_WARN_MINUTES (server-side env), default 15.
*/
export function deriveWedgeSignal(wedge: {
+ queue?: string;
active_healthy: number;
waiting: number;
minutes_since_completion: number | null;
-}): { wedged: boolean; wedge_threshold_minutes: number } {
+}): { wedged: boolean; wedge_threshold_minutes: number; private_queue: boolean } {
const raw = parseInt(process.env.GBRAIN_WEDGED_QUEUE_WARN_MINUTES ?? '', 10);
const wedge_threshold_minutes = Number.isFinite(raw) && raw > 0 ? raw : 15;
+ // A dream-inline private queue is parent-owned: no shared worker will ever
+ // claim it, so "wedged — restart the worker" is impossible advice (the
+ // incident bug class). Surface it as private_queue instead so every consumer
+ // (jobs stats, get_job_stats op, doctor) points at reconciliation.
+ const private_queue = wedge.queue !== undefined && isDreamInlinePrivateQueue(wedge.queue);
const mins = wedge.minutes_since_completion;
- const wedged = wedge.active_healthy === 0 && wedge.waiting > 0
+ const wedged = !private_queue && wedge.active_healthy === 0 && wedge.waiting > 0
&& (mins === null || mins > wedge_threshold_minutes);
- return { wedged, wedge_threshold_minutes };
+ return { wedged, wedge_threshold_minutes, private_queue };
}
diff --git a/src/core/minions/supervisor.ts b/src/core/minions/supervisor.ts
index df091ab025..3eb1805cc8 100644
--- a/src/core/minions/supervisor.ts
+++ b/src/core/minions/supervisor.ts
@@ -45,6 +45,7 @@ import {
import { dirname, resolve } from 'path';
import type { BrainEngine } from '../engine.ts';
import { tryAcquireDbLock, 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';
@@ -789,6 +790,35 @@ 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.stopping) return;
@@ -1024,6 +1054,11 @@ 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,
diff --git a/src/core/minions/types.ts b/src/core/minions/types.ts
index bc6a498c91..1038e1d1f7 100644
--- a/src/core/minions/types.ts
+++ b/src/core/minions/types.ts
@@ -76,6 +76,12 @@ export interface MinionJob {
remove_on_complete: boolean;
remove_on_fail: boolean;
idempotency_key: string | null;
+ /** Private dream-inline queue owner job, when this job is owned by an inline parent. */
+ private_queue_owner_job_id: number | null;
+ /** Private dream-inline queue owner token; random per phase run. */
+ private_queue_owner_token: string | null;
+ /** Renewable private-queue lease. Startup recovery may cancel only after this expires. */
+ private_queue_lease_until: Date | null;
// v12: scheduler polish — quiet-hours gate + deterministic stagger
quiet_hours: Record<string, unknown> | null;
@@ -140,6 +146,13 @@ export interface MinionJobInput {
max_spawn_depth?: number;
/** Global dedup key. Same key returns the existing job, no second row created. */
idempotency_key?: string;
+ /**
+ * Internal: owner metadata for parent-owned `dream-inline-*` queues. Used by
+ * startup recovery to distinguish crashed owners from live private queues.
+ */
+ private_queue_owner_job_id?: number | null;
+ private_queue_owner_token?: string | null;
+ private_queue_lease_ms?: number | null;
/** Submission backpressure: cap waiting jobs with this name before inserting
* a new row. Scope is (name, queue, source), where source reads
* data.sourceId ?? data.source_id; a submission with NO source key counts
@@ -455,6 +468,9 @@ export function rowToMinionJob(row: Record<string, unknown>): MinionJob {
remove_on_complete: row.remove_on_complete === true,
remove_on_fail: row.remove_on_fail === true,
idempotency_key: (row.idempotency_key as string) || null,
+ private_queue_owner_job_id: (row.private_queue_owner_job_id as number | null) ?? null,
+ private_queue_owner_token: (row.private_queue_owner_token as string) || null,
+ private_queue_lease_until: row.private_queue_lease_until ? new Date(row.private_queue_lease_until as string) : null,
quiet_hours: row.quiet_hours ? (typeof row.quiet_hours === 'string' ? JSON.parse(row.quiet_hours) : row.quiet_hours) as Record<string, unknown> : null,
stagger_key: (row.stagger_key as string) || null,
result: row.result ? (typeof row.result === 'string' ? JSON.parse(row.result) : row.result) as Record<string, unknown> : null,
diff --git a/src/core/minions/wait-for-completion.ts b/src/core/minions/wait-for-completion.ts
index f75bb6258c..55c8a23f9b 100644
--- a/src/core/minions/wait-for-completion.ts
+++ b/src/core/minions/wait-for-completion.ts
@@ -38,6 +38,35 @@ export interface WaitOpts {
signal?: AbortSignal;
}
+/**
+ * waitForCompletion in bounded chunks, invoking `renew` between chunks — the
+ * dream phases' post-drain waits can outlast a private-queue lease, and an
+ * unrenewed lease reads as orphaned to startup recovery. Chunking keeps the
+ * lease (and cycle lock, via the phases' composite renew wrapper) fresh for
+ * the whole wait without threading a callback into the poll loop.
+ */
+export async function waitForCompletionRenewing(
+ queue: MinionQueue,
+ jobId: number,
+ opts: WaitOpts & { renew?: () => Promise<void>; chunkMs?: number } = {},
+): Promise<MinionJob> {
+ const totalMs = opts.timeoutMs ?? 24 * 60 * 60 * 1000;
+ const chunkMs = Math.max(1000, opts.chunkMs ?? 60_000);
+ const deadline = Date.now() + totalMs;
+ for (;;) {
+ const remaining = deadline - Date.now();
+ try {
+ return await waitForCompletion(queue, jobId, {
+ ...opts,
+ timeoutMs: Math.max(1, Math.min(chunkMs, remaining)),
+ });
+ } catch (e) {
+ if (!(e instanceof TimeoutError) || Date.now() >= deadline) throw e;
+ if (opts.renew) { try { await opts.renew(); } catch { /* best-effort */ } }
+ }
+ }
+}
+
export async function waitForCompletion(
queue: MinionQueue,
jobId: number,
diff --git a/src/core/ops/jobs.ts b/src/core/ops/jobs.ts
index 4f468b7050..c38479abf2 100644
--- a/src/core/ops/jobs.ts
+++ b/src/core/ops/jobs.ts
@@ -108,7 +108,7 @@ const submit_job: Operation = {
// Amendments 24/25: post-enqueue queue-state probe (time-bounded,
// fail-open). The job is already persisted; a probe failure degrades to
// {probe_failed: true}, never an error on a successful submission.
- return { ...job, queue_state: await probeQueueStateSafe(ctx, job.queue, [name]) };
+ return { ...job, private_queue_owner_token: job.private_queue_owner_token == null ? null : '[redacted]', queue_state: await probeQueueStateSafe(ctx, job.queue, [name]) };
},
};
@@ -498,7 +498,9 @@ const get_job: Operation = {
const queue = new MinionQueue(ctx.engine);
const job = await queue.getJob(p.id as number);
if (!job) throw new OperationError('invalid_params', `Job not found: ${p.id}`);
- return job;
+ // private_queue_owner_token is a capability credential (lease renewal /
+ // attach), not job data — never expose it over MCP envelopes.
+ return { ...job, private_queue_owner_token: job.private_queue_owner_token == null ? null : '[redacted]' };
},
};
@@ -515,12 +517,15 @@ const list_jobs: Operation = {
handler: async (ctx, p) => {
const { MinionQueue } = await import('../minions/queue.ts');
const queue = new MinionQueue(ctx.engine);
- return queue.getJobs({
+ const jobs = await queue.getJobs({
status: p.status as string | undefined,
queue: p.queue as string | undefined,
name: p.name as string | undefined,
limit: (p.limit as number) || 50,
} as Parameters<typeof queue.getJobs>[0]);
+ // private_queue_owner_token is a capability credential (lease renewal /
+ // attach), not job data — never expose it over MCP envelopes.
+ return jobs.map(j => ({ ...j, private_queue_owner_token: j.private_queue_owner_token == null ? null : '[redacted]' }));
},
};
@@ -660,6 +665,9 @@ const get_job_stats: Operation = {
'(unfiltered); by_type is windowed by since_hours; only the wedge block is scoped to ' +
'the queue param. wedged: true is the silent-halt signal (a worker is alive but claiming ' +
'nothing while work waits) — suggest restarting the jobs supervisor on the brain host. ' +
+ 'private_queue: true means the queue is a parent-owned dream-inline queue: wedged is ' +
+ 'NEVER true for it and a worker restart cannot help — recovery runs automatically at ' +
+ 'worker spawn / dream-cycle start; suggest gbrain doctor for the per-queue verdict. ' +
'Host-process diagnostics (renice, backpressure hints) stay on the gbrain jobs stats CLI.',
params: {
queue: { type: 'string', required: false, description: "Queue for the wedge signature (default 'default'). The other blocks stay global/windowed." },
@@ -678,8 +686,10 @@ const get_job_stats: Operation = {
since: new Date(Date.now() - hours * 3_600_000),
queue: typeof p.queue === 'string' && p.queue.length > 0 ? p.queue : 'default',
});
- const { wedged, wedge_threshold_minutes } = deriveWedgeSignal(stats.wedge);
- return { schema_version: 1, window_hours: hours, ...stats, wedged, wedge_threshold_minutes };
+ const { wedged, wedge_threshold_minutes, private_queue } = deriveWedgeSignal(stats.wedge);
+ // private_queue tells the MCP consumer "restart the worker" is dead-end
+ // advice for this queue — it is parent-owned and needs reconciliation.
+ return { schema_version: 1, window_hours: hours, ...stats, wedged, wedge_threshold_minutes, private_queue };
}, 'Job queue statistics (minions schema)');
},
};
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 5601cacdc2..4cbf6a80bb 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -1138,7 +1138,13 @@ export class PGLiteEngine implements BrainEngine {
EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_schema='public' AND table_name='minion_jobs' AND column_name='timeout_at') AS minion_jobs_timeout_at_exists,
EXISTS (SELECT 1 FROM information_schema.columns
- WHERE table_schema='public' AND table_name='minion_jobs' AND column_name='idempotency_key') AS minion_jobs_idempotency_key_exists
+ WHERE table_schema='public' AND table_name='minion_jobs' AND column_name='idempotency_key') AS minion_jobs_idempotency_key_exists,
+ EXISTS (SELECT 1 FROM information_schema.columns
+ WHERE table_schema='public' AND table_name='minion_jobs' AND column_name='private_queue_owner_job_id') AS minion_jobs_pq_owner_exists,
+ EXISTS (SELECT 1 FROM information_schema.columns
+ WHERE table_schema='public' AND table_name='minion_jobs' AND column_name='private_queue_owner_token') AS minion_jobs_pq_token_exists,
+ EXISTS (SELECT 1 FROM information_schema.columns
+ WHERE table_schema='public' AND table_name='minion_jobs' AND column_name='private_queue_lease_until') AS minion_jobs_pq_lease_exists
`);
const probe = rows[0] as {
pages_exists: boolean;
@@ -1188,6 +1194,9 @@ export class PGLiteEngine implements BrainEngine {
minion_jobs_exists: boolean;
minion_jobs_timeout_at_exists: boolean;
minion_jobs_idempotency_key_exists: boolean;
+ minion_jobs_pq_owner_exists: boolean;
+ minion_jobs_pq_token_exists: boolean;
+ minion_jobs_pq_lease_exists: boolean;
};
const needsPagesBootstrap = probe.pages_exists && !probe.source_id_exists;
@@ -1279,6 +1288,11 @@ export class PGLiteEngine implements BrainEngine {
// exactly like the v121 incident.
const needsMinionJobsTimeoutAt = probe.minion_jobs_exists && !probe.minion_jobs_timeout_at_exists;
const needsMinionJobsIdempotencyKey = probe.minion_jobs_exists && !probe.minion_jobs_idempotency_key_exists;
+ // Token rides the probe too: a token-only-missing brain (partial upgrade)
+ // would otherwise be unrepairable — the ALTER block adds all three.
+ const needsMinionJobsPrivateQueue = probe.minion_jobs_exists
+ && (!probe.minion_jobs_pq_owner_exists || !probe.minion_jobs_pq_token_exists
+ || !probe.minion_jobs_pq_lease_exists);
// Fresh installs (no tables yet) and modern brains both no-op.
if (!needsPagesBootstrap && !needsLinksBootstrap && !needsChunksBootstrap
@@ -1293,7 +1307,8 @@ export class PGLiteEngine implements BrainEngine {
&& !needsPagesEmbeddingSignature
&& !needsPagesLinksExtractedAt
&& !needsTimelineEventPageId
- && !needsMinionJobsTimeoutAt && !needsMinionJobsIdempotencyKey) return;
+ && !needsMinionJobsTimeoutAt && !needsMinionJobsIdempotencyKey
+ && !needsMinionJobsPrivateQueue) return;
process.stderr.write(' Pre-v0.21 brain detected, applying forward-reference bootstrap\n');
@@ -1574,6 +1589,18 @@ export class PGLiteEngine implements BrainEngine {
ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS idempotency_key TEXT;
`);
}
+ if (needsMinionJobsPrivateQueue) {
+ // v0.46.26: blob indexes idx_minion_jobs_private_queue_recovery /
+ // idx_minion_jobs_private_queue_owner reference the private-queue
+ // owner/lease columns; a pre-upgrade minion_jobs wedges blob replay
+ // without them (same class as v121). The token column is not indexed
+ // but rides along so upgraded rows carry the full lifecycle shape.
+ await this.db.exec(`
+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_owner_job_id INTEGER REFERENCES minion_jobs(id) ON DELETE SET NULL;
+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_owner_token TEXT;
+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_lease_until TIMESTAMPTZ;
+ `);
+ }
}
async withReservedConnection<T>(fn: (conn: ReservedConnection) => Promise<T>): Promise<T> {
diff --git a/src/core/pglite-schema.ts b/src/core/pglite-schema.ts
index f07128f281..e643e6f1d1 100644
--- a/src/core/pglite-schema.ts
+++ b/src/core/pglite-schema.ts
@@ -470,6 +470,9 @@ CREATE TABLE IF NOT EXISTS minion_jobs (
remove_on_complete BOOLEAN NOT NULL DEFAULT FALSE,
remove_on_fail BOOLEAN NOT NULL DEFAULT FALSE,
idempotency_key TEXT,
+ private_queue_owner_job_id INTEGER REFERENCES minion_jobs(id) ON DELETE SET NULL,
+ private_queue_owner_token TEXT,
+ private_queue_lease_until TIMESTAMPTZ,
result JSONB,
progress JSONB,
error_text TEXT,
@@ -504,6 +507,13 @@ CREATE UNIQUE INDEX IF NOT EXISTS uniq_minion_jobs_idempotency ON minion_jobs (i
-- WP4/WP5 (v127, ENG-10): wedge-signal index — covers the queue-health count
-- FILTERs and max(updated_at) reads in queryWedgeSignals (supervisor.ts).
CREATE INDEX IF NOT EXISTS idx_minion_jobs_queue_status_updated ON minion_jobs (queue, status, updated_at);
+CREATE INDEX IF NOT EXISTS idx_minion_jobs_private_queue_recovery
+ ON minion_jobs (queue, private_queue_lease_until)
+ WHERE queue LIKE 'dream-inline-%'
+ AND status IN ('waiting','active','delayed','waiting-children','paused');
+CREATE INDEX IF NOT EXISTS idx_minion_jobs_private_queue_owner
+ ON minion_jobs (private_queue_owner_job_id)
+ WHERE private_queue_owner_job_id IS NOT NULL;
-- Inbox table for sidechannel messaging
CREATE TABLE IF NOT EXISTS minion_inbox (
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index e9ea9b981d..a3e60bee35 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -662,7 +662,13 @@ export class PostgresEngine implements BrainEngine {
EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'timeout_at') AS minion_jobs_timeout_at_exists,
EXISTS (SELECT 1 FROM information_schema.columns
- WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'idempotency_key') AS minion_jobs_idempotency_key_exists
+ WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'idempotency_key') AS minion_jobs_idempotency_key_exists,
+ EXISTS (SELECT 1 FROM information_schema.columns
+ WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'private_queue_owner_job_id') AS minion_jobs_pq_owner_exists,
+ EXISTS (SELECT 1 FROM information_schema.columns
+ WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'private_queue_owner_token') AS minion_jobs_pq_token_exists,
+ EXISTS (SELECT 1 FROM information_schema.columns
+ WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'private_queue_lease_until') AS minion_jobs_pq_lease_exists
`;
const probe = probeRows[0]!;
@@ -755,6 +761,9 @@ export class PostgresEngine implements BrainEngine {
minion_jobs_exists?: boolean;
minion_jobs_timeout_at_exists?: boolean;
minion_jobs_idempotency_key_exists?: boolean;
+ minion_jobs_pq_owner_exists?: boolean;
+ minion_jobs_pq_token_exists?: boolean;
+ minion_jobs_pq_lease_exists?: boolean;
};
const needsContextualRetrievalColumns = (probe.pages_exists
&& (!probeCr.pages_cr_mode_exists || !probeCr.pages_corpus_generation_exists))
@@ -785,6 +794,11 @@ export class PostgresEngine implements BrainEngine {
&& !probeCr.minion_jobs_timeout_at_exists;
const needsMinionJobsIdempotencyKey = probeCr.minion_jobs_exists === true
&& !probeCr.minion_jobs_idempotency_key_exists;
+ // Token rides the probe too: a token-only-missing brain (partial upgrade)
+ // would otherwise be unrepairable — the ALTER block adds all three.
+ const needsMinionJobsPrivateQueue = probeCr.minion_jobs_exists === true
+ && (!probeCr.minion_jobs_pq_owner_exists || !probeCr.minion_jobs_pq_token_exists
+ || !probeCr.minion_jobs_pq_lease_exists);
if (!needsPagesBootstrap && !needsLinksBootstrap && !needsChunksBootstrap
&& !needsPagesDeletedAt && !needsMcpLogBootstrap && !needsSubagentProviderId
@@ -798,7 +812,8 @@ export class PostgresEngine implements BrainEngine {
&& !needsPagesEmbeddingSignature
&& !needsPagesLinksExtractedAt
&& !needsTimelineEventPageId
- && !needsMinionJobsTimeoutAt && !needsMinionJobsIdempotencyKey) return;
+ && !needsMinionJobsTimeoutAt && !needsMinionJobsIdempotencyKey
+ && !needsMinionJobsPrivateQueue) return;
process.stderr.write(' Pre-v0.21 brain detected, applying forward-reference bootstrap\n');
@@ -1079,6 +1094,18 @@ export class PostgresEngine implements BrainEngine {
ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS idempotency_key TEXT;
`);
}
+ if (needsMinionJobsPrivateQueue) {
+ // v0.46.26: blob indexes idx_minion_jobs_private_queue_recovery /
+ // idx_minion_jobs_private_queue_owner reference the private-queue
+ // owner/lease columns; a pre-upgrade minion_jobs wedges blob replay
+ // without them (same class as v121). The token column is not indexed
+ // but rides along so upgraded rows carry the full lifecycle shape.
+ await conn.unsafe(`
+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_owner_job_id INTEGER REFERENCES minion_jobs(id) ON DELETE SET NULL;
+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_owner_token TEXT;
+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_lease_until TIMESTAMPTZ;
+ `);
+ }
}
async transaction<T>(fn: (engine: BrainEngine) => Promise<T>): Promise<T> {
diff --git a/src/core/schema-embedded.ts b/src/core/schema-embedded.ts
index a12fa57da8..095cb7ad18 100644
--- a/src/core/schema-embedded.ts
+++ b/src/core/schema-embedded.ts
@@ -935,6 +935,9 @@ CREATE TABLE IF NOT EXISTS minion_jobs (
remove_on_complete BOOLEAN NOT NULL DEFAULT FALSE,
remove_on_fail BOOLEAN NOT NULL DEFAULT FALSE,
idempotency_key TEXT,
+ private_queue_owner_job_id INTEGER REFERENCES minion_jobs(id) ON DELETE SET NULL,
+ private_queue_owner_token TEXT,
+ private_queue_lease_until TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
started_at TIMESTAMPTZ,
finished_at TIMESTAMPTZ,
@@ -962,6 +965,13 @@ CREATE UNIQUE INDEX IF NOT EXISTS uniq_minion_jobs_idempotency ON minion_jobs (i
-- WP4/WP5 (v127, ENG-10): wedge-signal index — covers the queue-health count
-- FILTERs and max(updated_at) reads in queryWedgeSignals (supervisor.ts).
CREATE INDEX IF NOT EXISTS idx_minion_jobs_queue_status_updated ON minion_jobs (queue, status, updated_at);
+CREATE INDEX IF NOT EXISTS idx_minion_jobs_private_queue_recovery
+ ON minion_jobs (queue, private_queue_lease_until)
+ WHERE queue LIKE 'dream-inline-%'
+ AND status IN ('waiting','active','delayed','waiting-children','paused');
+CREATE INDEX IF NOT EXISTS idx_minion_jobs_private_queue_owner
+ ON minion_jobs (private_queue_owner_job_id)
+ WHERE private_queue_owner_job_id IS NOT NULL;
-- Inbox table for sidechannel messaging
CREATE TABLE IF NOT EXISTS minion_inbox (
diff --git a/src/schema.sql b/src/schema.sql
index 9eec2ba161..f625aad951 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -931,6 +931,9 @@ CREATE TABLE IF NOT EXISTS minion_jobs (
remove_on_complete BOOLEAN NOT NULL DEFAULT FALSE,
remove_on_fail BOOLEAN NOT NULL DEFAULT FALSE,
idempotency_key TEXT,
+ private_queue_owner_job_id INTEGER REFERENCES minion_jobs(id) ON DELETE SET NULL,
+ private_queue_owner_token TEXT,
+ private_queue_lease_until TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
started_at TIMESTAMPTZ,
finished_at TIMESTAMPTZ,
@@ -958,6 +961,13 @@ CREATE UNIQUE INDEX IF NOT EXISTS uniq_minion_jobs_idempotency ON minion_jobs (i
-- WP4/WP5 (v127, ENG-10): wedge-signal index — covers the queue-health count
-- FILTERs and max(updated_at) reads in queryWedgeSignals (supervisor.ts).
CREATE INDEX IF NOT EXISTS idx_minion_jobs_queue_status_updated ON minion_jobs (queue, status, updated_at);
+CREATE INDEX IF NOT EXISTS idx_minion_jobs_private_queue_recovery
+ ON minion_jobs (queue, private_queue_lease_until)
+ WHERE queue LIKE 'dream-inline-%'
+ AND status IN ('waiting','active','delayed','waiting-children','paused');
+CREATE INDEX IF NOT EXISTS idx_minion_jobs_private_queue_owner
+ ON minion_jobs (private_queue_owner_job_id)
+ WHERE private_queue_owner_job_id IS NOT NULL;
-- Inbox table for sidechannel messaging
CREATE TABLE IF NOT EXISTS minion_inbox (
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index 391d725e4f..22c2156fe6 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.46.25.0 -->
+<!-- gbrain-template-stamp: 0.46.26.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/autopilot-global-maintenance.test.ts b/test/autopilot-global-maintenance.test.ts
index 64c427c35c..ffe188bbd7 100644
--- a/test/autopilot-global-maintenance.test.ts
+++ b/test/autopilot-global-maintenance.test.ts
@@ -319,7 +319,9 @@ describe('autopilot-global-maintenance handler stamps last_global_at (PGLite)',
const repoPath = mkdtempSync(join(tmpdir(), 'gbrain-global-default-'));
const handlers = await captureHandlers();
const handler = handlers.get('autopilot-global-maintenance');
- const result = await handler!({ data: { repoPath }, signal: undefined });
+ // id present so the handler threads a real privateQueueOwnerJobId into
+ // runCycle (worker jobs always carry one).
+ const result = await handler!({ id: 4101, data: { repoPath }, signal: undefined });
const ranPhases = result.report.phases.map((p: any) => p.phase);
for (const p of MAINTENANCE_PHASES) expect(ranPhases).toContain(p);
expect(ranPhases).toContain('synthesize');
@@ -339,7 +341,10 @@ describe('autopilot-global-maintenance handler stamps last_global_at (PGLite)',
const handler = handlers.get('autopilot-global-maintenance');
expect(handler).toBeTruthy();
+ // id present so the handler threads a real privateQueueOwnerJobId into
+ // runCycle (worker jobs always carry one).
const result = await handler!({
+ id: 4102,
data: { phases: ['orphans', 'embed'], repoPath },
signal: undefined,
});
diff --git a/test/autopilot-supervisor-wiring.test.ts b/test/autopilot-supervisor-wiring.test.ts
index ac3ec2f775..a9d27316b3 100644
--- a/test/autopilot-supervisor-wiring.test.ts
+++ b/test/autopilot-supervisor-wiring.test.ts
@@ -61,6 +61,18 @@ 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.
+ expect(AUTOPILOT_SRC).toMatch(
+ /env:\s*\{\s*\.\.\.process\.env,\s*GBRAIN_SUPERVISED:\s*undefined\s*\}/,
+ );
+ });
+
it("constructs ChildWorkerSupervisor with maxCrashes: 5", () => {
// Matches the legacy `crashCount >= 5` give-up rule from the inline
// loop. The shared core uses this to decide when to fire
diff --git a/test/child-worker-supervisor.test.ts b/test/child-worker-supervisor.test.ts
index 297d0f2f20..e071df8693 100644
--- a/test/child-worker-supervisor.test.ts
+++ b/test/child-worker-supervisor.test.ts
@@ -31,6 +31,7 @@ import {
ChildWorkerSupervisor,
type ChildSupervisorEvent,
} from '../src/core/minions/child-worker-supervisor.ts';
+import { withEnv } from './helpers/with-env.ts';
/**
* Per-test bun timeout for the spawn-driving tests. Generous because each test
@@ -140,6 +141,7 @@ async function runUntilTerminal(
watchdogLoopBudget: number;
watchdogLoopWindowMs: number;
watchdogBackoffMs: number;
+ beforeSpawn: () => Promise<void>;
_now: () => number;
stopAfterEvents: number; // safety net so a buggy test can't hang
deadlineMs: number; // wall-clock safety net (see below)
@@ -165,6 +167,7 @@ async function runUntilTerminal(
watchdogLoopWindowMs: overrides.watchdogLoopWindowMs,
watchdogBackoffMs: overrides.watchdogBackoffMs,
_now: overrides._now,
+ beforeSpawn: overrides.beforeSpawn,
isStopping: () => stopping,
onMaxCrashesExceeded: (count, max) => {
maxCrashesFired = { count, max };
@@ -231,6 +234,23 @@ afterEach(() => {
});
describe('ChildWorkerSupervisor', () => {
+ it('runs the maintenance hook before every crash respawn', async () => {
+ const h = makeConstantExitHarness(1);
+ let beforeSpawnCalls = 0;
+ try {
+ const res = await runUntilTerminal(h, {
+ maxCrashes: 2,
+ hardStopMaxCrashes: 3,
+ beforeSpawn: async () => { beforeSpawnCalls++; },
+ });
+ const spawns = res.events.filter((e) => e.kind === 'worker_spawned').length;
+ expect(spawns).toBeGreaterThanOrEqual(2);
+ expect(beforeSpawnCalls).toBe(spawns);
+ } finally {
+ h.cleanup();
+ }
+ });
+
describe('D1 — code=0 exit classifier', () => {
it('code=0 worker exit does not count as crash; restarts immediately', async () => {
const h = makeConstantExitHarness(0);
@@ -870,4 +890,116 @@ describe('ChildWorkerSupervisor', () => {
expect(events.length).toBeLessThan(60);
}, TEST_TIMEOUT_MS);
});
+
+ // autopilot.ts builds its spawn env as {...process.env, GBRAIN_SUPERVISED:
+ // undefined} because worker-startup recovery (jobs.ts 'work') is gated on
+ // GBRAIN_SUPERVISED !== '1' and is autopilot's ONLY private-queue recovery
+ // lane — an inherited =1 would silently disable it. This proves the strip
+ // actually reaches the child at spawn (an undefined value must be OMITTED
+ // from the child env, never stringified to "undefined").
+ describe('GBRAIN_SUPERVISED env strip (autopilot spawn-env shape)', () => {
+ it('a spawn env of {...process.env, GBRAIN_SUPERVISED: undefined} leaves the child without the variable', async () => {
+ // withEnv (not raw assignment) keeps this file in the parallel lane.
+ await withEnv({ GBRAIN_SUPERVISED: '1' }, async () => {
+ expect(process.env.GBRAIN_SUPERVISED).toBe('1'); // parent really has it
+ // Child exits 0 iff GBRAIN_SUPERVISED is unset/empty in ITS env.
+ const h: Harness = process.platform === 'win32'
+ ? {
+ cliPath: process.env.COMSPEC ?? 'cmd.exe',
+ args: ['/c', 'if defined GBRAIN_SUPERVISED (exit 1) else (exit 0)'],
+ cleanup: () => {},
+ }
+ : { cliPath: '/bin/sh', args: ['-c', 'test -z "$GBRAIN_SUPERVISED"'], cleanup: () => {} };
+
+ const runOnce = async (env: NodeJS.ProcessEnv): Promise<number | null> => {
+ const events: ChildSupervisorEvent[] = [];
+ let stopping = false;
+ const sup = new ChildWorkerSupervisor({
+ cliPath: h.cliPath,
+ args: h.args,
+ env,
+ maxCrashes: 1,
+ hardStopMaxCrashes: 1,
+ _backoffFloorMs: 1,
+ isStopping: () => stopping,
+ onMaxCrashesExceeded: () => { stopping = true; },
+ onEvent: (e) => {
+ events.push(e);
+ if (e.kind === 'worker_exited') stopping = true;
+ },
+ });
+ await sup.run();
+ const exit = events.find(
+ (e): e is Extract<ChildSupervisorEvent, { kind: 'worker_exited' }> =>
+ e.kind === 'worker_exited',
+ );
+ expect(exit).toBeDefined();
+ return exit!.code;
+ };
+
+ // The exact env expression autopilot.ts constructs: stripped → unset.
+ const strippedExit = await runOnce(
+ { ...process.env, GBRAIN_SUPERVISED: undefined } as Record<string, string | undefined>,
+ );
+ expect(strippedExit).toBe(0);
+
+ // Control: a plain inherit leaks =1 into the child → child sees it set.
+ const inheritedExit = await runOnce({ ...process.env });
+ expect(inheritedExit).toBe(1);
+ });
+ }, TEST_TIMEOUT_MS);
+ });
+
+ // The composer seam the private-queue recovery hook rides (documented
+ // contract at child-worker-supervisor.ts's beforeSpawn opt): the composer
+ // owns error handling AND bounding.
+ describe('beforeSpawn contract', () => {
+ it('a REJECTING beforeSpawn propagates out of run() with no spawn and no crash accounting', async () => {
+ const h = makeConstantExitHarness(0);
+ const events: ChildSupervisorEvent[] = [];
+ const sup = new ChildWorkerSupervisor({
+ cliPath: h.cliPath,
+ args: h.args,
+ maxCrashes: 3,
+ _backoffFloorMs: 1,
+ isStopping: () => false,
+ onMaxCrashesExceeded: () => {},
+ onEvent: (e) => events.push(e),
+ beforeSpawn: async () => {
+ throw new Error('spawn-blocking precondition failed');
+ },
+ });
+ await expect(sup.run()).rejects.toThrow('spawn-blocking precondition failed');
+ // No respawn loop, no spawn at all, no crash/backoff bookkeeping.
+ expect(events).toEqual([]);
+ expect(sup.crashCount).toBe(0);
+ expect(sup.childAlive).toBe(false);
+ }, TEST_TIMEOUT_MS);
+
+ it('isStopping flipping true INSIDE beforeSpawn prevents any spawn afterward', async () => {
+ const h = makeConstantExitHarness(0);
+ const events: ChildSupervisorEvent[] = [];
+ let stopping = false;
+ let hookCalls = 0;
+ const sup = new ChildWorkerSupervisor({
+ cliPath: h.cliPath,
+ args: h.args,
+ maxCrashes: 3,
+ _backoffFloorMs: 1,
+ isStopping: () => stopping,
+ onMaxCrashesExceeded: () => {},
+ onEvent: (e) => events.push(e),
+ beforeSpawn: async () => {
+ hookCalls++;
+ stopping = true; // shutdown raced the hook — the re-check must win
+ },
+ });
+ await sup.run();
+ expect(hookCalls).toBe(1);
+ // The post-hook isStopping re-check returned before spawnOnce: zero
+ // worker_spawned (or any other) events.
+ expect(events).toEqual([]);
+ expect(sup.childAlive).toBe(false);
+ }, TEST_TIMEOUT_MS);
+ });
});
diff --git a/test/cycle-patterns-completed-outcome.serial.test.ts b/test/cycle-patterns-completed-outcome.serial.test.ts
index c9b3781cf0..96713cd5ff 100644
--- a/test/cycle-patterns-completed-outcome.serial.test.ts
+++ b/test/cycle-patterns-completed-outcome.serial.test.ts
@@ -21,6 +21,17 @@ mock.module('../src/core/minions/wait-for-completion.ts', () => ({
id: jobId,
status: 'completed',
}),
+ // patterns/synthesize import the lease-renewing variant; a module mock
+ // replaces the WHOLE module, so it must export every named import its
+ // consumers reach for (a missing one is a load-time SyntaxError).
+ waitForCompletionRenewing: async (
+ _queue: unknown,
+ jobId: number,
+ opts?: { renew?: () => Promise<void> },
+ ) => {
+ if (opts?.renew) await opts.renew();
+ return { id: jobId, status: 'completed' };
+ },
}));
const { runPhasePatterns } = await import('../src/core/cycle/patterns.ts');
diff --git a/test/cycle-patterns.test.ts b/test/cycle-patterns.test.ts
index d4be4916ca..20573254fb 100644
--- a/test/cycle-patterns.test.ts
+++ b/test/cycle-patterns.test.ts
@@ -20,8 +20,13 @@ const patternsSrc = readFileSync(
describe('patterns phase wiring', () => {
test('imports queue + waitForCompletion + types', () => {
- expect(patternsSrc).toContain("import { MinionQueue }");
- expect(patternsSrc).toContain('waitForCompletion');
+ expect(patternsSrc).toContain("import { DEFAULT_PRIVATE_QUEUE_LEASE_MS, MinionQueue }");
+ // The post-drain wait must be the lease-renewing variant — a plain
+ // waitForCompletion would let the private-queue lease lapse mid-wait.
+ expect(patternsSrc).toContain('waitForCompletionRenewing');
+ // The keepalive must come from the shared throttled factory (T0
+ // extraction) — an inline closure here and in synthesize drifts.
+ expect(patternsSrc).toContain('makeThrottledLeaseRenewer');
expect(patternsSrc).toContain('SubagentHandlerData');
});
diff --git a/test/cycle-start-recovery-throw.serial.test.ts b/test/cycle-start-recovery-throw.serial.test.ts
new file mode 100644
index 0000000000..1620a33168
--- /dev/null
+++ b/test/cycle-start-recovery-throw.serial.test.ts
@@ -0,0 +1,56 @@
+/**
+ * Pins the catch arm of the cycle-start private-queue recovery lane
+ * (src/core/cycle.ts ~:2054): recovery is best-effort and must NEVER block
+ * the cycle — a throwing reconcileOrphanedPrivateQueues is swallowed with a
+ * warning and runCycle still completes.
+ *
+ * Serial (*.serial.test.ts): uses mock.module, which leaks across files in a
+ * shared shard process. The mock swaps MinionQueue for a subclass whose
+ * reconcileOrphanedPrivateQueues throws while every other member stays real
+ * (`const real = await import(...)` re-export pattern, same style as
+ * test/cycle-patterns-completed-outcome.serial.test.ts).
+ */
+import { afterAll, beforeAll, describe, expect, mock, test } from 'bun:test';
+
+const real = await import('../src/core/minions/queue.ts');
+
+let reconcileCalls = 0;
+
+class ThrowingRecoveryQueue extends real.MinionQueue {
+ override async reconcileOrphanedPrivateQueues(): Promise<never> {
+ reconcileCalls++;
+ throw new Error('injected reconcile failure (cycle-start-recovery-throw)');
+ }
+}
+
+mock.module('../src/core/minions/queue.ts', () => ({
+ ...real,
+ MinionQueue: ThrowingRecoveryQueue,
+}));
+
+// Import AFTER the mock so cycle.ts's dynamic `import('./minions/queue.ts')`
+// at the recovery site resolves to the throwing subclass.
+const { runCycle } = await import('../src/core/cycle.ts');
+const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');
+
+let engine: InstanceType<typeof PGLiteEngine>;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+}, 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+describe('cycle-start recovery failure is non-fatal (cycle.ts catch arm)', () => {
+ test('runCycle completes even when reconcileOrphanedPrivateQueues throws', async () => {
+ const report = await runCycle(engine, { brainDir: null, phases: [] });
+ // The lane was actually reached (the mock threw) AND the cycle survived.
+ expect(reconcileCalls).toBe(1);
+ expect(report.phases).toEqual([]);
+ expect(typeof report.status).toBe('string');
+ }, 60_000);
+});
diff --git a/test/cycle-start-recovery.test.ts b/test/cycle-start-recovery.test.ts
new file mode 100644
index 0000000000..4e851f4874
--- /dev/null
+++ b/test/cycle-start-recovery.test.ts
@@ -0,0 +1,107 @@
+/**
+ * Cycle-start orphaned-private-queue recovery lane (src/core/cycle.ts ~:2038).
+ *
+ * On engines that never run a supervisor/worker process (PGLite inlines every
+ * child) this lane is the ONLY recovery net for dream-inline-* queues whose
+ * owner job went terminal while children were still non-terminal. Pins:
+ * - a real runCycle (dryRun unset) cancels the orphan's children with the
+ * machine-readable 'private_queue_reconciled:' reason family carrying
+ * 'cycle startup recovery';
+ * - dryRun: true never touches the fixture (recovery is a write and the
+ * whole block is gated on !dryRun).
+ *
+ * Harness: phases: [] is an explicit no-op cycle (no lock, zero phases — see
+ * the empty-phase test in autopilot-global-maintenance.test.ts) but the
+ * startup recovery block still runs, so each test costs milliseconds beyond
+ * the shared engine boot.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { runCycle } from '../src/core/cycle.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+let queueSeq = 0;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' }); // in-memory
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+}, 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ // Targeted DELETE preserves the `config.version` key that
+ // MinionQueue.ensureSchema requires (full resetPgliteState wipes it).
+ // Same pattern as test/autopilot-cycle-handler.test.ts.
+ await engine.executeRaw('DELETE FROM minion_jobs');
+ await engine.executeRaw('DELETE FROM gbrain_cycle_locks').catch(() => {});
+});
+
+/**
+ * Seed a provably-orphaned private dream queue: a waiting 'subagent' child
+ * whose private_queue_owner_job_id points at a TERMINAL owner job, with
+ * updated_at aged past the classifier's 2-minute recently-touched guard.
+ */
+async function seedOrphanQueue(): Promise<{ queueName: string; childId: number }> {
+ const queueName = `dream-inline-cycle-recovery-${++queueSeq}`;
+ const owner = await queue.add('autopilot-cycle', {});
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'completed', finished_at = now() WHERE id = $1`,
+ [owner.id],
+ );
+ const child = await queue.add(
+ 'subagent',
+ { prompt: 'orphan fixture' },
+ {
+ queue: queueName,
+ private_queue_owner_job_id: owner.id,
+ private_queue_owner_token: 'cycle-recovery-token',
+ private_queue_lease_ms: 600_000,
+ },
+ { allowProtectedSubmit: true },
+ );
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET updated_at = now() - interval '5 minutes' WHERE id = $1`,
+ [child.id],
+ );
+ return { queueName, childId: child.id };
+}
+
+async function childRow(id: number): Promise<{ status: string; error_text: string | null }> {
+ const rows = await engine.executeRaw<{ status: string; error_text: string | null }>(
+ `SELECT status, error_text FROM minion_jobs WHERE id = $1`,
+ [id],
+ );
+ return rows[0]!;
+}
+
+describe('cycle-start private-queue recovery lane', () => {
+ test('a real cycle cancels an orphaned dream-inline queue with the cycle-startup reason', async () => {
+ const { childId } = await seedOrphanQueue();
+
+ const report = await runCycle(engine, { brainDir: null, phases: [] });
+ expect(report.phases).toEqual([]); // explicit no-op cycle — recovery ran regardless
+
+ const row = await childRow(childId);
+ expect(row.status).toBe('cancelled');
+ expect(row.error_text).toStartWith('private_queue_reconciled:');
+ expect(row.error_text).toContain('cycle startup recovery');
+ }, 60_000);
+
+ test('dryRun: true leaves the orphan fixture untouched (still waiting)', async () => {
+ const { childId } = await seedOrphanQueue();
+
+ const report = await runCycle(engine, { brainDir: null, phases: [], dryRun: true });
+ expect(report.phases).toEqual([]);
+
+ const row = await childRow(childId);
+ expect(row.status).toBe('waiting');
+ expect(row.error_text).toBeNull();
+ }, 60_000);
+});
diff --git a/test/doctor-stale-lock-hints.test.ts b/test/doctor-stale-lock-hints.test.ts
new file mode 100644
index 0000000000..98861c2949
--- /dev/null
+++ b/test/doctor-stale-lock-hints.test.ts
@@ -0,0 +1,88 @@
+/**
+ * checkStaleLocks (src/commands/doctor/checks/routing-federation.ts) —
+ * per-lock break hints. First coverage of this check's hint dispatch:
+ *
+ * - cycle locks (`gbrain-cycle`, `gbrain-cycle:<source>`) point at
+ * `gbrain doctor --fix`. The removed hint `gbrain dream --break-lock`
+ * must NEVER come back: dream never implemented the flag, so a pasting
+ * operator ran a full (paid) dream cycle instead of breaking a lock.
+ * - sync locks (`gbrain-sync:<source>`) get the paste-ready
+ * `gbrain sync --break-lock --source <source>` command.
+ * - any other lock id falls back to the swept-at-next-acquire text.
+ *
+ * Runs without opts.fix so no reaping happens — the hints render for rows
+ * `listStaleLocks` returns (ttl_expires_at < NOW()), seeded via direct SQL
+ * like test/db-lock-inspect.test.ts.
+ */
+
+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { checkStaleLocks } from '../src/commands/doctor.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+async function seedStaleLock(id: string): Promise<void> {
+ await engine.executeRaw(
+ `INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at)
+ VALUES ($1, 43210, 'dead-host', NOW() - INTERVAL '2 hours', NOW() - INTERVAL '1 hour')`,
+ [id],
+ );
+}
+
+describe('checkStaleLocks — per-lock break hints', () => {
+ it('ok with no stale rows', async () => {
+ // A live (unexpired) lock is not stale.
+ await engine.executeRaw(
+ `INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at)
+ VALUES ('gbrain-cycle', 1234, 'live-host', NOW(), NOW() + INTERVAL '30 minutes')`,
+ );
+ const check = await checkStaleLocks(engine as unknown as BrainEngine);
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain('No stale locks');
+ });
+
+ it('stale cycle locks hint at doctor --fix, never the removed dream --break-lock', async () => {
+ await seedStaleLock('gbrain-cycle');
+ await seedStaleLock('gbrain-cycle:src');
+ const check = await checkStaleLocks(engine as unknown as BrainEngine);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('gbrain-cycle');
+ expect(check.message).toContain('gbrain-cycle:src');
+ expect(check.message).toContain('gbrain doctor --fix');
+ // The circular hint that ran a full paid dream cycle when pasted.
+ expect(check.message).not.toContain('dream --break-lock');
+ });
+
+ it('a stale sync lock gets the paste-ready break command with its source id', async () => {
+ await seedStaleLock('gbrain-sync:foo');
+ const check = await checkStaleLocks(engine as unknown as BrainEngine);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('gbrain sync --break-lock --source foo');
+ });
+
+ it('any other stale lock id falls back to the swept-at-next-acquire text', async () => {
+ await seedStaleLock('custom-maintenance-lock');
+ const check = await checkStaleLocks(engine as unknown as BrainEngine);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('swept at the next acquire');
+ // The fallback must not misroute to either named break command.
+ expect(check.message).not.toContain('--break-lock');
+ expect(check.message).not.toContain('doctor --fix');
+ });
+});
diff --git a/test/doctor-wedged-queue.test.ts b/test/doctor-wedged-queue.test.ts
index 1ba0c1b47a..7d0bf3febf 100644
--- a/test/doctor-wedged-queue.test.ts
+++ b/test/doctor-wedged-queue.test.ts
@@ -129,6 +129,29 @@ describe('issue #1801 fix #3 — computeWedgedQueueCheck', () => {
expect(check.message).not.toContain("'q-healthy'");
});
+ it('shell-escapes an embedded single quote in the restart hint (producer-controlled queue names)', async () => {
+ // The hint is copy-pasted by operators AND remediation agents, so a
+ // queue named q-wedge'd must arrive POSIX-escaped, never raw.
+ await seed("q-wedge'd", 'cycle', 'waiting');
+ await seed("q-wedge'd", 'cycle', 'completed', { updatedAtSql: "now() - interval '30 min'" });
+ const check = await computeWedgedQueueCheck(pgLike);
+ expect(check.status).toBe('fail');
+ expect(check.message).toContain(String.raw`--queue 'q-wedge'\''d'`);
+ });
+
+ it('hint union: wedged default AND non-default queues → bare hint plus --queue variant, comma-joined', async () => {
+ await seed('default', 'cycle', 'waiting');
+ await seed('default', 'cycle', 'completed', { updatedAtSql: "now() - interval '30 min'" });
+ await seed('q-side', 'cycle', 'waiting');
+ await seed('q-side', 'cycle', 'completed', { updatedAtSql: "now() - interval '30 min'" });
+ const check = await computeWedgedQueueCheck(pgLike);
+ expect(check.status).toBe('fail');
+ // The bare pair (for 'default') terminates with a backtick — no --queue —
+ // and the comma-join carries the per-queue variant right behind it.
+ expect(check.message).toContain('`gbrain jobs supervisor stop && gbrain jobs supervisor start`, `');
+ expect(check.message).toContain("--queue 'q-side'");
+ });
+
it('does NOT misclassify parent-owned dream queues as worker wedges', async () => {
await seed('dream-inline-dead-parent', 'subagent', 'waiting', {
createdAtSql: "now() - interval '2 hours'",
@@ -155,8 +178,15 @@ describe('orphaned private dream queues', () => {
const check = await computeOrphanedPrivateQueueCheck(pgLike);
expect(check.status).toBe('fail');
expect(check.message).toContain('supervisor restart cannot consume');
- expect(check.message).toContain('queue-reconciliation dry run');
- expect(check.details).toMatchObject({ orphaned_private_queues: 1, waiting_jobs: 1 });
+ // No owner metadata seeded → the legacy bucket, whose ONLY advertised
+ // remediation is the retriage preview (never a worker restart).
+ expect(check.message).toContain('gbrain dream retriage');
+ expect(check.details).toMatchObject({
+ orphaned_private_queues: 1,
+ waiting_jobs: 1,
+ legacy_unowned_queues: 1,
+ recoverable_queues: 0,
+ });
});
it('does not flag a private queue whose parent still holds a live job lock', async () => {
@@ -178,9 +208,46 @@ describe('orphaned private dream queues', () => {
expect(check.status).toBe('ok');
});
- it('returns ok on PGLite', async () => {
+ it('runs on PGLite too (no engine short-circuit): a dead-parent queue is flagged', async () => {
+ // PGLite mints the same dream-inline-* queues (children are inlined
+ // precisely because no worker process can run) — the old short-circuit
+ // hid exactly the brains with the fewest recovery lanes.
+ await seed('dream-inline-pglite-dead', 'subagent', 'waiting', {
+ createdAtSql: "now() - interval '2 hours'",
+ });
const check = await computeOrphanedPrivateQueueCheck(base as unknown as BrainEngine);
+ expect(check.status).toBe('fail');
+ // Engine-aware remediation: on PGLite the auto-recovery trigger is the
+ // next dream run, never a supervisor command.
+ expect(check.message).not.toContain('supervisor start`');
+ });
+
+ it('buckets a metadata-backed orphan as recoverable with the auto-recovery remediation', async () => {
+ // Terminal owner + expired lease → the classifier verdict is 'orphan':
+ // auto-recovery cancels it at the next worker spawn / cycle start.
+ await base.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, created_at) VALUES ('parent', 'cycle', 'completed', now() - interval '3 hours')`,
+ );
+ const owner = await base.executeRaw<{ id: number }>(`SELECT max(id)::int AS id FROM minion_jobs`);
+ await base.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, created_at, updated_at, private_queue_owner_job_id, private_queue_owner_token, private_queue_lease_until)
+ VALUES ('child', 'dream-inline-owned-dead', 'waiting', now() - interval '2 hours', now() - interval '2 hours', $1, 'tok', now() - interval '1 hour')`,
+ [owner[0].id],
+ );
+ const check = await computeOrphanedPrivateQueueCheck(pgLike);
+ expect(check.status).toBe('fail');
+ expect(check.message).toContain('Auto-recovery cancels the metadata-backed queue(s)');
+ expect(check.details).toMatchObject({ recoverable_queues: 1, legacy_unowned_queues: 0 });
+ });
+
+ it('suppresses a queue whose owner lease is still in the future (live, never flagged)', async () => {
+ await base.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, created_at, private_queue_owner_token, private_queue_lease_until)
+ VALUES ('child', 'dream-inline-leased', 'waiting', now() - interval '2 hours', 'tok', now() + interval '30 min')`,
+ );
+ const check = await computeOrphanedPrivateQueueCheck(pgLike);
expect(check.status).toBe('ok');
+ expect(check.details).toMatchObject({ suppressed_by_live_lease: 1 });
});
});
@@ -304,6 +371,120 @@ describe('orphaned private dream queues — cycle-lock liveness + ownership corr
});
});
+describe('orphaned private dream queues — classify cap, buckets, flagged-only counts (749a7dcb)', () => {
+ beforeEach(async () => {
+ // Leftover live cycle locks from earlier describes must not suppress
+ // these candidates via the ownership correlation.
+ await base.executeRaw('DELETE FROM gbrain_cycle_locks');
+ });
+
+ it('caps classification at 100 candidates and reports the remainder as unclassified (fail path)', async () => {
+ // 101 metadata-backed orphan candidates (aged, waiting, expired lease —
+ // classifier verdict 'orphan'), one row per queue for speed.
+ await base.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, created_at, updated_at, private_queue_lease_until)
+ SELECT 'subagent', 'dream-inline-cap-' || i, 'waiting',
+ now() - interval '2 hours', now() - interval '2 hours', now() - interval '1 hour'
+ FROM generate_series(1, 101) AS i`,
+ );
+ const check = await computeOrphanedPrivateQueueCheck(pgLike);
+ expect(check.status).toBe('fail');
+ expect((check.details as any).orphaned_private_queues).toBeLessThanOrEqual(100);
+ expect((check.details as any).orphaned_private_queues).toBe(100);
+ expect((check.details as any).unclassified_candidates).toBe(1);
+ });
+
+ it('ok-path truncation honesty: 100 live + 1 never-classified is NOT a clean bill of health', async () => {
+ // First 100 candidates classify 'live' (future lease + fresh updated_at);
+ // the 101st never gets classified. Status stays ok but the message and
+ // details must still surface the unclassified remainder.
+ await base.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, created_at, updated_at, private_queue_lease_until)
+ SELECT 'subagent', 'dream-inline-live-' || i, 'waiting',
+ now() - interval '2 hours', now(), now() + interval '30 minutes'
+ FROM generate_series(1, 101) AS i`,
+ );
+ const check = await computeOrphanedPrivateQueueCheck(pgLike);
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain('unclassified');
+ expect((check.details as any).unclassified_candidates).toBe(1);
+ expect((check.details as any).suppressed_by_live_lease).toBe(100);
+ });
+
+ it('buckets a NON-terminal unclaimed owner as owner_pending with the inspect-first remediation', async () => {
+ // Owner job still waiting (not claimed, no lock) → verdict not_orphan:
+ // doctor must say "inspect the owner", never advertise cancellation.
+ await base.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, created_at) VALUES ('dream-cycle', 'default', 'waiting', now() - interval '3 hours')`,
+ );
+ const owner = await base.executeRaw<{ id: number }>(`SELECT max(id)::int AS id FROM minion_jobs`);
+ await base.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, created_at, updated_at, private_queue_owner_job_id, private_queue_owner_token)
+ VALUES ('subagent', 'dream-inline-owner-pending', 'waiting', now() - interval '2 hours', now() - interval '2 hours', $1, 'tok')`,
+ [owner[0].id],
+ );
+ const check = await computeOrphanedPrivateQueueCheck(pgLike);
+ expect(check.status).toBe('fail');
+ expect(check.message).toContain('inspect it with');
+ expect(check.message).toContain('gbrain jobs get');
+ expect(check.details).toMatchObject({
+ owner_pending_queues: 1,
+ recoverable_queues: 0,
+ legacy_unowned_queues: 0,
+ });
+ });
+
+ it('PGLite recoverable fixture advertises `gbrain dream` as the trigger, never the supervisor', async () => {
+ // Terminal owner + aged + expired lease → recoverable bucket. On PGLite
+ // the engine-aware remediation must name the dream trigger (a supervisor
+ // command is impossible advice — no worker process can ever run there).
+ await base.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, created_at) VALUES ('dream-cycle', 'default', 'completed', now() - interval '3 hours')`,
+ );
+ const owner = await base.executeRaw<{ id: number }>(`SELECT max(id)::int AS id FROM minion_jobs`);
+ await base.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, created_at, updated_at, private_queue_owner_job_id, private_queue_owner_token, private_queue_lease_until)
+ VALUES ('subagent', 'dream-inline-pglite-recoverable', 'waiting', now() - interval '2 hours', now() - interval '2 hours', $1, 'tok', now() - interval '1 hour')`,
+ [owner[0].id],
+ );
+ const check = await computeOrphanedPrivateQueueCheck(base as unknown as BrainEngine);
+ expect(check.status).toBe('fail');
+ expect(check.message).toContain('Auto-recovery cancels the metadata-backed queue(s)');
+ expect(check.message).toContain('trigger now: `gbrain dream`');
+ expect(check.message).not.toContain('supervisor start`');
+ });
+
+ it('waiting_jobs counts FLAGGED queues only — live-lease-suppressed waiting rows are excluded (749a7dcb)', async () => {
+ // Recoverable orphan with 3 waiting rows (terminal owner, expired lease).
+ await base.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, created_at) VALUES ('dream-cycle', 'default', 'completed', now() - interval '3 hours')`,
+ );
+ const owner = await base.executeRaw<{ id: number }>(`SELECT max(id)::int AS id FROM minion_jobs`);
+ await base.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, created_at, updated_at, private_queue_owner_job_id, private_queue_owner_token, private_queue_lease_until)
+ SELECT 'subagent', 'dream-inline-orphan-n', 'waiting',
+ now() - interval '2 hours', now() - interval '2 hours', $1, 'tok', now() - interval '1 hour'
+ FROM generate_series(1, 3)`,
+ [owner[0].id],
+ );
+ // Aged candidate suppressed by a live lease, carrying 2 waiting rows that
+ // must NOT leak into waiting_jobs (pre-fix it summed N+M during the scan).
+ await base.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, created_at, updated_at, private_queue_lease_until)
+ SELECT 'subagent', 'dream-inline-lively-m', 'waiting',
+ now() - interval '2 hours', now() - interval '2 hours', now() + interval '30 minutes'
+ FROM generate_series(1, 2)`,
+ );
+ const check = await computeOrphanedPrivateQueueCheck(pgLike);
+ expect(check.status).toBe('fail');
+ expect(check.details).toMatchObject({
+ orphaned_private_queues: 1,
+ waiting_jobs: 3,
+ suppressed_by_live_lease: 1,
+ });
+ });
+});
+
describe('Minions-visibility wave — computeQueueHealthCheck structured details', () => {
it('ok path carries {depth, oldest_age_seconds, worker_alive} (messages unchanged)', async () => {
const check = await computeQueueHealthCheck(pgLike, { readWorkers: () => [] });
diff --git a/test/dream-owner-id-threading.serial.test.ts b/test/dream-owner-id-threading.serial.test.ts
new file mode 100644
index 0000000000..597cbfa648
--- /dev/null
+++ b/test/dream-owner-id-threading.serial.test.ts
@@ -0,0 +1,117 @@
+/**
+ * Owner-id threading from registerBuiltinHandlers into runCycle
+ * (src/commands/jobs.ts): every cycle-running handler must pass
+ * `privateQueueOwnerJobId: job.id` so phase-created dream-inline-* private
+ * queues carry an owner and the orphan-recovery lanes can classify them.
+ * Pins the three call sites:
+ * - 'autopilot-cycle' (per-source / legacy cycle handler)
+ * - 'autopilot-global-maintenance' (brain-wide maintenance lane)
+ * - makePhaseHandler (the dream-phase wrappers; exercised via
+ * 'resolve_symbol_edges')
+ *
+ * Serial (*.serial.test.ts): mock.module replaces cycle.ts's runCycle with a
+ * capturing stub (everything else re-exported real), which leaks across files
+ * in a shared shard process.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const realCycle = await import('../src/core/cycle.ts');
+
+const capturedOpts: Array<Record<string, unknown>> = [];
+
+mock.module('../src/core/cycle.ts', () => ({
+ ...realCycle,
+ runCycle: async (_engine: unknown, opts: Record<string, unknown>) => {
+ capturedOpts.push(opts);
+ // Minimal successful CycleReport shape: handlers read `report.status`
+ // (and the maintenance handler stamps config when it is ok/clean/partial).
+ return {
+ schema_version: '1',
+ timestamp: new Date().toISOString(),
+ duration_ms: 0,
+ status: 'ok',
+ brain_dir: (opts.brainDir as string | null) ?? null,
+ phases: [],
+ totals: {},
+ };
+ },
+}));
+
+// Import AFTER the mock so the handlers' dynamic `import('../core/cycle.ts')`
+// resolves to the capturing stub.
+const { registerBuiltinHandlers } = await import('../src/commands/jobs.ts');
+const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');
+
+let engine: InstanceType<typeof PGLiteEngine>;
+let handlers: Map<string, (job: unknown) => Promise<Record<string, unknown>>>;
+let repoPath: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ handlers = new Map();
+ const fakeWorker = {
+ register(name: string, fn: (job: unknown) => Promise<Record<string, unknown>>) {
+ handlers.set(name, fn);
+ },
+ };
+ await registerBuiltinHandlers(fakeWorker as never, engine, { quiet: true });
+ repoPath = mkdtempSync(join(tmpdir(), 'gbrain-owner-id-threading-'));
+}, 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(() => {
+ capturedOpts.length = 0;
+});
+
+describe('privateQueueOwnerJobId === job.id threading', () => {
+ test("'autopilot-cycle' threads its job id into runCycle", async () => {
+ const handler = handlers.get('autopilot-cycle');
+ expect(handler).toBeTruthy();
+ const result = await handler!({
+ id: 42,
+ name: 'autopilot-cycle',
+ data: { repoPath },
+ signal: new AbortController().signal,
+ });
+ expect(result.status).toBe('ok');
+ expect(capturedOpts.length).toBe(1);
+ expect(capturedOpts[0].privateQueueOwnerJobId).toBe(42);
+ });
+
+ test("'autopilot-global-maintenance' threads its job id into runCycle", async () => {
+ const handler = handlers.get('autopilot-global-maintenance');
+ expect(handler).toBeTruthy();
+ const result = await handler!({
+ id: 43,
+ name: 'autopilot-global-maintenance',
+ data: { repoPath },
+ signal: new AbortController().signal,
+ });
+ expect(result.status).toBe('ok');
+ expect(capturedOpts.length).toBe(1);
+ expect(capturedOpts[0].privateQueueOwnerJobId).toBe(43);
+ });
+
+ test('the dream-phase wrapper (makePhaseHandler) threads its job id into runCycle', async () => {
+ const handler = handlers.get('resolve_symbol_edges');
+ expect(handler).toBeTruthy();
+ const result = await handler!({
+ id: 44,
+ name: 'resolve_symbol_edges',
+ data: { repoPath },
+ signal: new AbortController().signal,
+ });
+ expect(result.status).toBe('ok');
+ expect(capturedOpts.length).toBe(1);
+ expect(capturedOpts[0].privateQueueOwnerJobId).toBe(44);
+ expect(capturedOpts[0].phases).toEqual(['resolve_symbol_edges']);
+ });
+});
diff --git a/test/e2e/dream-synthesize-pglite.test.ts b/test/e2e/dream-synthesize-pglite.test.ts
index 02b59d9e8f..263a46fdb2 100644
--- a/test/e2e/dream-synthesize-pglite.test.ts
+++ b/test/e2e/dream-synthesize-pglite.test.ts
@@ -759,7 +759,13 @@ describe('E2E synthesize — PGLite inline subagent drain (takeover of #2699)',
return { ok: true };
},
);
- expect(ticks).toBe(0); // 60s keepalive never fires for a fast child
+ // Per-child lease keepalive (v0.46.25): the drain fires yieldDuringPhase
+ // once per claimed child so fast children (<60s, never reaching a timer
+ // tick) still renew the private-queue lease. Two-sided: the upper bound
+ // catches the opposite regression — firing per 1s idle poll, the exact
+ // runaway the wrapper's 30s throttle exists to prevent.
+ expect(ticks).toBeGreaterThanOrEqual(1);
+ expect(ticks).toBeLessThanOrEqual(3);
const final = await queue.getJob(child.id);
expect(final?.status).toBe('completed');
diff --git a/test/e2e/postgres-bootstrap.test.ts b/test/e2e/postgres-bootstrap.test.ts
index 0d275a9ee0..dbd8ddd7a7 100644
--- a/test/e2e/postgres-bootstrap.test.ts
+++ b/test/e2e/postgres-bootstrap.test.ts
@@ -157,6 +157,67 @@ describe.skipIf(skip)('PostgresEngine forward-reference bootstrap (E2E)', () =>
expect(idx).toHaveLength(2);
}, 60_000);
+ test('pre-v136 minion_jobs private-queue shape (dream-inline lifecycle) converges on REAL Postgres', async () => {
+ // v0.46.25 (#4332): the private-queue owner/lease columns are migration-
+ // added AND referenced by the blob partial indexes — the same wedge class
+ // as v121 and pre-v7 above. Strip all three columns + both indexes, then
+ // assert the bootstrap → SCHEMA_SQL replay re-adds every piece.
+ await engine.initSchema();
+ const conn = (engine as any).sql;
+ await conn.unsafe(`
+ DROP INDEX IF EXISTS idx_minion_jobs_private_queue_recovery;
+ DROP INDEX IF EXISTS idx_minion_jobs_private_queue_owner;
+ ALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_owner_job_id;
+ ALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_owner_token;
+ ALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_lease_until;
+ `);
+
+ await engine.initSchema();
+
+ const cols = await conn`
+ SELECT column_name FROM information_schema.columns
+ WHERE table_schema = current_schema()
+ AND table_name = 'minion_jobs'
+ AND column_name IN ('private_queue_owner_job_id', 'private_queue_owner_token', 'private_queue_lease_until')
+ `;
+ expect(cols).toHaveLength(3);
+ const idx = await conn`
+ SELECT indexname, indexdef FROM pg_indexes
+ WHERE tablename = 'minion_jobs'
+ AND indexname IN ('idx_minion_jobs_private_queue_recovery', 'idx_minion_jobs_private_queue_owner')
+ `;
+ expect(idx).toHaveLength(2);
+ // The recovery index must come back PARTIAL — the dream-inline predicate
+ // is what keeps the startup recovery scan off the general job table.
+ const recovery = idx.find(
+ (r: { indexname: string; indexdef: string }) => r.indexname === 'idx_minion_jobs_private_queue_recovery',
+ );
+ expect(recovery?.indexdef).toContain('dream-inline-');
+ }, 60_000);
+
+ test('token-only-missing minion_jobs is repaired by the pq_token probe on REAL Postgres (749a7dcb)', async () => {
+ // Partial-upgrade shape: ONLY private_queue_owner_token is missing.
+ // Neither blob index references the token, so SCHEMA_SQL replay cannot
+ // crash on it, and the ledger is already at LATEST so runMigrations won't
+ // re-run v136 — the ONLY repair path is the minion_jobs_pq_token_exists
+ // probe (749a7dcb) triggering the bootstrap's three-column ALTER block.
+ await engine.initSchema();
+ const conn = (engine as any).sql;
+ await conn.unsafe(`
+ ALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_owner_token;
+ `);
+
+ await engine.initSchema();
+
+ const cols = await conn`
+ SELECT column_name FROM information_schema.columns
+ WHERE table_schema = current_schema()
+ AND table_name = 'minion_jobs'
+ AND column_name = 'private_queue_owner_token'
+ `;
+ expect(cols).toHaveLength(1);
+ }, 60_000);
+
// Migration v120 — schema-lint hardening (#1647 / #171). Postgres-only
// assertions (security_invoker has no surface on embedded PGLite).
test('v120: page_links view runs with security_invoker=on (#1647b)', async () => {
diff --git a/test/get-job-stats-op.test.ts b/test/get-job-stats-op.test.ts
index f7cb3233cf..dd0ea2bc37 100644
--- a/test/get-job-stats-op.test.ts
+++ b/test/get-job-stats-op.test.ts
@@ -73,6 +73,45 @@ describe('get_job_stats op', () => {
});
});
+describe('get_job_stats — private dream-inline queues', () => {
+ const PRIVATE_QUEUE = 'dream-inline-1700000000000-abcd1234';
+
+ test('a would-be-wedged dream-inline queue reports private_queue true, wedged false', async () => {
+ // Exact wedge signature (waiting, 0 live-lock active, stale completion):
+ // ONLY the private-queue classification keeps wedged false here — if it
+ // regressed, this fixture would trip the wedge derivation.
+ await engine.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, created_at, updated_at)
+ VALUES ('subagent', '${PRIVATE_QUEUE}', 'waiting', now() - interval '2 hours', now() - interval '2 hours')`,
+ );
+ await engine.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, updated_at)
+ VALUES ('subagent', '${PRIVATE_QUEUE}', 'completed', now() - interval '90 minutes')`,
+ );
+ await withEnv({ GBRAIN_WEDGED_QUEUE_WARN_MINUTES: undefined }, async () => {
+ const res = await dispatchToolCall(engine, 'get_job_stats', { queue: PRIVATE_QUEUE }, { ...STDIO });
+ expect(res.isError ?? false).toBe(false);
+ const body = parsed(res);
+ expect(body.wedge.queue).toBe(PRIVATE_QUEUE);
+ expect(body.wedge.waiting).toBeGreaterThan(0); // the fixture really is the wedge shape
+ expect(body.private_queue).toBe(true);
+ expect(body.wedged).toBe(false);
+ });
+ });
+
+ test('the default queue reports private_queue false', async () => {
+ const res = await dispatchToolCall(engine, 'get_job_stats', { queue: 'default' }, { ...STDIO });
+ const body = parsed(res);
+ expect(body.private_queue).toBe(false);
+ });
+
+ test('description pins the private-queue wedge guidance MCP consumers act on', () => {
+ const desc = operationsByName['get_job_stats'].description ?? '';
+ expect(desc).toContain('wedged is NEVER true');
+ expect(desc).toContain('parent-owned dream-inline queue');
+ });
+});
+
describe('deriveWedgeSignal (shared with the CLI line + doctor check)', () => {
// deriveWedgeSignal reads GBRAIN_WEDGED_QUEUE_WARN_MINUTES per call — pin
// it to unset so a tuned dev/CI host (e.g. =120) can't flip the 60-minute
diff --git a/test/inline-drain-keepalive.test.ts b/test/inline-drain-keepalive.test.ts
new file mode 100644
index 0000000000..d8f0a88762
--- /dev/null
+++ b/test/inline-drain-keepalive.test.ts
@@ -0,0 +1,108 @@
+/**
+ * Inline-drain idle-poll keepalive (src/core/cycle/inline-drain.ts :239) and
+ * its swallow-on-throw catch arms.
+ *
+ * The idle branch fires when nothing is claimable but pending > 0 (e.g. a
+ * 'delayed' child backing off). It MUST renew via yieldDuringPhase there:
+ * with every child delayed no per-child keepalive is armed, and an unrenewed
+ * lease reads as orphaned to spawn recovery — which would cancel a LIVE
+ * queue. Both yieldDuringPhase call sites (idle poll :239 and post-claim
+ * :250) swallow a throwing keepalive: renewal is best-effort and must never
+ * fail the drain.
+ *
+ * Harness mirrors test/cycle-synthesize-inline-concurrency.test.ts: drive
+ * runSubagentsInline directly with a controllable handler against a real
+ * MinionQueue on PGLite. A child seeded with `delay` (status 'delayed',
+ * future delay_until) forces the idle branch until promoteDelayed picks it
+ * up (~the delay), keeping each test a few seconds (idle poll starts at 1s).
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { runSubagentsInline } from '../src/core/cycle/inline-drain.ts';
+import type { MinionHandler } from '../src/core/minions/types.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+let queueSeq = 0;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' }); // in-memory
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+}, 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ // Targeted DELETE preserves the `config.version` key MinionQueue's
+ // ensureSchema requires (full resetPgliteState wipes it).
+ await engine.executeRaw('DELETE FROM minion_jobs');
+});
+
+async function seedDelayedChild(queueName: string, delayMs: number): Promise<number> {
+ const job = await queue.add(
+ 'subagent',
+ { prompt: 'delayed child' },
+ { queue: queueName, delay: delayMs },
+ { allowProtectedSubmit: true },
+ );
+ return job.id;
+}
+
+async function status(id: number): Promise<string> {
+ const rows = await engine.executeRaw<{ status: string }>(
+ `SELECT status FROM minion_jobs WHERE id = $1`,
+ [id],
+ );
+ return rows[0]!.status;
+}
+
+describe('inline-drain idle-poll keepalive', () => {
+ test('idle branch (pending > 0, nothing claimable) fires yieldDuringPhase each poll', async () => {
+ const queueName = `dream-inline-keepalive-${++queueSeq}`;
+ // 2.5s delay: polls at ~0s and ~1s are guaranteed idle (claim sees only a
+ // future-delayed row); the ~3s poll promotes + claims it.
+ const childId = await seedDelayedChild(queueName, 2_500);
+
+ let handlerStarted = false;
+ let yieldsBeforeHandler = 0;
+ const yieldDuringPhase = async () => {
+ if (!handlerStarted) yieldsBeforeHandler++;
+ };
+ const handler: MinionHandler = async () => {
+ handlerStarted = true;
+ return { ok: true };
+ };
+
+ await runSubagentsInline(engine, queue, queueName, yieldDuringPhase, handler);
+
+ // The post-claim site (:250) contributes exactly ONE pre-handler yield,
+ // so >= 2 proves the idle-poll site (:239) fired at least once.
+ expect(yieldsBeforeHandler).toBeGreaterThanOrEqual(2);
+ expect(await status(childId)).toBe('completed');
+ }, 30_000);
+
+ test('a THROWING yieldDuringPhase is swallowed at both call sites; the drain still completes', async () => {
+ const queueName = `dream-inline-keepalive-${++queueSeq}`;
+ const childId = await seedDelayedChild(queueName, 1_500);
+
+ let throws = 0;
+ const yieldDuringPhase = async () => {
+ throws++;
+ throw new Error('keepalive exploded');
+ };
+ const handler: MinionHandler = async () => ({ ok: true });
+
+ // Must resolve: both the idle-poll and post-claim call sites swallow.
+ await runSubagentsInline(engine, queue, queueName, yieldDuringPhase, handler);
+
+ // At least one idle-poll throw (the ~0s poll, while the child was still
+ // delayed) plus the post-claim throw — both arms were exercised.
+ expect(throws).toBeGreaterThanOrEqual(2);
+ expect(await status(childId)).toBe('completed');
+ }, 30_000);
+});
diff --git a/test/jobs-ops-token-redaction.test.ts b/test/jobs-ops-token-redaction.test.ts
new file mode 100644
index 0000000000..42b601ddc4
--- /dev/null
+++ b/test/jobs-ops-token-redaction.test.ts
@@ -0,0 +1,149 @@
+/**
+ * private_queue_owner_token redaction across the jobs MCP op envelopes
+ * (src/core/ops/jobs.ts). The token is a capability credential (lease
+ * renewal / queue attach), not job data — get_job, list_jobs, and submit_job
+ * must replace a present token with the literal '[redacted]' and pass a
+ * missing one through as null (NEVER the string '[redacted]').
+ *
+ * submit_job cannot mint a token through its declared params; the path that
+ * returns one is the param-coalesce hit onto an existing token-bearing
+ * waiting row (MinionQueue.add hydrates the FULL row, token included), so
+ * that is the shape this file exercises for the submit surface.
+ */
+
+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { _resetAdmissionCacheForTest } from '../src/core/minions/admission.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ // resetPgliteState truncates config; MinionQueue.add's ensureSchema reads
+ // the schema version from it (same re-seed as submit-queue-state.test.ts).
+ await engine.setConfig('version', '85');
+});
+
+const STDIO = { remote: true, transport: 'stdio' as const, sourceId: 'default' };
+const RAW_TOKEN = 'raw-owner-capability-token-5f3a9c81d2e4';
+
+function parsed(result: { content: Array<{ text: string }> }) {
+ return JSON.parse(result.content[0].text);
+}
+
+/** Direct SQL seed: a waiting private-queue job carrying the raw token. */
+async function seedPrivateJob(queue: string): Promise<number> {
+ const rows = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO minion_jobs (name, queue, status, data, private_queue_owner_token, private_queue_lease_until)
+ VALUES ('subagent', $1, 'waiting', '{}'::jsonb, $2, now() + interval '10 minutes')
+ RETURNING id`,
+ [queue, RAW_TOKEN],
+ );
+ return Number(rows[0].id);
+}
+
+async function seedPlainJob(): Promise<number> {
+ const rows = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO minion_jobs (name, queue, status, data)
+ VALUES ('embed', 'default', 'waiting', '{}'::jsonb)
+ RETURNING id`,
+ );
+ return Number(rows[0].id);
+}
+
+describe('get_job — owner-token redaction', () => {
+ it('redacts a present token and never leaks the raw value anywhere in the envelope', async () => {
+ const id = await seedPrivateJob('dream-inline-1700000000000-cafe0001');
+ const res = await dispatchToolCall(engine, 'get_job', { id }, { ...STDIO });
+ expect(res.isError ?? false).toBe(false);
+ const body = parsed(res);
+ expect(body.private_queue_owner_token).toBe('[redacted]');
+ // The raw capability must be absent from the WHOLE serialized response,
+ // not just the one field.
+ expect(res.content[0].text).not.toContain(RAW_TOKEN);
+ });
+
+ it('null passthrough: a plain job reports null, not the string [redacted]', async () => {
+ const id = await seedPlainJob();
+ const res = await dispatchToolCall(engine, 'get_job', { id }, { ...STDIO });
+ const body = parsed(res);
+ expect(body.private_queue_owner_token).toBeNull();
+ expect(body.private_queue_owner_token).not.toBe('[redacted]');
+ });
+});
+
+describe('list_jobs — owner-token redaction', () => {
+ it('redacts EVERY returned private-queue job; plain jobs stay null', async () => {
+ await seedPrivateJob('dream-inline-1700000000000-cafe0002');
+ await seedPrivateJob('dream-inline-1700000000000-cafe0003');
+ const plainId = await seedPlainJob();
+ const res = await dispatchToolCall(engine, 'list_jobs', { limit: 100 }, { ...STDIO });
+ expect(res.isError ?? false).toBe(false);
+ const body = parsed(res) as Array<{ id: number; queue: string; private_queue_owner_token: string | null }>;
+ const privateJobs = body.filter(j => j.queue.startsWith('dream-inline-'));
+ expect(privateJobs.length).toBe(2);
+ for (const j of privateJobs) expect(j.private_queue_owner_token).toBe('[redacted]');
+ const plain = body.find(j => j.id === plainId);
+ expect(plain?.private_queue_owner_token).toBeNull();
+ expect(res.content[0].text).not.toContain(RAW_TOKEN);
+ });
+});
+
+describe('submit_job — owner-token redaction', () => {
+ const submit_job = operationsByName['submit_job'];
+
+ function localCtx(): any {
+ return { engine, config: {}, logger: console, dryRun: false, remote: false };
+ }
+
+ it('a coalesce hit onto a token-bearing waiting row returns [redacted], never the raw token', async () => {
+ // Force a re-resolve so a policy another file cached for 'subagent'
+ // cannot mask the default-on param coalescing this test depends on.
+ _resetAdmissionCacheForTest();
+ const queueName = 'dream-inline-1700000000000-cafe0004';
+ const q = new MinionQueue(engine);
+ // Seed through add() so __param_hash is stamped identically to what the
+ // op handler's add() computes (opts identity: priority 0, max_attempts 3).
+ const seeded = await q.add(
+ 'subagent',
+ { prompt: 'coalesce-me' },
+ { queue: queueName, priority: 0, max_attempts: 3, private_queue_owner_token: RAW_TOKEN },
+ { allowProtectedSubmit: true },
+ );
+ // The queue layer itself hands back the raw token — redaction is the
+ // op envelope's job, which is exactly what this test pins.
+ expect(seeded.private_queue_owner_token).toBe(RAW_TOKEN);
+
+ const result = (await submit_job.handler(localCtx(), {
+ name: 'subagent',
+ data: { prompt: 'coalesce-me' },
+ queue: queueName,
+ })) as Record<string, unknown>;
+ expect(result.coalesced).toBe(true); // proves the token-bearing row was returned, not a fresh insert
+ expect(result.private_queue_owner_token).toBe('[redacted]');
+ expect(JSON.stringify(result)).not.toContain(RAW_TOKEN);
+ });
+
+ it('null passthrough: a fresh tokenless submission reports null, not the string [redacted]', async () => {
+ const res = await dispatchToolCall(engine, 'submit_job', { name: 'embed' }, { ...STDIO });
+ expect(res.isError ?? false).toBe(false);
+ const body = parsed(res);
+ expect(body.id).toBeGreaterThan(0);
+ expect(body.private_queue_owner_token).toBeNull();
+ expect(body.private_queue_owner_token).not.toBe('[redacted]');
+ });
+});
diff --git a/test/jobs-stats-private-queue.serial.test.ts b/test/jobs-stats-private-queue.serial.test.ts
new file mode 100644
index 0000000000..3af894fa81
--- /dev/null
+++ b/test/jobs-stats-private-queue.serial.test.ts
@@ -0,0 +1,101 @@
+/**
+ * `jobs stats --queue <dream-inline-*>` — ABANDONED PRIVATE QUEUE gating
+ * (src/commands/jobs.ts stats case). The line is gated on the SAME classifier
+ * recovery uses (classifyPrivateQueueForRecovery), so the scream and the
+ * advertised repair cannot drift:
+ *
+ * - orphan (terminal owner, aged, expired lease) → ABANDONED + the
+ * auto-recovery remediation (next worker spawn / dream-cycle start);
+ * - unowned (legacy, no owner metadata, aged) → ABANDONED + retriage;
+ * - live (future lease / fresh touch) → NEITHER the ABANDONED
+ * line NOR the WEDGED warning (a private queue is never "wedged" — the
+ * supervisor-restart advice would be a dead end).
+ *
+ * Serial: captures console.log around runJobs (process-global stdout seam),
+ * mirroring test/jobs-stats-divergence.serial.test.ts.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runJobs } from '../src/commands/jobs.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await engine.executeRaw(`DELETE FROM minion_jobs`, []);
+});
+
+async function captureStats(args: string[]): Promise<string> {
+ const origLog = console.log;
+ let out = '';
+ console.log = (...a: unknown[]) => { out += a.map(String).join(' ') + '\n'; };
+ try {
+ await runJobs(engine, args);
+ } finally {
+ console.log = origLog;
+ }
+ return out;
+}
+
+describe('jobs stats — ABANDONED PRIVATE QUEUE classifier gating', () => {
+ test('orphan (terminal owner, aged, expired lease) screams ABANDONED with the auto-recovery remediation', async () => {
+ const q = 'dream-inline-1700000000000-dead0001';
+ await engine.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, data, created_at)
+ VALUES ('dream-cycle', 'default', 'completed', '{}'::jsonb, now() - interval '3 hours')`,
+ [],
+ );
+ const owner = await engine.executeRaw<{ id: number }>(`SELECT max(id)::int AS id FROM minion_jobs`, []);
+ await engine.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, data, created_at, updated_at,
+ private_queue_owner_job_id, private_queue_owner_token, private_queue_lease_until)
+ SELECT 'subagent', $1, 'waiting', '{}'::jsonb, now() - interval '2 hours', now() - interval '2 hours',
+ $2, 'tok', now() - interval '1 hour'
+ FROM generate_series(1, 2)`,
+ [q, owner[0].id],
+ );
+ const out = await captureStats(['stats', '--queue', q]);
+ expect(out).toContain(`ABANDONED PRIVATE QUEUE '${q}'`);
+ expect(out).toContain('Auto-recovery cancels it at the next worker spawn or dream-cycle start');
+ expect(out).not.toContain('WEDGED QUEUE');
+ });
+
+ test('legacy unowned (no owner metadata, aged) screams ABANDONED with the retriage remediation', async () => {
+ const q = 'dream-inline-1700000000000-dead0002';
+ await engine.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, data, created_at, updated_at)
+ VALUES ('subagent', $1, 'waiting', '{}'::jsonb, now() - interval '2 hours', now() - interval '2 hours')`,
+ [q],
+ );
+ const out = await captureStats(['stats', '--queue', q]);
+ expect(out).toContain(`ABANDONED PRIVATE QUEUE '${q}'`);
+ expect(out).toContain('retriage');
+ expect(out).not.toContain('WEDGED QUEUE');
+ });
+
+ test('live (future lease) renders NEITHER the ABANDONED line NOR the wedged warning', async () => {
+ const q = 'dream-inline-1700000000000-live0003';
+ // Aged enough to be a candidate, but the future lease classifies live —
+ // a healthy mid-drain queue must not scream.
+ await engine.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, data, created_at, updated_at, private_queue_lease_until)
+ VALUES ('subagent', $1, 'waiting', '{}'::jsonb, now() - interval '2 hours', now() - interval '2 hours',
+ now() + interval '30 minutes')`,
+ [q],
+ );
+ const out = await captureStats(['stats', '--queue', q]);
+ expect(out).toContain('Queue health'); // stats really rendered (guards the not.toContain below)
+ expect(out).not.toContain('ABANDONED');
+ expect(out).not.toContain('WEDGED QUEUE');
+ });
+});
diff --git a/test/jobs-worker-startup-recovery.test.ts b/test/jobs-worker-startup-recovery.test.ts
new file mode 100644
index 0000000000..ac0b0dbf5f
--- /dev/null
+++ b/test/jobs-worker-startup-recovery.test.ts
@@ -0,0 +1,135 @@
+/**
+ * maybeRunWorkerStartupRecovery (src/commands/jobs.ts) — the bare-worker
+ * arm of the orphaned-private-queue recovery net. A deployment that starts
+ * `gbrain jobs work` directly (no supervisor) must still recover crashed
+ * dream-inline-* queues; supervised children (GBRAIN_SUPERVISED=1) skip it
+ * because their supervisor already ran the scan. Pins:
+ * - unsupervised env → orphan cancelled with the worker-startup reason;
+ * - GBRAIN_SUPERVISED=1 → fixture untouched;
+ * - a throwing queue → resolves (recovery failure never kills the worker);
+ * - structurally: the 'work' handler awaits the recovery right after
+ * ensureSchema, before the worker/work loop is constructed.
+ *
+ * Env is passed EXPLICITLY (the function's `env` parameter) so this file
+ * never mutates process.env (isolation rule R1).
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { maybeRunWorkerStartupRecovery } from '../src/commands/jobs.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+let queueSeq = 0;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' }); // in-memory
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+}, 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ // Targeted DELETE preserves the `config.version` key that
+ // MinionQueue.ensureSchema requires (full resetPgliteState wipes it).
+ await engine.executeRaw('DELETE FROM minion_jobs');
+});
+
+/** Orphan fixture: waiting 'subagent' child, terminal owner, aged updated_at. */
+async function seedOrphanQueue(): Promise<{ queueName: string; childId: number }> {
+ const queueName = `dream-inline-worker-recovery-${++queueSeq}`;
+ const owner = await queue.add('autopilot-cycle', {});
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'completed', finished_at = now() WHERE id = $1`,
+ [owner.id],
+ );
+ const child = await queue.add(
+ 'subagent',
+ { prompt: 'orphan fixture' },
+ {
+ queue: queueName,
+ private_queue_owner_job_id: owner.id,
+ private_queue_owner_token: 'worker-recovery-token',
+ private_queue_lease_ms: 600_000,
+ },
+ { allowProtectedSubmit: true },
+ );
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET updated_at = now() - interval '5 minutes' WHERE id = $1`,
+ [child.id],
+ );
+ return { queueName, childId: child.id };
+}
+
+async function childRow(id: number): Promise<{ status: string; error_text: string | null }> {
+ const rows = await engine.executeRaw<{ status: string; error_text: string | null }>(
+ `SELECT status, error_text FROM minion_jobs WHERE id = $1`,
+ [id],
+ );
+ return rows[0]!;
+}
+
+describe('maybeRunWorkerStartupRecovery', () => {
+ test('unsupervised (GBRAIN_SUPERVISED unset) cancels the orphan with the worker-startup reason', async () => {
+ const { childId } = await seedOrphanQueue();
+
+ await maybeRunWorkerStartupRecovery(queue, {});
+
+ const row = await childRow(childId);
+ expect(row.status).toBe('cancelled');
+ expect(row.error_text).toStartWith('private_queue_reconciled:');
+ expect(row.error_text).toContain('worker startup recovery');
+ });
+
+ test('GBRAIN_SUPERVISED=1 skips recovery entirely (supervisor already ran it)', async () => {
+ const { childId } = await seedOrphanQueue();
+
+ await maybeRunWorkerStartupRecovery(queue, { GBRAIN_SUPERVISED: '1' });
+
+ const row = await childRow(childId);
+ expect(row.status).toBe('waiting');
+ expect(row.error_text).toBeNull();
+ });
+
+ test('a throwing queue resolves without throwing (recovery failure never kills the worker)', async () => {
+ class ThrowingQueue extends MinionQueue {
+ override async reconcileOrphanedPrivateQueues(): Promise<never> {
+ throw new Error('injected recovery failure');
+ }
+ }
+ await expect(
+ maybeRunWorkerStartupRecovery(new ThrowingQueue(engine), {}),
+ ).resolves.toBeUndefined();
+ });
+
+});
+
+// Structural (separate suite so the behavioral tests above stay classified
+// behavioral; binding name is deliberately non-generic so the classifier's
+// reference heuristic can't leak onto sibling suites).
+describe('work-handler recovery placement (structural)', () => {
+ test('the work handler awaits recovery right after ensureSchema, before the worker spawns', () => {
+ const jobsSource = readFileSync(
+ join(import.meta.dir, '..', 'src', 'commands', 'jobs.ts'),
+ 'utf8',
+ );
+ const callSite = 'await maybeRunWorkerStartupRecovery(queue);';
+ const callIdx = jobsSource.indexOf(callSite);
+ expect(callIdx).toBeGreaterThan(-1);
+ // Exactly one call site — the work handler.
+ expect(jobsSource.indexOf(callSite, callIdx + 1)).toBe(-1);
+ // Anchored immediately after the schema guard…
+ const ensureIdx = jobsSource.lastIndexOf('await queue.ensureSchema();', callIdx);
+ expect(ensureIdx).toBeGreaterThan(-1);
+ expect(callIdx - ensureIdx).toBeLessThan(400);
+ // …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/migrate.test.ts b/test/migrate.test.ts
index d5deb5994b..6b8329986d 100644
--- a/test/migrate.test.ts
+++ b/test/migrate.test.ts
@@ -2332,8 +2332,8 @@ describe('v117 — context_volunteer_events_table', () => {
expect(m!.idempotent).toBe(true);
});
- test('LATEST_VERSION is at or above 117', () => {
- expect(LATEST_VERSION).toBeGreaterThanOrEqual(117);
+ test('LATEST_VERSION is at or above 136', () => {
+ expect(LATEST_VERSION).toBeGreaterThanOrEqual(136);
});
test('table exists after initSchema with the documented columns', async () => {
diff --git a/test/migrations-v136.test.ts b/test/migrations-v136.test.ts
new file mode 100644
index 0000000000..fe09519495
--- /dev/null
+++ b/test/migrations-v136.test.ts
@@ -0,0 +1,147 @@
+/**
+ * Migration v136 (minion_private_queue_owner_metadata) — #4332.
+ *
+ * Durable ownership/liveness metadata for parent-owned dream-inline private
+ * queues. Startup recovery uses the owner/token/lease columns to cancel only
+ * orphaned private queues (terminal/missing owner or expired lease), never
+ * live queues and never legacy unowned rows. The two partial indexes scope
+ * the recovery scan to `dream-inline-%` queues in live statuses and the
+ * owner lookup to non-NULL owners.
+ *
+ * Pinned contracts:
+ * 1. v136 exists in MIGRATIONS with the canonical name, idempotent flag, and
+ * one engine-agnostic sql block (no sqlFor split) carrying all three
+ * ADD COLUMN IF NOT EXISTS statements and both CREATE INDEX IF NOT EXISTS
+ * statements with the dream-inline partial predicate.
+ * 2. Fresh init: the schema declares all three columns and both partial
+ * indexes natively.
+ * 3. Upgrade: on a brain stripped to the pre-v136 shape (positive control:
+ * columns and indexes verifiably absent), a ledger rewind to 135 →
+ * runMigrations re-adds every piece, the partial predicates survive the
+ * round-trip, re-run applies nothing, and re-executing the v136 SQL
+ * directly is a no-op (IF NOT EXISTS everywhere).
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MIGRATIONS, LATEST_VERSION, runMigrations } from '../src/core/migrate.ts';
+
+let engine: PGLiteEngine;
+
+const V136_SQL = MIGRATIONS.find(m => m.version === 136)?.sql ?? '';
+
+const PQ_COLUMNS = [
+ 'private_queue_lease_until',
+ 'private_queue_owner_job_id',
+ 'private_queue_owner_token',
+];
+const PQ_INDEXES = [
+ 'idx_minion_jobs_private_queue_owner',
+ 'idx_minion_jobs_private_queue_recovery',
+];
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' }); // in-memory
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+/** The private-queue columns currently present on minion_jobs, sorted. */
+async function presentColumns(): Promise<string[]> {
+ const rows = await engine.executeRaw<{ column_name: string }>(
+ `SELECT column_name FROM information_schema.columns
+ WHERE table_name = 'minion_jobs'
+ AND column_name IN ('private_queue_owner_job_id','private_queue_owner_token','private_queue_lease_until')
+ ORDER BY column_name`,
+ );
+ return rows.map(r => r.column_name);
+}
+
+/** The private-queue indexes currently present on minion_jobs, sorted by name. */
+async function presentIndexes(): Promise<Array<{ indexname: string; indexdef: string }>> {
+ return engine.executeRaw<{ indexname: string; indexdef: string }>(
+ `SELECT indexname, indexdef FROM pg_indexes
+ WHERE tablename = 'minion_jobs'
+ AND indexname IN ('idx_minion_jobs_private_queue_recovery','idx_minion_jobs_private_queue_owner')
+ ORDER BY indexname`,
+ );
+}
+
+describe('migration v136 — structure', () => {
+ test('exists with canonical name, idempotent flag, engine-agnostic sql', () => {
+ const v136 = MIGRATIONS.find(m => m.version === 136);
+ expect(v136).toBeDefined();
+ expect(v136?.name).toBe('minion_private_queue_owner_metadata');
+ expect(v136?.idempotent).toBe(true);
+ expect(v136?.sqlFor).toBeUndefined();
+ for (const col of PQ_COLUMNS) {
+ expect(V136_SQL).toContain(`ADD COLUMN IF NOT EXISTS ${col}`);
+ }
+ for (const idx of PQ_INDEXES) {
+ expect(V136_SQL).toContain(`CREATE INDEX IF NOT EXISTS ${idx}`);
+ }
+ // The recovery index must be partial on dream-inline queues; the owner
+ // FK must detach (not cascade) when the owner row disappears.
+ expect(V136_SQL).toContain(`WHERE queue LIKE 'dream-inline-%'`);
+ expect(V136_SQL).toContain('REFERENCES minion_jobs(id) ON DELETE SET NULL');
+ expect(LATEST_VERSION).toBeGreaterThanOrEqual(136);
+ });
+});
+
+describe('migration v136 — fresh init (PGLite)', () => {
+ test('fresh schema has all three private-queue columns and both partial indexes', async () => {
+ expect(await presentColumns()).toEqual(PQ_COLUMNS);
+ const idx = await presentIndexes();
+ expect(idx.map(i => i.indexname)).toEqual(PQ_INDEXES);
+ });
+});
+
+describe('migration v136 — upgrade from a pre-v136 brain (PGLite)', () => {
+ test('re-adds columns + dream-inline partial indexes; re-run applies nothing', async () => {
+ // Simulate a pre-v136 brain: strip everything the migration adds.
+ // Indexes first — dropping a column silently drops indexes that
+ // reference it, which would mask a broken index-side assertion.
+ await engine.executeRaw('DROP INDEX IF EXISTS idx_minion_jobs_private_queue_recovery');
+ await engine.executeRaw('DROP INDEX IF EXISTS idx_minion_jobs_private_queue_owner');
+ await engine.executeRaw('ALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_owner_job_id');
+ await engine.executeRaw('ALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_owner_token');
+ await engine.executeRaw('ALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_lease_until');
+
+ // Positive control: the pre-v136 shape is verifiably column- and index-free.
+ expect(await presentColumns()).toEqual([]);
+ expect(await presentIndexes()).toEqual([]);
+
+ // Apply v136 via the real migration runner (ledger rewind below 136).
+ await engine.setConfig('version', '135');
+ const res = await runMigrations(engine);
+ expect(res.applied).toBeGreaterThanOrEqual(1);
+ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));
+
+ expect(await presentColumns()).toEqual(PQ_COLUMNS);
+ const idx = await presentIndexes();
+ expect(idx.map(i => i.indexname)).toEqual(PQ_INDEXES);
+
+ // The partial predicates survived the round-trip (pg renders LIKE as ~~
+ // in indexdef, so pin the literal + WHERE rather than the keyword).
+ const recovery = idx.find(i => i.indexname === 'idx_minion_jobs_private_queue_recovery');
+ expect(recovery?.indexdef).toContain('WHERE');
+ expect(recovery?.indexdef).toContain('dream-inline-');
+ const owner = idx.find(i => i.indexname === 'idx_minion_jobs_private_queue_owner');
+ expect(owner?.indexdef).toContain('private_queue_owner_job_id IS NOT NULL');
+
+ // Ledger idempotency: re-run applies nothing.
+ const rerun = await runMigrations(engine);
+ expect(rerun.applied).toBe(0);
+
+ // SQL-level idempotency: re-executing the multi-statement v136 block on
+ // an up-to-date brain is a no-op (IF NOT EXISTS everywhere), not an
+ // error. runMigration is the production execution path for the block.
+ await engine.runMigration(136, V136_SQL);
+ expect(await presentColumns()).toEqual(PQ_COLUMNS);
+ expect((await presentIndexes()).map(i => i.indexname)).toEqual(PQ_INDEXES);
+ });
+});
diff --git a/test/private-queue-schema-parity.test.ts b/test/private-queue-schema-parity.test.ts
new file mode 100644
index 0000000000..13964204d3
--- /dev/null
+++ b/test/private-queue-schema-parity.test.ts
@@ -0,0 +1,78 @@
+/**
+ * 3-way private-queue schema-surface parity (v0.46.25, #4332).
+ *
+ * Three schema blobs must carry the dream-inline private-queue lifecycle
+ * surface in lockstep:
+ * - src/schema.sql (authoring source; build:schema input)
+ * - src/core/schema-embedded.ts (generated Postgres blob)
+ * - src/core/pglite-schema.ts (PGLite blob)
+ *
+ * A blob missing the columns re-introduces the v121 wedge class (its own
+ * CREATE INDEX references a column its CREATE TABLE no longer declares on a
+ * fresh install); a blob missing an index silently loses the partial-index
+ * scoping that keeps startup private-queue recovery off the general job
+ * table. Assertions are text-level with whitespace normalization so
+ * formatting-only divergence between the blobs can't false-fail.
+ *
+ * Scope is deliberately narrow: ONLY the private-queue surface. Full blob
+ * parity is a known TODO — do not grow this file into it.
+ *
+ * Parallel-lane file: no DB boot, no env mutation, no mock.module.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { readFileSync } from 'fs';
+import { resolve as resolvePath } from 'path';
+
+const BLOBS = [
+ 'src/schema.sql',
+ 'src/core/schema-embedded.ts',
+ 'src/core/pglite-schema.ts',
+] as const;
+
+/**
+ * Collapse whitespace runs and strip spaces around parens/commas. Applied to
+ * BOTH haystack and needle, so any formatting-only difference (indentation,
+ * line wrapping, `(queue, x)` vs `(queue,x)`) compares equal.
+ */
+function normalizeSql(s: string): string {
+ return s.replace(/\s+/g, ' ').replace(/\s*([(),])\s*/g, '$1');
+}
+
+// The three column definitions from migration v136 / the minion_jobs
+// CREATE TABLE body. The FK must SET NULL (detach, never cascade-delete a
+// child job) when the owner row disappears.
+const COLUMN_DEFS = [
+ 'private_queue_owner_job_id INTEGER REFERENCES minion_jobs(id) ON DELETE SET NULL',
+ 'private_queue_owner_token TEXT',
+ 'private_queue_lease_until TIMESTAMPTZ',
+];
+
+// Both partial indexes, INCLUDING their predicates: the recovery index is
+// only useful scoped to dream-inline queues in live statuses, and the owner
+// index only over non-NULL owners.
+const INDEX_DEFS = [
+ `CREATE INDEX IF NOT EXISTS idx_minion_jobs_private_queue_recovery
+ ON minion_jobs (queue, private_queue_lease_until)
+ WHERE queue LIKE 'dream-inline-%'
+ AND status IN ('waiting','active','delayed','waiting-children','paused')`,
+ `CREATE INDEX IF NOT EXISTS idx_minion_jobs_private_queue_owner
+ ON minion_jobs (private_queue_owner_job_id)
+ WHERE private_queue_owner_job_id IS NOT NULL`,
+];
+
+describe('private-queue schema surface parity (3-way)', () => {
+ for (const blob of BLOBS) {
+ test(`${blob} declares the three private-queue columns and both dream-inline partial indexes`, () => {
+ const normalized = normalizeSql(
+ readFileSync(resolvePath(process.cwd(), blob), 'utf-8'),
+ );
+ for (const def of COLUMN_DEFS) {
+ expect(normalized).toContain(normalizeSql(def));
+ }
+ for (const def of INDEX_DEFS) {
+ expect(normalized).toContain(normalizeSql(def));
+ }
+ });
+ }
+});
diff --git a/test/queue-child-done.test.ts b/test/queue-child-done.test.ts
index 624af7cd3b..51dec7e2df 100644
--- a/test/queue-child-done.test.ts
+++ b/test/queue-child-done.test.ts
@@ -14,7 +14,7 @@
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { MinionQueue } from '../src/core/minions/queue.ts';
+import { MinionQueue, DEFAULT_PRIVATE_QUEUE_LEASE_MS } from '../src/core/minions/queue.ts';
import type { ChildDoneMessage } from '../src/core/minions/types.ts';
let engine: PGLiteEngine;
@@ -230,6 +230,222 @@ describe('v0.15 parent-resolution terminal set', () => {
});
});
+describe('private queue terminal reconciliation', () => {
+ test('cancels every non-terminal job in the owned queue and preserves unrelated work', async () => {
+ const privateQueue = `dream-inline-${Date.now()}-deadbeef`;
+ const waiting = await queue.add('private-waiting', {}, { queue: privateQueue });
+ const active = await queue.add('private-active', {}, { queue: privateQueue });
+ const unrelated = await queue.add('unrelated', {}, { queue: 'default' });
+ const claimed = await queue.claim(nextToken(), 30_000, privateQueue, ['private-active']);
+ expect(claimed?.id).toBe(active.id);
+
+ const reconciled = await queue.reconcilePrivateQueue(privateQueue, 'owner terminalized');
+
+ expect(reconciled.map(j => j.id).sort((a, b) => a - b)).toEqual([waiting.id, active.id].sort((a, b) => a - b));
+ expect((await queue.getJob(waiting.id))?.status).toBe('cancelled');
+ expect((await queue.getJob(active.id))?.status).toBe('cancelled');
+ expect((await queue.getJob(waiting.id))?.error_text).toBe('private_queue_reconciled: owner terminalized');
+ expect((await queue.getJob(unrelated.id))?.status).toBe('waiting');
+
+ // Idempotent: a second finally/recovery pass finds nothing to do.
+ expect(await queue.reconcilePrivateQueue(privateQueue, 'second pass')).toEqual([]);
+ });
+
+ test('refuses to reconcile a shared queue', async () => {
+ await expect(queue.reconcilePrivateQueue('default', 'bad target')).rejects.toThrow('refusing to reconcile non-private queue');
+ });
+
+ test('startup recovery cancels an ownerless private queue only after its lease expires', async () => {
+ const privateQueue = `dream-inline-${Date.now()}-expired1`;
+ const token = 'ownerless-expired';
+ const job = await queue.add('private-waiting', {}, {
+ queue: privateQueue,
+ private_queue_owner_token: token,
+ private_queue_lease_ms: 600_000,
+ });
+ // A crashed run's rows go untouched — age updated_at past the 2-minute
+ // recently-touched guard so the fixture models a real crash, not a queue
+ // something is actively working.
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET private_queue_lease_until = now() - interval '1 second', updated_at = now() - interval '5 minutes' WHERE id = $1`,
+ [job.id],
+ );
+
+ const first = await queue.reconcileOrphanedPrivateQueues({ reason: 'test startup recovery' });
+ expect(first.cancelled_jobs).toBe(1);
+ expect(first.cancelled_queues).toBe(1);
+ expect((await queue.getJob(job.id))?.status).toBe('cancelled');
+ expect((await queue.getJob(job.id))?.error_text).toBe('private_queue_reconciled: test startup recovery');
+
+ const second = await queue.reconcileOrphanedPrivateQueues({ reason: 'second pass' });
+ expect(second.cancelled_jobs).toBe(0);
+ expect(second.cancelled_queues).toBe(0);
+ });
+
+ test('startup recovery never cancels a private queue with a future lease', async () => {
+ const privateQueue = `dream-inline-${Date.now()}-future1`;
+ const job = await queue.add('private-waiting', {}, {
+ queue: privateQueue,
+ private_queue_owner_token: 'ownerless-live',
+ private_queue_lease_ms: 600_000,
+ });
+
+ const result = await queue.reconcileOrphanedPrivateQueues();
+ expect(result.cancelled_jobs).toBe(0);
+ expect(result.skipped_live_queues).toBeGreaterThanOrEqual(1);
+ expect((await queue.getJob(job.id))?.status).toBe('waiting');
+ });
+
+ test('startup recovery never cancels a private queue whose owner job is live', async () => {
+ const owner = await queue.add('autopilot-cycle', {});
+ const ownerToken = nextToken();
+ const claimedOwner = await queue.claim(ownerToken, 30_000, 'default', ['autopilot-cycle']);
+ expect(claimedOwner?.id).toBe(owner.id);
+ const privateQueue = `dream-inline-${Date.now()}-liveown`;
+ const child = await queue.add('private-waiting', {}, {
+ queue: privateQueue,
+ private_queue_owner_job_id: owner.id,
+ private_queue_owner_token: 'live-owner-token',
+ private_queue_lease_ms: 1,
+ });
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET private_queue_lease_until = now() - interval '1 second' WHERE id = $1`,
+ [child.id],
+ );
+
+ const result = await queue.reconcileOrphanedPrivateQueues();
+ expect(result.cancelled_jobs).toBe(0);
+ expect(result.skipped_live_queues).toBeGreaterThanOrEqual(1);
+ expect((await queue.getJob(child.id))?.status).toBe('waiting');
+ });
+
+ test('startup recovery cancels when the owner job is terminal even if the lease has not expired', async () => {
+ const owner = await queue.add('autopilot-cycle', {});
+ await claimAndComplete('autopilot-cycle', { ok: true });
+ const privateQueue = `dream-inline-${Date.now()}-termown`;
+ const child = await queue.add('private-waiting', {}, {
+ queue: privateQueue,
+ private_queue_owner_job_id: owner.id,
+ private_queue_owner_token: 'terminal-owner-token',
+ private_queue_lease_ms: 600_000,
+ });
+
+ // Age past the recently-touched guard (see the expired-lease fixture note).
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET updated_at = now() - interval '5 minutes' WHERE id = $1`,
+ [child.id],
+ );
+
+ const result = await queue.reconcileOrphanedPrivateQueues({ reason: 'owner terminal' });
+ expect(result.cancelled_jobs).toBe(1);
+ expect((await queue.getJob(child.id))?.status).toBe('cancelled');
+ expect((await queue.getJob(child.id))?.error_text).toBe('private_queue_reconciled: owner terminal');
+ });
+
+ test('startup recovery preserves legacy unowned private queues for manual Doctor/retriage handling', async () => {
+ const privateQueue = `dream-inline-${Date.now()}-legacy1`;
+ const job = await queue.add('legacy-private-waiting', {}, { queue: privateQueue });
+
+ const result = await queue.reconcileOrphanedPrivateQueues();
+ expect(result.cancelled_jobs).toBe(0);
+ // The scan's HAVING excludes metadata-less queues at the SQL level (they
+ // are never recoverable by this lane and must not occupy the LIMIT
+ // window), so they no longer even count as scanned/skipped.
+ expect(result.skipped_unowned_queues).toBe(0);
+ expect((await queue.getJob(job.id))?.status).toBe('waiting');
+ });
+
+ test('startup recovery uses normal cancellation semantics for descendants and aggregators', async () => {
+ const owner = await queue.add('autopilot-cycle', {});
+ await claimAndComplete('autopilot-cycle', { ok: true });
+ const aggregator = await queue.add('aggregator', {});
+ const privateQueue = `dream-inline-${Date.now()}-tree001`;
+ const child = await queue.add('private-child', {}, {
+ queue: privateQueue,
+ parent_job_id: aggregator.id,
+ on_child_fail: 'continue',
+ private_queue_owner_job_id: owner.id,
+ private_queue_owner_token: 'tree-token',
+ private_queue_lease_ms: 600_000,
+ });
+ const grandchild = await queue.add('private-grandchild', {}, {
+ queue: privateQueue,
+ parent_job_id: child.id,
+ on_child_fail: 'continue',
+ private_queue_owner_job_id: owner.id,
+ private_queue_owner_token: 'tree-token',
+ private_queue_lease_ms: 600_000,
+ });
+
+ // Age past the recently-touched guard (see the expired-lease fixture note).
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET updated_at = now() - interval '5 minutes' WHERE id = ANY($1::int[])`,
+ [[child.id, grandchild.id]],
+ );
+
+ const result = await queue.reconcileOrphanedPrivateQueues({ reason: 'owner terminal tree' });
+ expect(result.cancelled_jobs).toBeGreaterThanOrEqual(2);
+ expect((await queue.getJob(child.id))?.status).toBe('cancelled');
+ expect((await queue.getJob(grandchild.id))?.status).toBe('cancelled');
+ expect((await queue.getJob(aggregator.id))?.status).toBe('waiting');
+ const msgs = await readChildDoneInbox(aggregator.id);
+ expect(msgs.some(m => m.child_id === child.id && m.outcome === 'cancelled')).toBe(true);
+ });
+});
+
+describe('recovery freshness guard (fix-wave review)', () => {
+ test('a terminal-owner queue touched in the last 2 minutes is LIVE, never cancelled', async () => {
+ // The laptop-sleep shape: the owner job row went terminal (stall-swept)
+ // but the drain loop survived and still renews/claims — updated_at is
+ // fresh. Recovery must classify live and touch nothing; the queue becomes
+ // orphaned only after 2 minutes of silence.
+ const owner = await queue.add('autopilot-cycle', {});
+ await claimAndComplete('autopilot-cycle', { ok: true });
+ const privateQueue = `dream-inline-${Date.now()}-fresh01`;
+ const child = await queue.add('private-waiting', {}, {
+ queue: privateQueue,
+ private_queue_owner_job_id: owner.id,
+ private_queue_owner_token: 'fresh-token',
+ private_queue_lease_ms: 600_000,
+ });
+ expect(await queue.classifyPrivateQueueForRecovery(privateQueue)).toBe('live');
+ const result = await queue.reconcileOrphanedPrivateQueues({ reason: 'must not fire' });
+ expect(result.cancelled_jobs).toBe(0);
+ expect((await queue.getJob(child.id))?.status).toBe('waiting');
+ });
+
+ test('renewPrivateQueueLease negative paths: wrong token renews nothing; empty token and shared queues throw', async () => {
+ const privateQueue = `dream-inline-${Date.now()}-neg001`;
+ await queue.add('private-waiting', {}, {
+ queue: privateQueue,
+ private_queue_owner_token: 'right-token',
+ private_queue_lease_ms: 600_000,
+ });
+ expect(await queue.renewPrivateQueueLease(privateQueue, 'wrong-token')).toBe(0);
+ await expect(queue.renewPrivateQueueLease(privateQueue, '')).rejects.toThrow('owner token cannot be empty');
+ await expect(queue.renewPrivateQueueLease('default', 'right-token')).rejects.toThrow('refusing to renew non-private queue');
+ });
+
+ test('owner nonterminal without a lease classifies not_orphan and is skipped', async () => {
+ const owner = await queue.add('autopilot-cycle', {}); // stays waiting (non-terminal)
+ const privateQueue = `dream-inline-${Date.now()}-pend01`;
+ const child = await queue.add('private-waiting', {}, {
+ queue: privateQueue,
+ private_queue_owner_job_id: owner.id,
+ private_queue_owner_token: 'pending-token',
+ });
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET updated_at = now() - interval '5 minutes' WHERE id = $1`,
+ [child.id],
+ );
+ expect(await queue.classifyPrivateQueueForRecovery(privateQueue)).toBe('not_orphan');
+ const result = await queue.reconcileOrphanedPrivateQueues();
+ expect(result.cancelled_jobs).toBe(0);
+ expect(result.skipped_non_orphan_queues).toBeGreaterThanOrEqual(1);
+ expect((await queue.getJob(child.id))?.status).toBe('waiting');
+ });
+});
+
describe('v0.16 MinionJobInput.max_stalled', () => {
test('default max_stalled picks up schema DEFAULT when omitted (regression)', async () => {
// v0.14.3 bumped the schema column DEFAULT from 1 → 5 (max_stalled becomes
@@ -259,3 +475,390 @@ describe('v0.16 MinionJobInput.max_stalled', () => {
expect(second.max_stalled).toBe(3);
});
});
+
+describe('private queue lease + wedge-signal hardening (fix wave)', () => {
+ test('lease renewal is MONOTONIC: a default-horizon renewal never shrinks a longer creation-time lease', async () => {
+ const q = 'dream-inline-monotonic';
+ const job = await queue.add('subagent', {}, {
+ queue: q,
+ private_queue_owner_token: 'tok-mono',
+ // Creation-time horizon: 2 hours (a long phase's wait timeout).
+ private_queue_lease_ms: 2 * 60 * 60 * 1000,
+ }, { allowProtectedSubmit: true });
+ const before = await engine.executeRaw<{ lease: string }>(
+ `SELECT private_queue_lease_until::text AS lease FROM minion_jobs WHERE id = $1`, [job.id],
+ );
+ // Renew with the (shorter) 10-min default — GREATEST must keep the 2h horizon.
+ const renewed = await queue.renewPrivateQueueLease(q, 'tok-mono');
+ expect(renewed).toBe(1);
+ const after = await engine.executeRaw<{ lease: string }>(
+ `SELECT private_queue_lease_until::text AS lease FROM minion_jobs WHERE id = $1`, [job.id],
+ );
+ expect(new Date(after[0].lease).getTime()).toBeGreaterThanOrEqual(new Date(before[0].lease).getTime());
+ // And a LONGER explicit horizon still extends.
+ await queue.renewPrivateQueueLease(q, 'tok-mono', 4 * 60 * 60 * 1000);
+ const extended = await engine.executeRaw<{ lease: string }>(
+ `SELECT private_queue_lease_until::text AS lease FROM minion_jobs WHERE id = $1`, [job.id],
+ );
+ expect(new Date(extended[0].lease).getTime()).toBeGreaterThan(new Date(after[0].lease).getTime());
+ });
+
+ test('reconcile reason family: every cancellation is stamped with the machine-readable prefix', async () => {
+ const q = 'dream-inline-reason-family';
+ const job = await queue.add('subagent', {}, { queue: q }, { allowProtectedSubmit: true });
+ const cancelled = await queue.reconcilePrivateQueue(q, 'anything a call site writes');
+ expect(cancelled).toHaveLength(1);
+ const row = await queue.getJob(job.id);
+ expect(row?.error_text?.startsWith('private_queue_reconciled: ')).toBe(true);
+ });
+
+ test('deriveWedgeSignal never calls a dream-inline queue wedged — it reports private_queue instead', async () => {
+ const { deriveWedgeSignal } = await import('../src/core/minions/queue.ts');
+ const shape = { active_healthy: 0, waiting: 5, minutes_since_completion: 120 };
+ const shared = deriveWedgeSignal({ ...shape, queue: 'default' });
+ expect(shared.wedged).toBe(true);
+ expect(shared.private_queue).toBe(false);
+ // The incident bug class: a private queue must NEVER produce the
+ // "restart the worker" wedge signal — no worker can claim it.
+ const priv = deriveWedgeSignal({ ...shape, queue: 'dream-inline-123-abc' });
+ expect(priv.wedged).toBe(false);
+ expect(priv.private_queue).toBe(true);
+ });
+});
+
+describe('makeThrottledLeaseRenewer (shared phase keepalive)', () => {
+ async function readLease(id: number): Promise<number | null> {
+ const rows = await engine.executeRaw<{ lease: string | null }>(
+ `SELECT private_queue_lease_until::text AS lease FROM minion_jobs WHERE id = $1`, [id],
+ );
+ return rows[0].lease === null ? null : new Date(rows[0].lease).getTime();
+ }
+
+ test('first call renews then yields; second call inside the throttle is a no-op for BOTH', async () => {
+ const q = 'dream-inline-renewer-throttle';
+ const job = await queue.add('subagent', {}, {
+ queue: q, private_queue_owner_token: 'tok-renewer', private_queue_lease_ms: 1000,
+ }, { allowProtectedSubmit: true });
+ const order: string[] = [];
+ let leaseWhenYielded: number | null = null;
+ const renew = queue.makeThrottledLeaseRenewer(q, 'tok-renewer', async () => {
+ order.push('yield');
+ leaseWhenYielded = await readLease(job.id);
+ });
+ const before = await readLease(job.id);
+ await renew();
+ const after = await readLease(job.id);
+ expect(after!).toBeGreaterThan(before!);
+ // Order is fixed: the lease was already extended when onRenewed ran.
+ expect(order).toEqual(['yield']);
+ expect(leaseWhenYielded!).toBe(after!);
+ // Inside the 30s throttle window: neither the renew nor the yield fires.
+ await renew();
+ expect(order).toEqual(['yield']);
+ expect(await readLease(job.id)).toBe(after);
+ });
+
+ test('throttleMs elapses → renews again; onRenewed is optional', async () => {
+ const q = 'dream-inline-renewer-elapse';
+ const job = await queue.add('subagent', {}, {
+ queue: q, private_queue_owner_token: 'tok-elapse', private_queue_lease_ms: 1000,
+ }, { allowProtectedSubmit: true });
+ const renew = queue.makeThrottledLeaseRenewer(q, 'tok-elapse', undefined, 0);
+ await renew();
+ const first = await readLease(job.id);
+ await new Promise(r => setTimeout(r, 5));
+ await renew();
+ expect((await readLease(job.id))!).toBeGreaterThanOrEqual(first!);
+ });
+
+ test('a throwing renewal propagates to the caller (shared queue refused)', async () => {
+ const renew = queue.makeThrottledLeaseRenewer('default', 'tok-shared');
+ await expect(renew()).rejects.toThrow('refusing to renew non-private queue');
+ });
+});
+
+describe('private queue recovery classification + lease hardening (lane A backfill)', () => {
+ async function readLeaseMs(id: number): Promise<number | null> {
+ const rows = await engine.executeRaw<{ lease: string | null }>(
+ `SELECT private_queue_lease_until::text AS lease FROM minion_jobs WHERE id = $1`, [id],
+ );
+ return rows[0].lease === null ? null : new Date(rows[0].lease).getTime();
+ }
+
+ // Age past the 2-minute recently-touched guard so the freshness fast path
+ // cannot mask the arm under test (see the expired-lease fixture note above).
+ async function ageUpdatedAt(ids: number[]): Promise<void> {
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET updated_at = now() - interval '5 minutes' WHERE id = ANY($1::int[])`,
+ [ids],
+ );
+ }
+
+ test('K10: lease-only queue with a FUTURE lease classifies live even when updated_at is stale', async () => {
+ // The long-quiet-subagent safety arm: no owner metadata, nothing touched
+ // the rows in >2min (freshness guard does NOT short-circuit), but the
+ // creation-time lease is still hours out — recovery must skip it.
+ const q = `dream-inline-${Date.now()}-k10lease`;
+ const job = await queue.add('private-waiting', {}, {
+ queue: q,
+ private_queue_lease_ms: 2 * 60 * 60 * 1000,
+ });
+ await ageUpdatedAt([job.id]);
+
+ expect(await queue.classifyPrivateQueueForRecovery(q)).toBe('live');
+ const result = await queue.reconcileOrphanedPrivateQueues({ reason: 'must not fire' });
+ expect(result.cancelled_jobs).toBe(0);
+ expect(result.skipped_live_queues).toBe(1);
+ expect((await queue.getJob(job.id))?.status).toBe('waiting');
+ });
+
+ test('K2: an actively claimed child with a healthy lock classifies live despite stale updated_at and expired lease', async () => {
+ const q = `dream-inline-${Date.now()}-k2active`;
+ const job = await queue.add('private-active', {}, {
+ queue: q,
+ private_queue_owner_token: 'k2-token',
+ private_queue_lease_ms: 600_000,
+ });
+ const claimed = await queue.claim(nextToken(), 30_000, q, ['private-active']);
+ expect(claimed?.id).toBe(job.id);
+ // Expire the lease and age updated_at — the healthy lock alone keeps it live.
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET private_queue_lease_until = now() - interval '1 second', updated_at = now() - interval '5 minutes' WHERE id = $1`,
+ [job.id],
+ );
+
+ expect(await queue.classifyPrivateQueueForRecovery(q)).toBe('live');
+ const result = await queue.reconcileOrphanedPrivateQueues();
+ expect(result.cancelled_jobs).toBe(0);
+ expect(result.skipped_live_queues).toBe(1);
+ expect((await queue.getJob(job.id))?.status).toBe('active');
+ });
+
+ test('L6: renewPrivateQueueLease returns 0 when every job in the queue is terminal', async () => {
+ const q = `dream-inline-${Date.now()}-l6term`;
+ const job = await queue.add('private-active', {}, {
+ queue: q,
+ private_queue_owner_token: 'l6-token',
+ private_queue_lease_ms: 600_000,
+ });
+ const token = nextToken();
+ const claimed = await queue.claim(token, 30_000, q, ['private-active']);
+ expect(claimed?.id).toBe(job.id);
+ await queue.completeJob(job.id, token, { ok: true });
+
+ expect(await queue.renewPrivateQueueLease(q, 'l6-token')).toBe(0);
+ });
+
+ test('L4: renew COALESCEs a NULL lease — returns 1 and stamps ~now + default horizon', async () => {
+ const q = `dream-inline-${Date.now()}-l4null`;
+ const job = await queue.add('private-waiting', {}, {
+ queue: q,
+ private_queue_owner_token: 'l4-token',
+ // NO private_queue_lease_ms: the row starts with a NULL lease.
+ });
+ expect(await readLeaseMs(job.id)).toBeNull();
+
+ const before = Date.now();
+ expect(await queue.renewPrivateQueueLease(q, 'l4-token')).toBe(1);
+ const lease = await readLeaseMs(job.id);
+ expect(lease).not.toBeNull();
+ expect(lease!).toBeGreaterThanOrEqual(before + DEFAULT_PRIVATE_QUEUE_LEASE_MS - 60_000);
+ expect(lease!).toBeLessThanOrEqual(Date.now() + DEFAULT_PRIVATE_QUEUE_LEASE_MS + 60_000);
+ });
+
+ test('add() clamps private_queue_lease_ms 0 and negatives to the 1ms floor without crashing', async () => {
+ const qZero = `dream-inline-${Date.now()}-clamp0`;
+ const zero = await queue.add('private-waiting', {}, { queue: qZero, private_queue_lease_ms: 0 });
+ const zeroLease = await readLeaseMs(zero.id);
+ expect(zeroLease).not.toBeNull();
+ expect(Math.abs(zeroLease! - Date.now())).toBeLessThan(10_000);
+
+ const qNeg = `dream-inline-${Date.now()}-clampneg`;
+ const neg = await queue.add('private-waiting', {}, { queue: qNeg, private_queue_lease_ms: -3_600_000 });
+ const negLease = await readLeaseMs(neg.id);
+ expect(negLease).not.toBeNull();
+ // Floored at 1ms after submit — NOT an hour in the past.
+ expect(negLease!).toBeGreaterThan(Date.now() - 10_000);
+ });
+
+ test('renewPrivateQueueLease with leaseMs 0 clamps to 1ms and GREATEST never shrinks the horizon', async () => {
+ const q = `dream-inline-${Date.now()}-renew0`;
+ const job = await queue.add('private-waiting', {}, {
+ queue: q,
+ private_queue_owner_token: 'renew0-token',
+ private_queue_lease_ms: 600_000,
+ });
+ const before = await readLeaseMs(job.id);
+ expect(await queue.renewPrivateQueueLease(q, 'renew0-token', 0)).toBe(1);
+ const after = await readLeaseMs(job.id);
+ expect(after).not.toBeNull();
+ expect(after!).toBeGreaterThanOrEqual(before!);
+ });
+
+ test('reconcilePrivateQueue does not double-stamp an already-prefixed reason', async () => {
+ const q = `dream-inline-${Date.now()}-prefix1`;
+ const job = await queue.add('private-waiting', {}, { queue: q });
+ const cancelled = await queue.reconcilePrivateQueue(q, 'private_queue_reconciled: caller stamped');
+ expect(cancelled).toHaveLength(1);
+ const row = await queue.getJob(job.id);
+ expect(row?.error_text).toBe('private_queue_reconciled: caller stamped');
+ expect(row!.error_text!.split('private_queue_reconciled').length - 1).toBe(1);
+ });
+
+ test('reconcileOrphanedPrivateQueues default reason is the exact startup-recovery literal', async () => {
+ const owner = await queue.add('autopilot-cycle', {});
+ await claimAndComplete('autopilot-cycle', { ok: true });
+ const q = `dream-inline-${Date.now()}-defreason`;
+ const job = await queue.add('private-waiting', {}, {
+ queue: q,
+ private_queue_owner_job_id: owner.id,
+ private_queue_owner_token: 'defreason-token',
+ private_queue_lease_ms: 600_000,
+ });
+ await ageUpdatedAt([job.id]);
+
+ const result = await queue.reconcileOrphanedPrivateQueues(); // NO reason opt
+ expect(result.cancelled_jobs).toBe(1);
+ expect((await queue.getJob(job.id))?.error_text).toBe(
+ 'private_queue_reconciled: startup recovery: orphaned dream-inline private queue',
+ );
+ });
+
+ test('O8: a verdict flipping to live on the pre-cancel recheck cancels nothing and bumps skipped_non_orphan_queues', async () => {
+ // Simulated TOCTOU race: a claim/renewal lands between the first classify
+ // and the cancel. The recheck must catch it — and its non-orphan verdict
+ // routes to skipped_non_orphan_queues, NOT skipped_live_queues.
+ let calls = 0;
+ class FlipVerdictQueue extends MinionQueue {
+ override async classifyPrivateQueueForRecovery(): Promise<'orphan' | 'live' | 'unowned' | 'not_orphan'> {
+ calls++;
+ return calls === 1 ? 'orphan' : 'live';
+ }
+ }
+ const flip = new FlipVerdictQueue(engine);
+ const q = `dream-inline-${Date.now()}-toctou1`;
+ const job = await queue.add('private-waiting', {}, {
+ queue: q,
+ private_queue_owner_token: 'toctou-token',
+ private_queue_lease_ms: 600_000,
+ });
+
+ const result = await flip.reconcileOrphanedPrivateQueues();
+ expect(calls).toBe(2);
+ expect(result.cancelled_queues).toBe(0);
+ expect(result.cancelled_jobs).toBe(0);
+ expect(result.skipped_non_orphan_queues).toBe(1);
+ expect(result.skipped_live_queues).toBe(0);
+ expect((await queue.getJob(job.id))?.status).toBe('waiting');
+ });
+
+ test('O1/O3: maxQueues bounds the scan ordered by min(created_at) — only the OLDER orphan is processed', async () => {
+ const older = `dream-inline-${Date.now()}-older01`;
+ const newer = `dream-inline-${Date.now()}-newer01`;
+ const olderJob = await queue.add('private-waiting', {}, {
+ queue: older, private_queue_owner_token: 'older-token', private_queue_lease_ms: 600_000,
+ });
+ const newerJob = await queue.add('private-waiting', {}, {
+ queue: newer, private_queue_owner_token: 'newer-token', private_queue_lease_ms: 600_000,
+ });
+ // Both orphan-shaped (expired lease + stale updated_at), distinct created_at.
+ await engine.executeRaw(
+ `UPDATE minion_jobs
+ SET private_queue_lease_until = now() - interval '1 second',
+ updated_at = now() - interval '5 minutes'
+ WHERE id = ANY($1::int[])`,
+ [[olderJob.id, newerJob.id]],
+ );
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET created_at = now() - interval '10 minutes' WHERE id = $1`,
+ [olderJob.id],
+ );
+
+ const result = await queue.reconcileOrphanedPrivateQueues({ maxQueues: 1 });
+ expect(result.scanned_queues).toBe(1);
+ expect(result.cancelled_queues).toBe(1);
+ expect(result.cancelled_jobs).toBe(1);
+ expect((await queue.getJob(olderJob.id))?.status).toBe('cancelled');
+ expect((await queue.getJob(newerJob.id))?.status).toBe('waiting');
+ });
+
+ test('O4: scanned_queues counts only metadata-bearing non-terminal queues on a mixed fixture', async () => {
+ const liveQ = `dream-inline-${Date.now()}-mixlive`;
+ const orphanQ = `dream-inline-${Date.now()}-mixorph`;
+ const legacyQ = `dream-inline-${Date.now()}-mixleg`;
+ const liveJob = await queue.add('private-waiting', {}, {
+ queue: liveQ, private_queue_lease_ms: 2 * 60 * 60 * 1000,
+ });
+ const orphanJob = await queue.add('private-waiting', {}, {
+ queue: orphanQ, private_queue_owner_token: 'mix-token', private_queue_lease_ms: 1,
+ });
+ const legacyJob = await queue.add('legacy-private-waiting', {}, { queue: legacyQ });
+ await ageUpdatedAt([liveJob.id, orphanJob.id, legacyJob.id]);
+
+ const result = await queue.reconcileOrphanedPrivateQueues();
+ expect(result.scanned_queues).toBe(2); // legacy metadata-less queue never scanned
+ expect(result.skipped_live_queues).toBe(1);
+ expect(result.cancelled_queues).toBe(1);
+ expect(result.cancelled_jobs).toBe(1);
+ expect(result.skipped_unowned_queues).toBe(0);
+ expect((await queue.getJob(liveJob.id))?.status).toBe('waiting');
+ expect((await queue.getJob(orphanJob.id))?.status).toBe('cancelled');
+ expect((await queue.getJob(legacyJob.id))?.status).toBe('waiting');
+ });
+
+ test('O11: an orphan verdict over an all-terminal queue cancels nothing — cancelled_queues stays 0', async () => {
+ // Race shape: every child terminalizes between the scan and the cancel.
+ // Both classify calls say orphan, but reconcilePrivateQueue finds nothing
+ // to cancel, so the cancelled_* counters must not budge.
+ const q = `dream-inline-${Date.now()}-allterm`;
+ const job = await queue.add('private-waiting', {}, {
+ queue: q, private_queue_owner_token: 'allterm-token', private_queue_lease_ms: 600_000,
+ });
+ let victimCancelled = false;
+ class TerminalizeOnClassifyQueue extends MinionQueue {
+ override async classifyPrivateQueueForRecovery(): Promise<'orphan' | 'live' | 'unowned' | 'not_orphan'> {
+ if (!victimCancelled) {
+ victimCancelled = true;
+ await this.cancelJob(job.id);
+ }
+ return 'orphan';
+ }
+ }
+ const raced = new TerminalizeOnClassifyQueue(engine);
+
+ const result = await raced.reconcileOrphanedPrivateQueues();
+ expect(result.scanned_queues).toBe(1);
+ expect(result.cancelled_queues).toBe(0);
+ expect(result.cancelled_jobs).toBe(0);
+ expect((await queue.getJob(job.id))?.status).toBe('cancelled'); // by the simulated race, not recovery
+ });
+
+ test('rowToMinionJob maps private-queue metadata: owner id number, token string, lease Date; missing token → null', async () => {
+ const owner = await queue.add('owner-job', {});
+ const q = `dream-inline-${Date.now()}-rowmap1`;
+ const withToken = await queue.add('private-waiting', {}, {
+ queue: q,
+ private_queue_owner_job_id: owner.id,
+ private_queue_owner_token: 'rowmap-token',
+ private_queue_lease_ms: 600_000,
+ });
+ const fetched = await queue.getJob(withToken.id);
+ expect(typeof fetched?.private_queue_owner_job_id).toBe('number');
+ expect(fetched?.private_queue_owner_job_id).toBe(owner.id);
+ expect(fetched?.private_queue_owner_token).toBe('rowmap-token');
+ expect(fetched?.private_queue_lease_until).toBeInstanceOf(Date);
+ expect(fetched!.private_queue_lease_until!.getTime()).toBeGreaterThan(Date.now());
+
+ // types.ts maps the token with `|| null`, so an absent (NULL) token — and
+ // by the same operator an empty string — surfaces as null, never ''.
+ const q2 = `dream-inline-${Date.now()}-rowmap2`;
+ const noToken = await queue.add('private-waiting', {}, {
+ queue: q2,
+ private_queue_owner_job_id: owner.id,
+ });
+ const fetched2 = await queue.getJob(noToken.id);
+ expect(fetched2?.private_queue_owner_job_id).toBe(owner.id);
+ expect(fetched2?.private_queue_owner_token).toBeNull();
+ expect(fetched2?.private_queue_lease_until).toBeNull();
+ });
+});
diff --git a/test/remediation-run-extras.serial.test.ts b/test/remediation-run-extras.serial.test.ts
index 33e40ecd2e..d73fdd5c0e 100644
--- a/test/remediation-run-extras.serial.test.ts
+++ b/test/remediation-run-extras.serial.test.ts
@@ -33,6 +33,9 @@ mock.module('../src/core/minions/queue.ts', () => ({
}));
mock.module('../src/core/minions/wait-for-completion.ts', () => ({
waitForCompletion: async () => ({ status: 'completed' }),
+ // Module mocks must export every named import any transitively-loaded
+ // consumer reaches for (patterns/synthesize use the renewing variant).
+ waitForCompletionRenewing: async () => ({ status: 'completed' }),
}));
let engine: PGLiteEngine;
diff --git a/test/remediation-run-loop.serial.test.ts b/test/remediation-run-loop.serial.test.ts
index edbc59d735..5dff5ab1de 100644
--- a/test/remediation-run-loop.serial.test.ts
+++ b/test/remediation-run-loop.serial.test.ts
@@ -27,6 +27,17 @@ mock.module('../src/core/minions/wait-for-completion.ts', () => ({
id: jobId,
status: 'completed',
}),
+ // patterns/synthesize import the lease-renewing variant; a module mock
+ // replaces the WHOLE module, so it must export every named import its
+ // consumers reach for (a missing one is a load-time SyntaxError).
+ waitForCompletionRenewing: async (
+ _queue: unknown,
+ jobId: number,
+ opts?: { renew?: () => Promise<void> },
+ ) => {
+ if (opts?.renew) await opts.renew();
+ return { id: jobId, status: 'completed' };
+ },
}));
mock.module('../src/core/remediation-checkpoint.ts', () => ({
diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.ts
index 7308ac974e..6da78d5df5 100644
--- a/test/schema-bootstrap-coverage.test.ts
+++ b/test/schema-bootstrap-coverage.test.ts
@@ -183,6 +183,15 @@ const REQUIRED_BOOTSTRAP_COVERAGE: ForwardReference[] = [
// wedges the blob replay exactly like the v121 incident.
{ kind: 'column', table: 'minion_jobs', column: 'timeout_at' },
{ kind: 'column', table: 'minion_jobs', column: 'idempotency_key' },
+ // v0.46.26 private-queue lifecycle: blob indexes
+ // idx_minion_jobs_private_queue_recovery / _owner reference the owner and
+ // lease columns; a pre-upgrade minion_jobs wedges blob replay without the
+ // bootstrap ALTERs (same class as v121).
+ { kind: 'column', table: 'minion_jobs', column: 'private_queue_owner_job_id' },
+ { kind: 'column', table: 'minion_jobs', column: 'private_queue_lease_until' },
+ // Token rides the same bootstrap ALTER; registering it guards any FUTURE
+ // blob index on it against the same wedge.
+ { kind: 'column', table: 'minion_jobs', column: 'private_queue_owner_token' },
];
test('applyForwardReferenceBootstrap covers every forward reference declared in REQUIRED_BOOTSTRAP_COVERAGE', async () => {
@@ -284,6 +293,16 @@ test('applyForwardReferenceBootstrap covers every forward reference declared in
DROP INDEX IF EXISTS uniq_minion_jobs_idempotency;
ALTER TABLE minion_jobs DROP COLUMN IF EXISTS timeout_at;
ALTER TABLE minion_jobs DROP COLUMN IF EXISTS idempotency_key;
+
+ -- v136 private-queue strip: owner/token/lease are migration-added and
+ -- blob-indexed; without these drops the three REQUIRED_BOOTSTRAP_COVERAGE
+ -- entries assert on columns initSchema already created (vacuous) and the
+ -- needsMinionJobsPrivateQueue bootstrap branch never executes.
+ DROP INDEX IF EXISTS idx_minion_jobs_private_queue_recovery;
+ DROP INDEX IF EXISTS idx_minion_jobs_private_queue_owner;
+ ALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_owner_job_id;
+ ALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_owner_token;
+ ALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_lease_until;
`);
// Note: we don't strip sources.archived* here because they're inline in the
@@ -378,6 +397,15 @@ test('after bootstrap, PGLITE_SCHEMA_SQL replays without crashing on missing for
ALTER TABLE minion_jobs DROP COLUMN IF EXISTS timeout_at;
ALTER TABLE minion_jobs DROP COLUMN IF EXISTS idempotency_key;
+ -- v136 private-queue strip: the SCHEMA_SQL replay would crash on
+ -- idx_minion_jobs_private_queue_recovery / _owner without the bootstrap
+ -- re-adding these migration-added columns (the v121 wedge class).
+ DROP INDEX IF EXISTS idx_minion_jobs_private_queue_recovery;
+ DROP INDEX IF EXISTS idx_minion_jobs_private_queue_owner;
+ ALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_owner_job_id;
+ ALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_owner_token;
+ ALTER TABLE minion_jobs DROP COLUMN IF EXISTS private_queue_lease_until;
+
-- WP4 (v127) strip: surface columns + the wedge-signal index; replay
-- must succeed from the pre-v127 shape.
DROP INDEX IF EXISTS idx_minion_jobs_queue_status_updated;
@@ -1009,6 +1037,50 @@ test('extractAlterAddColumnsFromSql handles representative migration SQL shapes'
]);
});
+// ─────────────────────────────────────────────────────────────────
+// v0.46.26 private-queue guard symmetry — Postgres half (#4332).
+// The PGLite bootstrap is exercised live above (strip → bootstrap →
+// assert), but PostgresEngine.applyForwardReferenceBootstrap only runs
+// against real Postgres (test/e2e/postgres-bootstrap.test.ts, DATABASE_URL-
+// gated). Before this pin, deleting the entire Postgres private-queue
+// bootstrap block broke zero locally-runnable tests. This source-text
+// assertion is the local half of the guard; the e2e file is the live half.
+// ─────────────────────────────────────────────────────────────────
+
+test('postgres-engine.ts bootstrap carries the private-queue ALTERs and probes (guard symmetry with pglite-engine.ts)', async () => {
+ const { readFileSync } = await import('fs');
+ const { resolve: resolvePath } = await import('path');
+ const enginePath = resolvePath(process.cwd(), 'src/core/postgres-engine.ts');
+ const engineSrc = readFileSync(enginePath, 'utf-8');
+ const normalized = engineSrc.replace(/\s+/g, ' ');
+
+ // The exact three ALTERs the PGLite bootstrap applies — same statements,
+ // same types, same FK semantics — must exist verbatim in the Postgres
+ // bootstrap (modulo whitespace).
+ for (const stmt of [
+ 'ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_owner_job_id INTEGER REFERENCES minion_jobs(id) ON DELETE SET NULL;',
+ 'ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_owner_token TEXT;',
+ 'ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_lease_until TIMESTAMPTZ;',
+ ]) {
+ expect(normalized).toContain(stmt);
+ }
+
+ // The token probe (749a7dcb) is load-bearing: neither blob index references
+ // private_queue_owner_token, so a token-only-missing brain (partial
+ // upgrade) is repairable ONLY through this probe triggering the ALTER
+ // block. The owner/lease probes ride the same information_schema query.
+ expect(normalized).toContain('minion_jobs_pq_token_exists');
+ expect(normalized).toContain('minion_jobs_pq_owner_exists');
+ expect(normalized).toContain('minion_jobs_pq_lease_exists');
+
+ // The structural extractor sees the same three ALTERs (keeps this guard
+ // aligned with the parser-based coverage machinery above).
+ const pgBootstrapAdds = parseAlterAddColumns(engineSrc);
+ for (const column of ['private_queue_owner_job_id', 'private_queue_owner_token', 'private_queue_lease_until']) {
+ expect(pgBootstrapAdds).toContainEqual({ table: 'minion_jobs', column });
+ }
+});
+
test('planted-bug: simulated unprovided column produces a clear failure message', async () => {
// Negative case — regression guard. If the contract test silently passes
// on uncovered columns, the gate is fake. This test plants a fake column
diff --git a/test/supervisor.test.ts b/test/supervisor.test.ts
index f34e819fbb..a01d2c303b 100644
--- a/test/supervisor.test.ts
+++ b/test/supervisor.test.ts
@@ -1,10 +1,13 @@
-import { describe, it, expect, afterEach } from 'bun:test';
+import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
import { existsSync, readFileSync, writeFileSync, unlinkSync, chmodSync, mkdirSync, rmSync } from 'fs';
import { spawn } from 'child_process';
import { join } from 'path';
import { tmpdir } from 'os';
import { readSupervisorEvents, computeSupervisorAuditFilename } from '../src/core/minions/handlers/supervisor-audit.ts';
-import { calculateBackoffMs, resolveHardStopMaxCrashes } from '../src/core/minions/supervisor.ts';
+import { calculateBackoffMs, resolveHardStopMaxCrashes, MinionSupervisor, type SupervisorEmission } from '../src/core/minions/supervisor.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
const TEST_PID_FILE = '/tmp/gbrain-supervisor-test.pid';
@@ -510,6 +513,136 @@ describe('MinionSupervisor', () => {
}, 15_000);
});
+ // 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', () => {
+ let engine: PGLiteEngine;
+ let queue: MinionQueue;
+ let queueSeq = 0;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' }); // in-memory
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+ }, 120_000);
+
+ afterAll(async () => {
+ await engine.disconnect();
+ });
+
+ beforeEach(async () => {
+ // Targeted DELETE preserves the `config.version` key MinionQueue's
+ // ensureSchema requires (full resetPgliteState wipes it).
+ 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}`;
+ const owner = await queue.add('autopilot-cycle', {});
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'completed', finished_at = now() WHERE id = $1`,
+ [owner.id],
+ );
+ const child = await queue.add(
+ 'subagent',
+ { prompt: 'orphan fixture' },
+ {
+ queue: queueName,
+ private_queue_owner_job_id: owner.id,
+ private_queue_owner_token: 'sup-recovery-token',
+ private_queue_lease_ms: 600_000,
+ },
+ { allowProtectedSubmit: true },
+ );
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET updated_at = now() - interval '5 minutes' WHERE id = $1`,
+ [child.id],
+ );
+ return child.id;
+ }
+
+ it("cancels an orphaned queue and emits health_warn reason='private_queue_startup_recovery'", 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);
+ });
+
+ it("resolves and emits health_warn reason='private_queue_startup_recovery_failed' 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');
+ });
+
+ });
+
+ // Structural (separate suite so the behavioral recovery tests above stay
+ // classified behavioral; binding name is deliberately non-generic so the
+ // 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'),
+ 'utf8',
+ );
+ const hookStart = supervisorSource.indexOf('reconcileOrphanedPrivateQueuesBeforeWorkerSpawn');
+ expect(hookStart).toBeGreaterThan(-1);
+ const hookEnd = supervisorSource.indexOf('private async shutdown(');
+ expect(hookEnd).toBeGreaterThan(hookStart);
+ const body = supervisorSource.slice(hookStart, hookEnd);
+ expect(body).toContain('Promise.race');
+ expect(body).toContain('30_000');
+ });
+ });
+
describe('integration: audit file rotation + helper', () => {
it('computeSupervisorAuditFilename returns supervisor-YYYY-Www.jsonl format', () => {
const jan15_2026 = new Date(Date.UTC(2026, 0, 15)); // Thu
diff --git a/test/wait-for-completion.test.ts b/test/wait-for-completion.test.ts
index 0a4838fbdc..689b9b1ecc 100644
--- a/test/wait-for-completion.test.ts
+++ b/test/wait-for-completion.test.ts
@@ -6,7 +6,7 @@
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { MinionQueue } from '../src/core/minions/queue.ts';
-import { waitForCompletion, TimeoutError, __testing } from '../src/core/minions/wait-for-completion.ts';
+import { waitForCompletion, waitForCompletionRenewing, TimeoutError, __testing } from '../src/core/minions/wait-for-completion.ts';
let engine: PGLiteEngine;
let queue: MinionQueue;
@@ -110,3 +110,142 @@ describe('waitForCompletion terminal states', () => {
.rejects.toThrow(/not found/);
});
});
+
+describe('waitForCompletionRenewing', () => {
+ // Claim + complete the named job after `afterMs`. Returned promise is
+ // awaited alongside the wait so a fixture failure surfaces instead of
+ // vanishing in a detached timer callback.
+ function completeLater(name: string, afterMs: number): Promise<void> {
+ const token = `renew-tok-${afterMs}-${Math.random().toString(36).slice(2)}`;
+ return (async () => {
+ await new Promise(r => setTimeout(r, afterMs));
+ const claimed = await queue.claim(token, 30_000, 'default', [name]);
+ if (!claimed) throw new Error(`nothing to claim for ${name}`);
+ await queue.completeJob(claimed.id, token, { done: true });
+ })();
+ }
+
+ test('multi-chunk wait resolves with the terminal job after crossing >=2 chunk boundaries', async () => {
+ const j = await queue.add('t', {});
+ let renews = 0;
+ const t0 = Date.now();
+ const [res] = await Promise.all([
+ waitForCompletionRenewing(queue, j.id, {
+ pollMs: 25,
+ timeoutMs: 30_000,
+ chunkMs: 50, // clamped to the 1s floor — 2.3s completion spans >=2 chunks
+ renew: async () => { renews++; },
+ }),
+ completeLater('t', 2300),
+ ]);
+ expect(res.id).toBe(j.id);
+ expect(res.status).toBe('completed');
+ expect(Date.now() - t0).toBeGreaterThanOrEqual(2000);
+ expect(renews).toBeGreaterThanOrEqual(2);
+ });
+
+ test('renew is invoked between chunks when the wait spans a chunk boundary', async () => {
+ const j = await queue.add('t', {});
+ let renews = 0;
+ const [res] = await Promise.all([
+ waitForCompletionRenewing(queue, j.id, {
+ pollMs: 25,
+ timeoutMs: 30_000,
+ chunkMs: 50,
+ renew: async () => { renews++; },
+ }),
+ completeLater('t', 1300),
+ ]);
+ expect(res.status).toBe('completed');
+ expect(renews).toBeGreaterThanOrEqual(1);
+ });
+
+ test('a throwing renew is swallowed: the wait continues and still resolves', async () => {
+ const j = await queue.add('t', {});
+ let renews = 0;
+ const [res] = await Promise.all([
+ waitForCompletionRenewing(queue, j.id, {
+ pollMs: 25,
+ timeoutMs: 30_000,
+ chunkMs: 50,
+ renew: async () => { renews++; throw new Error('lease renewal exploded'); },
+ }),
+ completeLater('t', 1300),
+ ]);
+ expect(res.status).toBe('completed');
+ expect(renews).toBeGreaterThanOrEqual(1); // it DID throw at least once and was swallowed
+ });
+
+ test('a non-TimeoutError from the inner wait rethrows immediately without renewing', async () => {
+ let renews = 0;
+ const renew = async () => { renews++; };
+
+ // Fast-path arm: the inner first read throws 'not found'.
+ await expect(
+ waitForCompletionRenewing(queue, 99_999, { pollMs: 10, timeoutMs: 30_000, renew })
+ ).rejects.toThrow(/not found/);
+
+ // Poll-loop arm: the row vanishes mid-wait and the inner poll throws.
+ const j = await queue.add('t', {});
+ const p = waitForCompletionRenewing(queue, j.id, { pollMs: 25, timeoutMs: 30_000, renew });
+ setTimeout(() => { void engine.executeRaw('DELETE FROM minion_jobs WHERE id = $1', [j.id]); }, 60);
+ await expect(p).rejects.toThrow(/disappeared mid-wait/);
+
+ expect(renews).toBe(0);
+ });
+
+ test('total-deadline exhaustion propagates TimeoutError with jobId/elapsedMs and never renews or cancels', async () => {
+ const j = await queue.add('t', {});
+ let renews = 0;
+ const t0 = Date.now();
+ try {
+ await waitForCompletionRenewing(queue, j.id, {
+ pollMs: 25,
+ timeoutMs: 150,
+ chunkMs: 50,
+ renew: async () => { renews++; },
+ });
+ throw new Error('should have thrown');
+ } catch (e) {
+ expect(e).toBeInstanceOf(TimeoutError);
+ const te = e as TimeoutError;
+ expect(te.jobId).toBe(j.id);
+ expect(te.elapsedMs).toBeGreaterThan(0);
+ }
+ // The whole timeoutMs budget was honored before the throw.
+ expect(Date.now() - t0).toBeGreaterThanOrEqual(150);
+ // Deadline check precedes renew in the catch, so the final timeout never renews.
+ expect(renews).toBe(0);
+ // Like the plain wait, timing out never cancels the job.
+ expect((await queue.getJob(j.id))?.status).toBe('waiting');
+ });
+
+ test('chunkMs below the 1s floor is clamped: a sub-second completion sees zero chunk timeouts', async () => {
+ const j = await queue.add('t', {});
+ let renews = 0;
+ const [res] = await Promise.all([
+ waitForCompletionRenewing(queue, j.id, {
+ pollMs: 25,
+ timeoutMs: 30_000,
+ chunkMs: 1,
+ renew: async () => { renews++; },
+ }),
+ completeLater('t', 200),
+ ]);
+ expect(res.status).toBe('completed');
+ // If chunkMs 1 were honored literally, every 1ms chunk would time out and
+ // renew would have fired dozens of times before the 200ms completion.
+ expect(renews).toBe(0);
+ });
+
+ test('resolves across a chunk boundary when no renew option is provided', async () => {
+ const j = await queue.add('t', {});
+ const t0 = Date.now();
+ const [res] = await Promise.all([
+ waitForCompletionRenewing(queue, j.id, { pollMs: 25, timeoutMs: 30_000, chunkMs: 50 }),
+ completeLater('t', 1300),
+ ]);
+ expect(res.status).toBe('completed');
+ expect(Date.now() - t0).toBeGreaterThanOrEqual(1000); // crossed >=1 chunk boundary renew-less
+ });
+});