Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(jobs): queue honesty — no_worker refusal, PGLite drain, no_worker vs wedged, doctor PGLite queue_health, embedding_state disabled (E5)
garrytan3f97a1c63fe9
diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.mdindex 1c4df7a9a5..eb9db34405 100644--- a/docs/architecture/key-files/core-minions-2.md+++ b/docs/architecture/key-files/core-minions-2.md@@ -26,5 +26,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/worker-exit-codes.ts` — single source of truth for reserved worker process exit codes, shared by the worker (sets them) and supervisor/CLI (classify them). Exports `WORKER_EXIT_RSS_WATCHDOG = 12` and `WORKER_EXIT_CONFIGURATION = 16`; the latter blocks the owning supervisor before generic crash accounting and requires repair plus explicit restart. The RSS watchdog drain must be self-identifying: a code-0 exit is indistinguishable from a healthy queue-drain, so a `code===0 → clean_exit` classifier would never count it and a respawn loop would stay invisible. A distinct code makes the drain `likely_cause=rss_watchdog`. Code 12 is deliberately outside {0 clean, 1 runtime_error} and the 128+N signal range. Also reserves the `jobs run-child` codes: 13 usage/PGLite, 14 not-claimed/token-mismatch, 15 result-write-failed (result-file presence, not the exit code, classifies the normal path).- `src/core/minions/worker-registry.ts` — live worker registry backing niceness observability. Each running `gbrain jobs work` self-registers `worker-<pid>.json` under `gbrainPath('workers')` (brain-isolated via `GBRAIN_HOME`; entries tagged with `currentBrainId()` so multiple DBs under one home don't cross-report). `registerWorker(info)` is best-effort (never blocks the worker) and returns a cleanup fn the caller wires to BOTH the shutdown `finally` AND `process.on('exit')` (the unhealthy `process.exit(1)` bypasses the awaited finally). `readWorkers(getNice?)` enumerates the dir, drops confirmed-dead pids (`classifyLiveness`: ESRCH = dead/prune, EPERM = alive/keep), applies a pid-reuse start-time guard (zone-free `ps -o etime=` parsed by `parseEtimeToMs`, start = now - elapsed; rejects a pid that started >5s after the entry was written), and re-measures each live worker's niceness now. Reports the worker's REAL pid, sidestepping the tini-wrapper-pid problem. Pinned by `test/worker-registry.serial.test.ts`.+- `src/core/minions/no-worker.ts` — queue honesty (agent-first operator wave E5). `queueWorkerAlive(queue, read?)` (a live registered worker serves the queue on this host; undefined when the registry is unreadable), `runWaitingJobsFix(engineKind, queue)` (PGLite: `gbrain jobs work [--queue Q]`, a foreground drain, `requires_exclusive`; Postgres: `gbrain jobs supervisor start`), `noWorkerNotice(...)` (code `no_worker`, kind `degraded`). Consumers: CLI `jobs submit` on PGLite refuses without `--follow` unless `--queue-only` (`src/commands/jobs/submit.ts`); `gbrain jobs work` on PGLite drains via `drainPgliteQueue` (`src/commands/jobs/work.ts`) and exits; MCP `submit_job` / `get_job_stats` emit the notice (`src/core/ops/jobs.ts`, PGLite fix wrapped by readiness `exclusiveFix` behind a running serve); `deriveWedgeSignal(wedge, {workerAlive})` returns `no_worker` and never calls that case wedged (`jobs stats`, `get_job_stats`); doctor `queue_health` counts PGLite waiting rows (`src/commands/doctor/checks/queue-jobs.ts`). Pinned by `test/queue-no-worker.test.ts`.- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). The `ready` event follows final startup checks; listener failure stops startup before claims or timers. The renewal adapter latches typed configuration faults before the generic retry tick consumes them, including deadline verification. Configuration shutdown stops claims, tracks actual executions separately from scheduling slots, and releases only confirmed stopped work through `MinionQueue.releaseConfigurationJob` within one bounded shutdown envelope. The active/token-fenced release returns `released`, `no_op` or `unconfirmed`, leaves attempt/stall counters unchanged, and delays released work for 30 seconds; an unconfirmed stop or DB write falls back to lease expiry. Outstanding claims register their token before the post-claim configuration check so late claims cannot launch handlers. Aborted jobs call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`); `shutdownAbort` (instance field) fires on SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` (shell handler listens; non-shell handlers don't). Per-job timeout fires `abort.abort(new Error('timeout'))` then a 30s grace-then-evict safety net force-evicts the job from `inFlight` and marks it dead if the handler ignores the abort signal (the generic abort listener fires for ANY abort reason). The `launchJob` lock-renewal block is a thin sync wrapper around the pure `runLockRenewalTick` from `src/core/minions/lock-renewal-tick.ts` (NEVER `setInterval(async () => await renewLock(...))` — that shape surfaces an unhandledRejection during PgBouncer rotation). Guarantees: (1) `cancelled` flag captured in the timer closure stops in-flight IIFEs writing misleading audit events after the job ended; (2) re-entrancy guard `tickInFlight` (skips counted as `overlapSkips` telemetry) + per-call `Promise.race` timeout with best-effort AbortSignal cancellation; (3) verify-before-evict: eviction requires a fenced-false (certain loss) or the `hardEvictMs` backstop — never bare local arithmetic; the per-job lease (`job.lock_duration_ms ?? opts.lockDuration`) drives the renewal state, and the cadence clamps to `min(lease/2, 60s)`; (4) explicit `.catch()` on the stored `executeJob(...).finally(...)` promise closes the second unhandledRejection vector; (5) exported `INFRASTRUCTURE_ABORT_REASONS = new Set(['lock-renewal-failed', 'lock-lost'])` so executeJob's catch skips `failJob` for these (PgBouncer blips don't dead-letter healthy jobs; the stall detector reclaims); worker configuration shutdown is not in this set — it is gated separately by the typed `configurationError` latch; (6) inFlight generation-safety — force-evict and the handler's finally delete the inFlight entry ONLY when it still carries their own lockToken (the token is the generation; an evicted execution's late delete cannot remove a same-worker re-claim's entry); (7) eviction observability — the worker keeps a `perf_hooks.monitorEventLoopDelay` histogram (reset on every successful renewal, sampled ns→ms at eviction) plus raw loadavg, and both the abort and grace-evict log lines carry cause / since-last-success / tick-lateness / overlap-skips / load / event-loop-delay from the stashed `abortMeta`. CI guard `scripts/check-worker-lock-renewal-shape.sh` (in `bun run verify`) asserts the bug pattern stays absent AND `launchJob` keeps calling `runLockRenewalTick`. Engine-ownership invariant: `start()` does NOT call `engine.disconnect()` on shutdown — the CLI handler in `src/commands/jobs.ts case 'work'` owns engine lifecycle via try/finally with loud error logging. RSS watchdog uses non-file-backed pages on Linux: exported `parseRssFromProcStatus(status)` (pure parser; field-presence regex so `RssAnon: 0 + RssShmem: 512` parses correctly) and `getAccurateRss(readStatus?)` (reads `/proc/self/status` for `RssAnon + RssShmem`, falls back to `process.memoryUsage().rss` on macOS / restricted containers / kernel <4.5); the default `getRss` in `WorkerOpts` is `getAccurateRss`. `checkMemoryLimit` tracks peak RSS, fires an 80%-of-cap soft-warn (once per crossing, carrying peak + in-flight job kinds), and on exceed sets `_rssWatchdogTriggered=true` (exposed via `get rssWatchdogTriggered()`) so `jobs work`'s finally can `process.exit(WORKER_EXIT_RSS_WATCHDOG)` after disconnect (drain self-identifying instead of an opaque code-0 exit). The poll loop wraps `claim` in try/catch: on a retryable conn error it reconnects ONCE and continues to the next tick rather than blind-retrying (a retry after `UPDATE...RETURNING` committed but the socket died would double-claim). `LockRenewalDeps` is wired with `reconnect` when the engine supports it. The self-health DB-liveness probe runs EVEN under a supervisor (`GBRAIN_SUPERVISED=1`): the outer guard is `if (this.opts.healthCheckInterval > 0)` and only the STALL-detection block is wrapped in `if (!isSupervisedChild)` — so a supervised worker whose own pool dies self-exits `unhealthy(db_dead)` after `dbFailExitAfter` probes (the supervisor watches a different connection and can't see this worker's dead pool), while the supervisor's progress watchdog owns forward-progress. Pinned by the `test/worker-lock-renewal.test.ts` hermetic suite, `test/audit/lock-renewal-audit.test.ts`, `test/scripts/check-worker-lock-renewal-shape.test.ts`, `test/worker-shutdown-disconnect.test.ts` (asserts `disconnectSpy).not.toHaveBeenCalled()`), `test/worker-rss.test.ts` (11), `test/worker-supervised-db-probe.test.ts` (3). Per-job process isolation: `MinionWorkerOpts.jobIsolation` (`inline`|`process`) + `childCliInvocation`/`childTiniPath` swap `handler(context)` for `runJobInChild(...)` in executeJob — every reporting branch (completeJob, failJob, lease release, infra no-burn) is reused on the child outcome; when isolated the parent-side context is not built at all. Three extra no-burn child classes in the catch: `ChildSpawnInfraError` + `ChildWorkerShutdownError` (released, no attempt burned) and `ChildNotClaimedError` (the child proved the claim was already gone — reclaimed/cancelled before the handler ran — so nothing is recorded against it). The health probe delegates to `runDbProbe` (db-probe.ts) with a cancellation signal on every probe and emits a `verdict` (`pool_starved`/`server_unreachable`/`unknown`/`client_misconfigured`); typed configuration faults block immediately instead of burning the transient DB failure threshold. `getHandler(name)` is the read-only registry accessor run-child uses.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 4689034ae0..6765c982d9 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -9,7 +9,7 @@ src/commands/doctor.ts 666 ratchet refactor wave 1 split target (W4 doctor); ceisrc/commands/embed.ts 2217 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts)src/commands/extract-conversation-facts.ts 2182 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch)src/commands/extract.ts 2528 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit)-src/commands/jobs.ts 658 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2)+src/commands/jobs.ts 660 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5)src/commands/serve-http.ts 917 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts)src/core/ai/gateway.ts 4393 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts)src/commands/sync.ts 473 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals)diff --git a/src/commands/doctor/checks/queue-jobs.ts b/src/commands/doctor/checks/queue-jobs.tsindex b6fa60885b..92ec14157b 100644--- a/src/commands/doctor/checks/queue-jobs.ts+++ b/src/commands/doctor/checks/queue-jobs.ts@@ -7,7 +7,8 @@import type { BrainEngine } from '../../../core/engine.ts';import { resolveEnvNumber } from '../../../core/env-number.ts';import type { Check } from '../../doctor.ts';-import { checkError } from '../check-fix.ts';+import { checkError, doctorVerify } from '../check-fix.ts';+import { queueWorkerAlive, runWaitingJobsFix } from '../../../core/minions/no-worker.ts';/** Local alias; the shared warn-once memo lives in core so it can't fork per module. */const _resolveEnvNumber = resolveEnvNumber;@@ -32,7 +33,7 @@ const _resolveEnvNumber = resolveEnvNumber;* startup so bad GBRAIN_BULK_* config fails at doctor time, not first-retry.*//**- * queue_health: Postgres Minion queue diagnostics.+ * queue_health: Minion queue diagnostics (PGLite: waiting rows with no worker, see computePgliteQueueHealth).** Includes the original stalled/depth/memory/prompt checks plus the #2557* no-worker signal: old `embed-backfill` jobs waiting on a queue with no live@@ -48,13 +49,7 @@ export async function computeQueueHealthCheck(readWorkers?: () => Array<{ queue: string }>;} = {},): Promise<Check> {- if (engine.kind === 'pglite') {- return {- name: 'queue_health',- status: 'ok',- message: 'Skipped (PGLite — no multi-process worker surface)',- };- }+ if (engine.kind === 'pglite') return computePgliteQueueHealth(engine, opts.readWorkers);try {// issue #1801: column is `status`, not `state` (schema.sql:780).@@ -276,18 +271,48 @@ export async function computeQueueHealthCheck(details,};}+ const noWorkerQueue = oldWaitingRows.find(r => !liveWorkerQueues.has(r.queue))?.queue;return {name: 'queue_health',status: 'warn',message: problems.join(' '),details,+ ...(noWorkerQueue !== undefined+ ? { fix: { ...runWaitingJobsFix(engine.kind, noWorkerQueue), verify: doctorVerify('queue_health') } }+ : { fix_unavailable_reason: 'operator_judgement' as const }),};} catch (e) {+ return checkError('queue_health', 'scan queue health', e);+ }+}++/**+ * queue_health on PGLite (agent-first operator wave E5): there is no+ * background worker, so every waiting row (outside parent-owned dream-inline+ * queues) waits until a foreground `gbrain jobs work` drain runs it. Counted+ * and reported as `no_worker` with that drain as the fix (it needs the brain+ * exclusively). A live drain registered for the queue reads as ok.+ */+async function computePgliteQueueHealth(engine: BrainEngine, readWorkers?: () => Array<{ queue: string }>): Promise<Check> {+ try {+ const rows = await engine.executeRaw<{ queue: string; depth: number | string; oldest_age_seconds: number | string | null }>(+ `SELECT queue, count(*)::int AS depth, EXTRACT(EPOCH FROM (now() - min(created_at)))::int AS oldest_age_seconds+ FROM minion_jobs WHERE status = 'waiting' GROUP BY queue ORDER BY count(*) DESC, queue`,+ );+ const { isDreamInlinePrivateQueue } = await import('../../../core/minions/queue.ts');+ const waiting = rows.filter(r => !isDreamInlinePrivateQueue(r.queue) && queueWorkerAlive(r.queue, readWorkers) !== true);+ const depth = waiting.reduce((n, r) => n + Number(r.depth), 0);+ const details = { engine: 'pglite', depth, by_queue: Object.fromEntries(waiting.map(r => [r.queue, Number(r.depth)])), worker_alive: depth === 0 };+ if (depth === 0) return { name: 'queue_health', status: 'ok', message: 'PGLite: no jobs waiting for a worker.', details };+ const top = waiting[0]!;+ const hours = Math.floor(Number(top.oldest_age_seconds ?? 0) / 3600);return {- name: 'queue_health',- status: 'warn',- message: `queue_health scan skipped: ${e instanceof Error ? e.message : String(e)}`,+ name: 'queue_health', status: 'warn', details,+ message: `no_worker: ${depth} job(s) are waiting (${waiting.map(r => `${r.queue}=${Number(r.depth)}`).join(', ')}; oldest ${hours}h) and PGLite has no background worker, so they run only when a \`gbrain jobs work\` drain does.`,+ fix: { ...runWaitingJobsFix('pglite', top.queue), verify: doctorVerify('queue_health') },};+ } catch (e) {+ return checkError('queue_health', 'count waiting jobs', e);}}diff --git a/src/commands/jobs.ts b/src/commands/jobs.tsindex cf1d06d0c4..7c97053708 100644--- a/src/commands/jobs.ts+++ b/src/commands/jobs.ts@@ -250,7 +250,7 @@ Other subcommands are fully described above.* 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)+ work: `gbrain jobs work — start a worker daemon (PGLite: drain the queue and exit)USAGEgbrain jobs work [--queue Q] [--concurrency N] [--max-rss MB]@@ -287,8 +287,9 @@ OPTIONSNegative values need root.NOTES- Requires the Postgres engine — PGLite's exclusive file lock cannot host- a long-lived daemon. For crash-resilient operation prefer:+ PGLite's exclusive file lock cannot host a long-lived daemon: there it runs+ the waiting jobs in the foreground and exits once the queue is drained+ (stop any running \`gbrain serve\` first). On Postgres prefer:gbrain jobs supervisor start --detach --json`,supervisor: `gbrain jobs supervisor — auto-restarting wrapper around 'gbrain jobs work'@@ -337,14 +338,15 @@ USAGE[--backoff-type fixed|exponential] [--backoff-delay Nms][--backoff-jitter 0..1] [--timeout-ms Nms][--lock-duration-ms Nms]- [--idempotency-key K] [--queue Q] [--dry-run]- [--redact-secrets]+ [--idempotency-key K] [--queue Q] [--queue-only]+ [--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)+ --follow Run inline and stream progress (works on both engines;+ required on PGLite, which has no background worker)+ --queue-only PGLite: queue without running (\`gbrain jobs work\` drains)--priority N Lower runs first (default 0)--delay Nms Delay before the job becomes claimable (default 0)--max-attempts N Retry budget (default 3)diff --git a/src/commands/jobs/stats.ts b/src/commands/jobs/stats.tsindex be352fff58..a5d0959b72 100644--- a/src/commands/jobs/stats.ts+++ b/src/commands/jobs/stats.ts@@ -48,10 +48,15 @@ export async function runJobsStats({ args, engine, queue }: JobsCommandContext):const { sanitizeTypeForDisplay: sanitizeName } = await import('../../core/schema-pack/type-usage.ts');const { safeConfigSegment } = await import('../../core/minions/admission.ts');+ const { queueWorkerAlive } = await import('../../core/minions/no-worker.ts');+ const signal = deriveWedgeSignal(stats.wedge, { workerAlive: queueWorkerAlive(stats.wedge.queue) });+if (hasFlag(args, '--json')) {console.log(JSON.stringify({queue: statsQueue,...stats,+ wedged: signal.wedged,+ no_worker: signal.no_worker,divergent: divergent.map(t => ({name: t.name,intake_24h: t.total,@@ -137,7 +142,7 @@ export async function runJobsStats({ args, engine, queue }: JobsCommandContext):const mins = w.minutes_since_completion;// Shared derivation (queue.ts deriveWedgeSignal) so this line, the// doctor wedged_queue check, and the get_job_stats op agree (#1801).- const { wedged, wedge_threshold_minutes: wedgeMins, private_queue } = deriveWedgeSignal(w);+ const { wedged, no_worker, wedge_threshold_minutes: wedgeMins, private_queue } = signal;// Parent-owned dream-inline queue: no shared worker can EVER claim it,// so the supervisor-restart advice below would be a dead end (the// incident bug class). Gate the ABANDONED line on the SAME classifier@@ -155,6 +160,8 @@ export async function runJobsStats({ args, engine, queue }: JobsCommandContext):? ` Auto-recovery cancels it at the next worker spawn or dream-cycle start.`: ` Legacy unowned queue: preview \`gbrain dream retriage --help\` before manual cancellation.`),);+ } else if (no_worker) {+ await printNoWorker(engine.kind, w.queue, w.waiting);} else if (wedged) {const since = mins === null ? 'no completions on record' : `${mins}m since last completion`;console.log(@@ -293,3 +300,15 @@ export async function runJobsStats({ args, engine, queue }: JobsCommandContext):}}}++/** Queue honesty (agent-first operator wave E5): waiting work with no worker is not a wedge; name the fix. */+async function printNoWorker(engineKind: string, queue: string, waiting: number): Promise<void> {+ const { runWaitingJobsFix } = await import('../../core/minions/no-worker.ts');+ const { shellQuote } = await import('../../core/agent-output.ts');+ const fix = runWaitingJobsFix(engineKind, queue);+ console.log(+ `\n ⚠ NO WORKER for queue '${queue}': ${waiting} waiting and no worker is running` ++ `${engineKind === 'pglite' ? ' (PGLite has no background worker)' : ''}; nothing is stuck, nothing is running them.\n` ++ ` Fix: ${shellQuote(fix.argv ?? [])} # ${fix.why}`,+ );+}diff --git a/src/commands/jobs/submit.ts b/src/commands/jobs/submit.tsindex 35e8e25372..d03a387069 100644--- a/src/commands/jobs/submit.ts+++ b/src/commands/jobs/submit.ts@@ -99,6 +99,11 @@ export async function runJobsSubmit({ args, engine, queue }: JobsCommandContext)return;}+ if (engine.kind === 'pglite' && !follow && !hasFlag(args, '--queue-only')) {+ await refuseNoWorker(args, name, queueName);+ return;+ }+try { await queue.ensureSchema(); }catch (e) { console.error(e instanceof Error ? e.message : String(e)); process.exit(1); }@@ -221,3 +226,25 @@ export async function runJobsSubmit({ args, engine, queue }: JobsCommandContext)console.log(JSON.stringify(job, null, 2));}}++/**+ * Queue honesty (agent-first operator wave E5): PGLite has no background+ * worker, so a plain submit would leave the job waiting with no error. Refuse+ * with `no_worker` and the exact `--follow` command; `--queue-only` queues it+ * deliberately for a later `gbrain jobs work` drain.+ */+async function refuseNoWorker(args: string[], name: string, queueName: string): Promise<void> {+ const { opError } = await import('../../core/ops/contract.ts');+ const { renderCliError } = await import('../../core/agent-output.ts');+ const { setCliExitVerdict, writeStdoutFinal } = await import('../../core/cli-force-exit.ts');+ const err = opError('no_worker',+ `PGLite has no background worker, so job '${name}' would wait in queue '${queueName}' until something runs it. Nothing was queued.`,+ 'Run it now with --follow, or pass --queue-only to queue it for a later `gbrain jobs work` drain.',+ { why: 'PGLite brains have no background worker (the database is single-writer), so a queued job waits with no error until a `gbrain jobs work` drain runs it.',+ fix: { argv: ['gbrain', 'jobs', ...args, '--follow'], consent: [], actor: 'agent', requires_exclusive: true,+ why: '--follow runs the job in this process and waits for its result; it needs the brain to itself, so any running `gbrain serve` must stop first.' } });+ const out = renderCliError(err, { json: hasFlag(args, '--json'), command: 'jobs submit', tty: !!process.stderr.isTTY });+ if (out.stdout) await writeStdoutFinal(out.stdout);+ if (out.stderr) process.stderr.write(out.stderr);+ setCliExitVerdict(out.exitCode);+}diff --git a/src/commands/jobs/work.ts b/src/commands/jobs/work.tsindex 8b8368f679..6e7a30f5a9 100644--- a/src/commands/jobs/work.ts+++ b/src/commands/jobs/work.ts@@ -7,6 +7,7 @@ import { LocalConfigurationError, isLocalConfigurationError } from '../../core/mimport { WORKER_EXIT_CONFIGURATION, WORKER_EXIT_RSS_WATCHDOG } from '../../core/minions/worker-exit-codes.ts';import { MinionWorker, type UnhealthyReason } from '../../core/minions/worker.ts';import type { MinionQueue } from '../../core/minions/queue.ts';+import type { BrainEngine } from '../../core/engine.ts';export async function maybeRunWorkerStartupRecovery(queue: MinionQueue,@@ -41,14 +42,6 @@ export async function maybeRunWorkerStartupRecovery(export async function runJobsWork({ args, engine, queue }: JobsCommandContext): Promise<void> {// Lazy: jobs.ts imports this module statically, so a static import back would be a cycle.const { registerBuiltinHandlers } = await import('../jobs.ts');- // Check if PGLite- const config = (await import('../../core/config.ts')).loadConfig();- if (config?.engine === 'pglite') {- console.error('Error: Worker daemon requires Postgres. PGLite uses an exclusive file lock that blocks other processes.');- console.error('Use --follow for inline execution: gbrain jobs submit <name> --follow');- process.exit(1);- }-// --allow-shell-jobs (supervisor pass-through, see buildWorkerArgs): the// startup cwd-.env quarantine drops GBRAIN_ALLOW_SHELL_JOBS when a .env// in this worker's cwd assigns it, so the flag re-asserts the operator's@@ -56,6 +49,10 @@ export async function runJobsWork({ args, engine, queue }: JobsCommandContext):if (hasFlag(args, '--allow-shell-jobs')) process.env.GBRAIN_ALLOW_SHELL_JOBS = '1';const queueName = parseFlag(args, '--queue') ?? 'default';+ if (engine.kind === 'pglite') {+ await drainPgliteQueue(engine, queue, queueName, registerBuiltinHandlers);+ return;+ }const concurrency = resolveWorkerConcurrency(args);// --max-rss: explicit value wins (including 0 to disable the watchdog).// Absent → cgroup-aware auto-size (issue #1678): the flat 2048MB default@@ -290,6 +287,47 @@ export async function runJobsWork({ args, engine, queue }: JobsCommandContext):}}+/**+ * PGLite has no background worker (the brain is single-writer, so a daemon+ * would lock every other command out). There `gbrain jobs work` drains (agent-+ * first operator wave E5): it runs the queue's waiting jobs in the foreground,+ * registered as a live worker, and exits once none it can run are waiting or+ * active. Jobs scheduled for a later retry stay queued and are named.+ */+export async function drainPgliteQueue(+ engine: BrainEngine,+ queue: MinionQueue,+ queueName: string,+ registerHandlers: (worker: MinionWorker, engine: BrainEngine) => Promise<void>,+): Promise<{ delayed: number }> {+ await queue.ensureSchema();+ const worker = new MinionWorker(engine, { queue: queueName, pollInterval: 200, healthCheckInterval: 0 });+ await registerHandlers(worker, engine);+ const names = worker.registeredNames;+ const count = async (statuses: string[]): Promise<number> => {+ const [row] = await engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM minion_jobs WHERE queue = $1 AND status = ANY($2::text[]) AND name = ANY($3::text[])',+ [queueName, statuses, names]);+ return Number(row?.n ?? 0);+ };+ const { registerWorker } = await import('../../core/minions/worker-registry.ts');+ const unregister = registerWorker({ pid: process.pid, queue: queueName, nice_requested: null, nice_effective: null, started_at: Date.now() });+ console.log(`Draining queue '${queueName}' in the foreground (PGLite has no background worker): ${await count(['waiting', 'active'])} runnable job(s).`);+ const running = worker.start();+ const poll = setInterval(() => {+ count(['waiting', 'active']).then(n => { if (n === 0) worker.stop(); }, () => worker.stop());+ }, 500);+ try {+ await running;+ } finally {+ clearInterval(poll);+ unregister();+ }+ const delayed = await count(['delayed']);+ console.log(`Queue '${queueName}' drained.${delayed > 0 ? ` ${delayed} job(s) are scheduled for a later retry; run \`gbrain jobs work${queueName === 'default' ? '' : ` --queue ${queueName}`}\` again after their backoff.` : ''}`);+ return { delayed };+}+/*** `jobs work` listener for the worker's self-health failures: report the* failing layer and exit so the process manager restarts the worker.diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex fb872252c8..a587d891ec 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -72,7 +72,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'init': ['--all', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--quiet', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--version', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],- 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--fact', '--facts', '--federated-read', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--images', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--prune-orphans', '--queue', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--take', '--target', '--thin', '--thin-threshold', '--timeline', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--fact', '--facts', '--federated-read', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--images', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--take', '--target', '--thin', '--thin-threshold', '--timeline', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all', '--wait'],'loops': ['--all', '--as-of', '--brain', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],diff --git a/src/core/minions/no-worker.ts b/src/core/minions/no-worker.tsnew file mode 100644index 0000000000..c4ab1853a9--- /dev/null+++ b/src/core/minions/no-worker.ts@@ -0,0 +1,54 @@+/**+ * Queue honesty (agent-first operator wave, Lane E5): whether anything runs a+ * queue's waiting jobs, and the one Action that runs them when nothing does.+ *+ * PGLite has no background worker (the database is single-writer), so a job+ * queued there waits until `gbrain jobs work` drains the queue in the+ * foreground or `gbrain jobs submit --follow` runs it inline. A Postgres queue+ * needs a running worker (`gbrain jobs supervisor start`). `jobs submit`,+ * `submit_job`, `jobs stats` / `get_job_stats` and doctor's queue_health all+ * build their `no_worker` advice here so the surfaces cannot disagree.+ */+import type { Action, Notice } from '../agent-output.ts';+import { readWorkers } from './worker-registry.ts';++/**+ * True when a live registered worker (`gbrain jobs work`, supervised or a+ * PGLite drain) serves `queue` on this host; undefined when the registry+ * cannot be read (callers keep their pre-E5 behavior).+ */+export function queueWorkerAlive(queue: string, read: () => Array<{ queue: string }> = () => readWorkers(() => null)): boolean | undefined {+ try {+ return read().some(w => w.queue === queue);+ } catch {+ return undefined;+ }+}++/** The fix that runs a queue's waiting jobs: a foreground drain on PGLite, the supervisor on Postgres. */+export function runWaitingJobsFix(engineKind: string, queue: string): Action {+ const queueArgs = queue === 'default' ? [] : ['--queue', queue];+ const verify = { argv: ['gbrain', 'jobs', 'stats', '--json', ...queueArgs] };+ if (engineKind === 'pglite') {+ return {+ argv: ['gbrain', 'jobs', 'work', ...queueArgs], consent: [], actor: 'agent', requires_exclusive: true, verify,+ why: 'PGLite has no background worker: `gbrain jobs work` runs the waiting jobs in the foreground and exits once the queue is drained. It needs the brain to itself, so any running `gbrain serve` must stop first.',+ };+ }+ return {+ argv: ['gbrain', 'jobs', 'supervisor', 'start', ...queueArgs], consent: [], actor: 'agent', requires_exclusive: false, verify,+ why: 'Starts the job supervisor, which keeps a worker running for this queue and restarts it if it dies.',+ };+}++/** The `no_worker` notice: jobs are waiting (or were just queued) and nothing will run them until a worker does. */+export function noWorkerNotice(engineKind: string, queue: string, waiting: number, fix: Action = runWaitingJobsFix(engineKind, queue)): Notice {+ const pglite = engineKind === 'pglite';+ return {+ code: 'no_worker', kind: 'degraded', fix,+ why: `${waiting} job(s) are waiting on queue '${queue}' and no worker is running${pglite ? ' (PGLite has no background worker)' : ''}, so they will not run until one does.`,+ user_message: pglite+ ? 'Queued background jobs only run when gbrain is given the database to itself for a moment. Can I pause the gbrain server briefly to run them?'+ : 'Background jobs are queued but no gbrain worker is running. Can I start the job supervisor so they run?',+ };+}diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.tsindex 712459815d..302fba3f43 100644--- a/src/core/minions/queue.ts+++ b/src/core/minions/queue.ts@@ -2476,13 +2476,19 @@ export class MinionQueue {* zero live-lock active rows, waiting > 0, and the last completion is older* than the threshold (or absent). Threshold matches the doctor wedged_queue* check: GBRAIN_WEDGED_QUEUE_WARN_MINUTES (server-side env), default 15.+ *+ * Queue honesty (agent-first operator wave E5): when the caller knows no+ * worker is running for the queue (`workerAlive: false` — always on PGLite+ * unless a `gbrain jobs work` drain is live), waiting work is `no_worker`, not+ * wedged: nothing is stuck, nothing is running it. Omitted liveness keeps the+ * pre-E5 derivation (doctor's wedged_queue check).*/export function deriveWedgeSignal(wedge: {queue?: string;active_healthy: number;waiting: number;minutes_since_completion: number | null;-}): { wedged: boolean; wedge_threshold_minutes: number; private_queue: boolean } {+}, liveness: { workerAlive?: boolean } = {}): { wedged: boolean; no_worker: boolean; wedge_threshold_minutes: number; private_queue: boolean } {const raw = parseInt(process.env.GBRAIN_WEDGED_QUEUE_WARN_MINUTES ?? '', 10);const wedge_threshold_minutes = Number.isFinite(raw) && raw > 0 ? raw : 15;// A dream-inline private queue is parent-owned: no shared worker will ever@@ -2491,7 +2497,8 @@ export function deriveWedgeSignal(wedge: {// (jobs stats, get_job_stats op, doctor) points at reconciliation.const private_queue = wedge.queue !== undefined && isDreamInlinePrivateQueue(wedge.queue);const mins = wedge.minutes_since_completion;- const wedged = !private_queue && wedge.active_healthy === 0 && wedge.waiting > 0+ const no_worker = !private_queue && liveness.workerAlive === false && wedge.waiting > 0;+ const wedged = !private_queue && !no_worker && wedge.active_healthy === 0 && wedge.waiting > 0&& (mins === null || mins > wedge_threshold_minutes);- return { wedged, wedge_threshold_minutes, private_queue };+ return { wedged, no_worker, wedge_threshold_minutes, private_queue };}diff --git a/src/core/ops/jobs.ts b/src/core/ops/jobs.tsindex 24a817dbb8..05b642204c 100644--- a/src/core/ops/jobs.ts+++ b/src/core/ops/jobs.ts@@ -204,10 +204,36 @@ const submit_job: Operation = {// Amendments 24/25: post-enqueue queue-state probe (time-bounded,// fail-open). The job is already persisted; a probe failure degrades to// {probe_failed: true}, never an error on a successful submission.+ await emitNoWorkerNotice(ctx, job.queue);return { ...publicJob(job), queue_state: await probeQueueStateSafe(ctx, job.queue, [name]) };},};+/**+ * Queue honesty (agent-first operator wave E5): an accepted job on a queue no+ * worker serves (always on PGLite unless a `gbrain jobs work` drain is live)+ * gets a model-visible `no_worker` notice with the drain/supervisor fix; a+ * PGLite fix behind a running serve becomes the stop-serve-then-run plan.+ * Best-effort: advice never fails a committed submission.+ */+async function emitNoWorkerNotice(ctx: OperationContext, queueName: string): Promise<void> {+ if (!ctx.emitNotice) return;+ try {+ const { queueWorkerAlive, noWorkerNotice, runWaitingJobsFix } = await import('../minions/no-worker.ts');+ const alive = queueWorkerAlive(queueName);+ if (alive !== false) return;+ const [row] = await ctx.engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM minion_jobs WHERE queue = $1 AND status = 'waiting'", [queueName]);+ const waiting = Number(row?.n ?? 0);+ if (waiting === 0) return;+ let fix = runWaitingJobsFix(ctx.engine.kind, queueName);+ if (ctx.config) {+ const { configReadiness, exclusiveFix } = await import('../readiness.ts');+ fix = exclusiveFix(fix, configReadiness(ctx.config, { transport: ctx.transport ?? 'stdio' }).lock_owner);+ }+ ctx.emitNotice(noWorkerNotice(ctx.engine.kind, queueName, waiting, fix));+ } catch { /* advice is best-effort */ }+}+/*** Wrapper around `probeQueueState` that also swallows module-load failures,* so BOTH submit surfaces (submit_job, submit_agent) satisfy amendment 24's@@ -747,6 +773,8 @@ const get_job_stats: Operation = {'(unfiltered); by_type is windowed by since_hours; only the wedge block is scoped to ' +'the queue param. wedged: true is the silent-halt signal (a worker is alive but claiming ' +'nothing while work waits) — suggest restarting the jobs supervisor on the brain host. ' ++ 'no_worker: true means work is waiting and NO worker is running for the queue (always on PGLite ' ++ 'unless a gbrain jobs work drain is live); wedged is then false and the no_worker notice names the fix. ' +'private_queue: true means the queue is a parent-owned dream-inline queue: wedged is ' +'NEVER true for it and a worker restart cannot help — recovery runs automatically at ' +'worker spawn / dream-cycle start; suggest gbrain doctor for the per-queue verdict. ' +@@ -768,10 +796,12 @@ const get_job_stats: Operation = {since: new Date(Date.now() - hours * 3_600_000),queue: typeof p.queue === 'string' && p.queue.length > 0 ? p.queue : 'default',});- const { wedged, wedge_threshold_minutes, private_queue } = deriveWedgeSignal(stats.wedge);+ const { queueWorkerAlive } = await import('../minions/no-worker.ts');+ const { wedged, no_worker, wedge_threshold_minutes, private_queue } = deriveWedgeSignal(stats.wedge, { workerAlive: queueWorkerAlive(stats.wedge.queue) });+ if (no_worker) await emitNoWorkerNotice(ctx, stats.wedge.queue);// private_queue tells the MCP consumer "restart the worker" is dead-end// advice for this queue — it is parent-owned and needs reconciliation.- return { schema_version: 1, window_hours: hours, ...stats, wedged, wedge_threshold_minutes, private_queue };+ return { schema_version: 1, window_hours: hours, ...stats, wedged, no_worker, wedge_threshold_minutes, private_queue };}, 'Job queue statistics (minions schema)');},};diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.tsindex ff26878199..bfe5d1b2af 100644--- a/src/core/persistence/effect-journal.ts+++ b/src/core/persistence/effect-journal.ts@@ -8,6 +8,7 @@ import { sha256 } from './digest.ts';import { PARK_AFTER_FAILURES, type EffectKind, type PersistenceEffect, type EffectRequest } from './effect-model.ts';import type { SqlEngine } from './model.ts';import { isFactsExtractionEnabled } from '../facts/extract.ts';+import { loadConfig } from '../config.ts';import { resolveDefaultVisibility } from '../facts/visibility.ts';import { declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { refreshFenceClear } from './worktree-refresh-schema.ts';@@ -33,7 +34,7 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques}if (snapshot && !snapshot.page.deleted_at) {if (!prepared?.deferEmbedding) await queue('embedding');- outcome.embedding_state = prepared?.deferEmbedding ? 'deferred' : 'queued';+ outcome.embedding_state = await embeddingDisabled(tx) ? 'disabled' : prepared?.deferEmbedding ? 'deferred' : 'queued';if ((outcome.facts_backstop as { queued?: boolean } | undefined)?.queued) {if (!(await isFactsExtractionEnabled(tx))) outcome.facts_backstop = { skipped: 'extraction_disabled' };else await queue('facts-backstop', { visibility: await resolveDefaultVisibility(tx) });@@ -41,6 +42,18 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques}}+/**+ * A keyless brain (`init --no-embedding`: `embedding_disabled` on the file or+ * DB plane, the same pair the embedding effect refuses on) reports+ * `embedding_state: "disabled"` (agent-first operator wave E5): its+ * embedding effect settles as skipped, so "queued" would promise vectors that+ * never arrive.+ */+async function embeddingDisabled(tx: BrainEngine): Promise<boolean> {+ if (loadConfig()?.embedding_disabled === true) return true;+ return (await tx.getConfig('embedding_disabled')) === 'true';+}+/** Claims release their database connection before waiting for a filesystem lock/provider. Nothing on a refresh-fenced worktree is claimed. */export async function claimPersistenceEffect(engine: BrainEngine, hostId: string): Promise<PersistenceEffect | null> {return engine.transactionDirect(async tx => {diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex c08fca9bdf..d6d9c8eed8 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 229615,- "stdoutSha256": "aaf93740a028c3db9ce963308738d61d0d1b008b249b4cbf6430e1a6fd859630",+ "stdoutBytes": 229813,+ "stdoutSha256": "4723e380e7694e87602f51aa5c272495285d56340cd528c20090aea849125d1f","toolNames": ["remember","entity",@@ -3391,7 +3391,7 @@"scope": "agent"},{- "description": "Job queue statistics. PER-BLOCK scoping: by_status and queue_health are GLOBAL (unfiltered); by_type is windowed by since_hours; only the wedge block is scoped to the queue param. wedged: true is the silent-halt signal (a worker is alive but claiming nothing while work waits) — suggest restarting the jobs supervisor on the brain host. private_queue: true means the queue is a parent-owned dream-inline queue: wedged is NEVER true for it and a worker restart cannot help — recovery runs automatically at worker spawn / dream-cycle start; suggest gbrain doctor for the per-queue verdict. Host-process diagnostics (renice, backpressure hints) stay on the gbrain jobs stats CLI.",+ "description": "Job queue statistics. PER-BLOCK scoping: by_status and queue_health are GLOBAL (unfiltered); by_type is windowed by since_hours; only the wedge block is scoped to the queue param. wedged: true is the silent-halt signal (a worker is alive but claiming nothing while work waits) — suggest restarting the jobs supervisor on the brain host. no_worker: true means work is waiting and NO worker is running for the queue (always on PGLite unless a gbrain jobs work drain is live); wedged is then false and the no_worker notice names the fix. private_queue: true means the queue is a parent-owned dream-inline queue: wedged is NEVER true for it and a worker restart cannot help — recovery runs automatically at worker spawn / dream-cycle start; suggest gbrain doctor for the per-queue verdict. Host-process diagnostics (renice, backpressure hints) stay on the gbrain jobs stats CLI.","idempotent": true,"local_only": false,"mutating": false,diff --git a/test/queue-no-worker.test.ts b/test/queue-no-worker.test.tsnew file mode 100644index 0000000000..e87c006992--- /dev/null+++ b/test/queue-no-worker.test.ts@@ -0,0 +1,192 @@+/**+ * Lane E5 (agent-first operator wave): queue honesty.+ *+ * - CLI `jobs submit` on PGLite without --follow refuses with `no_worker` and+ * the exact --follow command; --queue-only queues deliberately.+ * - `gbrain jobs work` on PGLite drains the queue in the foreground and exits.+ * - MCP submit_job accepts and emits a `no_worker` notice.+ * - get_job_stats / deriveWedgeSignal distinguish no_worker from wedged.+ * - doctor queue_health counts waiting rows on PGLite with a drain fix.+ * - put_page reports embedding_state "disabled" on a keyless brain.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import { MinionQueue, deriveWedgeSignal } from '../src/core/minions/queue.ts';+import { MinionWorker } from '../src/core/minions/worker.ts';+import { runWaitingJobsFix, noWorkerNotice, queueWorkerAlive } from '../src/core/minions/no-worker.ts';+import { runJobsSubmit } from '../src/commands/jobs/submit.ts';+import { drainPgliteQueue } from '../src/commands/jobs/work.ts';+import { computeQueueHealthCheck } from '../src/commands/doctor/checks/queue-jobs.ts';+import { operations } from '../src/core/operations.ts';+import type { OperationContext } from '../src/core/operations.ts';+import type { Notice } from '../src/core/agent-output.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { resetGateway } from '../src/core/ai/gateway.ts';+import { LATEST_VERSION } from '../src/core/migrate.ts';++let engine: PGLiteEngine;+let home: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 120_000);+afterAll(async () => {+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+ resetGateway();+});+beforeEach(async () => {+ await disposePersistenceConsumer(engine);+ await resetPgliteState(engine);+ await engine.setConfig('version', String(LATEST_VERSION));+ home = mkdtempSync(join(tmpdir(), 'gbrain-no-worker-'));+});++const inHome = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home }, fn);+const op = (name: string) => operations.find(o => o.name === name)!;+async function waitingRows(): Promise<number> {+ const [row] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM minion_jobs WHERE status = 'waiting'");+ return Number(row?.n ?? 0);+}+function ctx(notices: Notice[], overrides: Partial<OperationContext> = {}): OperationContext {+ return {+ engine, config: { engine: 'pglite' as const }, dryRun: false, remote: false, sourceId: 'default',+ logger: { info() {}, warn() {}, error() {} }, emitNotice: n => notices.push(n), ...overrides,+ };+}++describe('deriveWedgeSignal liveness', () => {+ test('no live worker → no_worker, never wedged', () => {+ expect(deriveWedgeSignal({ active_healthy: 0, waiting: 3, minutes_since_completion: 60 }, { workerAlive: false }))+ .toMatchObject({ no_worker: true, wedged: false });+ });+ test('a live worker claiming nothing stays wedged', () => {+ expect(deriveWedgeSignal({ active_healthy: 0, waiting: 3, minutes_since_completion: 60 }, { workerAlive: true }))+ .toMatchObject({ no_worker: false, wedged: true });+ });+ test('unknown liveness keeps the pre-E5 derivation; empty queue is neither', () => {+ expect(deriveWedgeSignal({ active_healthy: 0, waiting: 3, minutes_since_completion: null })).toMatchObject({ no_worker: false, wedged: true });+ expect(deriveWedgeSignal({ active_healthy: 0, waiting: 0, minutes_since_completion: null }, { workerAlive: false })).toMatchObject({ no_worker: false, wedged: false });+ });+ test('a parent-owned dream-inline queue is never no_worker', () => {+ expect(deriveWedgeSignal({ queue: 'dream-inline-abc', active_healthy: 0, waiting: 3, minutes_since_completion: null }, { workerAlive: false }).no_worker).toBe(false);+ });+});++describe('no_worker fix', () => {+ test('PGLite drains in the foreground and needs the brain exclusively; Postgres starts the supervisor', () => {+ expect(runWaitingJobsFix('pglite', 'default')).toMatchObject({ argv: ['gbrain', 'jobs', 'work'], requires_exclusive: true, actor: 'agent' });+ expect(runWaitingJobsFix('pglite', 'bulk')).toMatchObject({ argv: ['gbrain', 'jobs', 'work', '--queue', 'bulk'] });+ expect(runWaitingJobsFix('postgres', 'default')).toMatchObject({ argv: ['gbrain', 'jobs', 'supervisor', 'start'], requires_exclusive: false });+ expect(noWorkerNotice('pglite', 'default', 2)).toMatchObject({ code: 'no_worker', kind: 'degraded' });+ });+ test('liveness reads the worker registry by queue', () => {+ expect(queueWorkerAlive('default', () => [{ queue: 'default' }])).toBe(true);+ expect(queueWorkerAlive('default', () => [{ queue: 'other' }])).toBe(false);+ expect(queueWorkerAlive('default', () => { throw new Error('unreadable'); })).toBeUndefined();+ });+});++describe('CLI jobs submit on PGLite', () => {+ test('without --follow refuses with no_worker and the exact --follow command; nothing is queued', () => inHome(async () => {+ _resetCliExitVerdictForTests();+ const stderr = spyOn(process.stderr, 'write').mockImplementation(() => true);+ try {+ await runJobsSubmit({ args: ['submit', 'sync', '--params', '{}'], engine, queue: new MinionQueue(engine) } as never);+ const text = stderr.mock.calls.map(c => String(c[0])).join('');+ expect(text).toContain('Error [no_worker]');+ expect(text).toContain("Fix: gbrain jobs submit sync --params '{}' --follow");+ expect(currentExitCode()).toBe(1);+ const [row] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM minion_jobs');+ expect(Number(row?.n ?? 0)).toBe(0);+ } finally {+ stderr.mockRestore();+ _resetCliExitVerdictForTests();+ }+ }));++ test('--queue-only queues deliberately', () => inHome(async () => {+ const log = spyOn(console, 'log').mockImplementation(() => {});+ try {+ await runJobsSubmit({ args: ['submit', 'sync', '--params', '{}', '--queue-only'], engine, queue: new MinionQueue(engine) } as never);+ expect(await waitingRows()).toBe(1);+ } finally {+ log.mockRestore();+ }+ }));+});++describe('jobs work on PGLite', () => {+ test('drains the waiting jobs it can run, then exits', () => inHome(async () => {+ const queue = new MinionQueue(engine);+ await queue.ensureSchema();+ await queue.add('noop-example', {}, {});+ await queue.add('noop-example', {}, {});+ const log = spyOn(console, 'log').mockImplementation(() => {});+ try {+ const out = await drainPgliteQueue(engine, queue, 'default', async (worker: MinionWorker) => {+ worker.register('noop-example', async () => ({ ok: true }));+ });+ expect(out.delayed).toBe(0);+ } finally {+ log.mockRestore();+ }+ const [row] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM minion_jobs WHERE status = 'completed'");+ expect(Number(row?.n ?? 0)).toBe(2);+ expect(await waitingRows()).toBe(0);+ }), 60_000);+});++describe('MCP no_worker surfaces', () => {+ test('submit_job accepts and emits a no_worker notice', () => inHome(async () => {+ const notices: Notice[] = [];+ const result = await op('submit_job').handler(ctx(notices), { name: 'noop-example', data: {} }) as { id: number };+ expect(result.id).toBeGreaterThan(0);+ expect(notices).toHaveLength(1);+ expect(notices[0]).toMatchObject({ code: 'no_worker', kind: 'degraded', fix: { argv: ['gbrain', 'jobs', 'work'] } });+ }));++ test('get_job_stats reports no_worker, not wedged, with waiting work and no worker', () => inHome(async () => {+ await new MinionQueue(engine).add('noop-example', {}, {});+ const notices: Notice[] = [];+ const stats = await op('get_job_stats').handler(ctx(notices), {}) as { wedged: boolean; no_worker: boolean };+ expect(stats.no_worker).toBe(true);+ expect(stats.wedged).toBe(false);+ expect(notices.map(n => n.code)).toEqual(['no_worker']);+ }));+});++describe('doctor queue_health on PGLite', () => {+ test('counts waiting rows and names the foreground drain', async () => {+ await new MinionQueue(engine).add('noop-example', {}, {});+ const check = await computeQueueHealthCheck(engine, { readWorkers: () => [] });+ expect(check.status).toBe('warn');+ expect(check.message).toContain('no_worker');+ expect(check.fix).toMatchObject({ argv: ['gbrain', 'jobs', 'work'], requires_exclusive: true,+ verify: { argv: ['gbrain', 'doctor', '--only', 'queue_health', '--json'] } });+ expect((check.details as { depth: number }).depth).toBe(1);+ });+ test('a live drain on the queue, or an empty queue, is ok', async () => {+ expect((await computeQueueHealthCheck(engine, { readWorkers: () => [] })).status).toBe('ok');+ await new MinionQueue(engine).add('noop-example', {}, {});+ expect((await computeQueueHealthCheck(engine, { readWorkers: () => [{ queue: 'default' }] })).status).toBe('ok');+ });+});++describe('put_page embedding_state', () => {+ test('a keyless brain reports embedding_state "disabled"', () => inHome(async () => {+ await engine.setConfig('embedding_disabled', 'true');+ const result = await op('put_page').handler(ctx([]), {+ slug: 'notes/keyless-example', content: '---\ntitle: Keyless\n---\n\nA keyless brain keeps keyword search only.',+ }) as { embedding_state?: string; persistence?: { embedding_state?: string } };+ expect(result.embedding_state ?? result.persistence?.embedding_state).toBe('disabled');+ }), 60_000);+});