Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(dream): drain stops map to one exit contract; permanent provider failures and no_progress exit 1 (#6817)
time-attack5b6363263ffd
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.mdindex 42fd4fdc1d..6a95a5e929 100644--- a/docs/architecture/key-files/commands-2-continued.md+++ b/docs/architecture/key-files/commands-2-continued.md@@ -16,9 +16,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/dream-reset-key.ts` — `gbrain dream reset-key <base-key>` persists a breaker reset for one dream key (deaths finished before it stop counting; survives restarts); `gbrain dream reset-key --list [--json]` lists tripped keys with counts and reset commands. Dispatched from `dream.ts` before cycle flag parsing. The `dream_paid_loop` doctor check (`src/commands/doctor/checks/dream-breaker.ts`) warns on keys at the limit through the same counter. Its help names the per-source patterns key `dream:patterns:source:<id>`; doctor `dream_paid_loop` reports that prefix as the key's `key_prefix`.-- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed; a `cycle_already_running` skip names the lock holder (pid, host, age) from `report.lock_holder`. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved `--source`'s `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining, stopped}`. `--window` is a hard deadline for starting work (the item in flight finishes). Exits `EXIT_DRAIN_INCOMPLETE` (= `BUDGET_STOP_EXIT_CODE` 11; was 3, which A3 reserves for confirmation_required) unless `stopped: drained` with `remaining: 0` (a null count is exit 11, never a drained success; `--json` adds `resume_command`), printing the rerun command (`gbrain dream --drain --window <s> [--source <id>]`) on stderr; `LockUnavailableError` → `cycle_already_running` skip (also exit 11). Under `--json` (D2) every path is one document: usage errors are `invalid_params` envelopes (exit 2, unknown `--phase` included), a failed or contained cycle under the guard is a `cycle_failed` envelope leading with the CycleReport keys, and `retriage` / `reset-key` refusals are envelopes. The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE). `--eval-run` opts the process in to `GBRAIN_DECIDE_SLOTS` (`enableDecideEvalOverride`) for eval harnesses; consent, egress and the daily cap still apply.+- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed; a `cycle_already_running` skip names the lock holder (pid, host, age) from `report.lock_holder`. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved `--source`'s `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining, stopped}`. `--window` is a hard deadline for starting work (the item in flight finishes). Every stop maps through `drainOutcome` (`src/core/cycle/extract-atoms-drain-outcome.ts`): exit 0 only for `stopped: drained` with `remaining: 0`; exit 11 (`BUDGET_STOP_EXIT_CODE`) for a retryable stop (`atom_drain_incomplete`: window, deadline, lock, batch cap, budget, a null count; `atom_drain_provider_failure` reasons `rate_limit`/`transient`), printing the rerun command (`gbrain dream --drain --window <s> [--source <id>]`) on stderr and adding `resume_command` under `--json`; exit 1 for a stop a rerun cannot clear (`atom_drain_provider_failure` reasons `auth`/`billing`/`model_not_found`/`content_block`, `atom_drain_no_progress` over a counted backlog), printing the registry suggestion as a `Fix:` line and adding the rendered `fix` instead of `resume_command`. `--json` of any incomplete stop carries `status` (`incomplete` or `provider_failure`, never `ok`), `retryable`, `code` and `reason`; `LockUnavailableError` → `cycle_already_running` skip (also exit 11). Under `--json` (D2) every path is one document: usage errors are `invalid_params` envelopes (exit 2, unknown `--phase` included), a failed or contained cycle under the guard is a `cycle_failed` envelope leading with the CycleReport keys, and `retriage` / `reset-key` refusals are envelopes. The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE). `--eval-run` opts the process in to `GBRAIN_DECIDE_SLOTS` (`enableDecideEvalOverride`) for eval harnesses; consent, egress and the daily cap still apply.-- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed; a `cycle_already_running` skip names the lock holder (pid, host, age) from `report.lock_holder`. Source scope enters the shared 6-tier resolver whenever `--source <id>` is given OR `GBRAIN_SOURCE` is set (a null explicit falls through to tier 2: validated + `assertSourceExists`, so an invalid/unknown env value is a clean exit 1; the `__all__` sentinel is excluded and falls through to the unscoped routing, which already spans every source); an env scope naming the brain's default-like source keeps the full implicit cycle (#4700 semantics), any other keeps the `--source` freshness boundary. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved source's `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining, stopped}`. `--window` is a hard deadline for starting work (the item in flight finishes). Exits `EXIT_DRAIN_INCOMPLETE` (= `BUDGET_STOP_EXIT_CODE` 11; was 3, which A3 reserves for confirmation_required) unless `stopped: drained` with `remaining: 0` (a null count is exit 11, never a drained success; `--json` adds `resume_command`), printing the rerun command (`gbrain dream --drain --window <s> [--source <id>]`) on stderr; `LockUnavailableError` → `cycle_already_running` skip (also exit 11). Under `--json` (D2) every path is one document: usage errors are `invalid_params` envelopes (exit 2, unknown `--phase` included), a failed or contained cycle under the guard is a `cycle_failed` envelope leading with the CycleReport keys, and `retriage` / `reset-key` refusals are envelopes. The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE). `--eval-run` opts the process in to `GBRAIN_DECIDE_SLOTS` (`enableDecideEvalOverride`) for eval harnesses; consent, egress and the daily cap still apply.+- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed; a `cycle_already_running` skip names the lock holder (pid, host, age) from `report.lock_holder`. Source scope enters the shared 6-tier resolver whenever `--source <id>` is given OR `GBRAIN_SOURCE` is set (a null explicit falls through to tier 2: validated + `assertSourceExists`, so an invalid/unknown env value is a clean exit 1; the `__all__` sentinel is excluded and falls through to the unscoped routing, which already spans every source); an env scope naming the brain's default-like source keeps the full implicit cycle (#4700 semantics), any other keeps the `--source` freshness boundary. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved source's `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining, stopped}`. `--window` is a hard deadline for starting work (the item in flight finishes). Every stop maps through `drainOutcome` (`src/core/cycle/extract-atoms-drain-outcome.ts`): exit 0 only for `stopped: drained` with `remaining: 0`; exit 11 (`BUDGET_STOP_EXIT_CODE`) for a retryable stop (`atom_drain_incomplete`: window, deadline, lock, batch cap, budget, a null count; `atom_drain_provider_failure` reasons `rate_limit`/`transient`), printing the rerun command (`gbrain dream --drain --window <s> [--source <id>]`) on stderr and adding `resume_command` under `--json`; exit 1 for a stop a rerun cannot clear (`atom_drain_provider_failure` reasons `auth`/`billing`/`model_not_found`/`content_block`, `atom_drain_no_progress` over a counted backlog), printing the registry suggestion as a `Fix:` line and adding the rendered `fix` instead of `resume_command`. `--json` of any incomplete stop carries `status` (`incomplete` or `provider_failure`, never `ok`), `retryable`, `code` and `reason`; `LockUnavailableError` → `cycle_already_running` skip (also exit 11). Under `--json` (D2) every path is one document: usage errors are `invalid_params` envelopes (exit 2, unknown `--phase` included), a failed or contained cycle under the guard is a `cycle_failed` envelope leading with the CycleReport keys, and `retriage` / `reset-key` refusals are envelopes. The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE). `--eval-run` opts the process in to `GBRAIN_DECIDE_SLOTS` (`enableDecideEvalOverride`) for eval harnesses; consent, egress and the daily cap still apply.- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in `test/embedding-recovery.serial.test.ts` (PGLite) and its PostgreSQL wrapper, `test/e2e/embedding-recovery-parity.test.ts`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; a budget stop that leaves stale chunks is never silent: `src/core/embed-budget-stop.ts` records `reason: 'time_budget'`, `remaining_stale` and `resume_command`, `runEmbed` prints the verdict on stdout and the CLI exits 11 (`BUDGET_STOP_EXIT_CODE`); an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). In `--stale`, a page whose guarded projection snapshot is unavailable when its turn comes (edited, tagged or unsealed after the readiness gate) counts its chunks as failures and is named in one end-of-run batch-summary sample (the first five slugs plus a count of the rest); a page whose source was archived mid-run is left to the archived-work report so it is counted once. Pinned by `test/embed-stale-unavailable-snapshot.serial.test.ts`. Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-default-concurrency.test.ts` (20 page workers on both paths when the env var is unset) and `test/embed-pool-abort.test.ts` (an abort stops both page pools from claiming further pages). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `--stale` progress (#5968) is exact chunk accounting through `src/core/embed-stale-progress.ts`: `onProgress(done, total, embedded)` carries cumulative stale chunks against a total that grows by heal splits, behind-cursor rows and re-entries, the CLI ticks `embed.pages` by the delta and forwards the grown total with `setTotal`, and `done <= total` holds at every callback. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. Its result prints from `runEmbed` only without `--json`; under `--json` the CLI dispatch writes the one document. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed. #5183: the page-embedding worker count comes from `resolveEmbedConcurrency` in `src/core/embed-concurrency.ts` (GBRAIN_EMBED_CONCURRENCY, a paced cap, and on Postgres never above the client pool; one warning when an explicit setting is lowered). A chunkless page whose projection install loses to another installer (the resident rebuild) re-reads through `retryProjectionConflict` and embeds the sealed chunks it finds; a conflict that outlasts the retries is recorded as a `[page_projection_conflict]` failure sample with the envelope's next step (`test/embedding-recovery.serial.test.ts`). `--all` passes the sliding pool an `onError` handler: an error that escapes `embedOnePage` (its snapshot read runs before the page's own try) counts that page once on `result.failures` with an `Error embedding <slug>` stderr line, unless the run is already aborting when the error arrives (shutdown, not a failure); `test/embed-partial-failure-3037.serial.test.ts`. #6223: pages still blocked after bounded projection recovery no longer end `--stale` early; healthy chunks embed, the blocked pages' chunks count as failures, and one sample names them (not the mid-run "changed" summary) with `gbrain embed --stale --images` / `gbrain sync --full` for image and media pages. Fix wave 13 P1.18 (#6400): `runEmbed` takes the CLI's consent outcome; a finite approved `cap_usd` runs the foreground text and `--images` paths under `embedCostCap` (`src/core/embed-cost-cap.ts`) and returns `reason: 'cost_cap'` (exit `BUDGET_STOP_EXIT_CODE` from `src/cli/commands/embed.ts`, which now returns the Authorization from `authorizeEmbed`); `--background` stores it on the row through `maybeBackground(...spendAuthorization)` (PGLite runs inline, metered). `--slugs` takes the arguments up to the next flag. Tests: `test/embed-max-usd-metered.serial.test.ts`, `test/e2e/embed-background-cap.test.ts`. #6529: `runEmbed` with `--stale` (no `--slugs`) first runs `runStaleImageSweepFirst` (`core/embed-stale-images.ts`, multimodal installs only) inside the same cost cap and folds it into `EmbedResult.images`; the text pass's blocked-projection hint (`core/embedding-readiness.ts`) then points at that sweep's `missing_samples` instead of a separate `--images` command, and at `GBRAIN_EMBEDDING_MULTIMODAL=true` or `--images` / `sync --full` on a text-only install.diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 889892d297..986e328d42 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -17,8 +17,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/extract-atoms-cost-gate.ts` — cost-gate decision for the extract_atoms `BudgetTracker`, shared with the Life Chronicle `chronicle` phase through `settleExtractAtomsCostGate`'s `target` (phase name, refusal key prefix `chronicle.no_pricing.`, no rollup). `resolveExtractAtomsCostGate(extractModel, embedModel, overrides?, {explicitBudget?})` (pure) returns `{enforceCap, unpricedModel?, unpricedKind?, refusal?}`: the cap is enforceable only when EVERY model billed under the phase's tracker is priceable — the extraction chat model AND the embedding model the atom import (`importFromContent`, inside the same `withBudgetTracker` scope) calls — with operator `pricing.overrides` consulted first, matching `BudgetTracker.reserve()`. `resolveEmbedModelForCostGate()` mirrors the write site's `isAvailable('embedding')` gate (null when embedding is unavailable). A DEFAULT cap is dropped for an unpriced route (warn and run). When the operator SET `cycle.extract_atoms.budget_usd` (`explicitBudget`), an unpriced chat model or embed route yields `refusal` (the shared `no_pricing` guidance). `settleExtractAtomsCostGate` acts before any work item: it warns on a dropped cap; on a refusal it returns the phase's `warn` result (`details.reason: 'no_pricing'`, `details.no_pricing`, no model call), records the guidance at `cycle.extract_atoms.no_pricing.<source>` and upserts the rollup as an expected limit, not a halt; any run past the gate clears the source's record (dry runs record nothing). `readExtractAtomsNoPricing` + `withExtractAtomsNoPricing` overlay doctor's `extract_health` (wired in `doctor/checks/local-audits.ts`) with a `warn` naming the model and `register_command`. Pinned by `test/extract-atoms-embed-cost-gate.test.ts` and `test/extract-atoms-explicit-cap-no-pricing.test.ts`.-- `src/core/cycle/extract-atoms-drain.ts` — pure single-hold bounded drain for the silent lens-phase backlog. `runExtractAtomsDrain(deps, opts)` over injected deps (`withLock`, `runBatch`, `countRemaining`, `now`, optional `onBatch`) loops bounded batches under ONE lock hold, rediscovering eligibility each batch (idempotent NOT-EXISTS-on-`source_hash`; no cross-window cursor), until the backlog is empty or the window ends. Two stop signals: HARD (job `signal` + the lock's lease-loss signal + `deadlineAtMs`) reaches the chat call, the pacing pause and every backlog count; SOFT (hard + the window timer) is checked only between batches and items, so the item in flight finishes. Counts are cancellable and bounded (`countTimeoutMs`, capped by the remaining deadline). `stopped` is a `DrainStop` (`drained|window|deadline|lock_lost|aborted|no_progress|max_batches|provider_failure|budget`); `budget` (#6425) stops after the first batch that reports `budgetSkipped > 0` (the attempt's one tracker is spent) and carries `spent_usd`/`budget_usd`, which `dream --drain` renders as the spend, the cap and an `atom_drain_budget` notice whose paid fix raises `cycle.extract_atoms.budget_usd`; the Minion handler completes it normally; a hard stop skips `onBatch` and the recount and reports the last count as `remaining`, and the lease loss `withRefreshingLock` rethrows becomes `lock_lost` with the partial counters. Backs `gbrain dream --phase extract_atoms --drain` under the SAME `cycleLockIdFor(sourceId)` the routine cycle takes (a concurrent tick defers with `cycle_already_running`). `runExtractAtomsDrainForSource(engine, {sourceId, windowSeconds, brainDir?, maxBatches?, onBatch?, signal?, deadlineAtMs?})` owns the lock+batch+count wiring for all three callers — `dream --drain`, the `extract-atoms-drain` Minion handler, autopilot auto-drain. `sourceId: undefined` → legacy `gbrain-cycle` lock + `'default'`; a real id → `gbrain-cycle:<id>`. `LockUnavailableError` propagates. One `runExtractAtomsDrainForSource` call is one drain attempt: its batches share one `BudgetTracker` (the per-run `cycle.extract_atoms.budget_usd` cap is the attempt's cap) and one `MaintenanceWriteWait` (`persistence/maintenance-wait.ts`, bounded by `deadlineAtMs`). `structuralAtomRefusal` maps an `owner_unavailable`/`permission_denied` refusal from the atom session preflight to `STRUCTURAL_REFUSAL_PREFIX` text; the `extract-atoms-drain` Minion handler (`src/core/minions/handlers/extract-atoms-drain.ts`) throws it as `UnrecoverableError`, so the job dead-letters once with no model call and the auto-drain cap does not count it. `last_error` and the typed failure records pass through `sanitizeFailureText` (secret/DSN redaction, bounded). `formatDrainProviderFailure(result, {final?})` renders the handler's `provider_failure` throw; the handler throws `UnrecoverableError` on `deadline` or any failure at/past `deadlineAtMs`, the job's abort reason on `aborted`, and a retryable error on `lock_lost`. Tests: `test/extract-atoms-drain*.test.ts`.+- `src/core/cycle/extract-atoms-drain.ts` — pure single-hold bounded drain for the silent lens-phase backlog. `runExtractAtomsDrain(deps, opts)` over injected deps (`withLock`, `runBatch`, `countRemaining`, `now`, optional `onBatch`) loops bounded batches under ONE lock hold, rediscovering eligibility each batch (idempotent NOT-EXISTS-on-`source_hash`; no cross-window cursor), until the backlog is empty or the window ends. Two stop signals: HARD (job `signal` + the lock's lease-loss signal + `deadlineAtMs`) reaches the chat call, the pacing pause and every backlog count; SOFT (hard + the window timer) is checked only between batches and items, so the item in flight finishes. Counts are cancellable and bounded (`countTimeoutMs`, capped by the remaining deadline). `stopped` is a `DrainStop` (`drained|window|deadline|lock_lost|aborted|no_progress|max_batches|provider_failure|budget`); `budget` (#6425) stops after the first batch that reports `budgetSkipped > 0` (the attempt's one tracker is spent) and carries `spent_usd`/`budget_usd`, which `dream --drain` renders as the spend, the cap and an `atom_drain_budget` notice whose paid fix raises `cycle.extract_atoms.budget_usd`; the Minion handler completes it normally; a hard stop skips `onBatch` and the recount and reports the last count as `remaining`, and the lease loss `withRefreshingLock` rethrows becomes `lock_lost` with the partial counters. Backs `gbrain dream --phase extract_atoms --drain` under the SAME `cycleLockIdFor(sourceId)` the routine cycle takes (a concurrent tick defers with `cycle_already_running`). `runExtractAtomsDrainForSource(engine, {sourceId, windowSeconds, brainDir?, maxBatches?, onBatch?, signal?, deadlineAtMs?})` owns the lock+batch+count wiring for all three callers — `dream --drain`, the `extract-atoms-drain` Minion handler, autopilot auto-drain. `sourceId: undefined` → legacy `gbrain-cycle` lock + `'default'`; a real id → `gbrain-cycle:<id>`. `LockUnavailableError` propagates. One `runExtractAtomsDrainForSource` call is one drain attempt: its batches share one `BudgetTracker` (the per-run `cycle.extract_atoms.budget_usd` cap is the attempt's cap) and one `MaintenanceWriteWait` (`persistence/maintenance-wait.ts`, bounded by `deadlineAtMs`). `structuralAtomRefusal` maps an `owner_unavailable`/`permission_denied` refusal from the atom session preflight to `STRUCTURAL_REFUSAL_PREFIX` text; the `extract-atoms-drain` Minion handler (`src/core/minions/handlers/extract-atoms-drain.ts`) throws it as `UnrecoverableError`, so the job dead-letters once with no model call and the auto-drain cap does not count it. `last_error` and the typed failure records pass through `sanitizeFailureText` (secret/DSN redaction, bounded). A `provider_failure` result carries `provider_failure_class` (`batchProviderFailureClass`: the phase's `aborted_global_error` halt class `auth`/`billing`/`model_not_found`/`rate_limit`, `content_block` when every failure is a provider content block, else `transient`). `formatDrainProviderFailure(result, {final?})` renders the handler's `provider_failure` throw; the handler throws `UnrecoverableError` on `deadline`, on a provider failure `drainOutcome` marks not retryable, or any failure at/past `deadlineAtMs`, the job's abort reason on `aborted`, and a retryable error on `lock_lost`. Tests: `test/extract-atoms-drain*.test.ts`.+- `src/core/cycle/extract-atoms-drain-outcome.ts` — #6817: `drainOutcome(result)`, the one mapping from a drain stop to exit code, JSON `status` (never `ok` for an incomplete stop), `retryable`, `code` and `reason`, read from the error registry (`atom_drain_incomplete` exit 11, `atom_drain_provider_failure` exit 1 with `rate_limit`/`transient` overridden to retryable exit 11, `atom_drain_no_progress` exit 1; a null count is always `atom_drain_incomplete`/`count_unavailable`). Used by `dream --drain` and the `extract-atoms-drain` Minion handler; type-only import of the drain module. Tests: `test/extract-atoms-drain-outcome.test.ts`, `test/dream-drain-failure-summary.serial.test.ts`, `test/extract-atoms-drain-handler.test.ts`.- `src/core/cycle/extract-atoms-budget-notice.ts` — #6425: `drainBudgetNotice(result)` renders the `atom_drain_budget` notice a `budget`-stopped drain carries in `gbrain dream --drain --json` (spend, per-run cap, pages left; paid fix `gbrain config set cycle.extract_atoms.budget_usd <USD>`, verify `gbrain config get`), and `usd` formats the amounts for the stderr stop line. Dynamically imported by `dream.ts` so its notice-rendering imports stay out of the CLI flag scan. Tests: `test/dream-drain-failure-summary.serial.test.ts`.- `src/core/cycle/extract-atoms-input.ts` — #6503 the input cap and the partial disposition. `resolveExtractAtomsInputCap` reads `cycle.extract_atoms.max_input_chars` (floor 1000; the older `max_source_chars`, floor 500, loses when both are set; default 50 000) before discovery. `extractAtomsInput(item, cap)` binds the cut once: paste-stripped for a transcript (#5812), UTF-8-safe, with `truncated` measured on the text the cap applied to. A page item also takes its stored `extract_atoms` watermark (`src/core/extraction-watermark.ts`, large pages A7): when the body still starts with the watermarked prefix the model reads only the appended text (its newest `cap` characters when longer), which is still partial input, so the same disposition below applies; `inputTruncatedLine` is null for a complete tail read (not counted, no stderr) and names the window otherwise, and the phase commits the plan once the item's writes committed (a pending managed batch keeps the old watermark). A cut item is extracted once from its head and gets a partial disposition instead of a completion: `input_truncated` counts it on the phase result (and the drain sums it into `input_truncated`, with one `[drain]` line), `inputTruncatedLine` is written to stderr naming the knob, the head atoms publish, no completion stamp is written and nothing is retired. `recordPartialDisposition` stores the cap under (content hash, cap) in `extract_atoms_page_state` / `extract_atoms_transcript_state.partial_input_chars` (migration v240; the page row is pinned to the identity discovery read), and on a managed brain the origin carries `partialInputChars`, which enters the run key, keeps the completion's checkpoint `partial`, skips the page-state stamp and the retirement, and marks the completion outcome `status: 'partial'`. Discovery and the backlog count skip a partial row like a tombstone (`PAGE_SCAN_STATE_EXCLUSION_SQL`, `tombstonedTranscriptsForHashes`, the partial checkpoint); `releasePartialDispositions` runs before discovery with the current cap and clears the rows and checkpoints a raised cap supersedes, so the item is eligible again with zero model calls in between; a content change is a new row. Resumed and budget-skipped items are not counted. `stampTranscriptTombstone` (v146) lives here too. Tests: `test/extract-atoms-input-truncated-6503.test.ts` (PGLite and Postgres, page and transcript, managed and unmanaged).diff --git a/src/commands/dream.ts b/src/commands/dream.tsindex dc6953389a..e0ce2a5349 100644--- a/src/commands/dream.ts+++ b/src/commands/dream.ts@@ -36,6 +36,8 @@ import { jsonGuardActive, jsonRequested, setCliExitVerdict, writeJsonDocument }import { BUDGET_STOP_EXIT_CODE } from '../core/exit-codes.ts';import { opError, type OperationError } from '../core/ops/contract.ts';import { usageError, writeCliError, writeCliRefusal } from '../cli/cli-error.ts';+import { cliRenderContext, renderAction, shellQuote, type Action } from '../core/agent-output.ts';+import { codeEntry } from '../core/error-catalogue.ts';import { fetchSource } from '../core/sources-load.ts';import { existsSync } from 'fs';import { resolve } from 'node:path';@@ -450,9 +452,14 @@ Options:(the default phase when --drain is set). Holds thecycle lock once, processes batches until the backlogempties or --window elapses, reports {extracted,- remaining, stopped}, and exits 3 unless the backlog- drained (printing the rerun command) so a cron/agent- loop knows to run again. Use this to grind down an+ remaining, stopped}. Exits 0 when the backlog drained;+ 11 when running again can continue (window, budget,+ batch cap, deadline, lock, an unknown count, a rate+ limit or transient provider failure), printing the+ rerun command; 1 when it cannot until something+ changes (provider auth, billing, unknown model or+ content block; no_progress), printing the fix. --json+ adds status, retryable and code. Use this to grind down anextract_atoms backlog on a brain whose pack doesn'trun the phase in the routine cycle.--window <seconds> Drain window, a hard deadline: no page or transcript@@ -666,23 +673,39 @@ async function runDrain();}const { drainBudgetNotice, usd } = await import('../core/cycle/extract-atoms-budget-notice.ts');+ const { drainOutcome } = await import('../core/cycle/extract-atoms-drain-outcome.ts');+ // #6817: one stop → exit/status/retryable mapping, shared with the Minion handler.+ const outcome = drainOutcome(result);const budgetNotice = result.stopped === 'budget' ? drainBudgetNotice(result) : null;+ const fix = outcome.retryable || !outcome.code ? undefined : codeEntry(outcome.code)?.fix;if (opts.json) {- const done = result.stopped === 'drained' && result.remaining === 0;- await writeJsonDocument(JSON.stringify(done ? result : { ...result, resume_command: drainCommand(opts),+ await writeJsonDocument(JSON.stringify(outcome.status === 'ok' ? result : {+ ...result, status: outcome.status, retryable: outcome.retryable, code: outcome.code,+ ...(outcome.reason ? { reason: outcome.reason } : {}),+ ...(outcome.retryable ? { resume_command: drainCommand(opts) } : {}),+ ...(fix ? { fix: renderAction(fix, cliRenderContext()) } : {}),...(budgetNotice ? { notices: [budgetNotice] } : {}) }, null, 2));} else {console.log(`[drain] extracted ${result.extracted} atom(s) across ${result.batches} batch(es); ${result.remaining ?? '?'} remaining (stopped: ${result.stopped})`);}// null remaining = the final count query failed; do not report success.- if (result.stopped === 'drained' && result.remaining === 0) return;+ if (outcome.status === 'ok') return;+ const stop = `[drain] stopped: ${result.stopped}${outcome.status === 'provider_failure' ? ` (${outcome.reason})` : ''}; ${result.remaining ?? '?'} page(s) remaining.`;process.stderr.write(budgetNotice? `[drain] stopped: budget; spent ${usd(result.spent_usd)} of the ${usd(result.budget_usd)} per-run cap (cycle.extract_atoms.budget_usd); ` +`${result.remaining ?? '?'} page(s) remaining. Rerun: ${drainCommand(opts)}, or raise the cap: gbrain config set cycle.extract_atoms.budget_usd <usd>\n`- : `[drain] stopped: ${result.stopped}; ${result.remaining ?? '?'} page(s) remaining. ` +- `Rerun: ${drainCommand(opts)}\n`,+ : outcome.retryable+ ? `${stop} Rerun: ${drainCommand(opts)}\n`+ : `${stop} Fix: ${nonRetryableFixLine(outcome.code!, fix!)}\n`,);- process.exit(EXIT_DRAIN_INCOMPLETE);+ process.exit(outcome.exit);+}++/** The registry suggestion for a non-retryable drain stop, plus its read-only check when the prose does not already name it. */+function nonRetryableFixLine(code: string, fix: Action): string {+ const suggestion = codeEntry(code)!.suggestion;+ const check = shellQuote(fix.argv ?? []);+ return suggestion.includes(check) ? suggestion : `${suggestion} Read-only check: ${check}`;}function drainCommand(opts: DreamArgs): string {diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 2a176a76ec..1b7ab01fe0 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -907,6 +907,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// Fix wave 20 lane 2 (dream, transcripts, extraction, autopilot).{ since: '0.60.307.0', text: 'A same-day `dream` synthesize rerun that writes no pages now keeps that day\'s existing `dream-cycle-summaries/<date>` page (database row and file) on every brain, as managed brains already did, instead of replacing it with an empty summary. The first run of a day still writes its summary even when it wrote nothing.' },{ since: '0.60.307.0', text: 'Hermes transcript import now unwraps message content Hermes stores as `json:` followed by a block array, as it already did for a bare array: text blocks are kept and each image block becomes an `[image]` placeholder, so a pasted screenshot no longer imports as kilobytes of base64 text. Sessions already imported keep their old text until they are imported again.' },+ { since: '0.60.307.0', text: '`gbrain dream --drain` no longer exits 11 for every incomplete stop. A stop running again cannot clear now exits 1 with a `Fix:` line instead of a rerun hint: a provider failure on every item caused by auth, billing, an unknown model or a content block (`atom_drain_provider_failure`), and `no_progress` over a counted backlog (`atom_drain_no_progress`). A rate limit, a transient provider failure, the window, budget, batch cap, deadline, lock and an unknown backlog count still exit 11 with the rerun command. `--json` of an incomplete stop now reports `status` `incomplete` or `provider_failure` (never `ok`) with `retryable`, `code` and `reason`, and the help no longer says exit 3. The `extract-atoms-drain` job dead-letters an auth, billing, unknown-model or content-block failure at once instead of retrying it.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 9f8e4affad..cd6c1a044e 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -49,7 +49,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],- 'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],+ 'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--group', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-embed', '--no-embedding', '--no-hooks', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--scopes', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--to', '--wait', '--yes'],diff --git a/src/core/cycle/extract-atoms-drain-outcome.ts b/src/core/cycle/extract-atoms-drain-outcome.tsnew file mode 100644index 0000000000..59b4ed1cbc--- /dev/null+++ b/src/core/cycle/extract-atoms-drain-outcome.ts@@ -0,0 +1,44 @@+/**+ * #6817: the one mapping from an atom drain's stop to what its caller does+ * next, shared by `gbrain dream --drain` (exit code, JSON `status` /+ * `retryable` / `code`, the human last line) and the `extract-atoms-drain`+ * Minion handler (retry under backoff, or dead-letter).+ *+ * drained, backlog counted empty exit 0, status ok+ * provider_failure, auth/billing/model/+ * content block exit 1, not retryable (atom_drain_provider_failure)+ * provider_failure, rate limit/transient exit 11, retryable (atom_drain_provider_failure)+ * no_progress with a counted backlog exit 1, not retryable (atom_drain_no_progress)+ * every other stop, or an unknown count exit 11, retryable (atom_drain_incomplete)+ *+ * Exit codes and retryability come from the error registry entries, so this+ * table and `gbrain errors <code>` cannot disagree. Type-only import of the+ * drain module: dream.ts loads this next to a drain helper tests replace.+ */+import { codeRetryable, exitCodeForCode } from '../error-catalogue.ts';+import type { ExtractAtomsDrainResult } from './extract-atoms-drain.ts';++export type DrainOutcomeCode = 'atom_drain_incomplete' | 'atom_drain_provider_failure' | 'atom_drain_no_progress';++export interface DrainOutcome {+ /** Never `ok` for a stop that left work behind. */+ status: 'ok' | 'incomplete' | 'provider_failure';+ exit: number;+ retryable: boolean;+ code?: DrainOutcomeCode;+ reason?: string;+}++type OutcomeInput = Pick<ExtractAtomsDrainResult, 'status' | 'stopped' | 'remaining' | 'provider_failure_class'>;++export function drainOutcome(result: OutcomeInput): DrainOutcome {+ if (result.stopped === 'drained' && result.remaining === 0) return { status: 'ok', exit: 0, retryable: false };+ if (result.status === 'provider_failure') return classified('provider_failure', 'atom_drain_provider_failure', result.provider_failure_class ?? 'transient');+ if (result.remaining === null) return classified('incomplete', 'atom_drain_incomplete', 'count_unavailable');+ if (result.stopped === 'no_progress') return classified('incomplete', 'atom_drain_no_progress');+ return classified('incomplete', 'atom_drain_incomplete', result.stopped);+}++function classified(status: DrainOutcome['status'], code: DrainOutcomeCode, reason?: string): DrainOutcome {+ return { status, exit: exitCodeForCode(code, reason), retryable: codeRetryable(code, reason), code, ...(reason ? { reason } : {}) };+}diff --git a/src/core/cycle/extract-atoms-drain.ts b/src/core/cycle/extract-atoms-drain.tsindex 215d27f0fe..adfb582c0a 100644--- a/src/core/cycle/extract-atoms-drain.ts+++ b/src/core/cycle/extract-atoms-drain.ts@@ -116,6 +116,8 @@ export interface ExtractAtomsDrainDeps {budget?: { spentUsd: number; capUsd: number };/** #6503: items the batch cut at `cycle.extract_atoms.max_input_chars` (partial disposition, not complete). */inputTruncated?: number;+ /** #6817: with `providerFailure`, what the outage was; unset reads as `transient`. */+ providerFailureClass?: DrainProviderFailureClass;}>;/*** Count remaining eligible-but-unextracted pages, or null on query error.@@ -155,6 +157,14 @@ export type DrainStop =| 'drained' | 'window' | 'deadline' | 'lock_lost' | 'aborted'| 'no_progress' | 'max_batches' | 'provider_failure' | 'budget';+/**+ * #6817: why every item of a provider_failure batch failed. `auth`, `billing`,+ * `model_not_found` and `content_block` repeat on every retry until someone+ * changes the key, plan, model or content; `rate_limit` and `transient`+ * (5xx, timeout, network, an unclassified error) can clear on their own.+ */+export type DrainProviderFailureClass = 'auth' | 'billing' | 'model_not_found' | 'content_block' | 'rate_limit' | 'transient';+export const DRAIN_COUNT_TIMEOUT_MS = 60_000;/**@@ -217,6 +227,8 @@ export interface ExtractAtomsDrainResult {budget_usd?: number;/** #6503: items cut at the input cap across every batch; the model did not read their tails and they are not marked complete. */input_truncated?: number;+ /** #6817: with `status: 'provider_failure'`, the failing batch's class (`transient` when the batch named none). */+ provider_failure_class?: DrainProviderFailureClass;}/**@@ -251,6 +263,7 @@ export async function runExtractAtomsDrain(// the returned `status`, independent of how `stopped` reads after the// final (possibly overriding) remaining-count check below.let providerFailure = false;+ let providerFailureClass: DrainProviderFailureClass = 'transient';// #4539: accumulate per-item failure visibility across batches.let failureCount = 0;// #4730: bounded typed per-item records (batch order, sanitized).@@ -274,6 +287,7 @@ export async function runExtractAtomsDrain(last_error: lastError,...(stopped === 'budget' && budget ? { spent_usd: budget.spentUsd, budget_usd: budget.capUsd } : {}),input_truncated: inputTruncated,+ ...(providerFailure ? { provider_failure_class: providerFailureClass } : {}),});try {return await deps.withLock(async (signal) => {@@ -380,6 +394,7 @@ export async function runExtractAtomsDrain(// drain as a clean completion.if (r.providerFailure) {providerFailure = true;+ providerFailureClass = r.providerFailureClass ?? 'transient';stopped = 'provider_failure';break;}@@ -436,6 +451,18 @@ export async function runExtractAtomsDrain(}}+/**+ * #6817: classify a batch whose every item failed. The phase's whole-run halt+ * class (`details.aborted_global_error`) wins; a batch whose every failure is+ * a provider content block is `content_block`; anything else is `transient`,+ * because nothing shows that retrying cannot succeed.+ */+export function batchProviderFailureClass(halted: unknown, failures: ReadonlyArray<{ reason: string }>): DrainProviderFailureClass {+ if (halted === 'auth' || halted === 'billing' || halted === 'model_not_found' || halted === 'rate_limit') return halted;+ if (failures.length > 0 && failures.every(f => f.reason.startsWith('provider blocked content'))) return 'content_block';+ return 'transient';+}+// ─── Shared wiring helper (v0.42.x #1685 DECISION 5A) ──────────────────────//// ONE drain path, three callers: `gbrain dream --phase extract_atoms --drain`@@ -536,6 +563,7 @@ export async function runExtractAtomsDrainForSource(extracted: Number(d.atoms_extracted ?? 0),skipped: Number(d.duplicates_skipped ?? 0),providerFailure: failures.length > 0 && itemsSucceeded === 0,+ providerFailureClass: batchProviderFailureClass(d.aborted_global_error, typedFailures),failureCount: failures.length,failures: typedFailures,budgetSkipped: Number(d.pages_skipped_budget ?? 0) + Number(d.transcripts_skipped_budget ?? 0),diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 5a5436d9dc..ab685a1a0d 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -76,6 +76,9 @@ export const CODES = {answer_unavailable: { class: 'caller', summary: "The rated answer is not recorded: unknown, dropped, or older than the retention window.", docs: 'docs/guides/retrieval-feedback.md#answer_unavailable' },api_not_enabled: { class: 'host_only', summary: "Google connect credential error: api not enabled.", docs: 'docs/guides/google-connect.md#troubleshooting' },approval_required: { class: 'consent', summary: "The change needs the owner's explicit approval before it can proceed." },+ atom_drain_incomplete: { class: 'retryable', exit: 11, summary: "An atom drain (`gbrain dream --drain`) stopped with atoms still to extract, or with its backlog count unknown; the batches it finished stay committed and running it again continues.", why: "The drain is bounded by its window, batch cap, per-run budget, job deadline and the cycle lock, and a backlog count that fails is never read as drained; each of these stops can clear on the next run.", reasons: ['window', 'deadline', 'lock_lost', 'aborted', 'max_batches', 'budget', 'count_unavailable'], suggestion: 'Run the printed resume_command again (a budget stop also names the cap it hit).', fix: { argv: ['gbrain', 'doctor', '--only', 'extract_atoms_backlog', '--json'], consent: [], actor: 'agent', why: 'Read-only: counts the pages still waiting for atom extraction.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'extract_atoms_backlog', '--json'] } } },+ atom_drain_no_progress: { class: 'host_only', retryable: false, summary: "An atom drain batch extracted nothing and the backlog count did not fall, so the drain stopped instead of spending in a loop; batches it finished earlier stay committed.", why: "What is left is failing, skipped or ineligible, so running the drain unchanged repeats the same empty batch.", suggestion: 'Do not rerun this drain unchanged. Run gbrain doctor --json on the brain host and ask the operator to resolve the reported extraction blocker; earlier successful batches remain committed.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'host_admin', why: 'Read-only: names the extraction blocker (provider, eligibility or backlog) the drain could not get past.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'extract_atoms_backlog', '--json'] } } },+ atom_drain_provider_failure: { class: 'host_only', retryable: false, summary: "Every item an atom drain batch attempted failed at the model provider, so the drain stopped; batches it finished earlier stay committed.", why: "An auth, billing, unknown-model or content-block failure repeats on every retry until someone changes the key, plan, model or content, so it is not retryable. A rate limit or a transient failure (5xx, timeout, network, or a cause the provider did not name) can clear by itself, so those reasons stay retryable on exit 11.", reasons: ['auth', 'billing', 'model_not_found', 'content_block', 'rate_limit', 'transient'], reason_overrides: { rate_limit: { class: 'retryable', exit: 11 }, transient: { class: 'retryable', exit: 11 } }, suggestion: 'For auth, billing or model_not_found, ask the operator to fix the provider key, plan or model named in last_error, then run the drain again; content_block items are skipped once they fail repeatedly. For rate_limit or transient, run the drain again later.', fix: { argv: ['gbrain', 'models', '--json'], consent: [], actor: 'agent', why: 'Read-only: shows the extraction model and whether its provider is configured.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'extract_atoms_backlog', '--json'] } } },autopilot_job_owned_by_other_brain: { class: 'caller', summary: "The autopilot job is bound to a different brain." },body_staging_expired: { class: 'retryable', summary: "The staged body of a large-page write expired before it was published, so nothing was published.", why: "A segmented write stages its segments first and publishes them in one flip; a staging idle past its deadline is collected by maintenance, and publishing without its segments would leave the page missing text.", suggestion: 'Send the same write again; it stages a fresh copy.' },budget_below_recent_runtime: { class: 'unavailable', summary: "The cycle's remaining budget fits fewer reflections than dream patterns needs at the recorded runtime, so the in-cycle run was skipped before any spend.", why: 'An in-cycle patterns run is sized from dream.patterns.last_run; a run that cannot finish in the budget would spend tokens and be killed.', docs: 'docs/guides/dream-patterns.md#budget-sizing', suggestion: 'Run `gbrain dream --phase patterns` outside the cycle after the user agrees to the paid run (it is not budget-limited and records its cost), or reset the record with `gbrain config unset dream.patterns.last_run`.' },diff --git a/src/core/minions/handlers/extract-atoms-drain.ts b/src/core/minions/handlers/extract-atoms-drain.tsindex 868bc38f03..9e2aa4d075 100644--- a/src/core/minions/handlers/extract-atoms-drain.ts+++ b/src/core/minions/handlers/extract-atoms-drain.ts@@ -63,7 +63,9 @@ export function makeExtractAtomsDrainHandler(engine: BrainEngine): MinionHandler// over instead — matching the existing behavior for every other// handler failure. Partial success (>=1 item extracted) keeps// completing normally, unchanged.- if (result.status === 'provider_failure' && pastDeadline()) {+ // #6817: an auth, billing, unknown-model or content-block outage repeats on every attempt; dead-letter it once.+ const { drainOutcome } = await import('../../cycle/extract-atoms-drain-outcome.ts');+ if (result.status === 'provider_failure' && (pastDeadline() || !drainOutcome(result).retryable)) {throw new UnrecoverableError(formatDrainProviderFailure(result, { final: true }));}if (result.status === 'provider_failure') {diff --git a/test/dream-drain-failure-summary.serial.test.ts b/test/dream-drain-failure-summary.serial.test.tsindex ce30af4d6b..038b75346f 100644--- a/test/dream-drain-failure-summary.serial.test.ts+++ b/test/dream-drain-failure-summary.serial.test.ts@@ -254,3 +254,75 @@ describe('dream --drain budget stop (#6425)', () => {expect(payload.notices[0].why).toContain('$0.0151 of $0.03');});});+++// #6817: one mapping for every drain stop across exit code, JSON status/retryable/code and the human last line.+describe('dream --drain exit mapping (#6817)', () => {+ test('a permanent provider failure after a committed batch exits 1 with no rerun hint and names the fix', async () => {+ nextResult = baseResult({ status: 'provider_failure', stopped: 'provider_failure', provider_failure_class: 'auth', remaining: 9, extracted: 3, batches: 2,+ failure_count: 4, last_error: 'notes/a: Failed to authenticate: OAuth session expired' });+ const json = await runDrainCaptured(['--json']);+ expect(json.exitCode).toBe(1);+ const payload = JSON.parse(json.stdout.join('\n'));+ expect(payload).toMatchObject({ status: 'provider_failure', retryable: false, code: 'atom_drain_provider_failure', reason: 'auth', extracted: 3, remaining: 9 });+ expect(payload.resume_command).toBeUndefined();+ expect(payload.fix).toMatchObject({ argv: ['gbrain', 'models', '--json'] });+ const human = await runDrainCaptured([]);+ expect(human.exitCode).toBe(1);+ expect(human.stderr).toContain('[drain] stopped: provider_failure (auth); 9 page(s) remaining. Fix: ');+ expect(human.stderr).toContain('Read-only check: gbrain models --json');+ expect(human.stderr).not.toContain('Rerun:');+ });++ test('a rate-limited or transient provider failure stays retryable on exit 11', async () => {+ for (const cls of ['rate_limit', 'transient'] as const) {+ nextResult = baseResult({ status: 'provider_failure', stopped: 'provider_failure', provider_failure_class: cls, remaining: 5 });+ const json = await runDrainCaptured(['--json']);+ expect(json.exitCode, cls).toBe(11);+ expect(JSON.parse(json.stdout.join('\n'))).toMatchObject({ status: 'provider_failure', retryable: true, code: 'atom_drain_provider_failure', reason: cls,+ resume_command: 'gbrain dream --drain --window 300' });+ }+ });++ test('no_progress over a counted backlog exits 1, reports a non-ok status and says not to rerun unchanged', async () => {+ nextResult = baseResult({ stopped: 'no_progress', remaining: 7, extracted: 2, batches: 2 });+ const json = await runDrainCaptured(['--json']);+ expect(json.exitCode).toBe(1);+ const payload = JSON.parse(json.stdout.join('\n'));+ expect(payload).toMatchObject({ status: 'incomplete', retryable: false, code: 'atom_drain_no_progress', stopped: 'no_progress', extracted: 2 });+ expect(payload.resume_command).toBeUndefined();+ const human = await runDrainCaptured([]);+ expect(human.exitCode).toBe(1);+ expect(human.stderr).toContain('[drain] stopped: no_progress; 7 page(s) remaining. Fix: Do not rerun this drain unchanged. Run gbrain doctor --json on the brain host');+ expect(human.stderr).toContain('earlier successful batches remain committed');+ });++ test('a no_progress stop whose count failed stays retryable (count_unavailable)', async () => {+ nextResult = baseResult({ stopped: 'no_progress', remaining: null });+ const json = await runDrainCaptured(['--json']);+ expect(json.exitCode).toBe(11);+ expect(JSON.parse(json.stdout.join('\n'))).toMatchObject({ status: 'incomplete', retryable: true, code: 'atom_drain_incomplete', reason: 'count_unavailable' });+ });++ test('a resumable stop never reports status ok in JSON', async () => {+ nextResult = baseResult({ stopped: 'window', remaining: 12 });+ const json = await runDrainCaptured(['--json']);+ expect(json.exitCode).toBe(11);+ expect(JSON.parse(json.stdout.join('\n'))).toMatchObject({ status: 'incomplete', retryable: true, code: 'atom_drain_incomplete', reason: 'window' });+ });++ test('--help documents exits 0, 11 and 1, never 3', async () => {+ const out: string[] = [];+ const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.map(String).join(' ')); });+ try {+ await runDream(engine, ['--help']);+ } finally {+ logSpy.mockRestore();+ }+ const help = out.join('\n');+ expect(help).toContain('Exits 0 when the backlog drained;');+ expect(help).toContain('11 when running again can continue');+ expect(help).toContain('1 when it cannot until something');+ expect(help).not.toContain('exits 3');+ });+});diff --git a/test/extract-atoms-drain-handler.test.ts b/test/extract-atoms-drain-handler.test.tsindex 68686b7913..57add896db 100644--- a/test/extract-atoms-drain-handler.test.ts+++ b/test/extract-atoms-drain-handler.test.ts@@ -134,6 +134,32 @@ describe('extract-atoms-drain handler', () => {expect(await lockRows()).toEqual([]);});+ // #6817: one stop mapping for the CLI and this handler. A permanent provider+ // outage dead-letters once; a transient one keeps the retry under backoff.+ test('an auth failure on every item dead-letters at once; a transient one retries (#6817)', async () => {+ await seedEligiblePage('notes/provider-probe');+ const cases = [+ { error: () => Object.assign(new Error('401 Unauthorized: invalid x-api-key'), { status: 401 }), cls: 'auth' as const, final: true },+ { error: () => new Error('provider unavailable'), cls: 'transient' as const, final: false },+ ];+ for (const c of cases) {+ await engine.executeRaw('DELETE FROM gbrain_cycle_locks');+ __setChatTransportForTests(async () => { throw c.error(); });+ let direct: ExtractAtomsDrainResult;+ let err: unknown;+ try {+ direct = await runExtractAtomsDrainForSource(engine, { sourceId: 'default', windowSeconds: 120 });+ err = await makeExtractAtomsDrainHandler(engine)(drainJob(new AbortController().signal)).then(() => null, (e: unknown) => e);+ } finally {+ __setChatTransportForTests(null);+ }+ expect({ status: direct.status, cls: direct.provider_failure_class }).toEqual({ status: 'provider_failure', cls: c.cls });+ expect(err).toBeInstanceOf(Error);+ expect(err instanceof UnrecoverableError).toBe(c.final);+ expect((err as Error).message.includes('retrying')).toBe(!c.final);+ }+ });+// #5832: withRefreshingLock aborts the signal it hands its work when the// cycle lock's lease is lost; that signal must reach the model call even for// a caller that passes no signal of its own (gbrain dream --drain).diff --git a/test/extract-atoms-drain-outcome.test.ts b/test/extract-atoms-drain-outcome.test.tsnew file mode 100644index 0000000000..7ac2580e45--- /dev/null+++ b/test/extract-atoms-drain-outcome.test.ts@@ -0,0 +1,60 @@+/**+ * #6817: every DrainStop against its exit code, JSON status and retryability,+ * plus the provider-failure classification the drain carries to that mapping.+ */+import { describe, expect, test } from 'bun:test';+import { drainOutcome, type DrainOutcome } from '../src/core/cycle/extract-atoms-drain-outcome.ts';+import {+ batchProviderFailureClass,+ runExtractAtomsDrain,+ type DrainStop,+ type ExtractAtomsDrainDeps,+} from '../src/core/cycle/extract-atoms-drain.ts';++describe('drainOutcome: one row per stop (#6817)', () => {+ const rows: Array<[DrainStop, number | null, number, boolean, DrainOutcome['status'], DrainOutcome['code']]> = [+ ['drained', 0, 0, false, 'ok', undefined],+ ['drained', null, 11, true, 'incomplete', 'atom_drain_incomplete'],+ ['window', 4, 11, true, 'incomplete', 'atom_drain_incomplete'],+ ['deadline', 4, 11, true, 'incomplete', 'atom_drain_incomplete'],+ ['lock_lost', 4, 11, true, 'incomplete', 'atom_drain_incomplete'],+ ['aborted', 4, 11, true, 'incomplete', 'atom_drain_incomplete'],+ ['max_batches', 4, 11, true, 'incomplete', 'atom_drain_incomplete'],+ ['budget', 4, 11, true, 'incomplete', 'atom_drain_incomplete'],+ ['no_progress', 4, 1, false, 'incomplete', 'atom_drain_no_progress'],+ ['no_progress', null, 11, true, 'incomplete', 'atom_drain_incomplete'],+ ];+ test.each(rows)('%s with remaining %p exits %d (retryable %p)', (stopped, remaining, exit, retryable, status, code) => {+ const outcome = drainOutcome({ status: 'ok', stopped, remaining });+ expect({ exit: outcome.exit, retryable: outcome.retryable, status: outcome.status, code: outcome.code }).toEqual({ exit, retryable, status, code });+ });++ test.each([+ ['auth', 1, false], ['billing', 1, false], ['model_not_found', 1, false], ['content_block', 1, false],+ ['rate_limit', 11, true], ['transient', 11, true], [undefined, 11, true],+ ] as const)('provider_failure class %p exits %d', (cls, exit, retryable) => {+ for (const remaining of [5, 0, null]) {+ expect(drainOutcome({ status: 'provider_failure', stopped: 'provider_failure', remaining, provider_failure_class: cls }))+ .toEqual({ status: 'provider_failure', exit, retryable, code: 'atom_drain_provider_failure', reason: cls ?? 'transient' });+ }+ });+});++describe('provider failure classification (#6817)', () => {+ test('the phase halt class wins; an all-content-block batch is content_block; anything else is transient', () => {+ for (const halted of ['auth', 'billing', 'model_not_found', 'rate_limit'] as const) expect(batchProviderFailureClass(halted, [])).toBe(halted);+ expect(batchProviderFailureClass(undefined, [{ reason: 'provider blocked content: safety' }])).toBe('content_block');+ expect(batchProviderFailureClass(undefined, [{ reason: 'provider blocked content: safety' }, { reason: '503 overloaded' }])).toBe('transient');+ expect(batchProviderFailureClass(undefined, [])).toBe('transient');+ expect(batchProviderFailureClass('something_else', [{ reason: 'boom' }])).toBe('transient');+ });++ test('the drain result carries the failing batch class, and only on provider_failure', async () => {+ const lock: ExtractAtomsDrainDeps['withLock'] = (work) => work(new AbortController().signal);+ const run = (batch: Awaited<ReturnType<ExtractAtomsDrainDeps['runBatch']>>) => runExtractAtomsDrain(+ { withLock: lock, countRemaining: async () => 3, runBatch: async () => batch, now: () => 0 }, { windowMs: 1_000_000, maxBatches: 1 });+ expect((await run({ extracted: 0, skipped: 0, providerFailure: true, providerFailureClass: 'auth' })).provider_failure_class).toBe('auth');+ expect((await run({ extracted: 0, skipped: 0, providerFailure: true })).provider_failure_class).toBe('transient');+ expect((await run({ extracted: 1, skipped: 0 })).provider_failure_class).toBeUndefined();+ });+});diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 54e7bf44f8..f20dbe7d58 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -1840,7 +1840,7 @@"cause?: unknown","message: string","name: string",- "reason: \"unknown\" | \"timeout\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"unreachable\" | \"auth\" | \"payload_too_large\" | \"network\" | \"rate_limit\"",+ "reason: \"unknown\" | \"timeout\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"unreachable\" | \"auth\" | \"rate_limit\" | \"payload_too_large\" | \"network\"","stack?: string | undefined","status?: number | undefined"],@@ -5059,7 +5059,7 @@{"kind": "interface","members": [- "attachment: \"none\" | \"attached\" | \"window\" | \"other-links\"",+ "attachment: \"none\" | \"window\" | \"attached\" | \"other-links\"","context: string","index?: number | undefined","linkType: string",@@ -5076,7 +5076,7 @@{"kind": "interface","members": [- "attachment: \"none\" | \"attached\" | \"window\" | \"other-links\"",+ "attachment: \"none\" | \"window\" | \"attached\" | \"other-links\"","prior: string | null","rule: string | null","suppressed: string[]",@@ -6394,7 +6394,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",