Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.45.15.0 fix(minions,cli): duplicate-cycle single-flight, claim-time timeout backfill, real jobs --help (#2/#3/#4) (#4125)

Garry Tan0f03a0f929f0
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 2ccb6e7890..bf78157faf 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.45.14.0 -->
+<!-- gbrain-runbook-stamp: 0.45.15.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 6d78d71c6c..5af9e88841 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,24 @@
All notable changes to GBrain will be documented in this file.
+## [0.45.15.0] - 2026-08-14
+
+**The queue that drains itself: three background-jobs fixes reported from a downstream agent deployment (upstream issues #2, #3, #4).** A brain whose autopilot cycle stalled mid-run could accumulate byte-identical queued cycles forever while every long job queued before an upgrade died minutes in — and the operator diagnosing it couldn't even find the worker entry point, because `gbrain jobs --help` printed a one-line stub. All three failure modes are closed, and the queue now tells you when it's holding work back.
+
+### Fixed
+
+- **Stalled cycles no longer breed duplicates.** Autopilot dispatch now uses a single-flight guard (`maxPending`) that counts waiting jobs AND actively-running jobs with a live lock, scoped per source — so a cycle stuck in `active` suppresses re-dispatch instead of minting a new duplicate every tick. A job whose worker died stops counting the moment its lock lapses, so a dead worker can never silently freeze dispatch: the fresh waiting row keeps feeding the existing wedge detectors. Applies to per-source cycles, the legacy single-source path, and brain-wide maintenance.
+- **Long jobs queued before an upgrade get their real budget.** Handler wall-clock budgets now also resolve at claim time (not just at submit), so rows inserted with no budget — including anything queued on an older version — run with their documented allowance instead of being dead-lettered by the minutes-scale default. Migration v128 backfills budgets for everything still in flight and cancels the duplicate cycle backlog (newest per source survives; manually submitted cycles without a ticker-style idempotency key are never touched; cancelled rows are kept for audit).
+- **`gbrain jobs --help` prints the real surface.** The full subcommand list plus dedicated help for `work`, `supervisor`, `submit`, `watch`, and `prune` — engine-free, and a help flag after a subcommand can no longer fall through and start a real worker daemon.
+
+### Added
+
+- **`gbrain jobs stats` shows suppressed dispatch.** A `Backpressure (24h)` line reports submissions coalesced onto in-flight jobs, plus a hint naming the specific in-flight job holding a queue-empty name back — the visibility that was missing when "nothing queued, nothing completing" was the only symptom.
+- **`gbrain jobs get <id>` shows the effective wall-clock budget** — the stamped timeout and deadline, or which default applies and when it kicks in.
+- Autopilot cycle dispatch tells the truth: a submission that coalesced onto an existing job reports `dispatch_coalesced` (and `coalesced: true` in `jobs submit`'s JSON output) instead of claiming a dispatch that never inserted a row.
+
+To take advantage of v0.45.15.0: upgrade and run any gbrain command — migration v128 applies automatically, backfilling budgets for queued long jobs and clearing any duplicate cycle backlog. If a queue looked wedged before, `gbrain jobs stats` now names the in-flight job to inspect and `gbrain jobs work --help` documents the worker daemon flags end to end.
+
## [0.45.14.0] - 2026-08-14
**The box that already has a brain: framework-spawned coding agents get brain access by default.** The bootstrap door built in v0.45.0.0 was for a human at a laptop. A growing share of Claude Code and Codex sessions are spawned by an agent framework — your OpenClaw, or anything that shells out to headless sessions — on a machine that already hosts a brain and a running `gbrain serve --http`. Until now those sessions got nothing unless someone hand-replicated settings writers across every project directory. One command fixes that:
diff --git a/TODOS.md b/TODOS.md
index e33259942f..798a1b4cc6 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -1,5 +1,39 @@
# TODOS
+## Jobs fix-wave follow-ups (filed v0.45.15.0 — upstream issues #2/#3/#4)
+
+- [ ] **P2 — `jobs submit --max-pending` public flag.** maxPending stays an
+ internal submit option this wave (Codex C4): its semantics exclude
+ delayed/paused/waiting-children rows, and identity is (name, queue, source)
+ so distinct payloads collapse. Decide the public contract (include delayed?
+ explicit scope key?) after the primitive soaks in autopilot, then mirror
+ parseMaxWaitingFlag (clamp [1,100]) + help + flag-registry regen + optional
+ submit_job MCP param. Where: src/commands/jobs.ts, src/core/operations.ts.
+- [ ] **P2 — maxPending at the other single-flight dispatch sites.** The
+ freshness sync submit (src/commands/autopilot.ts freshness loop) and the
+ targeted remediation steps (autopilot.ts targeted-submit loop) still use
+ maxWaiting: 1; widening to maxPending changes behavior of those lanes
+ (suppression while a long run is active) and needs its own review. Where:
+ src/commands/autopilot.ts.
+- [ ] **P2 — Help-stub sweep for the other CLI_ONLY commands.** The `jobs`
+ defect class exists elsewhere: `gbrain search modes --help` connects an
+ engine before help routing, and the search subcommands have no help guards
+ (jobs/bootstrap/skillpack now carry the guard pattern to copy). Audit every
+ CLI_ONLY member missing from CLI_ONLY_SELF_HELP; the top-level help promises
+ per-command help for all of them. Where: src/cli.ts, src/commands/search.ts.
+- [ ] **P3 — jobs stats: fuller backpressure/audit surfacing.** The 24h
+ Backpressure line + suppressed-by hint shipped; per-decision breakdowns,
+ longer windows, and doctor integration remain (the audit file header's B4
+ follow-up). Where: src/commands/jobs.ts, src/core/minions/backpressure-audit.ts.
+- [ ] **P3 — jobs watch: timeout/deadline column.** `jobs get` shows the
+ effective budget; the live dashboard doesn't. Where: src/commands/jobs-watch.ts.
+- [ ] **P3 — jobs help + operator docs: handler catalog and dispatch-event
+ schema.** `gbrain jobs --help`'s HANDLER TYPES section lists 8 of the ~40
+ registered handlers, and the autopilot dispatch JSON events (`dispatched`,
+ `dispatch_coalesced`, `fanout_summary` with its `coalesced` array) have no
+ schema documentation outside the CHANGELOG. Where: src/commands/jobs.ts
+ (JOBS_HELP), docs/guides/queue-operations-runbook.md.
+
## Truthful-surface wave follow-ups (filed with T14, amendment 35 + D14.5)
Deferred from the MCP consumer-feedback wave (plan at
@@ -694,6 +728,16 @@ job) and sync. See CLAUDE.md "Pace Mode".
supervisor-detection downgrade. Today these inherit config/env pacing only when
they call `runEmbedCore`.
- [ ] **P1-companion — Supervisor concurrency 3→2 + job-kind slot fairness (E7).**
+ **v0.45.15.0 annotation (jobs fix wave):** make the whole wedge-detector FAMILY
+ suppression-aware while here — the supervisor watchdog (supervisor.ts wedge
+ predicate) and doctor's `wedged_queue` check both require waiting > 0, and
+ `maxPending` single-flight keeps waiting at 0 while a job is in flight.
+ Mitigations already shipped: maxPending counts only LIVE-LOCK actives (a
+ dead/blocked worker's expired-lock row never suppresses, so fresh waiting rows
+ re-feed the detectors) and `jobs stats` prints a Backpressure line + a
+ suppressed-by hint. Remaining: teach watchdog/doctor to treat
+ recent-coalesces + stale live active as wedge signal; also note the worker
+ in-flight stall-check hole (worker.ts stall check skips when inFlight > 0).
The daemon-side root cause the external wrapper's probe was blind to:
`embed-backfill`/`autopilot-cycle` jobs can occupy all supervisor slots
(`:215` below). Pacing makes backfills safe; this fixes the residual death rate.
@@ -1247,11 +1291,14 @@ but were deliberately scoped OUT — neither is a #1784 regression.
deserves its own deliberate change. Fix: mirror the extracted
`buildCostRefusal({json, ...})` helper (`reindex-code.ts`). The guardrail
(exit 2, no spend) stays; only the FORMAT splits on `--json`.
-- [ ] **P3 — `gbrain jobs --help` has no subcommand list.** jobs.ts dispatches
+- [x] **P3 — `gbrain jobs --help` has no subcommand list.** jobs.ts dispatches
on a bare subcommand string with no HELP const, so `watch` (and every other
jobs subcommand) is undocumented in `--help`. The new `watch` `--json` /
`--follow` flags are documented only in the file JSDoc. Add a HELP table to the
`jobs` command listing every subcommand + its flags.
+ **Completed:** v0.45.15.0 (2026-08-14) — JOBS_HELP + JOBS_SUBCOMMAND_HELP with a
+ guard above the thin-client refusal; `jobs`/`jobs work` etc. `--help` print real
+ usage engine-free and can never start a daemon.
## v0.42.12.0 self-upgrade follow-ups (v0.43+)
@@ -1423,7 +1470,11 @@ and tested; these are documented tradeoffs and stronger-but-bigger versions.
Deferred from the v0.41.38.0 wave (code-callers/callees pin + dream-on-postgres).
Documented tradeoffs, not blockers — the shipped bug fixes are complete and tested.
-- [ ] **P1 — Per-source autopilot fan-out passes the global repoPath.**
+- [x] **P1 — Per-source autopilot fan-out passes the global repoPath.**
+ **Completed (verified already fixed):** v0.45.15.0 audit (2026-08-14) — the
+ handler binds FS phases to the source's `local_path` and never falls through
+ to the global repoPath (`effectiveBrainDir = sourceId ? sourceLocalPath :
+ repoPath` in src/commands/jobs.ts, with per-source null → skip FS phases).
`src/commands/autopilot-fanout.ts:~206` submits every per-source `autopilot-cycle`
job with `repoPath: opts.repoPath` (the global checkout), not `src.local_path`.
With v0.41.38.0's `cycleSourceId = opts.sourceId ?? resolveSourceForDir(...)`,
diff --git a/VERSION b/VERSION
index ce20186d40..4650acc694 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.45.14.0
\ No newline at end of file
+0.45.15.0
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 5834593f5d..7a07155e1f 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -225,7 +225,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `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/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 `maxWaiting` coalesce path uses `pg_advisory_xact_lock` keyed on `(name, queue)` to serialize concurrent submits for the same key, and filters 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, so long handlers aren't wall-clock-killed mid-progress by the short null-default; an explicit `opts.timeout_ms` always wins. 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()` rejects `subagent` jobs whose `data.model` resolves via `isAnthropicProvider()` to a non-Anthropic provider. Lazy-imports `model-config.ts` to avoid pulling engine types into queue's eager-load surface. Layer 1 of the three-layer subagent provider enforcement (layers 2+3: `model-config.ts:enforceSubagentAnthropic` runtime fallback + `src/commands/doctor.ts` `subagent_provider` check). Pinned by `test/agent-cli.test.ts`.
+- `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. 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`.
- `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` + per-call `Promise.race` timeout (`GBRAIN_LOCK_RENEWAL_CALL_TIMEOUT_MS`, default `lockDuration/3`); (3) time-based abort (`Date.now() - lastSuccessfulRenewalAt >= lockDuration - GBRAIN_LOCK_RENEWAL_SAFETY_MARGIN_MS`) so we release the lock BEFORE another worker can reclaim; (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). 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 `test/worker-lock-renewal.test.ts` (18), `test/audit/lock-renewal-audit.test.ts` (11), `test/scripts/check-worker-lock-renewal-shape.test.ts` (5), `test/worker-shutdown-disconnect.test.ts` (asserts `disconnectSpy).not.toHaveBeenCalled()`), `test/worker-rss.test.ts` (11), `test/worker-supervised-db-probe.test.ts` (3).
- `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 fails past the threshold exits `LOCK_LOST` (code 4) rather than risk a split-brain. `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`.
- `src/core/minions/child-worker-supervisor.ts` — shared spawn-and-respawn core reused by both `MinionSupervisor` (standalone `gbrain jobs supervisor` daemon) and `src/commands/autopilot.ts` (autopilot daemon), so the two consumers can't drift into parallel-loop bugs. Pure class: NO PID file, NO signal handlers, NO `process.exit`, NO health check. Lifecycle events fire via injected `onEvent: (ChildSupervisorEvent) => void`. Exit classifier: `code === 0` leaves `crashCount` UNCHANGED (preserves flap detection across mixed exit sequences); `code != 0` follows `runDuration > stableRunResetMs ? 1 : ++crashCount`. Clean-restart budget: sliding window of code=0 exits; when count exceeds `cleanRestartBudget` (default 10) inside `cleanRestartWindowMs` (default 60s), emits `health_warn { reason: 'clean_restart_budget_exceeded' }` and applies `cleanRestartBudgetBackoffMs` (default 1s). The exit classifier special-cases `WORKER_EXIT_RSS_WATCHDOG` — `likely_cause='rss_watchdog'`, and that exit does NOT bump `crashCount` (routes to its own breaker); a dedicated `_watchdogExitTimestamps` sliding window trips a loud `rss_watchdog_loop` health_warn naming the cap when N watchdog exits land inside the window, INDEPENDENT of the stable-run reset (which would otherwise hide a >5-min-run watchdog drain loop). New opts `watchdogLoopBudget` (3), `watchdogLoopWindowMs` (600000), `watchdogBackoffMs` (30000); `ChildSupervisorEvent` extended. Public read-only accessors `childAlive`, `inBackoff`, `crashCount`; `killChild(signal)` gates on liveness (`exitCode === null && signalCode === null`), NOT `.killed` — `.killed` flips true once a signal is *sent*, so the old `!this._child.killed` guard made a follow-up SIGKILL after an ignored SIGTERM a silent no-op (#1801; the bug also lived in the `shutdown()` drain). `restartCurrentChild(graceMs)` (#1801 wedge self-heal) captures the CURRENT child ref, SIGTERM→grace→SIGKILLs THAT ref (never the respawn — closes the timer-kills-fresh-worker race), and flags `_intentionalRestart` so the exit is `likelyCause='wedge_restart'`, leaves `crashCount` UNTOUCHED (never trips `max_crashes`; like `rss_watchdog`), and respawns immediately (`backoff ms:0 reason='wedge_restart'`). `awaitChildExit(timeoutMs)` short-circuits when `child.exitCode !== null || child.signalCode !== null` so fast-SIGTERM responders don't cause a 35s shutdown hang. Degraded-retry (#1994/#2227): the `run()` loop no longer fires `onMaxCrashesExceeded` at the soft `maxCrashes`; it announces `health_warn { reason: 'crash_budget_degraded' }` once per episode and keeps respawning with capped backoff (the 60s cap makes it a paced retry, not a hot loop), re-arming after a stable-run reset drops the count. Permanent give-up fires only at `hardStopMaxCrashes` (default `maxCrashes × HARD_STOP_CRASH_MULTIPLIER` = 10×; `0` disables). Test hooks `_backoffFloorMs`, `_now`. `supervisor-audit.ts` adds `rss_watchdog` as a non-clean cause + its own `CrashSummary.by_cause` bucket, and `wedge_restart` to `CLEAN_EXIT_CAUSES` (a self-heal, not a crash; denylist preserved so future causes route to `legacy`). Pinned by `test/child-worker-supervisor.test.ts` (12 cases).
@@ -233,7 +233,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/minions/niceness.ts` — OS scheduling-priority (niceness) primitives for the `--nice` flag. `parseNiceValue(raw)` whole-string parses + range-validates to POSIX `[-20, 19]` (rejects `"3.5"`/`"10abc"` that `parseInt` would silently truncate). `applyNiceness(nice, setPriority?, getPriority?)` calls `os.setPriority(0, n)` and ALWAYS re-reads `os.getPriority(0)` afterwards — in both the success and the catch paths — so a denied renice (EPERM) or an `RLIMIT_NICE` clamp records the real effective value (e.g. `0`), not null; returns `{applied, requested, effective, error?}`. `getEffectiveNiceness(pid, getPriority?)` reads an arbitrary pid's niceness (null on dead/unreadable). `formatNice(n)` → `+10`/`0`/`-5`. Applied only at the CLI layer (jobs.ts) so worker.ts/supervisor.ts stay embeddable. Pinned by `test/niceness.test.ts`.
- `src/core/minions/worker-registry.ts` — live worker registry backing niceness observability. Each running `gbrain jobs work` self-registers `worker-<pid>.json` under `gbrainPath('workers')` (brain-isolated via `GBRAIN_HOME`; entries tagged with `currentBrainId()` so multiple DBs under one home don't cross-report). `registerWorker(info)` is best-effort (never blocks the worker) and returns a cleanup fn the caller wires to BOTH the shutdown `finally` AND `process.on('exit')` (the unhealthy `process.exit(1)` bypasses the awaited finally). `readWorkers(getNice?)` enumerates the dir, drops confirmed-dead pids (`classifyLiveness`: ESRCH = dead/prune, EPERM = alive/keep), applies a pid-reuse start-time guard (`ps -o lstart`, rejects a pid whose process started >5s after the entry was written), and re-measures each live worker's niceness now. Reports the worker's REAL pid, sidestepping the tini-wrapper-pid problem. Pinned by `test/worker-registry.test.ts`.
- `src/core/minions/supervisor-pid.ts` — `readSupervisorPid(pidFile) → {pid, running}`: the shared `existsSync → readFileSync → parseInt → process.kill(pid,0)` PID-file + liveness reader extracted from the three copies in `jobs.ts` (supervisor status), `jobs.ts` (stats), and `doctor.ts`. EPERM from the liveness probe counts as running. Pinned by `test/supervisor-pid.test.ts`.
-- `src/core/minions/handler-timeouts.ts` (#1737) — per-handler default wall-clock budgets. `HANDLER_DEFAULT_TIMEOUT_MS` maps the long handlers (`subagent`, `subagent_aggregator`, `embed-backfill`, `autopilot-cycle`, `autopilot-global-maintenance`) to a 30-min default (the value `cycle/patterns.ts` already passed for subagents, generalized). `defaultTimeoutMsFor(jobName)` returns that default or `null` for short handlers (keep the tight null-default wall-clock). `MinionQueue.add()` stamps this onto `minion_jobs.timeout_ms` at submit time when the caller passed no `timeout_ms`, so a long job submitted without one isn't wall-clock-killed mid-progress; an explicit value always wins and already-queued jobs are NOT backfilled. Pinned by `test/minions.test.ts`.
+- `src/core/minions/handler-timeouts.ts` (#1737) — per-handler default wall-clock budgets. `HANDLER_DEFAULT_TIMEOUT_MS` maps the long handlers to per-handler defaults: 30 min for `subagent`, `subagent_aggregator`, `embed-backfill`, `autopilot-cycle`, `autopilot-global-maintenance` (the value `cycle/patterns.ts` already passed for subagents, generalized); 10 min for `chronicle_extract` + `facts-absorb`; 60 min for `contextual_reindex_per_chunk`. `defaultTimeoutMsFor(jobName)` returns the mapped default or `null` for short handlers (keep the tight null-default wall-clock). Three layers apply it (explicit value always wins): `MinionQueue.add()` stamps at submit; `MinionQueue.claim()` COALESCEs a NULL `timeout_ms` from the map (durable invariant); migration v128 one-shot backfilled pre-existing non-terminal rows with authoring-time snapshot values — do NOT sync v128 when editing the map. Pinned by `test/minions.test.ts` + `test/migrations-v128.test.ts`.
- `src/core/minions/types.ts` — `MinionJobInput` + `MinionJobStatus` + handler context types. `MinionJobInput.max_stalled` is optional; omitted values let the schema DEFAULT (5) kick in, provided values are clamped to `[1, 100]`.
- `src/core/minions/protected-names.ts` — side-effect-free constant module exporting `PROTECTED_JOB_NAMES` + `isProtectedJobName()`. Kept pure so queue core can import without loading handler modules. `PROTECTED_JOB_NAMES` includes `synthesize`, `patterns`, `consolidate`. These phases internally submit `subagent` children with `allowProtectedSubmit=true` and can spend Anthropic credits. Only trusted local callers (CLI, autopilot, `doctor --remediate`) can submit them; MCP requests are rejected by `submit_job`'s protected-name guard.
- `src/core/minions/handlers/shell.ts` — `shell` job handler. Spawns `/bin/sh -c cmd` (absolute path, PATH-override-safe) or `argv[0] argv[1..]` (no shell). Env allowlist `PATH, HOME, USER, LANG, TZ, NODE_ENV` + caller `env:` overrides + `inherit:`-resolved keys. UTF-8-safe stdout/stderr tail via `string_decoder.StringDecoder`. Abort (either `ctx.signal` or `ctx.shutdownSignal`) fires SIGTERM → 5s grace → SIGKILL on child. Requires `GBRAIN_ALLOW_SHELL_JOBS=1` on worker (gated by `registerBuiltinHandlers`). `ShellJobParams.inherit?: string[]` is a free-form list of snake_case config-key names; the worker resolves each via `loadConfig()` and injects the value under the derived env key (`database_url` → `GBRAIN_DATABASE_URL`; else uppercased). Names persist in `minion_jobs.data` (and the shell-audit JSONL); values never do. The canonical validator `validateShellJobParams` (sibling `shell-validate.ts`) runs PRE-ENQUEUE in both submit surfaces — `gbrain jobs submit shell` (jobs.ts:271) AND the `submit_job` op for `name='shell'` (operations.ts:2085); the handler-entry re-validation here is defense-in-depth (closes the bug class where validation ran AFTER `queue.add()` persisted the row). The validator does NOT police which config keys the agent inherits — same-uid trust model treats the agent as a peer of the worker.
@@ -242,8 +242,8 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/minions/handlers/shell-redact.ts` — opt-in output-side scrubbing for shell-job stdout/stderr. Pure `redactSecretsInText(text, secrets)`: string-mode `replaceAll` so regex metacharacters in values stay literal. When the caller passes `redact_secrets: true` (or `--redact-secrets`), the handler builds a Map of inherit-name → resolved-value and post-processes both tails before throw/return so persisted `result.stdout_tail` / `result.stderr_tail` / `error_text` carry `<REDACTED:name>`. Only `inherit:`-resolved values are scrubbed; caller-supplied `env:` values pass through. Heuristic — defeats `echo "$GBRAIN_DATABASE_URL"`, not adversarial encode-then-print. Default `false`.
- `src/core/config.ts:ensureGitignore` — idempotent retroactive writer of `~/.gbrain/.gitignore` (single line `*`). Called from `saveConfig()` so every config-writing path lays it down, AND from `runPostUpgrade()` so existing users pick it up on `gbrain upgrade`. Never clobbers a user-customized `.gitignore` (checks file exists + content non-empty before writing). Scope: blocks casual `git add ~/.gbrain` from inside an enclosing worktree, but does NOT cover already-tracked files, screenshots, backups (Time Machine / iCloud / Dropbox), or `git add -f`. The doctor check `home_dir_in_worktree` surfaces what `.gitignore` can't.
- `src/core/minions/handlers/shell-audit.ts` — per-submission JSONL audit trail at `~/.gbrain/audit/shell-jobs-YYYY-Www.jsonl` (ISO-week rotation; override via `GBRAIN_AUDIT_DIR`). Best-effort: `mkdirSync(recursive)` + `appendFileSync`; failures logged to stderr, submission not blocked. Logs cmd (first 80 chars) or argv (JSON array). Never logs env values.
-- `src/core/minions/handlers/supervisor-audit.ts` — supervisor lifecycle JSONL audit at `~/.gbrain/audit/supervisor-YYYY-Www.jsonl` (ISO-week rotation; shares `computeIsoWeekName()` with `shell-audit.ts`). `writeSupervisorEvent(emission, supervisorPid)` appends one line per event (`started`, `worker_spawned`, `worker_exited`, `backoff`, `health_warn`, `health_error`, `max_crashes_exceeded`, `shutting_down`, `stopped`, `worker_spawn_failed`). `readSupervisorEvents({sinceMs})` is the readback for `gbrain doctor`. Exports `isCrashExit(event)`, `summarizeCrashes(events)`, `CrashSummary` type, and `CLEAN_EXIT_CAUSES` denylist (`'clean_exit' | 'graceful_shutdown'`). Single regression point — both `gbrain doctor` (supervisor check at `doctor.ts:1011-1043`) and `gbrain jobs supervisor status` (`jobs.ts:803-826`) import from here so the two surfaces can't drift. `isCrashExit` classifies a single `worker_exited` against the denylist: clean/graceful are NON-crashes; everything else (incl. any future `likely_cause` from `child-worker-supervisor.ts`) is a crash; audit lines lacking `likely_cause` fall back to `code !== 0`. `summarizeCrashes` returns `{total, by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}, clean_exits}` — the `legacy` bucket catches both old fallback entries AND unrecognized future causes (fail-loud, not silent underreport); denylist-over-allowlist is deliberate. Pinned by `test/supervisor-audit.test.ts` (14 cases) and 4 source-grep wiring assertions in `test/doctor.test.ts`.
-- `src/core/minions/backpressure-audit.ts` — sibling of shell-audit.ts for `maxWaiting` coalesce events. JSONL at `~/.gbrain/audit/backpressure-YYYY-Www.jsonl`. One line per coalesce with `(queue, name, waiting_count, max_waiting, returned_job_id, ts)`. Closes the silent-drop vector the maxWaiting guard introduced.
+- `src/core/minions/handlers/supervisor-audit.ts` — supervisor lifecycle JSONL audit at `~/.gbrain/audit/supervisor-YYYY-Www.jsonl` (ISO-week rotation; shares `computeIsoWeekName()` with `shell-audit.ts`). `writeSupervisorEvent(emission, supervisorPid)` appends one line per event (`started`, `worker_spawned`, `worker_exited`, `backoff`, `health_warn`, `health_error`, `max_crashes_exceeded`, `shutting_down`, `stopped`, `worker_spawn_failed`). `readSupervisorEvents({sinceMs})` is the readback for `gbrain doctor`. Exports `isCrashExit(event)`, `summarizeCrashes(events)`, `CrashSummary` type, and `CLEAN_EXIT_CAUSES` denylist (`'clean_exit' | 'graceful_shutdown'`). Single regression point — both `gbrain doctor` (supervisor check) and `gbrain jobs supervisor status` import from here so the two surfaces can't drift. `isCrashExit` classifies a single `worker_exited` against the denylist: clean/graceful are NON-crashes; everything else (incl. any future `likely_cause` from `child-worker-supervisor.ts`) is a crash; audit lines lacking `likely_cause` fall back to `code !== 0`. `summarizeCrashes` returns `{total, by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}, clean_exits}` — the `legacy` bucket catches both old fallback entries AND unrecognized future causes (fail-loud, not silent underreport); denylist-over-allowlist is deliberate. Pinned by `test/supervisor-audit.test.ts` (14 cases) and 4 source-grep wiring assertions in `test/doctor.test.ts`.
+- `src/core/minions/backpressure-audit.ts` — sibling of shell-audit.ts for `maxWaiting` AND `maxPending` coalesce events. JSONL at `~/.gbrain/audit/backpressure-YYYY-Www.jsonl`. One line per coalesce with `(queue, name, waiting_count/max_waiting OR pending_count/max_pending, returned_job_id, ts)`. `readRecentCoalesceCounts` feeds the `jobs stats` Backpressure line (reads current + previous ISO-week files so a 24h window survives week boundaries, filtered per queue). Closes the silent-drop vector the backpressure guards introduced. Pinned by `test/backpressure-audit-read.test.ts`.
- `src/core/minions/handlers/subagent.ts` — LLM-loop handler. Two-phase tool persistence (pending → complete/failed), replay reconciliation for mid-dispatch crashes, dual-signal abort (`ctx.signal` + `ctx.shutdownSignal`), Anthropic prompt caching on system + tool defs. `makeSubagentHandler({engine, client?, ...})` factory; `MessagesClient` is an injectable interface the real SDK implements structurally. Per-turn output cap resolves via `resolveMaxOutputTokens` (`data.max_tokens` → `agent.max_output_tokens` config → 8192 default); a `stop_reason: 'max_tokens'` final turn surfaces as `SubagentStopReason 'max_tokens'` (not a silent `end_turn`), and a max_tokens stop mid-tool-round injects a truncation note into the tool-result turn so the model re-issues the dropped call. Throws `RateLeaseUnavailableError` (renewable) when rate-lease capacity is full. Anthropic 400 `prompt is too long` responses (status 400 + body matches `/prompt is too long|prompt_too_long|context.*length/i`) classify as `UnrecoverableError` so the job goes straight to `dead` on first attempt instead of stalling three times. Catches both initial-prompt overflow and turn-N tool-loop accumulation that `synthesize.ts`'s chunker can't bound ahead of time. terminal-state short-circuit on resume. When a stored message thread already ends in `stop_reason: 'end_turn'`, the handler returns `{ ok: true }` immediately instead of issuing another `messages.create` call (re-prompting past `end_turn` would get a 400 and dead-letter an already-successful job). Pinned by `test/subagent-handler.test.ts`.
- `src/core/minions/handlers/subagent-aggregator.ts` — `subagent_aggregator` handler. Claims AFTER all children resolve (queue guarantees every terminal child posts a `child_done` inbox message with outcome). Reads inbox via `ctx.readInbox()`, builds a deterministic mixed-outcome markdown summary. No LLM call.
- `src/core/minions/handlers/subagent-audit.ts` — JSONL audit + heartbeat writer at `~/.gbrain/audit/subagent-jobs-YYYY-Www.jsonl`. Events: `submission` (one per submit) + `heartbeat` (per turn boundary: `llm_call_started | llm_call_completed | tool_called | tool_result | tool_failed`). Never logs prompts or tool inputs. `readSubagentAuditForJob(jobId, {sinceIso})` is the readback for `gbrain agent logs`.
@@ -264,7 +264,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/minions/attachments.ts` — Attachment validation (path traversal, null byte, oversize, base64, duplicate detection).
- `src/commands/agent.ts` — `gbrain agent run <prompt> [flags]` CLI. Submits `subagent` (or N children + 1 aggregator) under `{allowProtectedSubmit: true}`. Single-entry `--fanout-manifest` short-circuits. Children get `on_child_fail: 'continue'` + `max_stalled: 3`. `--follow` is the default on TTY; streams logs + polls `waitForCompletion` in parallel. Ctrl-C detaches, does not cancel.
- `src/commands/agent-logs.ts` — `gbrain agent logs <job> [--follow] [--since]`. Merges JSONL heartbeat audit + `subagent_messages` into a chronological timeline. `parseSince` accepts ISO-8601 or relative (`5m`, `1h`, `2d`). Transcript tail renders only for terminal jobs.
-- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. `case 'work'` wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the full `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`. `jobs smoke --sigkill-rescue` is the SIGKILL-rescue regression guard. `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo — the #2194/#2227 mixed-scope fix) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs the brain-wide `GLOBAL_PHASES` once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` on success. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status` at `jobs.ts:803-826` consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output gains per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's #2849 size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress.
+- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the subcommand switch — `jobs work --help` can never start a daemon; only `--help`/`-h` are help tokens (bare `help` can be a job name); cli.ts routes it engine-free via `SELF_HELP_WITHOUT_ENGINE` + `CLI_ONLY_SELF_HELP`. `formatJobDetail` prints the effective wall-clock budget (`Timeout:`/`Deadline:` — 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer; `timeout_at` is in `JOB_DATE_FIELDS` for thin-client rehydration. `jobs stats` prints a `Backpressure (24h)` line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the shared `GBRAIN_WEDGED_QUEUE_WARN_MINUTES` threshold — the read-only visibility for maxPending single-flight suppression. Pinned by `test/jobs-subcommand-help.serial.test.ts`, `test/jobs-format-detail.test.ts`, `test/jobs-stats-backpressure.serial.test.ts`. `case 'work'` wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke --sigkill-rescue` is the SIGKILL-rescue regression guard. `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo — the #2194/#2227 mixed-scope fix) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs the brain-wide `GLOBAL_PHASES` once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` on success. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status` consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output gains per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's #2849 size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress.
- `src/commands/features.ts` — `gbrain features --json --auto-fix`: usage scan + feature adoption salesman.
- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn (no inline `crashCount`/`startWorker`/`child.on('exit')`); `--max-rss 2048` and `maxCrashes: 5` preserved. `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` adds `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`); `src/core/config.ts` adds the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID, startup checks `kill -0 <pid>` before refusing to start (stale lock from a crashed process no longer blocks). (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector.
- `src/mcp/server.ts` — MCP stdio server (generated from operations). Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. Pinned by `test/serve-stdio-lifecycle.test.ts`.
diff --git a/docs/guides/minions-deployment.md b/docs/guides/minions-deployment.md
index 4e2f3087af..a12b335a53 100644
--- a/docs/guides/minions-deployment.md
+++ b/docs/guides/minions-deployment.md
@@ -140,7 +140,7 @@ Three-command pattern an agent can drive without shell archaeology:
```bash
# Start (returns PIDs + pid_file on stdout as JSON, then detaches)
gbrain jobs supervisor start --detach --json
-# → {"event":"started","supervisor_pid":1234,"worker_pid":1235,"pid_file":"/Users/you/.gbrain/supervisor.pid"}
+# → {"event":"started","supervisor_pid":1234,"pid_file":"/Users/you/.gbrain/supervisor-<brain-id>.pid","detached":true}
# Check health (machine-parseable JSON, no log scraping)
gbrain jobs supervisor status --json
diff --git a/docs/guides/queue-operations-runbook.md b/docs/guides/queue-operations-runbook.md
index a46527f84c..f7bd241c9f 100644
--- a/docs/guides/queue-operations-runbook.md
+++ b/docs/guides/queue-operations-runbook.md
@@ -85,8 +85,20 @@ gbrain jobs smoke --wedge-rescue
- **stalled-forever** — A worker claimed a job, started executing, and has
held the row for over an hour. The wall-clock sweep evicts jobs past
- 2× `timeout_ms`; if one's still active, either no `timeout_ms` was set
- or the sweep is newly deployed and this job predates it. Cancel it.
+ 2× `timeout_ms`. Long-lane handlers (subagent, autopilot-cycle,
+ embed-backfill, …) always have a budget now: it stamps at submit, is
+ COALESCEd from `HANDLER_DEFAULT_TIMEOUT_MS` at claim for legacy NULL rows,
+ and migration v128 backfilled rows that predate both. `gbrain jobs get <id>`
+ prints the effective budget and which kill path applies. If a short-lane
+ job is still active with no budget, the null-default sweep
+ (2 × lock-duration × max_stalled) evicts it within minutes. Cancel it if
+ you can't wait.
+- **duplicate cycles** — Historic brains could accumulate byte-identical
+ waiting `autopilot-cycle` rows when a job stalled in `active`. v128
+ cancelled that backlog (newest ticker-keyed row per source survives), and
+ the `maxPending` dispatch guard prevents new accumulation. Suppressed
+ dispatches are visible in `jobs stats` (Backpressure line) and the
+ backpressure audit JSONL.
- **waiting-depth** — Submitters are piling up jobs faster than workers
drain them. Set `--max-waiting N` on the submission or on the programmatic
`queue.add()` call. If you want a taller pile, raise the threshold via
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 0d68e763f3..f7356369b0 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.45.14.0",
+ "version": "0.45.15.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index faeea8c94c..78a098890f 100644
--- a/package.json
+++ b/package.json
@@ -155,7 +155,7 @@
"bun": ">=1.3.10"
},
"license": "MIT",
- "version": "0.45.14.0",
+ "version": "0.45.15.0",
"overrides": {
"@hono/node-server": "^2.0.5",
"fast-uri": "^3.1.5",
diff --git a/src/cli.ts b/src/cli.ts
index 02891ea4e4..833b4b7447 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -154,6 +154,11 @@ const CLI_ONLY_SELF_HELP = new Set([
// would leave that help dead code behind the generic stub (the init.ts:117
// trap ENG-2 names).
'bootstrap', 'hook', 'sweep',
+ // jobs ships JOBS_HELP + a per-subcommand record (JOBS_SUBCOMMAND_HELP) in
+ // jobs.ts, guarded BEFORE the thin-client refusal and the subcommand switch
+ // so `jobs work --help` prints help instead of starting a worker daemon.
+ // Without this entry the generic stub hid the worker entry point entirely.
+ 'jobs',
]);
/**
@@ -172,6 +177,9 @@ const SELF_HELP_WITHOUT_ENGINE: Record<string, () => Promise<(engine: never, arg
maintain: async () => (await import('./commands/maintain.ts')).runMaintain as never,
'extract-conversation-facts': async () =>
(await import('./commands/extract-conversation-facts.ts')).runExtractConversationFacts as never,
+ // runJobs accepts BrainEngine | null and its help guard returns before any
+ // engine (or subcommand body) is touched.
+ jobs: async () => (await import('./commands/jobs.ts')).runJobs as never,
};
/** Returns true when the command's own help was printed. */
@@ -3229,7 +3237,9 @@ JOBS (Minions)
jobs retry <id> Re-queue failed/dead job
jobs prune [--older-than 30d] Clean old jobs
jobs stats Job health dashboard
+ jobs watch [--follow] Live queue dashboard
jobs work [--queue Q] Start worker daemon (Postgres only)
+ jobs supervisor [start|status|stop] Auto-restarting worker wrapper
ADMIN
stats Brain statistics
diff --git a/src/commands/autopilot-fanout.ts b/src/commands/autopilot-fanout.ts
index e9adf99773..4c1fcc0b97 100644
--- a/src/commands/autopilot-fanout.ts
+++ b/src/commands/autopilot-fanout.ts
@@ -69,8 +69,13 @@ export interface FanoutOpts {
}
export interface FanoutResult {
- /** Source ids dispatched this tick. */
+ /** Source ids whose submission INSERTED a fresh job this tick. */
dispatched: string[];
+ /** Source ids whose submission coalesced onto an existing pending job
+ * (maxPending single-flight or same-slot idempotency) — work is in
+ * flight, but no new row was created. Kept separate so no surface
+ * claims a dispatch that didn't insert. */
+ coalesced: string[];
/** Source ids skipped because their last_full_cycle_at is still fresh. */
skipped_fresh: string[];
/** Source ids beyond the fanoutMax cap (will retry next tick). */
@@ -400,19 +405,32 @@ export async function dispatchPerSource(
{ repoPath: opts.repoPath },
{
queue: 'default',
+ // Slot key dedups repeats within one slot; maxPending: 1 is the
+ // cross-slot guard — an in-flight (waiting or live-lock active)
+ // cycle suppresses re-dispatch even after the slot rotates. This
+ // closes the unbounded-duplicate loop: slot rotation used to mint
+ // a fresh key every baseInterval while maxWaiting ignored the
+ // active row, growing the queue forever when a cycle stalled.
idempotency_key: `autopilot-cycle:${opts.slot}`,
max_attempts: 2,
timeout_ms: opts.timeoutMs,
- maxWaiting: 1,
+ maxPending: 1,
},
);
- if (opts.jsonMode) {
+ if (job.coalesced) {
+ if (opts.jsonMode) {
+ emit(JSON.stringify({ event: 'dispatch_coalesced', job_id: job.id, mode: 'legacy', slot: opts.slot }));
+ } else {
+ log(`[dispatch] coalesced onto job #${job.id} autopilot-cycle (legacy single-source; already in flight)`);
+ }
+ } else if (opts.jsonMode) {
emit(JSON.stringify({ event: 'dispatched', job_id: job.id, mode: 'legacy', slot: opts.slot }));
} else {
log(`[dispatch] job #${job.id} autopilot-cycle (legacy single-source)`);
}
return {
dispatched: [],
+ coalesced: [],
skipped_fresh: [],
skipped_cap: [],
skipped_cooldown: [],
@@ -448,6 +466,7 @@ export async function dispatchPerSource(
);
const dispatched: string[] = [];
+ const coalesced: string[] = [];
for (const src of dispatch) {
try {
const shouldPull = sourceConfigHasRemoteUrl(src.config);
@@ -470,26 +489,43 @@ export async function dispatchPerSource(
idempotency_key: `autopilot-cycle:${src.id}:${opts.slot}`,
max_attempts: 2,
timeout_ms: opts.timeoutMs,
- // DELIBERATELY no maxWaiting: 1 here. maxWaiting is per
- // (name, queue), so it would coalesce all N per-source jobs
- // sharing name='autopilot-cycle' down to ONE waiting job —
- // killing the fan-out. The per-source idempotency_key
- // already provides the right dedup granularity (one job per
- // source per slot, regardless of how many ticks try).
+ // Still DELIBERATELY no maxWaiting here (its NULL-as-wildcard
+ // source scope would coalesce N per-source jobs down to one).
+ // maxPending is safe: its scope is EXACT on
+ // COALESCE(data.sourceId, data.source_id), so each source keeps
+ // an independent single-flight cap — and unlike the slot key, it
+ // suppresses cross-slot re-dispatch while THIS source's cycle is
+ // still in flight (waiting or live-lock active).
+ maxPending: 1,
},
);
- dispatched.push(src.id);
- if (opts.jsonMode) {
- emit(JSON.stringify({
- event: 'dispatched',
- job_id: job.id,
- mode: 'per_source',
- source_id: src.id,
- pull: shouldPull,
- slot: opts.slot,
- }));
+ if (job.coalesced) {
+ coalesced.push(src.id);
+ if (opts.jsonMode) {
+ emit(JSON.stringify({
+ event: 'dispatch_coalesced',
+ job_id: job.id,
+ mode: 'per_source',
+ source_id: src.id,
+ slot: opts.slot,
+ }));
+ } else {
+ log(`[dispatch] coalesced onto job #${job.id} autopilot-cycle source=${src.id} (already in flight)`);
+ }
} else {
- log(`[dispatch] job #${job.id} autopilot-cycle source=${src.id}${shouldPull ? ' pull=yes' : ''}`);
+ dispatched.push(src.id);
+ if (opts.jsonMode) {
+ emit(JSON.stringify({
+ event: 'dispatched',
+ job_id: job.id,
+ mode: 'per_source',
+ source_id: src.id,
+ pull: shouldPull,
+ slot: opts.slot,
+ }));
+ } else {
+ log(`[dispatch] job #${job.id} autopilot-cycle source=${src.id}${shouldPull ? ' pull=yes' : ''}`);
+ }
}
} catch (e) {
// Per-source submit failure does NOT abort the tick (codex E1 F1
@@ -524,6 +560,7 @@ export async function dispatchPerSource(
return {
dispatched,
+ coalesced,
skipped_fresh: skippedFresh.map(s => s.id),
skipped_cap: skippedCap.map(s => s.id),
skipped_cooldown: skippedCooldown.map(s => s.id),
@@ -546,16 +583,18 @@ export function isGlobalMaintenanceStale(lastGlobalAtIso: string | null, now = D
* #2194 fix #3 / #2227 bug #3 — dispatch the single brain-wide maintenance job
* that runs the `global` cycle phases (embed, orphans, purge, …) ONCE per
* window, instead of N per-source cycles each running them concurrently (the
- * RSS blowout). Single-flight is structural: one `idempotency_key` +
- * `maxWaiting:1`, so a slow run never stacks. Gated on `autopilot.last_global_at`
- * (stamped by the handler on success). Postgres-only fan-out concern; on PGLite
- * the file lock already serializes, but the job is still correct there.
+ * RSS blowout). Single-flight is structural: one `idempotency_key` per slot +
+ * `maxPending:1` (an in-flight waiting/live-lock-active run suppresses
+ * re-dispatch even across slot rotation), so a slow run never stacks. Gated on
+ * `autopilot.last_global_at` (stamped by the handler on success). Postgres-only
+ * fan-out concern; on PGLite the file lock already serializes, but the job is
+ * still correct there.
*/
export async function dispatchGlobalMaintenance(
engine: BrainEngine,
queue: MinionQueue,
opts: { repoPath: string; slot: string; timeoutMs: number; jsonMode: boolean; emit?: (l: string) => void; log?: (l: string) => void },
-): Promise<{ dispatched: boolean; reason: 'stale' | 'fresh' }> {
+): Promise<{ dispatched: boolean; coalesced?: boolean; reason: 'stale' | 'fresh' }> {
const emit = opts.emit ?? ((line) => process.stderr.write(line + '\n'));
const log = opts.log ?? ((line) => console.log(line));
@@ -575,14 +614,26 @@ export async function dispatchGlobalMaintenance(
{ repoPath: opts.repoPath, phases: GLOBAL_PHASES },
{
queue: 'default',
- // Structural single-flight: one global job per slot; maxWaiting:1 coalesces
- // any surplus so a slow brain-wide pass never stacks duplicates.
+ // Structural single-flight: one global job per slot; maxPending:1
+ // coalesces any surplus — including across slot rotation while a slow
+ // brain-wide pass is still in flight — so duplicates never stack.
idempotency_key: `autopilot-global:${opts.slot}`,
max_attempts: 2,
timeout_ms: opts.timeoutMs,
- maxWaiting: 1,
+ maxPending: 1,
},
);
+ if (job.coalesced) {
+ if (opts.jsonMode) {
+ emit(JSON.stringify({ event: 'dispatch_coalesced', job_id: job.id, mode: 'global_maintenance', slot: opts.slot }));
+ } else {
+ log(`[dispatch] coalesced onto job #${job.id} autopilot-global-maintenance (already in flight)`);
+ }
+ // dispatched: false — no row was inserted (same honest-dispatch contract
+ // as dispatchPerSource, where coalesced sources are excluded from
+ // `dispatched`). The coalesced flag says work is already in flight.
+ return { dispatched: false, coalesced: true, reason: 'stale' };
+ }
if (opts.jsonMode) {
emit(JSON.stringify({ event: 'dispatched', job_id: job.id, mode: 'global_maintenance', slot: opts.slot }));
} else {
diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.ts
index 3f27cb21fd..b0777335b8 100644
--- a/src/commands/autopilot.ts
+++ b/src/commands/autopilot.ts
@@ -1209,13 +1209,19 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
// source timestamps say every source is fresh, advance the local
// clock too; otherwise a non-empty targeted plan would be skipped
// on every tick until the persisted 60-minute window elapsed.
- if (result.dispatched.length > 0 || result.legacy_fallback || result.all_sources_fresh) {
+ // Coalesced counts as work-in-flight: before dispatched/coalesced
+ // split, a coalesced submission advanced this clock via dispatched —
+ // keep that behavior, or an all-coalesced tick (single-flight
+ // suppression) would retake the full-cycle branch every tick and
+ // starve the targeted-plan path for the whole in-flight window.
+ if (result.dispatched.length > 0 || result.coalesced.length > 0 || result.legacy_fallback || result.all_sources_fresh) {
lastFullCycleAt = Date.now();
}
if (jsonMode) {
process.stderr.write(JSON.stringify({
event: 'fanout_summary',
dispatched: result.dispatched,
+ coalesced: result.coalesced,
skipped_fresh: result.skipped_fresh,
skipped_cap: result.skipped_cap,
skipped_cooldown: result.skipped_cooldown,
@@ -1225,7 +1231,8 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
}) + '\n');
} else if (!result.legacy_fallback) {
console.log(
- `[dispatch] fanout: ${result.dispatched.length} dispatched, ` +
+ `[dispatch] fanout: ${result.dispatched.length} dispatched` +
+ `${result.coalesced.length > 0 ? ` (${result.coalesced.length} coalesced onto in-flight)` : ''}, ` +
`${result.skipped_fresh.length} fresh, ${result.skipped_cap.length} capped, ` +
`${result.skipped_cooldown.length} cooldown ` +
`(score=${score}, max=${fanoutMax})`,
@@ -1254,7 +1261,16 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
submitOpts,
isProtected ? { allowProtectedSubmit: true } : undefined,
);
- if (jsonMode) {
+ // Honest-dispatch contract (same as the fanout paths): a
+ // coalesced submission never claims a dispatch that didn't
+ // insert a row.
+ if (job.coalesced) {
+ if (jsonMode) {
+ process.stderr.write(JSON.stringify({ event: 'dispatch_coalesced', job_id: job.id, mode: 'targeted', step: step.id, score, plan_size: plan.length }) + '\n');
+ } else {
+ console.log(`[dispatch] coalesced onto job #${job.id} ${step.job} (targeted: ${step.id}; already in flight)`);
+ }
+ } else if (jsonMode) {
process.stderr.write(JSON.stringify({ event: 'dispatched', job_id: job.id, mode: 'targeted', step: step.id, score, plan_size: plan.length }) + '\n');
} else {
console.log(`[dispatch] job #${job.id} ${step.job} (targeted: ${step.id}; score=${score})`);
diff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.ts
index 744edca691..b4c164cca6 100644
--- a/src/commands/bootstrap.ts
+++ b/src/commands/bootstrap.ts
@@ -1350,7 +1350,9 @@ export async function runBootstrap(args: string[], opts: RunBootstrapOpts = {}):
// interview) never falls through into the real operation, regardless of
// what other flags/values precede it in `rest`. No install-log entry
// either — this isn't a phase run.
- if (SUBCOMMAND_HELP[sub] && hasHelpToken(rest, sub !== 'interview')) {
+ if (Object.hasOwn(SUBCOMMAND_HELP, sub) && hasHelpToken(rest, sub !== 'interview')) {
+ // Object.hasOwn: a plain-object lookup resolves inherited keys, so
+ // `bootstrap constructor --help` would print Object.prototype.constructor.
console.log(SUBCOMMAND_HELP[sub]);
return 0;
}
diff --git a/src/commands/jobs.ts b/src/commands/jobs.ts
index 8490a3dfc6..e5b2ef7b83 100644
--- a/src/commands/jobs.ts
+++ b/src/commands/jobs.ts
@@ -12,6 +12,7 @@ import type { PaceKeyOverrides } from '../core/pace-mode.ts';
import { loadConfig, isThinClient } from '../core/config.ts';
import { callRemoteTool, unpackToolResult } from '../core/mcp-client.ts';
import { parseNiceValue, applyNiceness, getEffectiveNiceness, formatNice } from '../core/minions/niceness.ts';
+import { defaultTimeoutMsFor } from '../core/minions/handler-timeouts.ts';
function parseFlag(args: string[], flag: string): string | undefined {
const idx = args.indexOf(flag);
@@ -163,6 +164,7 @@ export function resolveWorkerConcurrency(args: string[], env: NodeJS.ProcessEnv
*/
const JOB_DATE_FIELDS = [
'created_at', 'updated_at', 'started_at', 'finished_at', 'lock_until', 'delay_until',
+ 'timeout_at',
] as const;
export function rehydrateJobDates<T>(job: T): T {
@@ -187,12 +189,41 @@ function formatJob(job: MinionJob): string {
return ` ${String(job.id).padEnd(6)} ${job.name.padEnd(14)} ${(job.status + stalled).padEnd(20)} ${job.queue.padEnd(10)} ${dur.padEnd(8)} ${job.created_at.toISOString().slice(0, 19)}`;
}
-function formatJobDetail(job: MinionJob): string {
+/** Render a timestamp that is a Date locally but may arrive as an ISO string
+ * on the thin-client path against an OLDER server (rehydrateJobDates only
+ * converts fields it knows about; a field the peer predates stays a string).
+ * Never call .toISOString() unguarded on wire-shaped job fields. */
+function formatWhen(v: Date | string | null | undefined): string {
+ if (v instanceof Date) return v.toISOString();
+ return String(v ?? '');
+}
+
+/** The effective wall-clock budget line for `jobs get`. Wording matters: the
+ * 1x deadline (handleTimeouts, stamped at claim) is the NORMAL kill; the 2x
+ * wall-clock sweep is the lock-state-agnostic backstop. */
+function formatTimeoutLines(job: MinionJob): string[] {
+ const lines: string[] = [];
+ if (job.timeout_ms != null) {
+ lines.push(` Timeout: ${job.timeout_ms}ms (deadline kill at 1x when claimed; wall-clock backstop at 2x)`);
+ if (job.timeout_at) lines.push(` Deadline: ${formatWhen(job.timeout_at)}`);
+ } else {
+ const d = defaultTimeoutMsFor(job.name);
+ if (d != null) {
+ lines.push(` Timeout: (unset) — handler default ${d}ms stamps at claim`);
+ } else {
+ lines.push(` Timeout: (unset) — null-default wall-clock sweep applies (2 x lock-duration x max_stalled, ~5m at defaults)`);
+ }
+ }
+ return lines;
+}
+
+export function formatJobDetail(job: MinionJob): string {
const lines = [
`Job #${job.id}: ${job.name} (${job.status.toUpperCase()}${job.status === 'dead' ? ` after ${job.attempts_made} attempts` : ''})`,
` Queue: ${job.queue} | Priority: ${job.priority}`,
` Attempts: ${job.attempts_made}/${job.max_attempts} (started: ${job.attempts_started}, stalled: ${job.stalled_counter}/${job.max_stalled})`,
` Backoff: ${job.backoff_type} ${job.backoff_delay}ms (jitter: ${job.backoff_jitter})`,
+ ...formatTimeoutLines(job),
];
if (job.started_at) lines.push(` Started: ${job.started_at.toISOString()}`);
if (job.finished_at) lines.push(` Finished: ${job.finished_at.toISOString()}`);
@@ -210,25 +241,13 @@ function formatJobDetail(job: MinionJob): string {
return lines.join('\n');
}
-export async function runJobs(engineOrNull: BrainEngine | null, args: string[]): Promise<void> {
- const sub = args[0];
-
- // Thin-client dispatch (cli.ts) passes engine=null for the subcommands
- // with remote MCP routing (`list`, `get`) so no scratch local engine is
- // ever built. Any other subcommand arriving with a null engine is a
- // routing bug upstream of this function — refuse instead of crashing
- // inside MinionQueue.
- if (!engineOrNull && sub !== 'list' && sub !== 'get') {
- console.error(`\`gbrain jobs ${sub ?? ''}\` needs a local engine and cannot run on a thin client.`);
- process.exit(1);
- }
- // Null only ever reaches the MCP-routed `list`/`get` branches, which
- // never touch the engine — narrowed once here so the host-only cases
- // below typecheck unchanged.
- const engine = engineOrNull as BrainEngine;
-
- if (!sub || sub === '--help' || sub === '-h') {
- console.log(`gbrain jobs — Minions job queue
+/**
+ * The full jobs help block. Hoisted to a constant so `gbrain jobs --help`
+ * (routed engine-free via cli.ts SELF_HELP_WITHOUT_ENGINE) and bare
+ * `gbrain jobs` print the same text. Issue: jobs --help used to print the
+ * generic CLI stub because 'jobs' was missing from CLI_ONLY_SELF_HELP.
+ */
+const JOBS_HELP = `gbrain jobs — Minions job queue
USAGE
gbrain jobs submit <name> [--params JSON] [--follow] [--priority N]
@@ -245,8 +264,9 @@ USAGE
gbrain jobs retry <id>
gbrain jobs prune [--older-than 30d] [--dry-run]
gbrain jobs delete <id>
- gbrain jobs stats
- gbrain jobs smoke
+ gbrain jobs stats [--queue Q] [--cluster-errors]
+ 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]
[--health-interval MS] [--nice N]
gbrain jobs supervisor [start] [--detach] [--json]
@@ -266,8 +286,9 @@ USAGE
Auto-restarting wrapper around 'gbrain jobs work'. Spawns the worker
as a child process and restarts on crash with exponential backoff
- (1s -> 60s cap). Writes a PID file to ~/.gbrain/supervisor.pid by
- default (override via --pid-file or GBRAIN_SUPERVISOR_PID_FILE env).
+ (1s -> 60s cap). Writes a brain-scoped PID file to
+ ~/.gbrain/supervisor-<brain-id>.pid by default (override via
+ --pid-file or GBRAIN_SUPERVISOR_PID_FILE env).
Lifecycle events are appended to
\${GBRAIN_AUDIT_DIR:-~/.gbrain/audit}/supervisor-YYYY-Www.jsonl
@@ -305,10 +326,170 @@ HANDLER TYPES (built in)
shell Run a command or argv. Requires GBRAIN_ALLOW_SHELL_JOBS=1
on the worker. Params: {cmd?, argv?, cwd, env?}.
See: docs/guides/minions-shell-jobs.md
-`);
+
+Detailed help: gbrain jobs {work|supervisor|submit|watch|prune} --help
+Other subcommands are fully described above.
+`;
+
+/**
+ * Per-subcommand help for the flag-heavy / side-effectful subcommands.
+ * Pattern from bootstrap.ts SUBCOMMAND_HELP: the guard below prints these
+ * BEFORE the switch, so \`jobs work --help\` can never start a worker
+ * daemon (the defect class this record exists to prevent). Subcommands
+ * without an entry fall back to JOBS_HELP, which documents them fully.
+ */
+const JOBS_SUBCOMMAND_HELP: Record<string, string> = {
+ work: `gbrain jobs work — start a worker daemon (Postgres only)
+
+USAGE
+ gbrain jobs work [--queue Q] [--concurrency N] [--max-rss MB]
+ [--health-interval MS] [--nice N]
+
+OPTIONS
+ --queue Q Queue to claim from (default: default)
+ --concurrency N Max jobs in flight. Resolution: flag, then
+ GBRAIN_WORKER_CONCURRENCY env, then 1. Values < 1
+ are clamped to 1 with a loud stderr note.
+ --max-rss MB RSS watchdog. Absent: auto-sized to 50% of
+ min(cgroup limit, host RAM), capped at 16384 MB,
+ raised to a 4096 MB floor when the basis allows.
+ 0 disables the watchdog. Values 1-255 are rejected
+ (megabytes, not gigabytes — unit-confusion guard).
+ --health-interval MS Health probe cadence (default 60000). 0 disables.
+ Values 1-999 are rejected as unit confusion.
+ Under GBRAIN_SUPERVISED=1 stall detection is off;
+ the DB probe stays.
+ --nice N OS scheduling priority, -20 (highest) to 19
+ (nicest). Env fallback: GBRAIN_NICE; flag wins.
+ Negative values need root.
+
+NOTES
+ Requires the Postgres engine — PGLite's exclusive file lock cannot host
+ a long-lived daemon. For crash-resilient operation prefer:
+ gbrain jobs supervisor start --detach --json
+`,
+ supervisor: `gbrain jobs supervisor — auto-restarting wrapper around 'gbrain jobs work'
+
+USAGE
+ gbrain jobs supervisor [start] [--detach] [--json]
+ [--concurrency N] [--queue Q] [--pid-file PATH]
+ [--max-crashes N] [--health-interval N]
+ [--allow-shell-jobs] [--cli-path PATH]
+ [--max-rss MB] [--nice N]
+ gbrain jobs supervisor status [--json] [--pid-file PATH]
+ gbrain jobs supervisor stop [--json] [--pid-file PATH]
+
+OPTIONS (start)
+ --detach Fork and print {event, supervisor_pid, pid_file} JSON
+ --json JSONL lifecycle events on stdout
+ --concurrency N Worker concurrency (default 2)
+ --queue Q Queue to claim from (default: default)
+ --pid-file PATH PID file (default: brain-scoped
+ ~/.gbrain/supervisor-<brain-id>.pid;
+ env GBRAIN_SUPERVISOR_PID_FILE)
+ --max-crashes N Soft crash threshold (default 10): past N crashes in
+ 24h the supervisor reports degraded and keeps backing
+ off. It only STOPS permanently at the hard ceiling —
+ default 10 x N; override or disable (0 = never) via
+ GBRAIN_SUPERVISOR_HARD_STOP_CRASHES.
+ --health-interval N Worker health probe cadence in ms
+ --allow-shell-jobs Enable the shell handler on the spawned worker
+ --cli-path PATH Explicit gbrain binary for the worker child
+ --max-rss MB RSS watchdog for the worker (same rules as jobs work)
+ --nice N OS priority for supervisor + worker children
+
+EXIT CODES (start)
+ 0 clean shutdown 1 max crashes exceeded
+ 2 another supervisor holds the PID lock 3 PID file unwritable
+ 4 DB queue lock lost (repeated refresh failures; restart re-acquires)
+`,
+ submit: `gbrain jobs submit — enqueue a background job
+
+USAGE
+ gbrain jobs submit <name> [--params JSON] [--follow] [--priority N]
+ [--delay Nms] [--max-attempts N] [--max-stalled N]
+ [--max-waiting N]
+ [--backoff-type fixed|exponential] [--backoff-delay Nms]
+ [--backoff-jitter 0..1] [--timeout-ms Nms]
+ [--idempotency-key K] [--queue Q] [--dry-run]
+ [--redact-secrets]
+
+OPTIONS
+ --params JSON Job payload (handler-specific; see HANDLER TYPES in
+ 'gbrain jobs --help')
+ --follow Run inline and stream progress (constructs a real
+ worker; works on both engines)
+ --priority N Lower runs first (default 0)
+ --delay Nms Delay before the job becomes claimable (default 0)
+ --max-attempts N Retry budget (default 3)
+ --max-stalled N Stall-requeue budget before dead-letter (default 5)
+ --max-waiting N Backpressure: cap waiting jobs with this name/queue/
+ source before coalescing new submissions ([1,100])
+ --timeout-ms Nms Per-job wall-clock budget. Long-lane handlers get a
+ default from HANDLER_DEFAULT_TIMEOUT_MS when omitted.
+ --idempotency-key K At-most-one row per key (dead/cancelled free the key)
+ --queue Q Target queue (default: default)
+ --dry-run Print what would be submitted, submit nothing
+ --redact-secrets (shell jobs) scrub inherited env values from output
+`,
+ watch: `gbrain jobs watch — live queue dashboard
+
+USAGE
+ gbrain jobs watch [--json] [--follow] [--refresh-ms=N]
+
+OPTIONS
+ --json JSON snapshots instead of the human dashboard
+ --follow Keep refreshing (default: on for TTY, off otherwise)
+ --refresh-ms=N Refresh cadence in ms (default 1000). Equals form only —
+ 'watch' does not accept a space-separated value.
+`,
+ prune: `gbrain jobs prune — delete old terminal jobs
+
+USAGE
+ gbrain jobs prune [--older-than 30d] [--dry-run]
+
+OPTIONS
+ --older-than AGE Delete completed/failed/dead/cancelled jobs older than
+ AGE in days (default 30d; bare N or Nd — hour forms
+ are not supported)
+ --dry-run Report what would be deleted without deleting
+`,
+};
+
+export async function runJobs(engineOrNull: BrainEngine | null, args: string[]): Promise<void> {
+ const sub = args[0];
+
+ // Help guards run BEFORE the thin-client refusal below: cli.ts routes
+ // `jobs … --help` here engine-free (SELF_HELP_WITHOUT_ENGINE), and help
+ // must never require an engine — or worse, fall through to a subcommand
+ // body and start a real daemon. Only --help/-h are recognized; the bare
+ // word 'help' is NOT (e.g. `jobs submit help` is a legitimate job name).
+ if (!sub || sub === '--help' || sub === '-h') {
+ console.log(JOBS_HELP);
+ return;
+ }
+ if (args.slice(1).includes('--help') || args.slice(1).includes('-h')) {
+ // Object.hasOwn: a plain-object lookup resolves inherited keys, so
+ // `jobs constructor --help` (toString/valueOf/…) would print the
+ // Object.prototype function instead of falling back to the full help.
+ console.log(Object.hasOwn(JOBS_SUBCOMMAND_HELP, sub) ? JOBS_SUBCOMMAND_HELP[sub] : JOBS_HELP);
return;
}
+ // Thin-client dispatch (cli.ts) passes engine=null for the subcommands
+ // with remote MCP routing (`list`, `get`) so no scratch local engine is
+ // ever built. Any other subcommand arriving with a null engine is a
+ // routing bug upstream of this function — refuse instead of crashing
+ // inside MinionQueue.
+ if (!engineOrNull && sub !== 'list' && sub !== 'get') {
+ console.error(`\`gbrain jobs ${sub ?? ''}\` needs a local engine and cannot run on a thin client.`);
+ process.exit(1);
+ }
+ // Null only ever reaches the MCP-routed `list`/`get` branches, which
+ // never touch the engine — narrowed once here so the host-only cases
+ // below typecheck unchanged.
+ const engine = engineOrNull as BrainEngine;
+
// The constructor just stores the reference; on the null (thin-client
// list/get) paths no queue method is ever reached.
const queue = new MinionQueue(engine);
@@ -720,6 +901,67 @@ HANDLER TYPES (built in)
` gbrain jobs retry <id> # for dead-lettered jobs`,
);
}
+
+ // Backpressure visibility: maxPending suppression keeps `waiting` at 0
+ // while a job is in flight, which silences the waiting>0 wedge line
+ // above — the exact operator-confusion cost of the duplicate-cycle
+ // incident. Surface the last 24h of coalesce events (per name, this
+ // queue) from the backpressure audit JSONL, plus a hint naming the
+ // in-flight job when a name shows suppression with zero waiting rows
+ // and a stale live-lock active. Best-effort: unreadable audit files
+ // simply omit the line.
+ try {
+ const { readRecentCoalesceCounts } = await import('../core/minions/backpressure-audit.ts');
+ const coalesceCounts = readRecentCoalesceCounts({ queue: statsQueue, windowMs: 24 * 3600_000 });
+ if (coalesceCounts.size > 0) {
+ // Sort once, reuse for the summary AND the hint slice — slicing
+ // insertion order would let low-volume early-in-file names crowd
+ // out the highest-volume (most likely wedged) ones the summary
+ // line just highlighted.
+ const sortedCoalesces = [...coalesceCounts.entries()]
+ .sort((a, b) => b[1].count - a[1].count);
+ const parts = sortedCoalesces.map(([name, s]) => `${name}: ${s.count}`);
+ console.log(`\n Backpressure (24h): submissions coalesced onto in-flight jobs — ${parts.join(', ')}`);
+ // Hint loop is bounded: names come from the 24h audit window
+ // (normally a handful), capped defensively — this is an
+ // operator-invoked diagnostic, not a hot path. Each hint is
+ // driven by the LATEST coalesce target for the name (the audit's
+ // returned_job_id), scoped to that job's source — a name-wide
+ // aggregate would let source A's waiting row mask source B's
+ // wedge, or name A's job for B's coalesce (multi-source brains).
+ const hints = sortedCoalesces.slice(0, 10);
+ for (const [name, summary] of hints) {
+ if (summary.last_returned_job_id == null) continue;
+ // The target CTE re-checks name+queue: the audit dir is shared
+ // across brains in one GBRAIN_HOME, so an id from another
+ // brain's audit trail must fail the match here rather than
+ // name an unrelated job as the suppressor.
+ const rows = await engine.executeRaw<{ waiting: string; live_id: string | null; age_min: string | null }>(
+ `WITH target AS (
+ SELECT id, started_at, status, lock_until,
+ COALESCE(data->>'sourceId', data->>'source_id') AS scope
+ FROM minion_jobs WHERE id = $3 AND name = $1 AND queue = $2
+ )
+ SELECT (SELECT count(*)::text FROM minion_jobs m, target t
+ WHERE m.name = $1 AND m.queue = $2 AND m.status = 'waiting'
+ AND COALESCE(m.data->>'sourceId', m.data->>'source_id') IS NOT DISTINCT FROM t.scope) AS waiting,
+ (SELECT id::text FROM target WHERE status = 'active' AND lock_until > now()) AS live_id,
+ (SELECT floor(EXTRACT(EPOCH FROM (now() - started_at)) / 60)::text FROM target
+ WHERE status = 'active' AND lock_until > now()) AS age_min`,
+ [name, statsQueue, summary.last_returned_job_id],
+ );
+ const r = rows[0];
+ const ageMin = r?.age_min != null ? parseInt(r.age_min, 10) : null;
+ if (r && parseInt(r.waiting ?? '0', 10) === 0 && r.live_id != null && ageMin != null && ageMin > wedgeMins) {
+ console.log(
+ ` ${name}: dispatch suppressed by in-flight job #${r.live_id} (age ${ageMin}m) — check \`gbrain jobs get ${r.live_id}\``,
+ );
+ }
+ }
+ }
+ } catch {
+ // Audit read is advisory; never break stats.
+ }
}
// v0.41 Bug 2 / Eng D8 — surface lease pressure to the operator.
diff --git a/src/core/migrate.ts b/src/core/migrate.ts
index cf11e8ce6c..073595214c 100644
--- a/src/core/migrate.ts
+++ b/src/core/migrate.ts
@@ -5710,6 +5710,90 @@ export const MIGRATIONS: Migration[] = [
ON minion_jobs (queue, status, updated_at);
`,
},
+ {
+ version: 128,
+ name: 'minion_jobs_timeout_backfill_and_duplicate_cycle_cleanup',
+ // Jobs fix wave (upstream issues #2/#3) — two one-shot repairs for rows
+ // that predate the fixes shipping alongside this migration:
+ //
+ // 1. HANDLER_DEFAULT_TIMEOUT_MS backfill. Submit-time stamping (#1737)
+ // never touched already-queued rows, so their timeout_ms = NULL fell
+ // to the minutes-scale null-default wall-clock sweep and long handlers
+ // were dead-lettered mid-progress. Values are SNAPSHOTTED at authoring
+ // time — deliberately NOT generated from the live map, so every brain
+ // applies identical SQL under this version number; the claim-time
+ // COALESCE in MinionQueue.claim owns all future drift. Do NOT sync
+ // this list when handler-timeouts.ts changes. No timeout_at stamp for
+ // already-active rows: that would arm the tighter 1x handleTimeouts
+ // kill mid-flight; the 2x wall-clock bound (via non-NULL timeout_ms)
+ // is the gentler, sufficient repair, and every future claim stamps
+ // timeout_at correctly.
+ //
+ // 2. Duplicate autopilot-cycle backlog cleanup. The slot-scoped dispatch
+ // guards accumulated byte-identical waiting cycles when a job stalled
+ // in 'active' (unbounded — one observed brain held ~111). Cancel all
+ // but the newest waiting row per (name, queue, source scope),
+ // restricted to ticker-keyed rows (idempotency-key prefix heuristic:
+ // manually submitted cycles carry no key unless the operator passes
+ // one; mimicking the ticker prefix opts into ticker dedup semantics)
+ // AND to rows without a camelCase data.sourceId — the ticker only
+ // ever writes snake_case source_id, so a sourceId row is by
+ // definition not ticker-provenance and must never be swept
+ // (adversarial-review tightening: prevents distinct sourceId scopes
+ // collapsing into the empty source_id group).
+ // Rows are preserved as 'cancelled' for audit; their idempotency keys
+ // free naturally via the dead/cancelled key-NULLing rule in add().
+ // Leaves <=1 waiting (+ possibly 1 active) per scope — converges to
+ // single-flight within one wall-clock window; the maxPending guard
+ // (shipped with this wave) prevents new accumulation.
+ //
+ // Non-terminal status set + row-lock race-safety per the v15 precedent
+ // (serializes against claim()'s FOR UPDATE SKIP LOCKED). Idempotent:
+ // statement 1 re-runs match zero rows (timeout_ms IS NULL guard);
+ // statement 2 re-runs keep only survivors.
+ idempotent: true,
+ sql: `
+ UPDATE minion_jobs
+ SET timeout_ms = CASE name
+ WHEN 'subagent' THEN 1800000
+ WHEN 'subagent_aggregator' THEN 1800000
+ WHEN 'embed-backfill' THEN 1800000
+ WHEN 'autopilot-cycle' THEN 1800000
+ WHEN 'autopilot-global-maintenance' THEN 1800000
+ WHEN 'chronicle_extract' THEN 600000
+ WHEN 'facts-absorb' THEN 600000
+ WHEN 'contextual_reindex_per_chunk' THEN 3600000
+ END,
+ updated_at = now()
+ WHERE timeout_ms IS NULL
+ AND status IN ('waiting','active','delayed','waiting-children','paused')
+ AND name IN ('subagent','subagent_aggregator','embed-backfill',
+ 'autopilot-cycle','autopilot-global-maintenance',
+ 'chronicle_extract','facts-absorb',
+ 'contextual_reindex_per_chunk');
+
+ UPDATE minion_jobs
+ SET status = 'cancelled',
+ finished_at = now(),
+ updated_at = now(),
+ error_text = 'v128: superseded duplicate autopilot cycle'
+ WHERE status = 'waiting' AND parent_job_id IS NULL
+ AND name IN ('autopilot-cycle','autopilot-global-maintenance')
+ AND (idempotency_key LIKE 'autopilot-cycle:%' OR idempotency_key LIKE 'autopilot-global:%')
+ AND data->>'sourceId' IS NULL
+ AND id NOT IN (
+ SELECT id FROM (
+ SELECT DISTINCT ON (name, queue, COALESCE(data->>'source_id','')) id
+ FROM minion_jobs
+ WHERE status = 'waiting' AND parent_job_id IS NULL
+ AND name IN ('autopilot-cycle','autopilot-global-maintenance')
+ AND (idempotency_key LIKE 'autopilot-cycle:%' OR idempotency_key LIKE 'autopilot-global:%')
+ AND data->>'sourceId' IS NULL
+ ORDER BY name, queue, COALESCE(data->>'source_id',''), created_at DESC, id DESC
+ ) keep
+ );
+ `,
+ },
];
export const LATEST_VERSION = MIGRATIONS.length > 0
diff --git a/src/core/minions/backpressure-audit.ts b/src/core/minions/backpressure-audit.ts
index 57173749a7..a573a85d22 100644
--- a/src/core/minions/backpressure-audit.ts
+++ b/src/core/minions/backpressure-audit.ts
@@ -1,5 +1,6 @@
/**
- * Backpressure audit log — operational trace for `maxWaiting` coalesce events.
+ * Backpressure audit log — operational trace for `maxWaiting` AND `maxPending`
+ * coalesce events.
*
* Mirrors the shell-audit.ts pattern (ISO-week-rotated JSONL, best-effort writes,
* failures go to stderr but never block submission). The incident that motivated
@@ -8,12 +9,16 @@
* trail answers "why is queue depth steady at 2 for this name?" without any
* doctor scan.
*
+ * A maxWaiting event carries waiting_count/max_waiting; a maxPending event
+ * carries pending_count/max_pending. Both use decision:'coalesced'.
+ *
* File: `~/.gbrain/audit/backpressure-YYYY-Www.jsonl` (override dir via
* `GBRAIN_AUDIT_DIR` for container/sandbox deployments where `$HOME` is read-only).
*
- * `gbrain jobs stats` will surface coalesce counts from this file in a v0.19.2+
- * follow-up (B4). The audit trail is for operators debugging live queues, not
- * for compliance — a disk-full attacker can silently disable it.
+ * `gbrain jobs stats` surfaces a 24h coalesce summary from this file (the
+ * Backpressure line); deeper per-decision history stays a follow-up. The audit
+ * trail is for operators debugging live queues, not for compliance — a
+ * disk-full attacker can silently disable it.
*/
import * as fs from 'node:fs';
@@ -24,8 +29,12 @@ export interface BackpressureAuditEvent {
ts: string;
queue: string;
name: string;
- waiting_count: number;
- max_waiting: number;
+ /** Present on maxWaiting coalesce events. */
+ waiting_count?: number;
+ max_waiting?: number;
+ /** Present on maxPending (single-flight) coalesce events. */
+ pending_count?: number;
+ max_pending?: number;
decision: 'coalesced';
returned_job_id: number;
}
@@ -57,6 +66,89 @@ export function resolveAuditDir(): string {
return gbrainPath('audit');
}
+/**
+ * Per-name coalesce counts within the window, for `jobs stats`.
+ *
+ * Reads the CURRENT and PREVIOUS ISO-week files — a 24h window crosses the
+ * week boundary for the first day of each ISO week, and a one-file read
+ * would silently under-count exactly then. Filters to the queue the stats
+ * command is scoped to. Best-effort: missing/unreadable files and malformed
+ * lines are skipped; callers omit the display line when the map is empty.
+ */
+export interface CoalesceSummary {
+ count: number;
+ /** returned_job_id of the LATEST coalesce event in the window — the
+ * specific in-flight job submissions coalesced onto. Lets consumers
+ * (jobs stats) scope diagnostics to the actual target instead of
+ * aggregating across every source sharing the job name. */
+ last_returned_job_id: number | null;
+}
+
+export function readRecentCoalesceCounts(opts: {
+ queue: string;
+ windowMs: number;
+ now?: Date;
+}): Map<string, CoalesceSummary> {
+ const now = opts.now ?? new Date();
+ const dir = resolveAuditDir();
+ const cutoff = now.getTime() - opts.windowMs;
+ const files = new Set([
+ computeAuditFilename(now),
+ computeAuditFilename(new Date(now.getTime() - 7 * 86400000)),
+ ]);
+ const counts = new Map<string, CoalesceSummary>();
+ const latestTs = new Map<string, number>();
+ // Cap per-file reads: coalesce volume is caller-influenced (webhook-driven
+ // submitters can grow the weekly file), and the newest events — the ones a
+ // 24h window wants — are at the END. Reading an uncapped file into memory
+ // would let the audit trail OOM the diagnostic that reads it.
+ const MAX_READ_BYTES = 4 * 1024 * 1024;
+ for (const filename of files) {
+ let raw: string;
+ try {
+ const fullPath = path.join(dir, filename);
+ const size = fs.statSync(fullPath).size;
+ if (size > MAX_READ_BYTES) {
+ const fd = fs.openSync(fullPath, 'r');
+ try {
+ const buf = Buffer.alloc(MAX_READ_BYTES);
+ fs.readSync(fd, buf, 0, MAX_READ_BYTES, size - MAX_READ_BYTES);
+ raw = buf.toString('utf8');
+ // Drop the first (likely partial) line of the tail slice.
+ raw = raw.slice(raw.indexOf('\n') + 1);
+ } finally {
+ fs.closeSync(fd);
+ }
+ } else {
+ raw = fs.readFileSync(fullPath, 'utf8');
+ }
+ } catch {
+ continue; // missing file for that week — fine
+ }
+ for (const line of raw.split('\n')) {
+ if (!line.trim()) continue;
+ try {
+ const ev = JSON.parse(line) as BackpressureAuditEvent;
+ if (ev.decision !== 'coalesced') continue;
+ if (ev.queue !== opts.queue) continue;
+ const t = Date.parse(ev.ts);
+ if (!Number.isFinite(t) || t < cutoff || t > now.getTime()) continue;
+ const prev = counts.get(ev.name);
+ const entry: CoalesceSummary = prev ?? { count: 0, last_returned_job_id: null };
+ entry.count += 1;
+ if ((latestTs.get(ev.name) ?? -Infinity) <= t && typeof ev.returned_job_id === 'number') {
+ entry.last_returned_job_id = ev.returned_job_id;
+ latestTs.set(ev.name, t);
+ }
+ counts.set(ev.name, entry);
+ } catch {
+ // malformed line — skip
+ }
+ }
+ }
+ return counts;
+}
+
export function logBackpressureCoalesce(event: Omit<BackpressureAuditEvent, 'ts' | 'decision'>): void {
const dir = resolveAuditDir();
const filename = computeAuditFilename();
diff --git a/src/core/minions/handler-timeouts.ts b/src/core/minions/handler-timeouts.ts
index 4523664df3..9e4e97cc77 100644
--- a/src/core/minions/handler-timeouts.ts
+++ b/src/core/minions/handler-timeouts.ts
@@ -8,15 +8,21 @@
* inherit that short null-default and get wall-clock-killed mid-progress —
* one half of #1737's thrash.
*
- * Fix: known long handlers get a sane long default STAMPED ONTO THE JOB ROW
- * at submit time (see `MinionQueue.add`). Stamping at submit (not mutating at
- * claim) keeps the wall-clock behavior stable across worker restart — the
- * value lives in `minion_jobs.timeout_ms`, not in worker memory.
+ * Three layers apply the default (an explicit `opts.timeout_ms` always wins):
*
- * Existing already-queued jobs are NOT backfilled: they keep whatever
- * `timeout_ms` they were inserted with (usually NULL → the old behavior).
- * Only NEW submissions pick up the default. An explicit `opts.timeout_ms`
- * always wins.
+ * 1. SUBMIT — `MinionQueue.add` stamps the default onto the row. The value
+ * lives in `minion_jobs.timeout_ms`, not worker memory, so wall-clock
+ * behavior is stable across worker restart.
+ * 2. CLAIM — `MinionQueue.claim` COALESCEs a NULL `timeout_ms` from this
+ * map (and derives `timeout_at` from the coalesced value). This is the
+ * durable invariant: it covers rows inserted before layer 1 existed and
+ * any writer that bypasses add(). Persisted by the claim UPDATE, so the
+ * restart-stability property holds here too.
+ * 3. ONE-SHOT — migration v128 backfilled `timeout_ms` for non-terminal
+ * rows that predate both layers (they would otherwise never re-claim
+ * or die at the short null-default first). v128's values are a
+ * deliberate authoring-time SNAPSHOT of this map — do NOT sync v128
+ * when editing the map below; layer 2 owns all future drift.
*
* The 30-min anchor matches the explicit value cycle/patterns.ts already
* passes for subagent jobs, so this generalizes an existing convention
diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.ts
index 1c83343309..27c04dae0b 100644
--- a/src/core/minions/queue.ts
+++ b/src/core/minions/queue.ts
@@ -16,7 +16,7 @@ import type {
import { rowToMinionJob, rowToInboxMessage, rowToAttachment } from './types.ts';
import { validateAttachment } from './attachments.ts';
import { isProtectedJobName } from './protected-names.ts';
-import { defaultTimeoutMsFor } from './handler-timeouts.ts';
+import { defaultTimeoutMsFor, HANDLER_DEFAULT_TIMEOUT_MS } from './handler-timeouts.ts';
import {
withRetry, BULK_RETRY_OPTS, resolveBulkRetryOpts, computeNextDelay,
isRetryableConnError,
@@ -42,6 +42,33 @@ const DEFAULT_MAX_ATTACHMENT_BYTES = 5 * 1024 * 1024; // 5 MiB
const TERMINAL_STATUSES = ['completed', 'failed', 'dead', 'cancelled'] as const;
+/** Audit payload deferred from inside the submission transaction. */
+type CoalesceAuditEvent = {
+ queue: string; name: string; returned_job_id: number;
+ waiting_count?: number; max_waiting?: number;
+ pending_count?: number; max_pending?: number;
+};
+
+/** Shared cap-hit coalesce return for the backpressure guards: hydrate the
+ * existing row, stamp the non-persisted `coalesced` marker, hand the audit
+ * payload to the caller's sink, return. Both maxWaiting and maxPending route
+ * through here so the coalesce contract cannot drift between them.
+ *
+ * The sink DEFERS the audit write to after the transaction commits: the
+ * audit append is filesystem I/O, and doing it while holding the advisory
+ * lock + a pool connection would let a hung audit volume serialize every
+ * submission for the scope (adversarial-review finding). */
+function coalesceReturn(
+ row: Record<string, unknown>,
+ audit: Omit<CoalesceAuditEvent, 'returned_job_id'>,
+ sink: (ev: CoalesceAuditEvent) => void,
+): MinionJob {
+ const coalesced = rowToMinionJob(row);
+ coalesced.coalesced = true;
+ sink({ ...audit, returned_job_id: coalesced.id });
+ return coalesced;
+}
+
export class MinionQueue {
readonly maxSpawnDepth: number;
readonly maxAttachmentBytes: number;
@@ -129,7 +156,11 @@ export class MinionQueue {
const delayUntil = opts?.delay ? new Date(Date.now() + opts.delay) : null;
const maxSpawnDepth = opts?.max_spawn_depth ?? this.maxSpawnDepth;
- return this.engine.transaction(async (tx) => {
+ // Set inside the transaction by a cap-hit coalesce; flushed AFTER commit
+ // so audit filesystem I/O never runs while holding the advisory lock.
+ let coalesceAudit: CoalesceAuditEvent | null = null;
+
+ const result = await this.engine.transaction(async (tx) => {
// 1. Idempotency fast path — if a row already exists for this key, return it
// without doing any other work. The unique partial index guarantees
// no second row can be inserted with the same non-null key.
@@ -151,77 +182,120 @@ export class MinionQueue {
[existingJob.id]
);
} else {
+ existingJob.coalesced = true;
return existingJob;
}
}
}
// 1b. Submission-time backpressure for high-frequency named jobs.
- // If waiting jobs for this (name, queue) already hit maxWaiting, return
- // the most-recent waiting row instead of inserting another slot.
+ // Two guards share the advisory-lock machinery but differ in what they
+ // count and how they scope:
+ // - maxWaiting (rate cap): counts status='waiting' only. Source scope
+ // is NULL-as-wildcard — a submission with no source key counts ALL
+ // rows for (name, queue). Intentional; existing callers rely on it.
+ // - maxPending (single-flight): counts waiting rows PLUS live-lock
+ // active rows (lock_until > now()). An expired-lock active belongs
+ // to a dead/blocked worker and must NOT suppress dispatch — the
+ // fresh waiting row keeps feeding the waitingClaimable>0 wedge
+ // detectors (supervisor watchdog, jobs stats) that a suppressed
+ // queue would otherwise starve. Source scope is EXACT (NULL matches
+ // only NULL-source rows), so a legacy no-source dispatch can never
+ // coalesce into an arbitrary per-source row.
//
- // Correctness: two concurrent submitters could both see waitingCount <
- // maxWaiting and both insert, violating the cap. `pg_advisory_xact_lock`
- // keyed on (name, queue) serializes concurrent count+insert decisions
- // for the SAME key while leaving different keys fully parallel. The
- // lock releases on txn commit/rollback automatically — no cleanup path
- // to leak. Cost: one no-op SELECT on the hot path per coalesce-guarded
- // submission; trivial compared to the protection.
+ // Correctness: two concurrent submitters could both see count < cap and
+ // both insert, violating the cap. `pg_advisory_xact_lock` keyed on
+ // (name, queue, source) serializes concurrent count+insert decisions
+ // for the SAME scope while leaving other scopes fully parallel; both
+ // guards share the key namespace so maxWaiting and maxPending
+ // submitters for one scope serialize against each other. The lock
+ // releases on txn commit/rollback automatically — no cleanup path to
+ // leak.
//
- // Queue scope: the filter includes `queue=$2` so a waiting
+ // Queue scope: the filters include `queue=$2` so a waiting
// 'autopilot-cycle' in queue 'default' does NOT suppress submissions
- // to queue 'shell' with the same name. Pre-D2 code filtered on `name`
- // alone — a real cross-queue bleed that sequential tests missed.
+ // to queue 'shell' with the same name (pre-D2 cross-queue bleed).
//
// Engine compatibility: PGLite (WASM Postgres 17) supports
// pg_advisory_xact_lock, so this works on both engines without branching.
- if (opts?.maxWaiting !== undefined) {
- const maxWaiting = Math.max(1, Math.floor(opts.maxWaiting));
+ if (opts?.maxWaiting !== undefined || opts?.maxPending !== undefined) {
const backpressureQueue = opts?.queue ?? 'default';
// Multi-source scope: jobs of the same (name, queue) but different
- // data.sourceId are independent workstreams (per-source sync/cycle).
- // Counting them together made a waiting default-source sync swallow
- // every other source's freshness sync — a secondary source sat 29h stale
- // while dispatch logs showed its syncs "dispatched" (coalesced into
- // the default row). Key the lock and the count on sourceId when the
- // submission carries one; NULL keeps legacy single-scope behavior.
- const bpSourceId = typeof (data as Record<string, unknown> | undefined)?.sourceId === 'string'
- ? (data as Record<string, unknown>).sourceId as string
+ // source are independent workstreams (per-source sync/cycle). Counting
+ // them together made a waiting default-source sync swallow every other
+ // source's freshness sync. Both payload spellings are read: sync/
+ // webhook payloads carry camelCase sourceId; per-source autopilot
+ // payloads carry snake_case source_id.
+ const d = data as Record<string, unknown> | undefined;
+ const bpSourceId = typeof d?.sourceId === 'string' ? d.sourceId as string
+ : typeof d?.source_id === 'string' ? d.source_id as string
: null;
await tx.executeRaw(
`SELECT pg_advisory_xact_lock(hashtext('minion_maxwaiting:' || $1 || ':' || $2 || ':' || coalesce($3, '')))`,
[jobName, backpressureQueue, bpSourceId]
);
- const waitingCountRows = await tx.executeRaw<{ count: string }>(
- `SELECT count(*)::text AS count
- FROM minion_jobs
- WHERE name = $1 AND queue = $2 AND status = 'waiting'
- AND ($3::text IS NULL OR data->>'sourceId' IS NOT DISTINCT FROM $3)`,
- [jobName, backpressureQueue, bpSourceId]
- );
- const waitingCount = parseInt(waitingCountRows[0]?.count ?? '0', 10);
- if (waitingCount >= maxWaiting) {
- const existingWaiting = await tx.executeRaw<Record<string, unknown>>(
- `SELECT * FROM minion_jobs
+ const scopeExact = `COALESCE(data->>'sourceId', data->>'source_id') IS NOT DISTINCT FROM $3`;
+ const scopeWildcard = `($3::text IS NULL OR ${scopeExact})`;
+
+ // maxPending first: the stricter, in-flight-aware guard.
+ if (opts?.maxPending !== undefined) {
+ const maxPending = Math.max(1, Math.floor(opts.maxPending));
+ const pendingCond = `(status = 'waiting' OR (status = 'active' AND lock_until > now()))`;
+ const pendingCountRows = await tx.executeRaw<{ count: string }>(
+ `SELECT count(*)::text AS count
+ FROM minion_jobs
+ WHERE name = $1 AND queue = $2 AND ${pendingCond}
+ AND ${scopeExact}`,
+ [jobName, backpressureQueue, bpSourceId]
+ );
+ const pendingCount = parseInt(pendingCountRows[0]?.count ?? '0', 10);
+ if (pendingCount >= maxPending) {
+ const existingPending = await tx.executeRaw<Record<string, unknown>>(
+ `SELECT * FROM minion_jobs
+ WHERE name = $1 AND queue = $2 AND ${pendingCond}
+ AND ${scopeExact}
+ ORDER BY CASE WHEN status = 'waiting' THEN 0 ELSE 1 END, created_at DESC, id DESC
+ LIMIT 1`,
+ [jobName, backpressureQueue, bpSourceId]
+ );
+ if (existingPending.length > 0) {
+ return coalesceReturn(existingPending[0], {
+ queue: backpressureQueue,
+ name: jobName,
+ pending_count: pendingCount,
+ max_pending: maxPending,
+ }, ev => { coalesceAudit = ev; });
+ }
+ }
+ }
+
+ if (opts?.maxWaiting !== undefined) {
+ const maxWaiting = Math.max(1, Math.floor(opts.maxWaiting));
+ const waitingCountRows = await tx.executeRaw<{ count: string }>(
+ `SELECT count(*)::text AS count
+ FROM minion_jobs
WHERE name = $1 AND queue = $2 AND status = 'waiting'
- AND ($3::text IS NULL OR data->>'sourceId' IS NOT DISTINCT FROM $3)
- ORDER BY created_at DESC, id DESC
- LIMIT 1`,
+ AND ${scopeWildcard}`,
[jobName, backpressureQueue, bpSourceId]
);
- if (existingWaiting.length > 0) {
- const coalesced = rowToMinionJob(existingWaiting[0]);
- try {
- const { logBackpressureCoalesce } = await import('./backpressure-audit.ts');
- logBackpressureCoalesce({
+ const waitingCount = parseInt(waitingCountRows[0]?.count ?? '0', 10);
+ if (waitingCount >= maxWaiting) {
+ const existingWaiting = await tx.executeRaw<Record<string, unknown>>(
+ `SELECT * FROM minion_jobs
+ WHERE name = $1 AND queue = $2 AND status = 'waiting'
+ AND ${scopeWildcard}
+ ORDER BY created_at DESC, id DESC
+ LIMIT 1`,
+ [jobName, backpressureQueue, bpSourceId]
+ );
+ if (existingWaiting.length > 0) {
+ return coalesceReturn(existingWaiting[0], {
queue: backpressureQueue,
name: jobName,
waiting_count: waitingCount,
max_waiting: maxWaiting,
- returned_job_id: coalesced.id,
- });
- } catch { /* audit failures never block submission */ }
- return coalesced;
+ }, ev => { coalesceAudit = ev; });
+ }
}
}
}
@@ -330,7 +404,9 @@ export class MinionQueue {
if (existing.length === 0) {
throw new Error(`idempotency_key ${opts.idempotency_key} insert returned no row and no existing row found`);
}
- return rowToMinionJob(existing[0]);
+ const raced = rowToMinionJob(existing[0]);
+ raced.coalesced = true; // third coalesce path: lost the insert race
+ return raced;
}
const child = rowToMinionJob(inserted[0]);
@@ -347,6 +423,18 @@ export class MinionQueue {
return child;
});
+
+ // Deferred audit flush — after commit, advisory lock released, connection
+ // returned to the pool. A hung/slow audit volume degrades only this one
+ // submission's latency, never the queue.
+ if (coalesceAudit) {
+ try {
+ const { logBackpressureCoalesce } = await import('./backpressure-audit.ts');
+ logBackpressureCoalesce(coalesceAudit);
+ } catch { /* audit failures never block submission */ }
+ }
+
+ return result;
}
/** Get a job by ID. Returns null if not found. */
@@ -661,6 +749,18 @@ export class MinionQueue {
*
* Sets timeout_at = now() + timeout_ms when the job has a per-job deadline,
* so handleTimeouts() can dead-letter expired jobs without rereading timeout_ms.
+ *
+ * Claim-time budget fallback: rows inserted before the submit-time stamping
+ * (or by any writer that bypasses add()) carry timeout_ms = NULL and used to
+ * fall through to the minutes-scale null-default wall-clock sweep — a 30-min
+ * handler died at ~5 min purely because of WHEN its row was inserted. The
+ * COALESCE below resolves HANDLER_DEFAULT_TIMEOUT_MS at claim as the durable
+ * invariant (the v128 migration is the one-shot repair for rows already in
+ * flight). Names outside the map stay NULL — exactly today's behavior.
+ * Postgres evaluates SET expressions against the OLD row, so the timeout_at
+ * CASE must repeat the COALESCE rather than reference the assigned column.
+ * The map binds as a RAW object (never JSON.stringify into ::jsonb — the
+ * postgres.js double-encode trap; PGLite hides it, real PG does not).
*/
async claim(lockToken: string, lockDurationMs: number, queue: string, registeredNames: string[]): Promise<MinionJob | null> {
if (registeredNames.length === 0) return null;
@@ -673,8 +773,9 @@ export class MinionQueue {
status = 'active',
lock_token = $1,
lock_until = now() + ($2::double precision * interval '1 millisecond'),
- timeout_at = CASE WHEN timeout_ms IS NOT NULL
- THEN now() + (timeout_ms::double precision * interval '1 millisecond')
+ timeout_ms = COALESCE(timeout_ms, ($5::jsonb ->> name)::int),
+ timeout_at = CASE WHEN COALESCE(timeout_ms, ($5::jsonb ->> name)::int) IS NOT NULL
+ THEN now() + (COALESCE(timeout_ms, ($5::jsonb ->> name)::int)::double precision * interval '1 millisecond')
ELSE NULL END,
attempts_started = attempts_started + 1,
started_at = COALESCE(started_at, now()),
@@ -687,7 +788,7 @@ export class MinionQueue {
LIMIT 1
)
RETURNING *`,
- [lockToken, lockDurationMs, queue, registeredNames]
+ [lockToken, lockDurationMs, queue, registeredNames, HANDLER_DEFAULT_TIMEOUT_MS]
);
return rows.length > 0 ? rowToMinionJob(rows[0]) : null;
}
diff --git a/src/core/minions/types.ts b/src/core/minions/types.ts
index 7a1b5f08e6..e78d7d5001 100644
--- a/src/core/minions/types.ts
+++ b/src/core/minions/types.ts
@@ -90,6 +90,14 @@ export interface MinionJob {
started_at: Date | null;
finished_at: Date | null;
updated_at: Date;
+
+ /** Submission metadata, NOT a DB column: set only by MinionQueue.add()
+ * when it returned an EXISTING row instead of inserting (idempotency
+ * fast-path, backpressure cap-hit, or the ON CONFLICT zero-row fallback).
+ * rowToMinionJob never sets it; absent on fresh inserts and on rows read
+ * back later. Surfaces in `jobs submit`'s JSON output — intended and
+ * additive, so scripts can tell a real dispatch from a coalesce. */
+ coalesced?: boolean;
}
// --- Input Types ---
@@ -128,8 +136,29 @@ export interface MinionJobInput {
max_spawn_depth?: number;
/** Global dedup key. Same key returns the existing job, no second row created. */
idempotency_key?: string;
- /** Submission backpressure: cap waiting jobs with this name before inserting a new row. */
+ /** 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
+ * ALL rows for (name, queue) — the NULL-as-wildcard arm is intentional and
+ * relied on by existing rate-cap callers. For single-flight semantics see
+ * maxPending (exact scoping, counts in-flight work too). */
maxWaiting?: number;
+ /** Submission single-flight: cap PENDING jobs — waiting rows plus LIVE-LOCK
+ * active rows (status='active' AND lock_until > now()) — for this
+ * (name, queue, source) scope before inserting a new row. Expired-lock
+ * actives belong to a dead/blocked worker and never count, so a wedged
+ * worker cannot suppress dispatch (new waiting rows keep feeding the
+ * waitingClaimable>0 wedge detectors); dead/cancelled/completed never
+ * count either. Cap-hit returns the most-recent waiting row, else the
+ * most-recent live-lock active row, stamped `coalesced: true`. Scope is
+ * EXACT (unlike maxWaiting): COALESCE(data.sourceId, data.source_id)
+ * compared with IS NOT DISTINCT FROM — a NULL-source submission matches
+ * only NULL-source rows, never a wildcard. If both maxPending and
+ * maxWaiting are supplied, both guards apply; maxPending is checked
+ * first. Internal option (autopilot dispatch single-flight); not exposed
+ * as a public submit flag yet — semantics exclude delayed/paused/
+ * waiting-children rows deliberately. */
+ maxPending?: number;
// v12: scheduler polish
/**
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index 091b543e16..9d12b629dd 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.45.14.0 -->
+<!-- gbrain-template-stamp: 0.45.15.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-fanout-wiring.test.ts b/test/autopilot-fanout-wiring.test.ts
index 9d10176559..8c27975d6d 100644
--- a/test/autopilot-fanout-wiring.test.ts
+++ b/test/autopilot-fanout-wiring.test.ts
@@ -73,6 +73,28 @@ describe('autopilot.ts ↔ dispatchPerSource wiring', () => {
);
});
+ test('lastFullCycleAt advance-gate counts coalesced ticks (parity with pre-split dispatched)', () => {
+ // Before the dispatched/coalesced split, a coalesced submission advanced
+ // the local full-cycle clock via result.dispatched. Without this arm, an
+ // all-coalesced tick (maxPending single-flight suppression) retakes the
+ // full-cycle branch every tick and starves the targeted-plan path for the
+ // whole in-flight window.
+ expect(AUTOPILOT_SRC).toMatch(
+ /result\.dispatched\.length > 0 \|\| result\.coalesced\.length > 0 \|\| result\.legacy_fallback \|\| result\.all_sources_fresh/,
+ );
+ });
+
+ test('fanout_summary reports coalesced separately from dispatched (honest surfaces)', () => {
+ expect(AUTOPILOT_SRC).toMatch(/event: 'fanout_summary',[\s\S]{0,200}coalesced: result\.coalesced/);
+ });
+
+ test('targeted-plan dispatch honors the honest-dispatch contract (red-team finding)', () => {
+ // The targeted remediation loop submits with maxWaiting:1 and expects
+ // coalesces when a handler outlives one interval — its events must split
+ // on job.coalesced like every other dispatch surface in this file.
+ expect(AUTOPILOT_SRC).toMatch(/event: 'dispatch_coalesced',[\s\S]{0,80}mode: 'targeted'/);
+ });
+
test('freshness sync dispatch uses the parsed source config for pull policy', () => {
const freshnessIdx = AUTOPILOT_SRC.indexOf('idempotency_key: `autopilot-sync:');
expect(freshnessIdx).toBeGreaterThan(-1);
@@ -111,8 +133,10 @@ describe('autopilot.ts ↔ dispatchPerSource wiring', () => {
test('updates lastFullCycleAt after dispatch or an all-fresh restart check', () => {
// After the dispatchPerSource call, the lastFullCycleAt module var
// must update so the next tick doesn't immediately re-fan-out.
+ // Coalesced counts as work-in-flight (see the dedicated advance-gate
+ // test below for the full condition).
expect(AUTOPILOT_SRC).toMatch(
- /result\.dispatched\.length > 0 \|\| result\.legacy_fallback \|\| result\.all_sources_fresh/,
+ /result\.dispatched\.length > 0 \|\| result\.coalesced\.length > 0 \|\| result\.legacy_fallback \|\| result\.all_sources_fresh/,
);
expect(AUTOPILOT_SRC).toMatch(/lastFullCycleAt\s*=\s*Date\.now\(\)/);
});
diff --git a/test/autopilot-fanout.test.ts b/test/autopilot-fanout.test.ts
index 07b8b2d32a..35234d6541 100644
--- a/test/autopilot-fanout.test.ts
+++ b/test/autopilot-fanout.test.ts
@@ -354,22 +354,63 @@ describe('dispatchPerSource — integration with stubbed engine + queue', () =>
expect(parsed.pending.length).toBe(2);
});
- test('per-source submit MUST NOT pass maxWaiting (regression — coalesces all sources to one job)', async () => {
- // Direct unit-stub queues can't enforce maxWaiting semantics (the
+ test('per-source submit MUST NOT pass maxWaiting, MUST pass maxPending: 1 (fan-out preserved + single-flight)', async () => {
+ // Direct unit-stub queues can't enforce backpressure semantics (the
// production MinionQueue implementation does), so this catches the
// regression by inspecting the submit opts at the dispatch boundary.
- // If a future refactor re-adds maxWaiting:1 to the per-source path,
- // the production fan-out would silently coalesce N sources to ONE
- // waiting job per tick — killing the entire feature. The e2e test
- // also catches this against a real queue, but this guard fires in
- // unit tests too so the bug surfaces 100x faster.
+ // maxWaiting's NULL-as-wildcard source scope would coalesce N per-source
+ // jobs sharing name='autopilot-cycle' down to ONE waiting job — killing
+ // the fan-out. maxPending is required instead: its EXACT source scope
+ // keeps N independent per-source caps while suppressing cross-slot
+ // re-dispatch when a source's cycle is still in flight (upstream
+ // issue #2). The e2e test also pins both against a real queue.
const { engine, queue, added, fanoutOpts } = makeStubs([src('a'), src('b'), src('c')]);
await dispatchPerSource(engine, queue, fanoutOpts);
+ expect(added.length).toBe(3);
for (const job of added) {
expect(job.opts.maxWaiting).toBeUndefined();
+ expect(job.opts.maxPending).toBe(1);
}
});
+ test('legacy fallback submit passes maxPending: 1 (cross-slot single-flight) and no maxWaiting', async () => {
+ const { engine, queue, added, fanoutOpts } = makeStubs([]);
+ await dispatchPerSource(engine, queue, fanoutOpts);
+ expect(added.length).toBe(1);
+ expect(added[0].opts.maxPending).toBe(1);
+ expect(added[0].opts.maxWaiting).toBeUndefined();
+ });
+
+ test('coalesced submissions are reported separately and emit dispatch_coalesced', async () => {
+ // Stub queue marks the second source's job as coalesced (already in
+ // flight) — the fanout must not claim it as a dispatch.
+ const added: Array<{ name: string; data: Record<string, unknown>; opts: Record<string, unknown> }> = [];
+ const events: string[] = [];
+ let nextId = 200;
+ const engine = {
+ kind: 'postgres' as const,
+ listAllSources: async () => [src('a'), src('b')],
+ getConfig: async () => null,
+ executeRaw: async () => [],
+ } as unknown as BrainEngine;
+ const queue = {
+ add: async (name: string, data: Record<string, unknown>, addOpts: Record<string, unknown>) => {
+ added.push({ name, data, opts: addOpts });
+ const coalesce = data.source_id === 'b';
+ return { id: nextId++, ...(coalesce ? { coalesced: true } : {}) };
+ },
+ } as unknown as Parameters<typeof dispatchPerSource>[1];
+ const result = await dispatchPerSource(engine, queue, {
+ repoPath: '/tmp/brain', slot: 's', timeoutMs: 1, fanoutMax: 4, jsonMode: true,
+ emit: (l: string) => events.push(l), log: () => {},
+ });
+ expect(result.dispatched).toEqual(['a']);
+ expect(result.coalesced).toEqual(['b']);
+ const kinds = events.map(e => JSON.parse(e).event);
+ expect(kinds).toContain('dispatched');
+ expect(kinds).toContain('dispatch_coalesced');
+ });
+
test('all-fresh tick dispatches nothing (no jobs added)', async () => {
const NOW = Date.now();
const recent = (id: string) =>
diff --git a/test/autopilot-global-maintenance.test.ts b/test/autopilot-global-maintenance.test.ts
index c5c500d882..322a197ca2 100644
--- a/test/autopilot-global-maintenance.test.ts
+++ b/test/autopilot-global-maintenance.test.ts
@@ -86,7 +86,11 @@ describe('dispatchGlobalMaintenance — single-flight gate', () => {
expect(added.length).toBe(1);
expect(added[0].name).toBe('autopilot-global-maintenance');
expect(added[0].opts.idempotency_key).toBe('autopilot-global:s1');
- expect(added[0].opts.maxWaiting).toBe(1); // structural single-flight
+ // Structural single-flight: maxPending (waiting + live-lock active),
+ // NOT maxWaiting — an in-flight active run must suppress re-dispatch
+ // across slot rotation (upstream issue #2).
+ expect(added[0].opts.maxPending).toBe(1);
+ expect(added[0].opts.maxWaiting).toBeUndefined();
expect(added[0].data.phases).toEqual(GLOBAL_PHASES);
});
@@ -96,6 +100,27 @@ describe('dispatchGlobalMaintenance — single-flight gate', () => {
expect(r.dispatched).toBe(false);
expect(added.length).toBe(0);
});
+
+ test('coalesced submission → coalesced-aware return + dispatch_coalesced event (never claims a dispatch that did not insert)', async () => {
+ const events: string[] = [];
+ const engine = {
+ kind: 'postgres' as const,
+ getConfig: async (k: string) => (k === LAST_GLOBAL_AT_KEY ? null : null),
+ } as unknown as BrainEngine;
+ const queue = {
+ add: async () => ({ id: 7, coalesced: true }),
+ } as any;
+ const r = await dispatchGlobalMaintenance(engine, queue, {
+ repoPath: '/tmp', slot: 's1', timeoutMs: 1, jsonMode: true, emit: (l: string) => events.push(l),
+ });
+ // Honest-dispatch contract: nothing was inserted, so dispatched is false;
+ // coalesced says the work is already in flight.
+ expect(r.dispatched).toBe(false);
+ expect(r.coalesced).toBe(true);
+ const kinds = events.map(e => JSON.parse(e).event);
+ expect(kinds).toContain('dispatch_coalesced');
+ expect(kinds).not.toContain('dispatched');
+ });
});
describe('dispatchPerSource — per-source jobs carry NON_GLOBAL phases (no embed)', () => {
diff --git a/test/backpressure-audit-read.test.ts b/test/backpressure-audit-read.test.ts
new file mode 100644
index 0000000000..1434bf2e84
--- /dev/null
+++ b/test/backpressure-audit-read.test.ts
@@ -0,0 +1,98 @@
+/**
+ * readRecentCoalesceCounts — the `jobs stats` Backpressure line's data source.
+ *
+ * Pins the three spec points from the review (Codex F5):
+ * 1. The 24h window reads the CURRENT and PREVIOUS ISO-week files — on the
+ * first day of an ISO week a one-file read silently under-counts.
+ * 2. Counts are filtered to the requested queue.
+ * 3. Best-effort: missing files and malformed lines are skipped, never thrown.
+ *
+ * Env discipline: GBRAIN_AUDIT_DIR is applied via withEnv() per test (rule
+ * R1 — no bare process.env mutation in parallel test files).
+ */
+
+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { withEnv } from './helpers/with-env.ts';
+import { computeAuditFilename, readRecentCoalesceCounts } from '../src/core/minions/backpressure-audit.ts';
+
+let dir: string;
+
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'gbrain-bp-audit-'));
+});
+
+afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+});
+
+function writeEvents(filename: string, events: Array<Record<string, unknown>>): void {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, filename), events.map(e => JSON.stringify(e)).join('\n') + '\n', 'utf8');
+}
+
+describe('readRecentCoalesceCounts', () => {
+ test('counts per name within the window, filtered by queue; both event field shapes', async () => {
+ const now = new Date('2026-08-14T12:00:00.000Z');
+ const recent = (offsetMin: number) => new Date(now.getTime() - offsetMin * 60_000).toISOString();
+ writeEvents(computeAuditFilename(now), [
+ { ts: recent(10), queue: 'default', name: 'autopilot-cycle', pending_count: 1, max_pending: 1, decision: 'coalesced', returned_job_id: 1 },
+ { ts: recent(20), queue: 'default', name: 'autopilot-cycle', pending_count: 1, max_pending: 1, decision: 'coalesced', returned_job_id: 1 },
+ { ts: recent(30), queue: 'default', name: 'sync', waiting_count: 1, max_waiting: 1, decision: 'coalesced', returned_job_id: 2 },
+ { ts: recent(40), queue: 'shell', name: 'autopilot-cycle', pending_count: 1, max_pending: 1, decision: 'coalesced', returned_job_id: 3 },
+ { ts: recent(25 * 60), queue: 'default', name: 'autopilot-cycle', pending_count: 1, max_pending: 1, decision: 'coalesced', returned_job_id: 4 },
+ ]);
+ await withEnv({ GBRAIN_AUDIT_DIR: dir }, async () => {
+ const counts = readRecentCoalesceCounts({ queue: 'default', windowMs: 24 * 3600_000, now });
+ expect(counts.get('autopilot-cycle')?.count).toBe(2); // other-queue + >24h excluded
+ expect(counts.get('sync')?.count).toBe(1);
+ expect(counts.size).toBe(2);
+ // Latest event wins the hint target: the 10-min-ago event (job 1) is
+ // newer than the 20-min-ago one, and other-queue/out-of-window events
+ // never contribute a target.
+ expect(counts.get('autopilot-cycle')?.last_returned_job_id).toBe(1);
+ expect(counts.get('sync')?.last_returned_job_id).toBe(2);
+ });
+ });
+
+ test('24h window crossing an ISO-week boundary reads BOTH week files', async () => {
+ // 2026-08-10 is a Monday: 06:00 Monday minus 24h lands in the previous
+ // ISO week. Events split across the two files must both count.
+ const now = new Date('2026-08-10T06:00:00.000Z');
+ const currentFile = computeAuditFilename(now);
+ const prevFile = computeAuditFilename(new Date(now.getTime() - 7 * 86400000));
+ expect(prevFile).not.toBe(currentFile); // sanity: genuinely two files
+ writeEvents(currentFile, [
+ { ts: new Date(now.getTime() - 3600_000).toISOString(), queue: 'default', name: 'autopilot-cycle', decision: 'coalesced', returned_job_id: 1 },
+ ]);
+ writeEvents(prevFile, [
+ // 20h ago = Sunday of the previous ISO week — inside the 24h window.
+ { ts: new Date(now.getTime() - 20 * 3600_000).toISOString(), queue: 'default', name: 'autopilot-cycle', decision: 'coalesced', returned_job_id: 2 },
+ // 30h ago — outside the window, same file.
+ { ts: new Date(now.getTime() - 30 * 3600_000).toISOString(), queue: 'default', name: 'autopilot-cycle', decision: 'coalesced', returned_job_id: 3 },
+ ]);
+ await withEnv({ GBRAIN_AUDIT_DIR: dir }, async () => {
+ const counts = readRecentCoalesceCounts({ queue: 'default', windowMs: 24 * 3600_000, now });
+ expect(counts.get('autopilot-cycle')?.count).toBe(2);
+ // Latest in-window event (1h ago, current week, job 1) wins the target
+ // over the older previous-week event (20h ago, job 2).
+ expect(counts.get('autopilot-cycle')?.last_returned_job_id).toBe(1);
+ });
+ });
+
+ test('missing files → empty map; malformed lines skipped', async () => {
+ const now = new Date('2026-08-14T12:00:00.000Z');
+ await withEnv({ GBRAIN_AUDIT_DIR: dir }, async () => {
+ expect(readRecentCoalesceCounts({ queue: 'default', windowMs: 24 * 3600_000, now }).size).toBe(0);
+ writeFileSync(join(dir, computeAuditFilename(now)),
+ 'not-json\n' +
+ JSON.stringify({ ts: now.toISOString(), queue: 'default', name: 'ok', decision: 'coalesced', returned_job_id: 1 }) + '\n' +
+ '{"truncated":\n', 'utf8');
+ const counts = readRecentCoalesceCounts({ queue: 'default', windowMs: 24 * 3600_000, now });
+ expect(counts.get('ok')?.count).toBe(1);
+ expect(counts.size).toBe(1);
+ });
+ });
+});
diff --git a/test/cli-help-without-brain.serial.test.ts b/test/cli-help-without-brain.serial.test.ts
index 7c9611caf9..27bd97b21c 100644
--- a/test/cli-help-without-brain.serial.test.ts
+++ b/test/cli-help-without-brain.serial.test.ts
@@ -25,6 +25,7 @@ const HELP_WITHOUT_BRAIN = [
'skillopt',
'maintain',
'extract-conversation-facts',
+ 'jobs',
];
/**
diff --git a/test/e2e/autopilot-fanout-postgres.test.ts b/test/e2e/autopilot-fanout-postgres.test.ts
index 3cc2f2779d..94f0e304e2 100644
--- a/test/e2e/autopilot-fanout-postgres.test.ts
+++ b/test/e2e/autopilot-fanout-postgres.test.ts
@@ -83,8 +83,12 @@ describeIfDB('autopilot fan-out — Postgres E2E', () => {
expect(result.legacy_fallback).toBe(false);
expect(result.dispatched.sort()).toEqual(['alpha', 'beta', 'gamma']);
+ expect(result.coalesced).toEqual([]);
- // Verify the 3 jobs land in minion_jobs with distinct idempotency keys
+ // REGRESSION (fan-out preservation): the per-source path now submits with
+ // maxPending: 1 — its EXACT source scope must keep N independent caps.
+ // If the scope ever regressed to maxWaiting's NULL-as-wildcard shape,
+ // sources beta/gamma would coalesce onto alpha's row and this would be 1.
const jobs = await engine.executeRaw<{ name: string; data: any; idempotency_key: string }>(
`SELECT name, data, idempotency_key FROM minion_jobs
WHERE name = 'autopilot-cycle' ORDER BY id`,
@@ -120,7 +124,11 @@ describeIfDB('autopilot fan-out — Postgres E2E', () => {
const r1 = await dispatchPerSource(engine, queue, opts);
const r2 = await dispatchPerSource(engine, queue, opts);
expect(r1.dispatched).toEqual(['alpha']);
- expect(r2.dispatched).toEqual(['alpha']);
+ // Honest dispatch surfaces: the second tick coalesced onto the existing
+ // row (idempotency fast-path) — it is reported as coalesced, NOT as a
+ // dispatch that didn't insert.
+ expect(r2.dispatched).toEqual([]);
+ expect(r2.coalesced).toEqual(['alpha']);
// Only ONE row in minion_jobs (idempotency-key coalesce)
const jobs = await engine.executeRaw<{ id: number }>(
`SELECT id FROM minion_jobs WHERE name = 'autopilot-cycle'`,
@@ -128,6 +136,145 @@ describeIfDB('autopilot fan-out — Postgres E2E', () => {
expect(jobs.length).toBe(1);
});
+ test('issue-#2 regression: stalled ACTIVE cycle suppresses cross-slot re-dispatch; dead frees the cap', async () => {
+ await seedSource('stuck');
+ await engine.executeRaw(`UPDATE sources SET local_path = NULL WHERE id = 'default'`);
+ // The #2194 failure cooldown is an INDEPENDENT gate: a freshly dead
+ // autopilot-cycle row puts the source into backoff, which would mask the
+ // property under test (the maxPending CAP freeing on dead). Disable it.
+ await engine.setConfig('autopilot.failure_cooldown_min', '0');
+ const queue = new MinionQueue(engine);
+ const mkOpts = (slot: string) => ({
+ repoPath: '/tmp', slot, timeoutMs: 60_000, fanoutMax: 10, jsonMode: true,
+ emit: () => {}, log: () => {},
+ });
+
+ // Tick 1 dispatches; the job is then claimed and stalls in 'active' with
+ // a LIVE lock (worker renewing) — the incident shape.
+ const r1 = await dispatchPerSource(engine, queue, mkOpts('slot-A'));
+ expect(r1.dispatched).toEqual(['stuck']);
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'active', lock_token = 'stuck-worker',
+ lock_until = now() + interval '5 minutes', started_at = now()
+ WHERE name = 'autopilot-cycle'`,
+ );
+
+ // Tick 2 in a DIFFERENT slot: the rotated idempotency key would have
+ // minted a fresh duplicate forever (the ~111-row incident); maxPending
+ // now coalesces onto the in-flight active row. Row count stays 1.
+ const r2 = await dispatchPerSource(engine, queue, mkOpts('slot-B'));
+ expect(r2.dispatched).toEqual([]);
+ expect(r2.coalesced).toEqual(['stuck']);
+ let rows = await engine.executeRaw<{ n: string }>(
+ `SELECT count(*)::text AS n FROM minion_jobs WHERE name = 'autopilot-cycle'`,
+ );
+ expect(parseInt(rows[0].n, 10)).toBe(1);
+
+ // Dead-letter frees the cap: tick 3 dispatches a fresh row.
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'dead', finished_at = now() WHERE name = 'autopilot-cycle'`,
+ );
+ const r3 = await dispatchPerSource(engine, queue, mkOpts('slot-C'));
+ expect(r3.dispatched).toEqual(['stuck']);
+ rows = await engine.executeRaw<{ n: string }>(
+ `SELECT count(*)::text AS n FROM minion_jobs WHERE name = 'autopilot-cycle' AND status = 'waiting'`,
+ );
+ expect(parseInt(rows[0].n, 10)).toBe(1);
+ });
+
+ test('recovery loop: legacy NULL-budget row → claim stamps budget → live lock suppresses → expiry frees → stall requeue re-suppresses', async () => {
+ // The mechanism test (Codex C9/F3): claim() is driven directly with a
+ // token and NO renewer — a live worker would renew the manually expired
+ // lock and mask the recovery path.
+ await engine.executeRaw(`UPDATE sources SET local_path = NULL WHERE id = 'default'`);
+ const queue = new MinionQueue(engine);
+ const mkOpts = (slot: string) => ({
+ repoPath: '/tmp/legacy', slot, timeoutMs: 60_000, fanoutMax: 10, jsonMode: true,
+ emit: () => {}, log: () => {},
+ });
+
+ // Phase 0: a legacy row queued before budget stamping existed.
+ const r0 = await dispatchPerSource(engine, queue, mkOpts('rl-slot-0'));
+ expect(r0.legacy_fallback).toBe(true);
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET timeout_ms = NULL, timeout_at = NULL WHERE name = 'autopilot-cycle'`,
+ );
+
+ // Phase 1: a REAL claim stamps the handler budget (claim-time fallback)
+ // and holds a live lock — dispatch in a new slot coalesces, no insert.
+ const claimed = await queue.claim('rl-token', 60_000, 'default', ['autopilot-cycle']);
+ expect(claimed).not.toBeNull();
+ expect(claimed!.timeout_ms).toBe(30 * 60 * 1000);
+ expect(claimed!.timeout_at).not.toBeNull();
+ const r1 = await dispatchPerSource(engine, queue, mkOpts('rl-slot-1'));
+ expect(r1.dispatched).toEqual([]);
+ let rows = await engine.executeRaw<{ n: string }>(
+ `SELECT count(*)::text AS n FROM minion_jobs WHERE name = 'autopilot-cycle'`,
+ );
+ expect(parseInt(rows[0].n, 10)).toBe(1);
+
+ // Phase 2: the worker dies — lock expires without renewal. An
+ // expired-lock active must NOT suppress (wedge detectors stay fed):
+ // the next slot INSERTS a fresh waiting row.
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET lock_until = now() - interval '1 second'
+ WHERE id = $1`, [claimed!.id],
+ );
+ const r2 = await dispatchPerSource(engine, queue, mkOpts('rl-slot-2'));
+ expect(r2.legacy_fallback).toBe(true);
+ rows = await engine.executeRaw<{ n: string }>(
+ `SELECT count(*)::text AS n FROM minion_jobs WHERE name = 'autopilot-cycle'`,
+ );
+ expect(parseInt(rows[0].n, 10)).toBe(2);
+
+ // Phase 3: the real sweep requeues the stalled original (max_stalled
+ // default 5 → requeue, not dead-letter). Two waiting rows in scope →
+ // the next dispatch coalesces onto the newest; no third row.
+ const stalled = await queue.handleStalled();
+ expect(stalled.requeued.map(j => j.id)).toContain(claimed!.id);
+ const requeued = await engine.executeRaw<{ status: string }>(
+ `SELECT status FROM minion_jobs WHERE id = $1`, [claimed!.id],
+ );
+ expect(requeued[0].status).toBe('waiting');
+ const r3 = await dispatchPerSource(engine, queue, mkOpts('rl-slot-3'));
+ expect(r3.dispatched).toEqual([]);
+ rows = await engine.executeRaw<{ n: string }>(
+ `SELECT count(*)::text AS n FROM minion_jobs WHERE name = 'autopilot-cycle'`,
+ );
+ expect(parseInt(rows[0].n, 10)).toBe(2);
+
+ // Phase 4: force the requeued original terminal → single-flight converges
+ // (one waiting row remains and still suppresses new dispatch).
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'dead', finished_at = now() WHERE id = $1`, [claimed!.id],
+ );
+ const r4 = await dispatchPerSource(engine, queue, mkOpts('rl-slot-4'));
+ expect(r4.dispatched).toEqual([]);
+ rows = await engine.executeRaw<{ n: string }>(
+ `SELECT count(*)::text AS n FROM minion_jobs WHERE name = 'autopilot-cycle' AND status = 'waiting'`,
+ );
+ expect(parseInt(rows[0].n, 10)).toBe(1);
+ });
+
+ test('concurrent same-scope submissions hold maxPending: 1 on real Postgres (advisory-lock guarantee)', async () => {
+ // PGLite is single-writer, so its Promise.all race is only a smoke test.
+ // The postgres.js pool gives genuine concurrent connections — this is
+ // the test that actually validates the pg_advisory_xact_lock serialization.
+ const queue = new MinionQueue(engine);
+ const results = await Promise.all(
+ Array.from({ length: 8 }, () =>
+ queue.add('race-single-flight', { source_id: 'race-src' }, { maxPending: 1 })),
+ );
+ const ids = new Set(results.map(r => r.id));
+ expect(ids.size).toBe(1);
+ const rows = await engine.executeRaw<{ n: string }>(
+ `SELECT count(*)::text AS n FROM minion_jobs WHERE name = 'race-single-flight'`,
+ );
+ expect(parseInt(rows[0].n, 10)).toBe(1);
+ // Exactly one submission inserted; the other seven carry coalesce metadata.
+ expect(results.filter(r => r.coalesced).length).toBe(7);
+ });
+
test('source with last_full_cycle_at < 60min ago is skipped by gate', async () => {
const recent = new Date(Date.now() - 30 * 60 * 1000).toISOString();
await seedSource('fresh');
diff --git a/test/jobs-format-detail.test.ts b/test/jobs-format-detail.test.ts
new file mode 100644
index 0000000000..83eed580d6
--- /dev/null
+++ b/test/jobs-format-detail.test.ts
@@ -0,0 +1,84 @@
+/**
+ * `jobs get` timeout/deadline rendering (jobs fix wave, upstream issue #3).
+ *
+ * Pins:
+ * 1. All three effective-budget states render, with the corrected wording:
+ * the 1x deadline (handleTimeouts) is the NORMAL kill and the 2x
+ * wall-clock sweep is the backstop — not the other way around.
+ * 2. Defensive timeout_at rendering: a thin client pointed at an OLDER
+ * server receives timeout_at as an ISO string (the peer predates the
+ * rehydration list entry) — the formatter must print it, never crash on
+ * an unguarded .toISOString().
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { formatJobDetail } from '../src/commands/jobs.ts';
+import type { MinionJob } from '../src/core/minions/types.ts';
+
+function job(overrides: Partial<MinionJob> & Record<string, unknown>): MinionJob {
+ return {
+ id: 42,
+ name: 'sync',
+ queue: 'default',
+ status: 'waiting',
+ priority: 0,
+ data: {},
+ attempts_made: 0,
+ attempts_started: 0,
+ max_attempts: 3,
+ stalled_counter: 0,
+ max_stalled: 5,
+ backoff_type: 'exponential',
+ backoff_delay: 1000,
+ backoff_jitter: 0,
+ created_at: new Date('2026-08-14T00:00:00.000Z'),
+ updated_at: new Date('2026-08-14T00:00:00.000Z'),
+ started_at: null,
+ finished_at: null,
+ lock_token: null,
+ lock_until: null,
+ delay_until: null,
+ timeout_ms: null,
+ timeout_at: null,
+ parent_job_id: null,
+ on_child_fail: 'fail',
+ error_text: null,
+ stacktrace: [],
+ progress: null,
+ result: null,
+ ...overrides,
+ } as unknown as MinionJob;
+}
+
+describe('formatJobDetail timeout/deadline lines', () => {
+ test('explicit budget: 1x-deadline wording + Deadline line from a Date', () => {
+ const out = formatJobDetail(job({
+ name: 'autopilot-cycle',
+ timeout_ms: 1_800_000,
+ timeout_at: new Date('2026-08-14T01:00:00.000Z'),
+ }));
+ expect(out).toContain('Timeout: 1800000ms (deadline kill at 1x when claimed; wall-clock backstop at 2x)');
+ expect(out).toContain('Deadline: 2026-08-14T01:00:00.000Z');
+ });
+
+ test('defensive render: timeout_at arriving as an ISO STRING (older server) does not crash', () => {
+ const out = formatJobDetail(job({
+ name: 'subagent',
+ timeout_ms: 1_800_000,
+ // Deliberately a string — rehydrateJobDates on an older peer never
+ // converted this field. An unguarded .toISOString() would throw here.
+ timeout_at: '2026-08-14T01:00:00.000Z' as unknown as Date,
+ }));
+ expect(out).toContain('Deadline: 2026-08-14T01:00:00.000Z');
+ });
+
+ test('unset budget + mapped handler: names the claim-time default', () => {
+ const out = formatJobDetail(job({ name: 'autopilot-cycle', timeout_ms: null }));
+ expect(out).toContain('Timeout: (unset) — handler default 1800000ms stamps at claim');
+ });
+
+ test('unset budget + unmapped handler: names the null-default sweep', () => {
+ const out = formatJobDetail(job({ name: 'sync', timeout_ms: null }));
+ expect(out).toContain('null-default wall-clock sweep applies');
+ });
+});
diff --git a/test/jobs-stats-backpressure.serial.test.ts b/test/jobs-stats-backpressure.serial.test.ts
new file mode 100644
index 0000000000..5327124311
--- /dev/null
+++ b/test/jobs-stats-backpressure.serial.test.ts
@@ -0,0 +1,99 @@
+/**
+ * `jobs stats` Backpressure (24h) line + suppression hint — WIRING test.
+ *
+ * readRecentCoalesceCounts (the data source) is pinned in
+ * test/backpressure-audit-read.test.ts; this file covers the stats-case
+ * composition the coverage audit flagged as the remaining gap:
+ * 1. the "Backpressure (24h)" line renders per-name counts for the queue
+ * 2. the suppression hint fires when waiting=0 AND a live-lock active row
+ * is older than the shared wedge threshold, naming the job id
+ * 3. no audit events → no Backpressure line (omission path)
+ *
+ * Serial: mutates GBRAIN_AUDIT_DIR + GBRAIN_WEDGED_QUEUE_WARN_MINUTES via
+ * withEnv around the runJobs call and captures console.log.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { withEnv } from './helpers/with-env.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { computeAuditFilename } from '../src/core/minions/backpressure-audit.ts';
+import { runJobs } from '../src/commands/jobs.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+async function captureStats(auditDir: string): Promise<string> {
+ const origLog = console.log;
+ let out = '';
+ console.log = (...args: unknown[]) => { out += args.map(String).join(' ') + '\n'; };
+ try {
+ await withEnv({ GBRAIN_AUDIT_DIR: auditDir, GBRAIN_WEDGED_QUEUE_WARN_MINUTES: '15' }, async () => {
+ await runJobs(engine, ['stats']);
+ });
+ } finally {
+ console.log = origLog;
+ }
+ return out;
+}
+
+describe('jobs stats — Backpressure line + suppression hint wiring', () => {
+ test('renders per-name counts and the suppressed-by hint for a stale live-lock active with zero waiting', async () => {
+ await engine.executeRaw('DELETE FROM minion_jobs');
+ // One ACTIVE autopilot-cycle with a LIVE lock, 30 minutes in (> 15m
+ // threshold), zero waiting rows — the exact post-maxPending suppression
+ // shape that used to be invisible to the waiting>0 wedge detectors.
+ const job = await queue.add('autopilot-cycle', {});
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'active', lock_token = 'live-worker',
+ lock_until = now() + interval '5 minutes',
+ started_at = now() - interval '30 minutes'
+ WHERE id = $1`,
+ [job.id],
+ );
+ const auditDir = mkdtempSync(join(tmpdir(), 'gbrain-stats-bp-'));
+ try {
+ mkdirSync(auditDir, { recursive: true });
+ writeFileSync(join(auditDir, computeAuditFilename()),
+ JSON.stringify({
+ ts: new Date().toISOString(), queue: 'default', name: 'autopilot-cycle',
+ pending_count: 1, max_pending: 1, decision: 'coalesced', returned_job_id: job.id,
+ }) + '\n', 'utf8');
+
+ const out = await captureStats(auditDir);
+
+ expect(out).toContain('Backpressure (24h)');
+ expect(out).toContain('autopilot-cycle: 1');
+ expect(out).toContain(`dispatch suppressed by in-flight job #${job.id}`);
+ expect(out).toContain(`gbrain jobs get ${job.id}`);
+ } finally {
+ rmSync(auditDir, { recursive: true, force: true });
+ }
+ }, 30_000);
+
+ test('no audit events → Backpressure line omitted entirely', async () => {
+ await engine.executeRaw('DELETE FROM minion_jobs');
+ const emptyDir = mkdtempSync(join(tmpdir(), 'gbrain-stats-bp-empty-'));
+ try {
+ const out = await captureStats(emptyDir);
+ expect(out).not.toContain('Backpressure (24h)');
+ expect(out).not.toContain('dispatch suppressed');
+ } finally {
+ rmSync(emptyDir, { recursive: true, force: true });
+ }
+ }, 30_000);
+});
diff --git a/test/jobs-subcommand-help.serial.test.ts b/test/jobs-subcommand-help.serial.test.ts
new file mode 100644
index 0000000000..7141ae4cfa
--- /dev/null
+++ b/test/jobs-subcommand-help.serial.test.ts
@@ -0,0 +1,131 @@
+/**
+ * `gbrain jobs [--help]` + `gbrain jobs <subcommand> --help` guard.
+ *
+ * Regression test for two defects:
+ * 1. `jobs` was in CLI_ONLY but not CLI_ONLY_SELF_HELP, so `jobs --help`
+ * printed the generic one-line stub — the real help block in jobs.ts was
+ * unreachable, and the worker entry point (`jobs work`) was undiscoverable
+ * from the CLI during an incident.
+ * 2. With the stub gone, a help token AFTER the subcommand name would have
+ * fallen through into the subcommand body — `jobs work --help` would have
+ * started a REAL worker daemon (same defect class the bootstrap
+ * subcommand-help guard fixed). The guard in runJobs intercepts before
+ * the thin-client refusal and the switch.
+ *
+ * Each case spawns the actual CLI with an empty GBRAIN_HOME and no database
+ * env (the cli-help-without-brain env hygiene), so a pass proves the whole
+ * dispatch path answers engine-free AND exits — a started daemon would hang
+ * the spawn until the test timeout.
+ *
+ * Serial: spawns the CLI; keeps its wall clock out of the parallel shards.
+ */
+import { describe, test, expect } from 'bun:test';
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const REPO = new URL('..', import.meta.url).pathname;
+const STUB_MARKER = 'run gbrain --help for the full command list';
+
+async function runJobsHelp(args: string[]): Promise<{ code: number; out: string }> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-jobshelp-'));
+ // Empty GBRAIN_HOME is not enough: loadConfig also honours
+ // GBRAIN_DATABASE_URL / DATABASE_URL, and bun auto-loads .env from cwd —
+ // both would let the CLI connect an engine and mask a broken guard.
+ const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: home };
+ delete env.GBRAIN_DATABASE_URL;
+ delete env.DATABASE_URL;
+ const proc = Bun.spawn(['bun', '--no-env-file', 'run', 'src/cli.ts', 'jobs', ...args], {
+ cwd: REPO,
+ env,
+ stdout: 'pipe',
+ stderr: 'pipe',
+ });
+ const [stdout, stderr] = await Promise.all([
+ new Response(proc.stdout).text(),
+ new Response(proc.stderr).text(),
+ ]);
+ const code = await proc.exited;
+ return { code, out: stdout + stderr };
+}
+
+describe('jobs --help and jobs <subcommand> --help print real help, never the stub, never a daemon', () => {
+ test('jobs --help: full help block, not the stub', async () => {
+ const { code, out } = await runJobsHelp(['--help']);
+ expect(code).toBe(0);
+ expect(out).toContain('Minions job queue');
+ expect(out).toContain('jobs work');
+ expect(out).toContain('jobs supervisor');
+ expect(out).toContain('jobs watch');
+ expect(out).not.toContain(STUB_MARKER);
+ expect(out).not.toContain('No brain configured');
+ }, 30_000);
+
+ test('jobs -h: short-flag parity', async () => {
+ const { code, out } = await runJobsHelp(['-h']);
+ expect(code).toBe(0);
+ expect(out).toContain('Minions job queue');
+ expect(out).not.toContain(STUB_MARKER);
+ }, 30_000);
+
+ test('jobs work --help: worker flags documented; NO worker daemon starts (fast exit proves it)', async () => {
+ const { code, out } = await runJobsHelp(['work', '--help']);
+ expect(code).toBe(0);
+ expect(out).toContain('--max-rss');
+ expect(out).toContain('--health-interval');
+ expect(out).toContain('GBRAIN_WORKER_CONCURRENCY');
+ expect(out).not.toContain(STUB_MARKER);
+ // A real `jobs work` on this fixture would refuse (thin-client/engine
+ // path) or start a daemon; either output would differ from the help.
+ expect(out).not.toContain('needs a local engine');
+ }, 30_000);
+
+ test('jobs supervisor --help: supervisor flags + exit codes', async () => {
+ const { code, out } = await runJobsHelp(['supervisor', '--help']);
+ expect(code).toBe(0);
+ expect(out).toContain('--max-crashes');
+ expect(out).toContain('--pid-file');
+ expect(out).not.toContain(STUB_MARKER);
+ }, 30_000);
+
+ test('jobs submit -h: submit flags documented', async () => {
+ const { code, out } = await runJobsHelp(['submit', '-h']);
+ expect(code).toBe(0);
+ expect(out).toContain('--idempotency-key');
+ expect(out).toContain('--max-waiting');
+ expect(out).not.toContain(STUB_MARKER);
+ }, 30_000);
+
+ test('jobs watch --help: documents the equals-only --refresh-ms form', async () => {
+ const { code, out } = await runJobsHelp(['watch', '--help']);
+ expect(code).toBe(0);
+ expect(out).toContain('--refresh-ms=N');
+ expect(out).not.toContain(STUB_MARKER);
+ }, 30_000);
+
+ test('jobs prune --help: prune flags documented, nothing pruned', async () => {
+ const { code, out } = await runJobsHelp(['prune', '--help']);
+ expect(code).toBe(0);
+ expect(out).toContain('--older-than');
+ expect(out).not.toContain(STUB_MARKER);
+ }, 30_000);
+
+ test('jobs stats --help: no dedicated entry → falls back to the full help block', async () => {
+ const { code, out } = await runJobsHelp(['stats', '--help']);
+ expect(code).toBe(0);
+ expect(out).toContain('Minions job queue');
+ expect(out).toContain('--cluster-errors');
+ expect(out).not.toContain(STUB_MARKER);
+ }, 30_000);
+
+ test('jobs constructor --help: prototype key falls back to the full help, never Object.prototype garbage', async () => {
+ // Red-team finding: a plain-object lookup resolves inherited keys, so
+ // without Object.hasOwn this printed `function Object() { ... }`.
+ const { code, out } = await runJobsHelp(['constructor', '--help']);
+ expect(code).toBe(0);
+ expect(out).toContain('Minions job queue');
+ expect(out).not.toContain('native code');
+ expect(out).not.toContain('function Object');
+ expect(out).not.toContain(STUB_MARKER);
+ }, 30_000);
+});
diff --git a/test/jobs-thin-client-date-rehydration.test.ts b/test/jobs-thin-client-date-rehydration.test.ts
index 5715c232d6..78507d3870 100644
--- a/test/jobs-thin-client-date-rehydration.test.ts
+++ b/test/jobs-thin-client-date-rehydration.test.ts
@@ -27,6 +27,7 @@ describe('rehydrateJobDates', () => {
started_at: '2026-07-21T04:02:12.001Z',
finished_at: '2026-07-21T04:02:14.900Z',
lock_until: '2026-07-21T04:03:12.001Z',
+ timeout_at: '2026-07-21T04:32:12.001Z',
delay_until: null,
};
const job = rehydrateJobDates(wire);
@@ -35,6 +36,7 @@ describe('rehydrateJobDates', () => {
expect(job.started_at).toBeInstanceOf(Date);
expect(job.finished_at).toBeInstanceOf(Date);
expect(job.lock_until).toBeInstanceOf(Date);
+ expect(job.timeout_at).toBeInstanceOf(Date);
expect((job.started_at as unknown as Date).toISOString()).toBe('2026-07-21T04:02:12.001Z');
// Date math used by formatJob's duration column works post-rehydration.
expect((job.finished_at as unknown as Date).getTime() - (job.started_at as unknown as Date).getTime())
diff --git a/test/migrations-v128.test.ts b/test/migrations-v128.test.ts
new file mode 100644
index 0000000000..53b96cc696
--- /dev/null
+++ b/test/migrations-v128.test.ts
@@ -0,0 +1,228 @@
+/**
+ * Jobs fix wave (upstream issues #2/#3) — migration v128
+ * (minion_jobs_timeout_backfill_and_duplicate_cycle_cleanup).
+ *
+ * Pinned contracts:
+ * 1. v128 exists in MIGRATIONS with the canonical name, idempotent flag, and
+ * one engine-agnostic sql block (no sqlFor split).
+ * 2. Statement 1 backfills NULL timeout_ms for the 8 long-lane handler names
+ * across ALL five non-terminal statuses — and ONLY those rows: terminal
+ * rows, unmapped names, and explicit budgets are untouched. Active rows
+ * get timeout_ms only (never a timeout_at stamp — that would arm the
+ * tighter 1x handleTimeouts kill mid-flight; the 2x wall-clock bound is
+ * the intended repair).
+ * 3. Statement 2 cancels all-but-newest ticker-keyed waiting autopilot
+ * cycles per (name, queue, source scope). Manual submissions (no ticker
+ * idempotency-key prefix) and parented rows are never touched; distinct
+ * sources each keep their newest row; cancelled rows carry error_text.
+ * 4. Ledger round-trip: rewind to 127 → runMigrations applies v128; re-run
+ * is 0 applied. AND (Codex C9) SQL-level idempotency: re-executing the
+ * v128 SQL directly changes zero rows — the ledger check alone only
+ * proves version bookkeeping.
+ * 5. Empty table → 0-row no-op.
+ */
+
+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 { MIGRATIONS, LATEST_VERSION, runMigrations } from '../src/core/migrate.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+
+const V128_SQL = MIGRATIONS.find(m => m.version === 128)?.sql ?? '';
+
+/** PGLite's prepared-statement path rejects multi-command SQL; the migration
+ * runner uses a different execution path. For the direct SQL-rerun check,
+ * split on statement terminators (the blob's only two `;` are terminators). */
+const V128_STATEMENTS = V128_SQL.split(';').map(s => s.trim()).filter(Boolean);
+
+async function execV128Directly(): Promise<void> {
+ for (const stmt of V128_STATEMENTS) {
+ await engine.executeRaw(stmt);
+ }
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' }); // in-memory
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM minion_jobs');
+});
+
+/** Force a row into a specific historical shape (add() stamps budgets and
+ * every row starts 'waiting', so legacy states are seeded by direct UPDATE —
+ * the same trick the wall-clock tests use). */
+async function forceRow(id: number, sets: string, params: unknown[] = []): Promise<void> {
+ await engine.executeRaw(`UPDATE minion_jobs SET ${sets} WHERE id = $${params.length + 1}`, [...params, id]);
+}
+
+async function snapshot(): Promise<Array<Record<string, unknown>>> {
+ return engine.executeRaw<Record<string, unknown>>(
+ `SELECT id, name, status, timeout_ms::text AS timeout_ms,
+ timeout_at IS NULL AS timeout_at_null, error_text
+ FROM minion_jobs ORDER BY id`,
+ );
+}
+
+describe('migration v128 — structure', () => {
+ test('exists with canonical name, idempotent flag, engine-agnostic sql', () => {
+ const v128 = MIGRATIONS.find(m => m.version === 128);
+ expect(v128).toBeDefined();
+ expect(v128?.name).toBe('minion_jobs_timeout_backfill_and_duplicate_cycle_cleanup');
+ expect(v128?.idempotent).toBe(true);
+ expect(v128?.sqlFor).toBeUndefined();
+ expect(LATEST_VERSION).toBeGreaterThanOrEqual(128);
+ });
+
+ test('statement 1 covers all five non-terminal statuses and never stamps timeout_at', () => {
+ expect(V128_SQL).toContain(`status IN ('waiting','active','delayed','waiting-children','paused')`);
+ expect(V128_SQL).not.toContain('SET timeout_at');
+ });
+
+ test('statement 2 is restricted to ticker idempotency-key prefixes and top-level rows', () => {
+ expect(V128_SQL).toContain(`idempotency_key LIKE 'autopilot-cycle:%'`);
+ expect(V128_SQL).toContain(`idempotency_key LIKE 'autopilot-global:%'`);
+ expect(V128_SQL).toContain('parent_job_id IS NULL');
+ });
+});
+
+describe('migration v128 — backfill + cleanup semantics (PGLite)', () => {
+ test('full matrix: backfill hits legacy non-terminal mapped rows only; cleanup keeps newest ticker row per scope', async () => {
+ // --- Backfill fixtures (statement 1) ---
+ // Legacy waiting subagent: NULL budget → 30min.
+ const legacyWaiting = await queue.add('subagent', {}, undefined, { allowProtectedSubmit: true });
+ await forceRow(legacyWaiting.id, `timeout_ms = NULL, timeout_at = NULL`);
+ // Legacy ACTIVE autopilot-cycle mid-flight: NULL budget → 30min, but
+ // timeout_at must STAY NULL (Codex C7 — no 1x kill armed mid-flight).
+ const legacyActive = await queue.add('autopilot-cycle', { source_id: 'src-active' }, {
+ idempotency_key: 'autopilot-cycle:src-active:slot-0',
+ });
+ await forceRow(legacyActive.id,
+ `timeout_ms = NULL, timeout_at = NULL, status = 'active',
+ lock_token = 'legacy-worker', lock_until = now() + interval '30 seconds',
+ started_at = now() - interval '10 minutes'`);
+ // Terminal row: NULL budget stays NULL (completed is not rescued).
+ const completed = await queue.add('subagent', { done: true }, undefined, { allowProtectedSubmit: true });
+ await forceRow(completed.id, `timeout_ms = NULL, status = 'completed', finished_at = now()`);
+ // Unmapped name: stays NULL.
+ const unmapped = await queue.add('sync', {});
+ expect(unmapped.timeout_ms).toBeNull();
+ // Explicit budget: untouched.
+ const explicit = await queue.add('embed-backfill', { sourceId: 'x' }, { timeout_ms: 5000 });
+
+ // --- Cleanup fixtures (statement 2) ---
+ // Three ticker-keyed waiting cycles for ONE source, staggered ages —
+ // newest must survive, older two cancelled.
+ const dupOld = await queue.add('autopilot-cycle', { source_id: 'src-dup' }, {
+ idempotency_key: 'autopilot-cycle:src-dup:slot-1',
+ });
+ await forceRow(dupOld.id, `timeout_ms = NULL, created_at = now() - interval '3 hours'`);
+ const dupMid = await queue.add('autopilot-cycle', { source_id: 'src-dup' }, {
+ idempotency_key: 'autopilot-cycle:src-dup:slot-2',
+ });
+ await forceRow(dupMid.id, `timeout_ms = NULL, created_at = now() - interval '2 hours'`);
+ const dupNew = await queue.add('autopilot-cycle', { source_id: 'src-dup' }, {
+ idempotency_key: 'autopilot-cycle:src-dup:slot-3',
+ });
+ await forceRow(dupNew.id, `timeout_ms = NULL, created_at = now() - interval '1 hour'`);
+ // A DIFFERENT source keeps its own newest row (scope isolation).
+ const otherSrc = await queue.add('autopilot-cycle', { source_id: 'src-other' }, {
+ idempotency_key: 'autopilot-cycle:src-other:slot-1',
+ });
+ await forceRow(otherSrc.id, `created_at = now() - interval '4 hours'`);
+ // Global maintenance duplicates (NULL source scope) dedupe independently.
+ const globalOld = await queue.add('autopilot-global-maintenance', {}, {
+ idempotency_key: 'autopilot-global:slot-1',
+ });
+ await forceRow(globalOld.id, `created_at = now() - interval '2 hours'`);
+ const globalNew = await queue.add('autopilot-global-maintenance', {}, {
+ idempotency_key: 'autopilot-global:slot-2',
+ });
+ // Manual submission: same name + source as the dup scope, custom phases,
+ // NO ticker key — must never be touched (Codex C5).
+ const manual = await queue.add('autopilot-cycle', { source_id: 'src-dup', phases: ['sync'] });
+ await forceRow(manual.id, `created_at = now() - interval '5 hours'`);
+ // Ticker-mimicking key but camelCase sourceId payload: the ticker never
+ // writes sourceId, so this row is not ticker-provenance — the cleanup's
+ // sourceId-IS-NULL guard must leave it alone even though its key matches
+ // the prefix (adversarial-review tightening: without the guard, distinct
+ // sourceId scopes would collapse into the empty source_id group).
+ const camelMimic = await queue.add('autopilot-cycle', { sourceId: 'camel-src' }, {
+ idempotency_key: 'autopilot-cycle:camel-mimic:slot-1',
+ });
+ await forceRow(camelMimic.id, `created_at = now() - interval '7 hours'`);
+ // Parented row with a ticker-looking key: guarded by parent_job_id IS NULL.
+ // Parent is seeded by direct UPDATE — add()'s parent_job_id opt would flip
+ // the parent row to 'waiting-children' and pollute the dup-scope fixtures.
+ const parented = await queue.add('autopilot-cycle', { source_id: 'src-dup' }, {
+ idempotency_key: 'autopilot-cycle:src-dup:slot-child',
+ });
+ await forceRow(parented.id,
+ `created_at = now() - interval '6 hours', parent_job_id = $1`, [dupNew.id]);
+
+ // --- Apply v128 via the real migration runner (ledger rewind). ---
+ await engine.setConfig('version', '127');
+ const res = await runMigrations(engine);
+ expect(res.applied).toBeGreaterThanOrEqual(1);
+ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));
+
+ const rows = await engine.executeRaw<{
+ id: number; status: string; timeout_ms: string | null;
+ timeout_at: string | null; error_text: string | null;
+ }>(`SELECT id, status, timeout_ms::text AS timeout_ms, timeout_at::text AS timeout_at, error_text
+ FROM minion_jobs`);
+ const byId = new Map(rows.map(r => [Number(r.id), r]));
+
+ // Statement 1 assertions.
+ expect(Number(byId.get(legacyWaiting.id)!.timeout_ms)).toBe(1_800_000);
+ expect(Number(byId.get(legacyActive.id)!.timeout_ms)).toBe(1_800_000);
+ expect(byId.get(legacyActive.id)!.timeout_at).toBeNull(); // C7: no 1x kill armed
+ expect(byId.get(legacyActive.id)!.status).toBe('active');
+ expect(byId.get(completed.id)!.timeout_ms).toBeNull(); // terminal untouched
+ expect(byId.get(unmapped.id)!.timeout_ms).toBeNull(); // not in map
+ expect(Number(byId.get(explicit.id)!.timeout_ms)).toBe(5000); // explicit wins
+
+ // Statement 2 assertions.
+ expect(byId.get(dupNew.id)!.status).toBe('waiting'); // newest survives
+ expect(byId.get(dupOld.id)!.status).toBe('cancelled');
+ expect(byId.get(dupMid.id)!.status).toBe('cancelled');
+ expect(byId.get(dupOld.id)!.error_text).toContain('superseded duplicate autopilot cycle');
+ expect(byId.get(otherSrc.id)!.status).toBe('waiting'); // other source keeps its one row
+ expect(byId.get(globalNew.id)!.status).toBe('waiting');
+ expect(byId.get(globalOld.id)!.status).toBe('cancelled');
+ expect(byId.get(manual.id)!.status).toBe('waiting'); // manual never touched (C5)
+ expect(byId.get(manual.id)!.error_text).toBeNull();
+ expect(byId.get(parented.id)!.status).toBe('waiting'); // parented never touched
+ expect(byId.get(camelMimic.id)!.status).toBe('waiting'); // camelCase sourceId never swept
+
+ // Ledger idempotency: re-run applies nothing.
+ const rerun = await runMigrations(engine);
+ expect(rerun.applied).toBe(0);
+
+ // SQL-level idempotency (Codex C9): re-execute the v128 SQL directly and
+ // prove zero rows change — version bookkeeping alone can't show this.
+ const before = await snapshot();
+ await execV128Directly();
+ const after = await snapshot();
+ expect(after).toEqual(before);
+
+ // Sanity on the split used above: exactly the two statements shipped.
+ expect(V128_STATEMENTS.length).toBe(2);
+ }, 30_000);
+
+ test('empty table: v128 SQL is a 0-row no-op', async () => {
+ const before = await snapshot();
+ expect(before).toEqual([]);
+ await execV128Directly();
+ expect(await snapshot()).toEqual([]);
+ });
+});
diff --git a/test/minions.test.ts b/test/minions.test.ts
index 36d0439519..a288f15f61 100644
--- a/test/minions.test.ts
+++ b/test/minions.test.ts
@@ -381,6 +381,55 @@ describe('MinionQueue: #1737 per-handler default timeout', () => {
});
});
+// --- Claim-time budget fallback (jobs fix wave, upstream issue #3) ---
+//
+// Rows inserted before submit-time stamping existed (or by writers that
+// bypass add()) carry timeout_ms = NULL and used to fall to the minutes-scale
+// null-default wall-clock sweep. claim() now COALESCEs the budget from
+// HANDLER_DEFAULT_TIMEOUT_MS and derives timeout_at from the coalesced value.
+// Seeding NULL requires a direct UPDATE because add() stamps at submit.
+
+describe('MinionQueue: claim-time timeout fallback', () => {
+ test('legacy NULL-timeout long-handler row gets the map budget stamped at claim', async () => {
+ const job = await queue.add('subagent', {}, undefined, { allowProtectedSubmit: true });
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET timeout_ms = NULL, timeout_at = NULL WHERE id = $1`,
+ [job.id],
+ );
+ const before = Date.now();
+ const claimed = await queue.claim('tok-fallback', 30_000, 'default', ['subagent']);
+ expect(claimed).not.toBeNull();
+ expect(claimed!.id).toBe(job.id);
+ expect(claimed!.timeout_ms).toBe(30 * 60 * 1000);
+ expect(claimed!.timeout_at).toBeInstanceOf(Date);
+ const deadline = claimed!.timeout_at!.getTime();
+ // timeout_at ≈ claim time + 30min (generous 60s slop for slow CI).
+ expect(deadline).toBeGreaterThan(before + 30 * 60 * 1000 - 60_000);
+ expect(deadline).toBeLessThan(before + 30 * 60 * 1000 + 60_000);
+ // Persisted, not just returned — a restarted worker sees the same budget.
+ const rows = await engine.executeRaw<{ timeout_ms: number | null }>(
+ `SELECT timeout_ms FROM minion_jobs WHERE id = $1`, [job.id],
+ );
+ expect(Number(rows[0].timeout_ms)).toBe(30 * 60 * 1000);
+ });
+
+ test('name outside the map keeps NULL budget at claim (fail-open, todays behavior)', async () => {
+ const job = await queue.add('noop', {});
+ expect(job.timeout_ms).toBeNull();
+ const claimed = await queue.claim('tok-nomap', 30_000, 'default', ['noop']);
+ expect(claimed).not.toBeNull();
+ expect(claimed!.timeout_ms).toBeNull();
+ expect(claimed!.timeout_at).toBeNull();
+ });
+
+ test('explicit timeout_ms is never overridden at claim', async () => {
+ await queue.add('embed-backfill', { sourceId: 'x' }, { timeout_ms: 5000 });
+ const claimed = await queue.claim('tok-explicit', 30_000, 'default', ['embed-backfill']);
+ expect(claimed).not.toBeNull();
+ expect(claimed!.timeout_ms).toBe(5000);
+ });
+});
+
// --- v0.13.1 #219 — max_stalled default + input surface ---
describe('MinionQueue: v0.13.1 max_stalled schema default (#219)', () => {
@@ -2090,6 +2139,167 @@ describe('MinionQueue: v0.19.1 maxWaiting — cap correctness + race (D2/H2)', (
const c = await queue.add('uncapped', {});
expect(new Set([a.id, b.id, c.id]).size).toBe(3);
});
+
+ // REGRESSION (jobs fix wave): the backpressure scope now reads BOTH payload
+ // spellings. A snake_case source_id submission previously fell into the
+ // NULL-wildcard arm (counted ALL rows for name+queue); it now scopes
+ // exactly like camelCase sourceId. Pin the new arm for maxWaiting too —
+ // the maxPending tests below cover it for the new option only.
+ test('maxWaiting + snake_case source_id: scoped per source, not wildcard', async () => {
+ const a1 = await queue.add('srcsync2', { source_id: 'src-a' }, { maxWaiting: 1 });
+ // Different source: must NOT be swallowed by src-a's waiting row.
+ const b1 = await queue.add('srcsync2', { source_id: 'src-b' }, { maxWaiting: 1 });
+ expect(b1.id).not.toBe(a1.id);
+ // Same source coalesces.
+ const a2 = await queue.add('srcsync2', { source_id: 'src-a' }, { maxWaiting: 1 });
+ expect(a2.id).toBe(a1.id);
+ expect(a2.coalesced).toBe(true);
+ });
+});
+
+// --- maxPending — single-flight counting waiting + LIVE-LOCK active rows ---
+//
+// Jobs fix wave (upstream issue #2): the autopilot dispatch guards failed once
+// a job sat in 'active' — maxWaiting counts only waiting rows and the slot
+// idempotency key rotates every baseInterval, so a stalled cycle accumulated
+// unbounded byte-identical duplicates. maxPending counts waiting rows PLUS
+// live-lock actives (lock_until > now()); an expired-lock active belongs to a
+// dead/blocked worker and must NOT suppress dispatch — the fresh waiting row
+// keeps feeding the waitingClaimable>0 wedge detectors. Scope is EXACT on
+// COALESCE(data.sourceId, data.source_id): NULL matches only NULL.
+//
+// NOTE: the Promise.all race here runs on single-writer PGLite — a smoke
+// check. The advisory-lock guarantee under real concurrency is pinned by the
+// DATABASE_URL-gated e2e (concurrent same-scope submissions on Postgres).
+
+describe('MinionQueue: maxPending — single-flight (waiting + live-lock active)', () => {
+ async function forceActive(id: number, lockUntilSql: string): Promise<void> {
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'active', lock_token = 'tok-mp',
+ lock_until = ${lockUntilSql}, started_at = now() - interval '5 minutes'
+ WHERE id = $1`,
+ [id],
+ );
+ }
+
+ test('cap 1: second submission coalesces onto the waiting row (coalesced metadata set)', async () => {
+ const a = await queue.add('single-flight', {}, { maxPending: 1 });
+ expect(a.coalesced).toBeUndefined(); // fresh insert carries no metadata
+ const b = await queue.add('single-flight', {}, { maxPending: 1 });
+ expect(b.id).toBe(a.id);
+ expect(b.coalesced).toBe(true);
+ });
+
+ test('LIVE-LOCK active row suppresses dispatch (the issue-#2 fix)', async () => {
+ const a = await queue.add('single-flight', {}, { maxPending: 1 });
+ await forceActive(a.id, `now() + interval '5 minutes'`);
+ const b = await queue.add('single-flight', {}, { maxPending: 1 });
+ expect(b.id).toBe(a.id); // coalesced onto the in-flight ACTIVE row
+ expect(b.coalesced).toBe(true);
+ expect(b.status).toBe('active');
+ });
+
+ test('EXPIRED-lock active row does NOT suppress — fresh insert (wedge detectors stay fed)', async () => {
+ const a = await queue.add('single-flight', {}, { maxPending: 1 });
+ await forceActive(a.id, `now() - interval '1 second'`);
+ const b = await queue.add('single-flight', {}, { maxPending: 1 });
+ expect(b.id).not.toBe(a.id);
+ expect(b.status).toBe('waiting');
+ expect(b.coalesced).toBeUndefined();
+ });
+
+ test('waiting row preferred over live active on cap-hit', async () => {
+ const active = await queue.add('single-flight', {}, { maxPending: 2 });
+ await forceActive(active.id, `now() + interval '5 minutes'`);
+ const waiting = await queue.add('single-flight', {}, { maxPending: 2 });
+ expect(waiting.status).toBe('waiting');
+ const c = await queue.add('single-flight', {}, { maxPending: 2 });
+ expect(c.id).toBe(waiting.id); // most-recent WAITING wins the coalesce
+ expect(c.coalesced).toBe(true);
+ });
+
+ test('dead row frees the cap', async () => {
+ const a = await queue.add('single-flight', {}, { maxPending: 1 });
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'dead', finished_at = now() WHERE id = $1`, [a.id],
+ );
+ const b = await queue.add('single-flight', {}, { maxPending: 1 });
+ expect(b.id).not.toBe(a.id);
+ expect(b.status).toBe('waiting');
+ });
+
+ test('EXACT source scope: NULL-source submission never coalesces onto a per-source row (and vice versa)', async () => {
+ const perSource = await queue.add('single-flight', { source_id: 'src-a' }, { maxPending: 1 });
+ // NULL-source submission: per-source row must not count for it.
+ const legacy = await queue.add('single-flight', {}, { maxPending: 1 });
+ expect(legacy.id).not.toBe(perSource.id);
+ // And a second NULL-source submission coalesces onto the legacy row only.
+ const legacy2 = await queue.add('single-flight', {}, { maxPending: 1 });
+ expect(legacy2.id).toBe(legacy.id);
+ // A second per-source submission coalesces onto the per-source row only.
+ const perSource2 = await queue.add('single-flight', { source_id: 'src-a' }, { maxPending: 1 });
+ expect(perSource2.id).toBe(perSource.id);
+ });
+
+ test('snake_case source_id scoping: two sources keep independent caps; same source coalesces', async () => {
+ const a1 = await queue.add('single-flight', { source_id: 'src-a' }, { maxPending: 1 });
+ const b1 = await queue.add('single-flight', { source_id: 'src-b' }, { maxPending: 1 });
+ expect(b1.id).not.toBe(a1.id);
+ const a2 = await queue.add('single-flight', { source_id: 'src-a' }, { maxPending: 1 });
+ expect(a2.id).toBe(a1.id);
+ });
+
+ test('camelCase sourceId scoping parity', async () => {
+ const a1 = await queue.add('single-flight', { sourceId: 'src-a' }, { maxPending: 1 });
+ const b1 = await queue.add('single-flight', { sourceId: 'src-b' }, { maxPending: 1 });
+ expect(b1.id).not.toBe(a1.id);
+ const a2 = await queue.add('single-flight', { sourceId: 'src-a' }, { maxPending: 1 });
+ expect(a2.id).toBe(a1.id);
+ });
+
+ test('clamp: maxPending 0 → 1; floor: 1.7 → 1', async () => {
+ const a = await queue.add('single-flight', {}, { maxPending: 0 });
+ const b = await queue.add('single-flight', {}, { maxPending: 0 });
+ expect(b.id).toBe(a.id); // 0 clamps to 1 → coalesce
+ await engine.executeRaw('DELETE FROM minion_jobs');
+ const c = await queue.add('single-flight', {}, { maxPending: 1.7 });
+ const d = await queue.add('single-flight', {}, { maxPending: 1.7 });
+ expect(d.id).toBe(c.id); // floor(1.7)=1 → coalesce
+ });
+
+ test('race: concurrent submissions hold the cap (PGLite smoke; PG e2e pins the real guarantee)', async () => {
+ const results = await Promise.all(
+ Array.from({ length: 4 }, () => queue.add('single-flight', {}, { maxPending: 1 })),
+ );
+ const ids = new Set(results.map(r => r.id));
+ expect(ids.size).toBe(1);
+ });
+
+ test('both guards supplied: maxPending checked first, both enforced', async () => {
+ // One waiting row. maxPending: 2 passes (1 pending < 2) but
+ // maxWaiting: 1 must still coalesce — both guards apply.
+ const a = await queue.add('single-flight', {}, { maxPending: 2, maxWaiting: 1 });
+ const b = await queue.add('single-flight', {}, { maxPending: 2, maxWaiting: 1 });
+ expect(b.id).toBe(a.id);
+ expect(b.coalesced).toBe(true);
+ // Now force it ACTIVE (live lock): maxWaiting alone would let a new row
+ // in (waiting=0), but maxPending: 1 fires FIRST and coalesces onto the
+ // in-flight row.
+ await forceActive(a.id, `now() + interval '5 minutes'`);
+ const c = await queue.add('single-flight', {}, { maxPending: 1, maxWaiting: 1 });
+ expect(c.id).toBe(a.id);
+ expect(c.coalesced).toBe(true);
+ });
+
+ test('ON CONFLICT idempotency race fallback also carries coalesced metadata', async () => {
+ // Same idempotency_key twice: the fast-path SELECT returns the existing
+ // row with coalesced: true (first coalesce path).
+ const a = await queue.add('single-flight', {}, { idempotency_key: 'sf-key-1' });
+ expect(a.coalesced).toBeUndefined();
+ const b = await queue.add('single-flight', {}, { idempotency_key: 'sf-key-1' });
+ expect(b.id).toBe(a.id);
+ expect(b.coalesced).toBe(true);
+ });
});
describe('resolveWorkerConcurrency (v0.19.1 H3): clamp + validation', () => {