Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(minions): defer jobs without counting an attempt; keyless facts-absorb jobs wait for a key
garrytan345a446689de
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex 6860ca5651..b6960db9ca 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -18,7 +18,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. `jobs-readiness.ts` orchestrates bounded driver-lane and selected-child readiness before worker schema/recovery, handler registration or claims. After `ensureSchema`, `maybeRunWorkerStartupRecovery(queue, process.env, true)` runs for both bare and supervised workers; the final worker `ready` event publishes readiness, and a worker handed an owner status channel (`GBRAIN_WORKER_STATUS_PATH` or `GBRAIN_WORKER_STATUS_TOKEN`, even partially) refuses admission if its status cannot be published, while a legacy supervised worker (`GBRAIN_SUPERVISED=1` from a pre-0.59.1 owner, no channel) publishes nothing and proceeds; typed faults report `configuration_blocked` and exit `WORKER_EXIT_CONFIGURATION`, while transient readiness failures admit no jobs and remain retryable. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the `JOBS_SUBCOMMANDS` dispatch — `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`. `jobs work` (`src/commands/jobs/work.ts`) wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke --sigkill-rescue` is the SIGKILL-rescue guard. `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs `MAINTENANCE_PHASES` (mixed ∪ global) once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` only when no phase failed, no synthesis/pattern child is incomplete, no work was explicitly budget/triage-deferred, and the run was neither aborted nor lock-stolen; benign warning-only runs remain eligible. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status --json` adds `processing_ready`, lowercase `processing_state` (`starting`/`ready`/`configuration_blocked`, or `unknown`/`stopped` without current state), `reason_code`, `blocked_since` and worker/child identities without changing `running` or crash counters. A live local pidfile keeps this diagnostic engine-free; a missing pidfile retains the DB-lock fallback. It consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output includes per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress. `parseJobIsolationFlag(args, env?)` (`--job-isolation`, space/= forms, `GBRAIN_JOB_ISOLATION` fallback, default inline); `jobs work` resolves the actual selected child and validates its bounded protocol/capability handshake and warns when `--max-rss` is combined with isolation (watchdog covers the worker only); `jobs run-child` is the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); the `db_dead` fatal text is verdict-aware (pool starved vs server unreachable). Generic `jobs submit` normalizes the job name once before trust, queueing, handler lookup, and audit; after the admission check and dry-run return, its explicit `ensureSchema()` preflight still runs before shell/handler validation so stale brains retain the canonical init/migration error precedence. On PGLite, `jobs submit embed-backfill` refuses with `no_worker_surface` and a paste-ready inline embed command before any queue access; `--dry-run` evaluates the same read-only feasibility gate and never says “Would submit” for an impossible job. `--follow` is the sole CLI exception because it starts and awaits the inline worker; padded names follow the same normalized path and cannot strand a row. The MCP `submit_job` operation applies the same gate (including dry-run), translates the expected refusal to branchable `OperationError('no_worker_surface')`, and never emits `internal_error` for this capability miss. The `sync` handler forwards `job.data.github_item` ({repo, number, kind}) into `performSync` for github-kind single-item webhook refreshes. `jobs work` registers the shell handler always; the startup line names the flag first (`--allow-shell-jobs` / `GBRAIN_ALLOW_SHELL_JOBS=1`); `jobs start` computes `allowShellJobs` as `--allow-shell-jobs || GBRAIN_ALLOW_SHELL_JOBS === '1'` — the same literal `handlers/shell.ts` and `buildChildArgs` check. `extract-atoms-drain` accepts a trusted `retryRequestId` in submitted params; a new job ID distinguishes a newly approved malformed-output provider attempt from provider-free publication replay. PGLite `jobs --follow` still requires exclusive owner access. D2: `jobs supervisor start --detach` writes its payload (`event`, `status:'started'`, `supervisor_pid`, `pid_file`, `detached`, `stderr_log`) through `writeStdoutFinal`; the `jobs` record declares no `json` because work/watch/foreground supervisor stream. Start refusals add an envelope under `--json` (`invalid_params` exit 2 for an unknown subcommand or bad `--health-interval`, `config_error` for PGLite).Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). `runJobs` resolves help and the thin-client refusal, builds the queue, then dispatches through `JOBS_SUBCOMMANDS` (Object.hasOwn lookup, same unknown-subcommand error) to one module per subcommand in `src/commands/jobs/<sub>.ts` (`runJobs<Sub>(ctx)`; parsers, formatters and `JobsCommandContext` in `jobs/shared.ts`; `maybeRunWorkerStartupRecovery` in `jobs/work.ts`), all re-exported from `jobs.ts`. Subcommands that register handlers import `registerBuiltinHandlers` lazily from `jobs.ts`. `registerBuiltinHandlers` is the ordered registration table (worker.register vs gateway-refreshing registerBuiltinJob stay here); handler bodies live in `src/core/minions/handlers/` (see core-minions-1). Registration names and order are pinned by `test/jobs-handler-registry-golden.test.ts`, which also drives the supervisor's `deriveHandlerNames` probe.-- `src/commands/jobs.ts:refreshGatewayForJob` + `src/core/ai/gateway.ts:refreshGatewayEnvFromFilePlane` — long-lived-worker staleness boundary, three tiers: (1) DB-plane model config re-resolves per gateway-refresh job (`reconfigureGatewayWithEngine`); (2) FILE-plane config (`~/.gbrain/config.json`, incl. provider API keys) re-folds per job via the env-ONLY `refreshGatewayEnvFromFilePlane` — never a full `configureGateway(buildGatewayConfig(loadConfig()))`, which would clobber DB-plane-merged fields (base_urls, chat options) with file-plane-only values; (3) true process env vars are fixed at worker start and need a restart. `gbrain config set *_api_key` writes the DB plane, which `loadConfigWithEngine()` deliberately never merges for key fields — those writes do NOT reach workers (TODO filed to reroute them to the file plane). `facts-absorb` sits in `GATEWAY_REFRESH_JOB_NAMES`; its handler converts execution-time `chat_unavailable` in a KEYED worker into a typed retryable failure (`factsAbsorbShouldRetry`) while a keyless worker completes the job as a calm skip. Pinned by `test/jobs-gateway-refresh.serial.test.ts`.+- `src/commands/jobs.ts:refreshGatewayForJob` + `src/core/ai/gateway.ts:refreshGatewayEnvFromFilePlane` — long-lived-worker staleness boundary, three tiers: (1) DB-plane model config re-resolves per gateway-refresh job (`reconfigureGatewayWithEngine`); (2) FILE-plane config (`~/.gbrain/config.json`, incl. provider API keys) re-folds per job via the env-ONLY `refreshGatewayEnvFromFilePlane` — never a full `configureGateway(buildGatewayConfig(loadConfig()))`, which would clobber DB-plane-merged fields (base_urls, chat options) with file-plane-only values; (3) true process env vars are fixed at worker start and need a restart. `gbrain config set *_api_key` writes the DB plane, which `loadConfigWithEngine()` deliberately never merges for key fields — those writes do NOT reach workers (TODO filed to reroute them to the file plane). `facts-absorb` sits in `GATEWAY_REFRESH_JOB_NAMES`; its handler converts execution-time `chat_unavailable` in a KEYED worker into a typed retryable failure (`factsAbsorbShouldRetry`) while a keyless worker defers it (`JobDeferredError`, 30 min, no attempt counted) so the backlog runs once a key exists. Pinned by `test/jobs-gateway-refresh.serial.test.ts`.- `src/commands/lint.ts` — Page quality linter (catches LLM artifacts, placeholder dates). `runLintCore(opts)` walks the tree ONCE; `--fix` applies fixes during that same scan and reports per-page results through the `onPageIssues(relPath, issues, fixedCount)` callback (issues = what remains after this run's fix attempt for the page; `fixedCount` = fixes actually applied), so the summary's auto-fixed count is the true count — a second scan run after fixing would see already-fixed files and report zero. `onScanStart` fires once with the collected page count for progress wiring. Pinned by `test/lint-fix-single-pass.test.ts`. On a durability-hardened brain (`isDurabilityHardened` on the target dir, or the page's directory for a single-file target) every non-dry-run `--fix` repair is committed path-limited via `commitWriteThroughFile` right after the `writeFileSync` — the same contract as put_page write-through, so the cycle, the `lint`/`lint-fix` minion handlers and the CLI never leave hardened repairs as uncommitted drift for the sync phase to flag (pinned by `test/cycle-lint-durability.test.ts`). Lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`. Rule `type-undeclared` flags an explicit frontmatter `type` the active schema pack neither declares nor aliases (resolved once per run from the shared/probed engine's DB-plane `schema_pack`, else file/env config; no resolvable pack skips it; `LintOpts.typePack` injects it), pinned by `test/lint-page-type-vocabulary.test.ts`. with `src/commands/sources.ts`: `gbrain lint` has a `markup-heavy` rule (flags pages whose prose-vs-markup ratio exceeds `content_sanity.max_markup_ratio`, reusing `assessContentSanity` so lint/gate/scan share one assessor); pinned by `test/lint-content-sanity.test.ts`. `gbrain sources audit <id>` is disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effective `content_sanity.junk_disposition` + markup config, so an operator previews the gate's verdict before sync. The `content-sanity-audit` JSONL (`src/core/audit/content-sanity-audit.ts`) records the quarantine/flag dispositions.diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.mdindex 87691d209b..521c477756 100644--- a/docs/architecture/key-files/core-minions-1.md+++ b/docs/architecture/key-files/core-minions-1.md@@ -30,7 +30,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/embed-backfill-admission.ts` — Centralized, dependency-light embed-backfill admission contract shared by the public `MinionQueue.add` boundary, CLI, MCP operations, automatic submitters, sync cost reporting, and doctor remediation. `embedBackfillWorkerSurface` recognizes only explicit `postgres` as worker-backed; the declared engine-kind switch is compile-time exhaustive, while untyped/cast unknown runtime values still fail closed as `no_worker_surface`. `assertEmbedBackfillQueueAdmission` refuses before any database/config access unless the explicit PGLite inline-worker trust is present, validates payload source IDs through the canonical `source-id.ts` contract before rendering any remedy, and `embedBackfillManualDrainCommand(sourceId)` is the single injection-safe exact `gbrain embed --stale --source <id>` recovery command.-- `src/core/minions/errors.ts` — dependency-free `UnrecoverableError`, re-exported through `types.ts` for compatibility. Delegated policy imports this leaf directly, avoiding initialization cycles through durable authority. Fresh-process import tests preserve the shared error identity and isolated-worker reconstruction.+- `src/core/minions/errors.ts` — dependency-free `UnrecoverableError` and `JobDeferredError(reason, message, retryInMs)`, re-exported through `types.ts` for compatibility. Delegated policy imports this leaf directly, avoiding initialization cycles through durable authority. Fresh-process import tests preserve the shared error identity and isolated-worker reconstruction. A `JobDeferredError` returns the job to `delayed` for `retryInMs` through `MinionQueue.deferJob` (no attempt counted, no stacktrace entry); the worker, the facts drain and the isolation codec (`errorKind: 'deferred'`) all route it (`test/facts-absorb-keyless-deferral.test.ts`).- `src/core/minions/handler-timeouts.ts` — per-handler-type defaults for BOTH per-job time knobs, co-located so they can't drift apart unseen (they are different quantities: the budget bounds total runtime, the lease bounds dead-worker reclaim — never derive one from the other). `HANDLER_DEFAULT_TIMEOUT_MS`: 30 min for `subagent`, `subagent_aggregator`, `embed-backfill`, `autopilot-cycle`, `autopilot-global-maintenance`, `extract` (a brain-wide `extract --stale` pass); 10 min for `chronicle_extract` + `facts-absorb`; 60 min for `contextual_reindex_per_chunk`. `HANDLER_DEFAULT_LOCK_DURATION_MS`: 300 s for the long LLM/loop handlers, 120 s for the single-LLM-call handlers, `shell` deliberately absent (fast dead-worker reclaim; verify-before-evict protects it anyway). `defaultTimeoutMsFor` / `defaultLockDurationMsFor` return the mapped default or `null` (short handlers keep the tight null-default wall-clock / the 30 s worker lease). `clampLockDurationMs` + `LOCK_DURATION_MS_MIN/MAX` ([5s, 1h]) is the ONE clamp shared by `queue.add`, the CLI `--lock-duration-ms` flag (`--dry-run` echoes the clamped value), and the MCP `submit_job` param; the same bound is mirrored in SQL at claim time and by the `minion_jobs.lock_duration_ms` range CHECK, so every layer agrees. Layers (explicit value always wins): `MinionQueue.add()` stamps at submit; `MinionQueue.claim()` COALESCEs NULL columns from the maps (durable invariant); migration v128 one-shot backfilled `timeout_ms` with authoring-time snapshot values — do NOT sync v128 when editing the maps (`lock_duration_ms` has no backfill: NULL = worker default). Pinned by `test/minions.test.ts` + `test/migrations-v128.test.ts` + `test/migrations-v130.test.ts`.diff --git a/src/core/minions/errors.ts b/src/core/minions/errors.tsindex 80bc7884ea..61a586d4b8 100644--- a/src/core/minions/errors.ts+++ b/src/core/minions/errors.ts@@ -7,3 +7,16 @@ export class UnrecoverableError extends Error {this.name = 'UnrecoverableError';}}++/**+ * Throw this from a handler when the job cannot run yet for a reason outside+ * the job itself (no provider key, a spend budget used up, shutdown). The+ * worker returns the job to `delayed` for `retryInMs` WITHOUT counting an+ * attempt, so the work waits instead of failing or completing empty.+ */+export class JobDeferredError extends Error {+ constructor(readonly reason: string, message: string, readonly retryInMs: number) {+ super(message);+ this.name = 'JobDeferredError';+ }+}diff --git a/src/core/minions/handlers/facts-absorb.ts b/src/core/minions/handlers/facts-absorb.tsindex 7a806de085..98be3dfe25 100644--- a/src/core/minions/handlers/facts-absorb.ts+++ b/src/core/minions/handlers/facts-absorb.ts@@ -5,7 +5,7 @@ import type { BrainEngine } from '../../engine.ts';import type { MinionHandler } from '../types.ts';import { loadConfig, loadConfigWithEngine } from '../../config.ts';import type { FactsBackstopResult } from '../../facts/backstop.ts';-import { UnrecoverableError } from '../errors.ts';+import { JobDeferredError, UnrecoverableError } from '../errors.ts';import { ERROR_CATALOGUE } from '../../error-catalogue.ts';/** Shared predicate: an inline result reporting execution-time unavailability. */@@ -20,10 +20,9 @@ export function factsAbsorbUnavailable(result: FactsBackstopResult): boolean {* The facts-absorb retry decision (@internal exported for tests). A job that* finds chat unavailable at EXECUTION in a KEYED worker is config drift — it* must throw (retry/backoff → visible, re-runnable failure), never return- * success and silently consume the job. A KEYLESS worker executing a job- * enqueued by some other process is the steady expected state — completing- * as a calm skip (the execution-time gate already printed the keyless note)- * beats a retry loop that parks every page write as a failed job.+ * success and silently consume the job. A KEYLESS worker defers the job+ * instead (JobDeferredError, no attempt counted), so a keyless backlog runs+ * once a key is configured rather than completing empty.*/export function factsAbsorbShouldRetry(result: FactsBackstopResult,@@ -42,6 +41,9 @@ export function factsAbsorbShouldRetry(* config re-stamped per job). #4310: wrapped in the provider-halt cooldown* (llm-halt-cooldown.ts) — a globally-broken provider defers the queue.*/+/** How long a keyless job waits before the next look for a key (no attempt is counted). */+export const FACTS_ABSORB_KEYLESS_RETRY_MS = 30 * 60_000;+export function makeFactsAbsorbHandler(engine: BrainEngine): MinionHandler {return async (job) => {const slug = typeof job.data.slug === 'string' ? job.data.slug : '';@@ -94,16 +96,18 @@ export function makeFactsAbsorbHandler(engine: BrainEngine): MinionHandler {notabilityFilter: coerceNotabilityFilter(job.data.notabilityFilter),visibility: job.data.visibility === 'world' ? 'world' : 'private',...(typeof job.data.model === 'string' && job.data.model ? { model: job.data.model } : {}),+ abortSignal: job.signal,},).catch(refuse);+ // An aborted run returns empty counts; completing it would consume the page's extraction.+ if (job.signal.aborted) throw job.signal.reason instanceof Error ? job.signal.reason : new Error('facts-absorb aborted');// Execution-time chat_unavailable in a KEYED worker is config drift —// throw (typed) so minion retry/backoff parks it as a VISIBLE, re-runnable// failure instead of consuming the job and silently losing the facts. A- // KEYLESS worker completes the job as a calm skip (its execution-time gate- // already printed the keyless note; a retry loop would turn every page- // write into failed-job noise). The retry conversion lives HERE, not in- // the shared pipeline — the same pipeline serves the extract_facts op,- // which must return its keyless envelope instead of throwing. The+ // KEYLESS worker defers the job without counting an attempt, so the page+ // is extracted once a key exists. The conversion lives HERE, not in the+ // shared pipeline — the same pipeline serves the extract_facts op, which+ // must return its keyless envelope instead of throwing. The// classification runs in the WORKER process (the submitting hook// subprocess may have a deliberately neutered env).if (factsAbsorbUnavailable(result)) {@@ -113,6 +117,7 @@ export function makeFactsAbsorbHandler(engine: BrainEngine): MinionHandler {const { FactsExtractionError } = await import('../../facts/extract.ts');throw new FactsExtractionError('chat_unavailable', jobModel);}+ throw new JobDeferredError('no_key', `no chat provider key; ${slug} waits for one (set OPENAI_API_KEY or ANTHROPIC_API_KEY)`, FACTS_ABSORB_KEYLESS_RETRY_MS);}return result;};diff --git a/src/core/minions/job-isolation.ts b/src/core/minions/job-isolation.tsindex 2f1219192b..8ca458799d 100644--- a/src/core/minions/job-isolation.ts+++ b/src/core/minions/job-isolation.ts@@ -36,7 +36,7 @@import { accessSync, constants, readdirSync, readFileSync, writeFileSync, renameSync, statSync } from 'node:fs';import { readFile, stat } from 'node:fs/promises';import { spawnSync } from 'node:child_process';-import { UnrecoverableError } from './types.ts';+import { JobDeferredError, UnrecoverableError } from './types.ts';import { RateLeaseUnavailableError } from './handlers/subagent.ts';import { LocalConfigurationError, isLocalConfigurationError } from './configuration-error.ts';import { basename, delimiter, resolve } from 'node:path';@@ -90,7 +90,7 @@ export function childConfigurationError(reason: typeof CHILD_CONFIGURATION_REASOreturn new LocalConfigurationError(reason, `${messages[reason]} Verify worker and child readiness, then restart. See docs/guides/minions-fix.md#configuration-blocked.`);}-export type ChildErrorKind = 'unrecoverable' | 'rate_lease' | 'generic' | 'local_configuration';+export type ChildErrorKind = 'unrecoverable' | 'rate_lease' | 'deferred' | 'generic' | 'local_configuration';export type ChildOutcome =| { outcome: 'success'; result: unknown }@@ -100,6 +100,7 @@ export type ChildOutcome =message: string;stack?: string;lease?: { key: string; active: number; max: number };+ deferral?: { reason: string; retryInMs: number };protocolVersion?: number;reasonCode?: typeof CHILD_CONFIGURATION_REASONS[number];};@@ -122,6 +123,9 @@ export function encodeHandlerError(err: unknown): ChildOutcome {lease: { key: err.key, active: err.active, max: err.max },};}+ if (err instanceof JobDeferredError) {+ return { outcome: 'error', errorKind: 'deferred', message: err.message, deferral: { reason: err.reason, retryInMs: err.retryInMs } };+ }if (err instanceof UnrecoverableError) {return {outcome: 'error',@@ -151,6 +155,9 @@ export function reconstructHandlerError(o: Extract<ChildOutcome, { outcome: 'errif (o.errorKind === 'unrecoverable') {return new UnrecoverableError(o.message);}+ if (o.errorKind === 'deferred' && o.deferral && Number.isFinite(o.deferral.retryInMs)) {+ return new JobDeferredError(String(o.deferral.reason), o.message, o.deferral.retryInMs);+ }const err = new Error(o.message);if (o.stack) {(err as Error & { childStack?: string }).childStack = o.stack;@@ -205,9 +212,12 @@ export function parseChildOutcome(raw: string, size: number, maxBytes = CHILD_OUNumber.isFinite(rawLease.max as number);// rate_lease without a valid lease payload degrades to generic — same// policy as the errorKind whitelist.+ const rawDeferral = (o as { deferral?: unknown }).deferral as { reason?: unknown; retryInMs?: unknown } | undefined;+ const deferralValid = rawDeferral != null && typeof rawDeferral.reason === 'string' && Number.isFinite(rawDeferral.retryInMs as number);const errorKind =kind === 'unrecoverable' ? 'unrecoverable': kind === 'rate_lease' && leaseValid ? 'rate_lease'+ : kind === 'deferred' && deferralValid ? 'deferred': 'generic';return {outcome: 'error',@@ -219,6 +229,9 @@ export function parseChildOutcome(raw: string, size: number, maxBytes = CHILD_OU...(errorKind === 'rate_lease' && leaseValid? { lease: { key: rawLease.key as string, active: rawLease.active as number, max: rawLease.max as number } }: {}),+ ...(errorKind === 'deferred' && deferralValid+ ? { deferral: { reason: rawDeferral.reason as string, retryInMs: rawDeferral.retryInMs as number } }+ : {}),};}throw new Error(`job child outcome file has an unrecognized shape (${size} bytes)`);diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.tsindex 302fba3f43..3b4cccb4cc 100644--- a/src/core/minions/queue.ts+++ b/src/core/minions/queue.ts@@ -1973,6 +1973,25 @@ export class MinionQueue {return rowToMinionJob(rows[0]);}+ /**+ * Return a claimed job to `delayed` without counting an attempt or growing+ * its stacktrace (a deferral is a state, not a failure; a job that waits for+ * a key for weeks must not accumulate one stack entry per retry).+ */+ async deferJob(id: number, lockToken: string, note: string, delayMs: number): Promise<MinionJob | null> {+ const rows = await this.engine.executeRaw<Record<string, unknown>>(+ `UPDATE minion_jobs SET+ status = 'delayed', error_text = $1,+ delay_until = now() + ($2::double precision * interval '1 millisecond'),+ started_at = NULL, timeout_at = NULL,+ lock_token = NULL, lock_until = NULL, updated_at = now()+ WHERE id = $3 AND status = 'active' AND lock_token = $4+ RETURNING *`,+ [note, Math.max(0, delayMs), id, lockToken],+ );+ return rows.length === 0 ? null : rowToMinionJob(rows[0]);+ }+async releaseConfigurationJob(id: number,lockToken: string,diff --git a/src/core/minions/types.ts b/src/core/minions/types.tsindex f04320e445..7d51a6473e 100644--- a/src/core/minions/types.ts+++ b/src/core/minions/types.ts@@ -431,7 +431,7 @@ export const ABORT_REASON_TIMEOUT = 'timeout';// --- Errors ----export { UnrecoverableError } from './errors.ts';+export { JobDeferredError, UnrecoverableError } from './errors.ts';// --- Row Mapping ---diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.tsindex 97295b8e28..373fd8e258 100644--- a/src/core/minions/worker.ts+++ b/src/core/minions/worker.ts@@ -20,6 +20,7 @@ import type {MinionQueueOpts, TokenUpdate,} from './types.ts';import {+ JobDeferredError,UnrecoverableError,ABORT_REASON_LOCK_RENEWAL_FAILED,ABORT_REASON_LOCK_LOST,@@ -1458,6 +1459,13 @@ export class MinionWorker extends EventEmitter {execution.promise = promise;}+ /** A handler deferral (JobDeferredError): back to delayed, no attempt counted. */+ private async deferJob(job: MinionJob, lockToken: string, err: JobDeferredError): Promise<void> {+ const deferred = await this.queue.deferJob(job.id, lockToken, `deferred (${err.reason}): ${err.message}`, err.retryInMs);+ if (!deferred) console.warn(`Job ${job.id} deferral dropped (lock token mismatch)`);+ else console.log(`Job ${job.id} (${job.name}) deferred (${err.reason}) for ${Math.round(err.retryInMs / 1000)}s (no attempt burned)`);+ }+private async executeJob(job: MinionJob,lockToken: string,@@ -1656,6 +1664,7 @@ export class MinionWorker extends EventEmitter {// `failJob` minus the `attempts_made` increment. Audit row to// `minion_lease_pressure_log` so operators see pressure live in// `gbrain doctor` + `gbrain jobs stats lease_pressure`.+ if (err instanceof JobDeferredError) return this.deferJob(job, lockToken, err);const isLeaseFull = err instanceof RateLeaseUnavailableError;if (isLeaseFull) {const leaseErr = err as RateLeaseUnavailableError;diff --git a/test/facts-absorb-keyless-deferral.test.ts b/test/facts-absorb-keyless-deferral.test.tsnew file mode 100644index 0000000000..eb7d50c756--- /dev/null+++ b/test/facts-absorb-keyless-deferral.test.ts@@ -0,0 +1,93 @@+/**+ * Keyless facts-absorb jobs wait instead of completing empty (Foundations 2,+ * Lane D, taste choice T8), and a job stopped by its signal is never+ * completed. Protects: a keyless backlog survives until a key exists; the+ * worker defers with no attempt counted and no stacktrace growth; the+ * process-isolation codec carries the deferral; the keyless extract_facts op+ * envelope is unchanged (covered by facts-backstop-outcome.serial.test.ts).+ */+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import { LATEST_VERSION } from '../src/core/migrate.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import { MinionWorker } from '../src/core/minions/worker.ts';+import { JobDeferredError } from '../src/core/minions/errors.ts';+import type { MinionHandler, MinionJobContext } from '../src/core/minions/types.ts';+import { encodeHandlerError, reconstructHandlerError } from '../src/core/minions/job-isolation.ts';+import { FACTS_ABSORB_KEYLESS_RETRY_MS, makeFactsAbsorbHandler } from '../src/core/minions/handlers/facts-absorb.ts';+import { configureGateway, resetGateway, __setChatTransportForTests } from '../src/core/ai/gateway.ts';++let engine: PGLiteEngine;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); });+afterAll(async () => { __setChatTransportForTests(null); resetGateway(); await engine.disconnect(); });+beforeEach(async () => { await resetPgliteState(engine); await engine.setConfig('version', String(LATEST_VERSION)); });++const BODY = `Acme Example shipped the beta in 2026. ${'A substantive project record with names, dates and decisions. '.repeat(5)}`;+function ctx(job: { id: number; data: Record<string, unknown> }, signal = new AbortController().signal): MinionJobContext {+ return { id: job.id, name: 'facts-absorb', data: job.data, attempts_made: 0, signal, deadlineAtMs: null, shutdownSignal: signal,+ updateProgress: async () => {}, updateTokens: async () => {}, log: async () => {}, isActive: async () => true, readInbox: async () => [] } as MinionJobContext;+}+async function queued(slug: string) {+ await engine.putPage(slug, { type: 'note', title: 'Note', compiled_truth: BODY, timeline: '', frontmatter: {} } as never);+ return new MinionQueue(engine).add('facts-absorb', { slug, sourceId: 'default', source: 'mcp:put_page', notabilityFilter: 'all', visibility: 'private' });+}++test('a keyless worker defers the facts-absorb job instead of completing it empty', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-keyless-'));+ try {+ await withEnv({ GBRAIN_HOME: home, ANTHROPIC_API_KEY: undefined, OPENAI_API_KEY: undefined, GBRAIN_MODEL: undefined }, async () => {+ configureGateway({ env: {} } as never);+ const job = await queued('notes/keyless-example');+ const err = await makeFactsAbsorbHandler(engine)(ctx(job)).then(() => null, e => e);+ expect(err).toBeInstanceOf(JobDeferredError);+ expect(err).toMatchObject({ reason: 'no_key', retryInMs: FACTS_ABSORB_KEYLESS_RETRY_MS });+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+});++test('an aborted run is never completed', async () => {+ configureGateway({ env: { ANTHROPIC_API_KEY: 'sk-test' } } as never);+ await engine.setConfig('facts.extraction_model', 'anthropic:claude-sonnet-4-6');+ __setChatTransportForTests(async () => { throw new Error('should not be called'); });+ const job = await queued('notes/aborted-example');+ const abort = new AbortController();+ abort.abort(new Error('shutdown'));+ await expect(makeFactsAbsorbHandler(engine)(ctx(job, abort.signal))).rejects.toThrow('shutdown');+ __setChatTransportForTests(null);+});++test('the worker returns a deferred job to delayed with no attempt counted and no stacktrace entry', async () => {+ const queue = new MinionQueue(engine);+ const job = await queue.add('defer-example', {}, { max_attempts: 2 });+ const worker = new MinionWorker(engine, { pollInterval: 50 });+ let calls = 0;+ const handler: MinionHandler = async () => { calls++; throw new JobDeferredError('no_key', 'waiting for a key', 60_000); };+ worker.register('defer-example', handler);+ const running = worker.start();+ for (let i = 0; i < 100; i++) {+ if ((await queue.getJob(job.id))?.status === 'delayed') break;+ await new Promise(r => setTimeout(r, 50));+ }+ worker.stop();+ await running;+ const row = (await queue.getJob(job.id))!;+ expect(calls).toBe(1);+ expect(row.status).toBe('delayed');+ expect(row.attempts_made).toBe(0);+ expect(row.error_text).toBe('deferred (no_key): waiting for a key');+ expect(row.stacktrace ?? []).toEqual([]);+ expect(row.delay_until!.getTime()).toBeGreaterThan(Date.now() + 30_000);+});++test('process isolation carries the deferral across the child boundary', () => {+ const encoded = encodeHandlerError(new JobDeferredError('budget_exhausted', 'cap reached', 1234));+ expect(encoded).toMatchObject({ outcome: 'error', errorKind: 'deferred', deferral: { reason: 'budget_exhausted', retryInMs: 1234 } });+ const rebuilt = reconstructHandlerError(encoded as never);+ expect(rebuilt).toBeInstanceOf(JobDeferredError);+ expect(rebuilt).toMatchObject({ reason: 'budget_exhausted', retryInMs: 1234, message: 'cap reached' });+});